1 //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/None.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/MemoryLocation.h"
34 #include "llvm/CodeGen/DAGCombine.h"
35 #include "llvm/CodeGen/ISDOpcodes.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/RuntimeLibcalls.h"
40 #include "llvm/CodeGen/SelectionDAG.h"
41 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
42 #include "llvm/CodeGen/SelectionDAGNodes.h"
43 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
44 #include "llvm/CodeGen/TargetLowering.h"
45 #include "llvm/CodeGen/TargetRegisterInfo.h"
46 #include "llvm/CodeGen/TargetSubtargetInfo.h"
47 #include "llvm/CodeGen/ValueTypes.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"
57 #include "llvm/Support/CommandLine.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/KnownBits.h"
62 #include "llvm/Support/MachineValueType.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Target/TargetMachine.h"
66 #include "llvm/Target/TargetOptions.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 #include <vector>
76 
77 using namespace llvm;
78 
79 #define DEBUG_TYPE "dagcombine"
80 
81 STATISTIC(NodesCombined   , "Number of dag nodes combined");
82 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
83 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
84 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
85 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
86 STATISTIC(SlicedLoads, "Number of load sliced");
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
97 static cl::opt<std::string>
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;
119     CombineLevel Level;
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) {
177       assert(N->getOpcode() != ISD::DELETED_NODE &&
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     /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
254     ///   load.
255     ///
256     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
257     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
258     /// \param EltNo index of the vector element to load.
259     /// \param OriginalLoad load that EVE came from to be replaced.
260     /// \returns EVE on success SDValue() on failure.
261     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
262         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
263     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
264     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
265     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
266     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
267     SDValue PromoteIntBinOp(SDValue Op);
268     SDValue PromoteIntShiftOp(SDValue Op);
269     SDValue PromoteExtend(SDValue Op);
270     bool PromoteLoad(SDValue Op);
271 
272     /// Call the node-specific routine that knows how to fold each
273     /// particular type of node. If that doesn't do anything, try the
274     /// target-specific DAG combines.
275     SDValue combine(SDNode *N);
276 
277     // Visitation implementation - Implement dag node combining for different
278     // node types.  The semantics are as follows:
279     // Return Value:
280     //   SDValue.getNode() == 0 - No change was made
281     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
282     //   otherwise              - N should be replaced by the returned Operand.
283     //
284     SDValue visitTokenFactor(SDNode *N);
285     SDValue visitMERGE_VALUES(SDNode *N);
286     SDValue visitADD(SDNode *N);
287     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
288     SDValue visitSUB(SDNode *N);
289     SDValue visitADDC(SDNode *N);
290     SDValue visitUADDO(SDNode *N);
291     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
292     SDValue visitSUBC(SDNode *N);
293     SDValue visitUSUBO(SDNode *N);
294     SDValue visitADDE(SDNode *N);
295     SDValue visitADDCARRY(SDNode *N);
296     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
297     SDValue visitSUBE(SDNode *N);
298     SDValue visitSUBCARRY(SDNode *N);
299     SDValue visitMUL(SDNode *N);
300     SDValue useDivRem(SDNode *N);
301     SDValue visitSDIV(SDNode *N);
302     SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N);
303     SDValue visitUDIV(SDNode *N);
304     SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N);
305     SDValue visitREM(SDNode *N);
306     SDValue visitMULHU(SDNode *N);
307     SDValue visitMULHS(SDNode *N);
308     SDValue visitSMUL_LOHI(SDNode *N);
309     SDValue visitUMUL_LOHI(SDNode *N);
310     SDValue visitSMULO(SDNode *N);
311     SDValue visitUMULO(SDNode *N);
312     SDValue visitIMINMAX(SDNode *N);
313     SDValue visitAND(SDNode *N);
314     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N);
315     SDValue visitOR(SDNode *N);
316     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N);
317     SDValue visitXOR(SDNode *N);
318     SDValue SimplifyVBinOp(SDNode *N);
319     SDValue visitSHL(SDNode *N);
320     SDValue visitSRA(SDNode *N);
321     SDValue visitSRL(SDNode *N);
322     SDValue visitRotate(SDNode *N);
323     SDValue visitABS(SDNode *N);
324     SDValue visitBSWAP(SDNode *N);
325     SDValue visitBITREVERSE(SDNode *N);
326     SDValue visitCTLZ(SDNode *N);
327     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
328     SDValue visitCTTZ(SDNode *N);
329     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
330     SDValue visitCTPOP(SDNode *N);
331     SDValue visitSELECT(SDNode *N);
332     SDValue visitVSELECT(SDNode *N);
333     SDValue visitSELECT_CC(SDNode *N);
334     SDValue visitSETCC(SDNode *N);
335     SDValue visitSETCCCARRY(SDNode *N);
336     SDValue visitSIGN_EXTEND(SDNode *N);
337     SDValue visitZERO_EXTEND(SDNode *N);
338     SDValue visitANY_EXTEND(SDNode *N);
339     SDValue visitAssertExt(SDNode *N);
340     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
341     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
342     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
343     SDValue visitTRUNCATE(SDNode *N);
344     SDValue visitBITCAST(SDNode *N);
345     SDValue visitBUILD_PAIR(SDNode *N);
346     SDValue visitFADD(SDNode *N);
347     SDValue visitFSUB(SDNode *N);
348     SDValue visitFMUL(SDNode *N);
349     SDValue visitFMA(SDNode *N);
350     SDValue visitFDIV(SDNode *N);
351     SDValue visitFREM(SDNode *N);
352     SDValue visitFSQRT(SDNode *N);
353     SDValue visitFCOPYSIGN(SDNode *N);
354     SDValue visitSINT_TO_FP(SDNode *N);
355     SDValue visitUINT_TO_FP(SDNode *N);
356     SDValue visitFP_TO_SINT(SDNode *N);
357     SDValue visitFP_TO_UINT(SDNode *N);
358     SDValue visitFP_ROUND(SDNode *N);
359     SDValue visitFP_ROUND_INREG(SDNode *N);
360     SDValue visitFP_EXTEND(SDNode *N);
361     SDValue visitFNEG(SDNode *N);
362     SDValue visitFABS(SDNode *N);
363     SDValue visitFCEIL(SDNode *N);
364     SDValue visitFTRUNC(SDNode *N);
365     SDValue visitFFLOOR(SDNode *N);
366     SDValue visitFMINNUM(SDNode *N);
367     SDValue visitFMAXNUM(SDNode *N);
368     SDValue visitBRCOND(SDNode *N);
369     SDValue visitBR_CC(SDNode *N);
370     SDValue visitLOAD(SDNode *N);
371 
372     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
373     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
374 
375     SDValue visitSTORE(SDNode *N);
376     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
377     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
378     SDValue visitBUILD_VECTOR(SDNode *N);
379     SDValue visitCONCAT_VECTORS(SDNode *N);
380     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
381     SDValue visitVECTOR_SHUFFLE(SDNode *N);
382     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
383     SDValue visitINSERT_SUBVECTOR(SDNode *N);
384     SDValue visitMLOAD(SDNode *N);
385     SDValue visitMSTORE(SDNode *N);
386     SDValue visitMGATHER(SDNode *N);
387     SDValue visitMSCATTER(SDNode *N);
388     SDValue visitFP_TO_FP16(SDNode *N);
389     SDValue visitFP16_TO_FP(SDNode *N);
390 
391     SDValue visitFADDForFMACombine(SDNode *N);
392     SDValue visitFSUBForFMACombine(SDNode *N);
393     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
394 
395     SDValue XformToShuffleWithZero(SDNode *N);
396     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
397                            SDValue N1);
398 
399     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
400 
401     SDValue foldSelectOfConstants(SDNode *N);
402     SDValue foldVSelectOfConstants(SDNode *N);
403     SDValue foldBinOpIntoSelect(SDNode *BO);
404     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
405     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
406     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
407     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
408                              SDValue N2, SDValue N3, ISD::CondCode CC,
409                              bool NotExtCompare = false);
410     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
411                                    SDValue N2, SDValue N3, ISD::CondCode CC);
412     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
413                               const SDLoc &DL);
414     SDValue unfoldMaskedMerge(SDNode *N);
415     SDValue unfoldExtremeBitClearingToShifts(SDNode *N);
416     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
417                           const SDLoc &DL, bool foldBooleans);
418     SDValue rebuildSetCC(SDValue N);
419 
420     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
421                            SDValue &CC) const;
422     bool isOneUseSetCC(SDValue N) const;
423 
424     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
425                                          unsigned HiOp);
426     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
427     SDValue CombineExtLoad(SDNode *N);
428     SDValue CombineZExtLogicopShiftLoad(SDNode *N);
429     SDValue combineRepeatedFPDivisors(SDNode *N);
430     SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
431     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
432     SDValue BuildSDIV(SDNode *N);
433     SDValue BuildSDIVPow2(SDNode *N);
434     SDValue BuildUDIV(SDNode *N);
435     SDValue BuildLogBase2(SDValue V, const SDLoc &DL);
436     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
437     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
438     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
439     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
440     SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations,
441                                 SDNodeFlags Flags, bool Reciprocal);
442     SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations,
443                                 SDNodeFlags Flags, bool Reciprocal);
444     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
445                                bool DemandHighBits = true);
446     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
447     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
448                               SDValue InnerPos, SDValue InnerNeg,
449                               unsigned PosOpcode, unsigned NegOpcode,
450                               const SDLoc &DL);
451     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
452     SDValue MatchLoadCombine(SDNode *N);
453     SDValue ReduceLoadWidth(SDNode *N);
454     SDValue ReduceLoadOpStoreWidth(SDNode *N);
455     SDValue splitMergedValStore(StoreSDNode *ST);
456     SDValue TransformFPLoadStorePair(SDNode *N);
457     SDValue convertBuildVecZextToZext(SDNode *N);
458     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
459     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
460     SDValue reduceBuildVecToShuffle(SDNode *N);
461     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
462                                   ArrayRef<int> VectorMask, SDValue VecIn1,
463                                   SDValue VecIn2, unsigned LeftIdx);
464     SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast);
465 
466     /// Walk up chain skipping non-aliasing memory nodes,
467     /// looking for aliasing nodes and adding them to the Aliases vector.
468     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
469                           SmallVectorImpl<SDValue> &Aliases);
470 
471     /// Return true if there is any possibility that the two addresses overlap.
472     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
473 
474     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
475     /// chain (aliasing node.)
476     SDValue FindBetterChain(SDNode *N, SDValue Chain);
477 
478     /// Try to replace a store and any possibly adjacent stores on
479     /// consecutive chains with better chains. Return true only if St is
480     /// replaced.
481     ///
482     /// Notice that other chains may still be replaced even if the function
483     /// returns false.
484     bool findBetterNeighborChains(StoreSDNode *St);
485 
486     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
487     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
488 
489     /// Holds a pointer to an LSBaseSDNode as well as information on where it
490     /// is located in a sequence of memory operations connected by a chain.
491     struct MemOpLink {
492       // Ptr to the mem node.
493       LSBaseSDNode *MemNode;
494 
495       // Offset from the base ptr.
496       int64_t OffsetFromBase;
497 
498       MemOpLink(LSBaseSDNode *N, int64_t Offset)
499           : MemNode(N), OffsetFromBase(Offset) {}
500     };
501 
502     /// This is a helper function for visitMUL to check the profitability
503     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
504     /// MulNode is the original multiply, AddNode is (add x, c1),
505     /// and ConstNode is c2.
506     bool isMulAddWithConstProfitable(SDNode *MulNode,
507                                      SDValue &AddNode,
508                                      SDValue &ConstNode);
509 
510     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
511     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
512     /// the type of the loaded value to be extended.
513     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
514                           EVT LoadResultTy, EVT &ExtVT);
515 
516     /// Helper function to calculate whether the given Load/Store can have its
517     /// width reduced to ExtVT.
518     bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType,
519                            EVT &MemVT, unsigned ShAmt = 0);
520 
521     /// Used by BackwardsPropagateMask to find suitable loads.
522     bool SearchForAndLoads(SDNode *N, SmallPtrSetImpl<LoadSDNode*> &Loads,
523                            SmallPtrSetImpl<SDNode*> &NodesWithConsts,
524                            ConstantSDNode *Mask, SDNode *&NodeToMask);
525     /// Attempt to propagate a given AND node back to load leaves so that they
526     /// can be combined into narrow loads.
527     bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG);
528 
529     /// Helper function for MergeConsecutiveStores which merges the
530     /// component store chains.
531     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
532                                 unsigned NumStores);
533 
534     /// This is a helper function for MergeConsecutiveStores. When the
535     /// source elements of the consecutive stores are all constants or
536     /// all extracted vector elements, try to merge them into one
537     /// larger store introducing bitcasts if necessary.  \return True
538     /// if a merged store was created.
539     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
540                                          EVT MemVT, unsigned NumStores,
541                                          bool IsConstantSrc, bool UseVector,
542                                          bool UseTrunc);
543 
544     /// This is a helper function for MergeConsecutiveStores. Stores
545     /// that potentially may be merged with St are placed in
546     /// StoreNodes. RootNode is a chain predecessor to all store
547     /// candidates.
548     void getStoreMergeCandidates(StoreSDNode *St,
549                                  SmallVectorImpl<MemOpLink> &StoreNodes,
550                                  SDNode *&Root);
551 
552     /// Helper function for MergeConsecutiveStores. Checks if
553     /// candidate stores have indirect dependency through their
554     /// operands. RootNode is the predecessor to all stores calculated
555     /// by getStoreMergeCandidates and is used to prune the dependency check.
556     /// \return True if safe to merge.
557     bool checkMergeStoreCandidatesForDependencies(
558         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
559         SDNode *RootNode);
560 
561     /// Merge consecutive store operations into a wide store.
562     /// This optimization uses wide integers or vectors when possible.
563     /// \return number of stores that were merged into a merged store (the
564     /// affected nodes are stored as a prefix in \p StoreNodes).
565     bool MergeConsecutiveStores(StoreSDNode *St);
566 
567     /// Try to transform a truncation where C is a constant:
568     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
569     ///
570     /// \p N needs to be a truncation and its first operand an AND. Other
571     /// requirements are checked by the function (e.g. that trunc is
572     /// single-use) and if missed an empty SDValue is returned.
573     SDValue distributeTruncateThroughAnd(SDNode *N);
574 
575     /// Helper function to determine whether the target supports operation
576     /// given by \p Opcode for type \p VT, that is, whether the operation
577     /// is legal or custom before legalizing operations, and whether is
578     /// legal (but not custom) after legalization.
579     bool hasOperation(unsigned Opcode, EVT VT) {
580       if (LegalOperations)
581         return TLI.isOperationLegal(Opcode, VT);
582       return TLI.isOperationLegalOrCustom(Opcode, VT);
583     }
584 
585   public:
586     /// Runs the dag combiner on all nodes in the work list
587     void Run(CombineLevel AtLevel);
588 
589     SelectionDAG &getDAG() const { return DAG; }
590 
591     /// Returns a type large enough to hold any valid shift amount - before type
592     /// legalization these can be huge.
593     EVT getShiftAmountTy(EVT LHSTy) {
594       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
595       return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes);
596     }
597 
598     /// This method returns true if we are running before type legalization or
599     /// if the specified VT is legal.
600     bool isTypeLegal(const EVT &VT) {
601       if (!LegalTypes) return true;
602       return TLI.isTypeLegal(VT);
603     }
604 
605     /// Convenience wrapper around TargetLowering::getSetCCResultType
606     EVT getSetCCResultType(EVT VT) const {
607       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
608     }
609 
610     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
611                          SDValue OrigLoad, SDValue ExtLoad,
612                          ISD::NodeType ExtType);
613   };
614 
615 /// This class is a DAGUpdateListener that removes any deleted
616 /// nodes from the worklist.
617 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
618   DAGCombiner &DC;
619 
620 public:
621   explicit WorklistRemover(DAGCombiner &dc)
622     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
623 
624   void NodeDeleted(SDNode *N, SDNode *E) override {
625     DC.removeFromWorklist(N);
626   }
627 };
628 
629 } // end anonymous namespace
630 
631 //===----------------------------------------------------------------------===//
632 //  TargetLowering::DAGCombinerInfo implementation
633 //===----------------------------------------------------------------------===//
634 
635 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
636   ((DAGCombiner*)DC)->AddToWorklist(N);
637 }
638 
639 SDValue TargetLowering::DAGCombinerInfo::
640 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
641   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
642 }
643 
644 SDValue TargetLowering::DAGCombinerInfo::
645 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
646   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
647 }
648 
649 SDValue TargetLowering::DAGCombinerInfo::
650 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
651   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
652 }
653 
654 void TargetLowering::DAGCombinerInfo::
655 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
656   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
657 }
658 
659 //===----------------------------------------------------------------------===//
660 // Helper Functions
661 //===----------------------------------------------------------------------===//
662 
663 void DAGCombiner::deleteAndRecombine(SDNode *N) {
664   removeFromWorklist(N);
665 
666   // If the operands of this node are only used by the node, they will now be
667   // dead. Make sure to re-visit them and recursively delete dead nodes.
668   for (const SDValue &Op : N->ops())
669     // For an operand generating multiple values, one of the values may
670     // become dead allowing further simplification (e.g. split index
671     // arithmetic from an indexed load).
672     if (Op->hasOneUse() || Op->getNumValues() > 1)
673       AddToWorklist(Op.getNode());
674 
675   DAG.DeleteNode(N);
676 }
677 
678 /// Return 1 if we can compute the negated form of the specified expression for
679 /// the same cost as the expression itself, or 2 if we can compute the negated
680 /// form more cheaply than the expression itself.
681 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
682                                const TargetLowering &TLI,
683                                const TargetOptions *Options,
684                                unsigned Depth = 0) {
685   // fneg is removable even if it has multiple uses.
686   if (Op.getOpcode() == ISD::FNEG) return 2;
687 
688   // Don't allow anything with multiple uses unless we know it is free.
689   EVT VT = Op.getValueType();
690   const SDNodeFlags Flags = Op->getFlags();
691   if (!Op.hasOneUse())
692     if (!(Op.getOpcode() == ISD::FP_EXTEND &&
693           TLI.isFPExtFree(VT, Op.getOperand(0).getValueType())))
694       return 0;
695 
696   // Don't recurse exponentially.
697   if (Depth > 6) return 0;
698 
699   switch (Op.getOpcode()) {
700   default: return false;
701   case ISD::ConstantFP: {
702     if (!LegalOperations)
703       return 1;
704 
705     // Don't invert constant FP values after legalization unless the target says
706     // the negated constant is legal.
707     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
708       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
709   }
710   case ISD::FADD:
711     if (!Options->UnsafeFPMath && !Flags.hasNoSignedZeros())
712       return 0;
713 
714     // After operation legalization, it might not be legal to create new FSUBs.
715     if (LegalOperations && !TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
716       return 0;
717 
718     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
719     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
720                                     Options, Depth + 1))
721       return V;
722     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
723     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
724                               Depth + 1);
725   case ISD::FSUB:
726     // We can't turn -(A-B) into B-A when we honor signed zeros.
727     if (!Options->NoSignedZerosFPMath &&
728         !Flags.hasNoSignedZeros())
729       return 0;
730 
731     // fold (fneg (fsub A, B)) -> (fsub B, A)
732     return 1;
733 
734   case ISD::FMUL:
735   case ISD::FDIV:
736     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
737     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
738                                     Options, Depth + 1))
739       return V;
740 
741     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
742                               Depth + 1);
743 
744   case ISD::FP_EXTEND:
745   case ISD::FP_ROUND:
746   case ISD::FSIN:
747     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
748                               Depth + 1);
749   }
750 }
751 
752 /// If isNegatibleForFree returns true, return the newly negated expression.
753 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
754                                     bool LegalOperations, unsigned Depth = 0) {
755   const TargetOptions &Options = DAG.getTarget().Options;
756   // fneg is removable even if it has multiple uses.
757   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
758 
759   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
760 
761   const SDNodeFlags Flags = Op.getNode()->getFlags();
762 
763   switch (Op.getOpcode()) {
764   default: llvm_unreachable("Unknown code");
765   case ISD::ConstantFP: {
766     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
767     V.changeSign();
768     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
769   }
770   case ISD::FADD:
771     assert(Options.UnsafeFPMath || Flags.hasNoSignedZeros());
772 
773     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
774     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
775                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
776       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
777                          GetNegatedExpression(Op.getOperand(0), DAG,
778                                               LegalOperations, Depth+1),
779                          Op.getOperand(1), Flags);
780     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
781     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
782                        GetNegatedExpression(Op.getOperand(1), DAG,
783                                             LegalOperations, Depth+1),
784                        Op.getOperand(0), Flags);
785   case ISD::FSUB:
786     // fold (fneg (fsub 0, B)) -> B
787     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
788       if (N0CFP->isZero())
789         return Op.getOperand(1);
790 
791     // fold (fneg (fsub A, B)) -> (fsub B, A)
792     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
793                        Op.getOperand(1), Op.getOperand(0), Flags);
794 
795   case ISD::FMUL:
796   case ISD::FDIV:
797     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
798     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
799                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
800       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
801                          GetNegatedExpression(Op.getOperand(0), DAG,
802                                               LegalOperations, Depth+1),
803                          Op.getOperand(1), Flags);
804 
805     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
806     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
807                        Op.getOperand(0),
808                        GetNegatedExpression(Op.getOperand(1), DAG,
809                                             LegalOperations, Depth+1), Flags);
810 
811   case ISD::FP_EXTEND:
812   case ISD::FSIN:
813     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
814                        GetNegatedExpression(Op.getOperand(0), DAG,
815                                             LegalOperations, Depth+1));
816   case ISD::FP_ROUND:
817       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
818                          GetNegatedExpression(Op.getOperand(0), DAG,
819                                               LegalOperations, Depth+1),
820                          Op.getOperand(1));
821   }
822 }
823 
824 // APInts must be the same size for most operations, this helper
825 // function zero extends the shorter of the pair so that they match.
826 // We provide an Offset so that we can create bitwidths that won't overflow.
827 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
828   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
829   LHS = LHS.zextOrSelf(Bits);
830   RHS = RHS.zextOrSelf(Bits);
831 }
832 
833 // Return true if this node is a setcc, or is a select_cc
834 // that selects between the target values used for true and false, making it
835 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
836 // the appropriate nodes based on the type of node we are checking. This
837 // simplifies life a bit for the callers.
838 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
839                                     SDValue &CC) const {
840   if (N.getOpcode() == ISD::SETCC) {
841     LHS = N.getOperand(0);
842     RHS = N.getOperand(1);
843     CC  = N.getOperand(2);
844     return true;
845   }
846 
847   if (N.getOpcode() != ISD::SELECT_CC ||
848       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
849       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
850     return false;
851 
852   if (TLI.getBooleanContents(N.getValueType()) ==
853       TargetLowering::UndefinedBooleanContent)
854     return false;
855 
856   LHS = N.getOperand(0);
857   RHS = N.getOperand(1);
858   CC  = N.getOperand(4);
859   return true;
860 }
861 
862 /// Return true if this is a SetCC-equivalent operation with only one use.
863 /// If this is true, it allows the users to invert the operation for free when
864 /// it is profitable to do so.
865 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
866   SDValue N0, N1, N2;
867   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
868     return true;
869   return false;
870 }
871 
872 static SDValue peekThroughBitcast(SDValue V) {
873   while (V.getOpcode() == ISD::BITCAST)
874     V = V.getOperand(0);
875   return V;
876 }
877 
878 // Returns the SDNode if it is a constant float BuildVector
879 // or constant float.
880 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
881   if (isa<ConstantFPSDNode>(N))
882     return N.getNode();
883   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
884     return N.getNode();
885   return nullptr;
886 }
887 
888 // Determines if it is a constant integer or a build vector of constant
889 // integers (and undefs).
890 // Do not permit build vector implicit truncation.
891 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
892   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
893     return !(Const->isOpaque() && NoOpaques);
894   if (N.getOpcode() != ISD::BUILD_VECTOR)
895     return false;
896   unsigned BitWidth = N.getScalarValueSizeInBits();
897   for (const SDValue &Op : N->op_values()) {
898     if (Op.isUndef())
899       continue;
900     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
901     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
902         (Const->isOpaque() && NoOpaques))
903       return false;
904   }
905   return true;
906 }
907 
908 // Determines if it is a constant null integer or a splatted vector of a
909 // constant null integer (with no undefs).
910 // Build vector implicit truncation is not an issue for null values.
911 static bool isNullConstantOrNullSplatConstant(SDValue N) {
912   // TODO: may want to use peekThroughBitcast() here.
913   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
914     return Splat->isNullValue();
915   return false;
916 }
917 
918 // Determines if it is a constant integer of one or a splatted vector of a
919 // constant integer of one (with no undefs).
920 // Do not permit build vector implicit truncation.
921 static bool isOneConstantOrOneSplatConstant(SDValue N) {
922   // TODO: may want to use peekThroughBitcast() here.
923   unsigned BitWidth = N.getScalarValueSizeInBits();
924   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
925     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
926   return false;
927 }
928 
929 // Determines if it is a constant integer of all ones or a splatted vector of a
930 // constant integer of all ones (with no undefs).
931 // Do not permit build vector implicit truncation.
932 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
933   N = peekThroughBitcast(N);
934   unsigned BitWidth = N.getScalarValueSizeInBits();
935   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
936     return Splat->isAllOnesValue() &&
937            Splat->getAPIntValue().getBitWidth() == BitWidth;
938   return false;
939 }
940 
941 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
942 // undef's.
943 static bool isAnyConstantBuildVector(const SDNode *N) {
944   return ISD::isBuildVectorOfConstantSDNodes(N) ||
945          ISD::isBuildVectorOfConstantFPSDNodes(N);
946 }
947 
948 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
949                                     SDValue N1) {
950   EVT VT = N0.getValueType();
951   if (N0.getOpcode() == Opc) {
952     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
953       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
954         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
955         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
956           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
957         return SDValue();
958       }
959       if (N0.hasOneUse()) {
960         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
961         // use
962         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
963         if (!OpNode.getNode())
964           return SDValue();
965         AddToWorklist(OpNode.getNode());
966         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
967       }
968     }
969   }
970 
971   if (N1.getOpcode() == Opc) {
972     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
973       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
974         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
975         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
976           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
977         return SDValue();
978       }
979       if (N1.hasOneUse()) {
980         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
981         // use
982         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
983         if (!OpNode.getNode())
984           return SDValue();
985         AddToWorklist(OpNode.getNode());
986         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
987       }
988     }
989   }
990 
991   return SDValue();
992 }
993 
994 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
995                                bool AddTo) {
996   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
997   ++NodesCombined;
998   LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";
999              To[0].getNode()->dump(&DAG);
1000              dbgs() << " and " << NumTo - 1 << " other values\n");
1001   for (unsigned i = 0, e = NumTo; i != e; ++i)
1002     assert((!To[i].getNode() ||
1003             N->getValueType(i) == To[i].getValueType()) &&
1004            "Cannot combine value to value of different type!");
1005 
1006   WorklistRemover DeadNodes(*this);
1007   DAG.ReplaceAllUsesWith(N, To);
1008   if (AddTo) {
1009     // Push the new nodes and any users onto the worklist
1010     for (unsigned i = 0, e = NumTo; i != e; ++i) {
1011       if (To[i].getNode()) {
1012         AddToWorklist(To[i].getNode());
1013         AddUsersToWorklist(To[i].getNode());
1014       }
1015     }
1016   }
1017 
1018   // Finally, if the node is now dead, remove it from the graph.  The node
1019   // may not be dead if the replacement process recursively simplified to
1020   // something else needing this node.
1021   if (N->use_empty())
1022     deleteAndRecombine(N);
1023   return SDValue(N, 0);
1024 }
1025 
1026 void DAGCombiner::
1027 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1028   // Replace all uses.  If any nodes become isomorphic to other nodes and
1029   // are deleted, make sure to remove them from our worklist.
1030   WorklistRemover DeadNodes(*this);
1031   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1032 
1033   // Push the new node and any (possibly new) users onto the worklist.
1034   AddToWorklist(TLO.New.getNode());
1035   AddUsersToWorklist(TLO.New.getNode());
1036 
1037   // Finally, if the node is now dead, remove it from the graph.  The node
1038   // may not be dead if the replacement process recursively simplified to
1039   // something else needing this node.
1040   if (TLO.Old.getNode()->use_empty())
1041     deleteAndRecombine(TLO.Old.getNode());
1042 }
1043 
1044 /// Check the specified integer node value to see if it can be simplified or if
1045 /// things it uses can be simplified by bit propagation. If so, return true.
1046 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
1047   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1048   KnownBits Known;
1049   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
1050     return false;
1051 
1052   // Revisit the node.
1053   AddToWorklist(Op.getNode());
1054 
1055   // Replace the old value with the new one.
1056   ++NodesCombined;
1057   LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
1058              dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);
1059              dbgs() << '\n');
1060 
1061   CommitTargetLoweringOpt(TLO);
1062   return true;
1063 }
1064 
1065 /// Check the specified vector node value to see if it can be simplified or
1066 /// if things it uses can be simplified as it only uses some of the elements.
1067 /// If so, return true.
1068 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op, const APInt &Demanded,
1069                                              bool AssumeSingleUse) {
1070   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1071   APInt KnownUndef, KnownZero;
1072   if (!TLI.SimplifyDemandedVectorElts(Op, Demanded, KnownUndef, KnownZero, TLO,
1073                                       0, AssumeSingleUse))
1074     return false;
1075 
1076   // Revisit the node.
1077   AddToWorklist(Op.getNode());
1078 
1079   // Replace the old value with the new one.
1080   ++NodesCombined;
1081   LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
1082              dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);
1083              dbgs() << '\n');
1084 
1085   CommitTargetLoweringOpt(TLO);
1086   return true;
1087 }
1088 
1089 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1090   SDLoc DL(Load);
1091   EVT VT = Load->getValueType(0);
1092   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1093 
1094   LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";
1095              Trunc.getNode()->dump(&DAG); dbgs() << '\n');
1096   WorklistRemover DeadNodes(*this);
1097   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1098   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1099   deleteAndRecombine(Load);
1100   AddToWorklist(Trunc.getNode());
1101 }
1102 
1103 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1104   Replace = false;
1105   SDLoc DL(Op);
1106   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1107     LoadSDNode *LD = cast<LoadSDNode>(Op);
1108     EVT MemVT = LD->getMemoryVT();
1109     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
1110                                                       : LD->getExtensionType();
1111     Replace = true;
1112     return DAG.getExtLoad(ExtType, DL, PVT,
1113                           LD->getChain(), LD->getBasePtr(),
1114                           MemVT, LD->getMemOperand());
1115   }
1116 
1117   unsigned Opc = Op.getOpcode();
1118   switch (Opc) {
1119   default: break;
1120   case ISD::AssertSext:
1121     if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1122       return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1123     break;
1124   case ISD::AssertZext:
1125     if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1126       return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1127     break;
1128   case ISD::Constant: {
1129     unsigned ExtOpc =
1130       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1131     return DAG.getNode(ExtOpc, DL, PVT, Op);
1132   }
1133   }
1134 
1135   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1136     return SDValue();
1137   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1138 }
1139 
1140 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1141   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1142     return SDValue();
1143   EVT OldVT = Op.getValueType();
1144   SDLoc DL(Op);
1145   bool Replace = false;
1146   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1147   if (!NewOp.getNode())
1148     return SDValue();
1149   AddToWorklist(NewOp.getNode());
1150 
1151   if (Replace)
1152     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1153   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1154                      DAG.getValueType(OldVT));
1155 }
1156 
1157 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1158   EVT OldVT = Op.getValueType();
1159   SDLoc DL(Op);
1160   bool Replace = false;
1161   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1162   if (!NewOp.getNode())
1163     return SDValue();
1164   AddToWorklist(NewOp.getNode());
1165 
1166   if (Replace)
1167     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1168   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1169 }
1170 
1171 /// Promote the specified integer binary operation if the target indicates it is
1172 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1173 /// i32 since i16 instructions are longer.
1174 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1175   if (!LegalOperations)
1176     return SDValue();
1177 
1178   EVT VT = Op.getValueType();
1179   if (VT.isVector() || !VT.isInteger())
1180     return SDValue();
1181 
1182   // If operation type is 'undesirable', e.g. i16 on x86, consider
1183   // promoting it.
1184   unsigned Opc = Op.getOpcode();
1185   if (TLI.isTypeDesirableForOp(Opc, VT))
1186     return SDValue();
1187 
1188   EVT PVT = VT;
1189   // Consult target whether it is a good idea to promote this operation and
1190   // what's the right type to promote it to.
1191   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1192     assert(PVT != VT && "Don't know what type to promote to!");
1193 
1194     LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1195 
1196     bool Replace0 = false;
1197     SDValue N0 = Op.getOperand(0);
1198     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1199 
1200     bool Replace1 = false;
1201     SDValue N1 = Op.getOperand(1);
1202     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1203     SDLoc DL(Op);
1204 
1205     SDValue RV =
1206         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1207 
1208     // We are always replacing N0/N1's use in N and only need
1209     // additional replacements if there are additional uses.
1210     Replace0 &= !N0->hasOneUse();
1211     Replace1 &= (N0 != N1) && !N1->hasOneUse();
1212 
1213     // Combine Op here so it is preserved past replacements.
1214     CombineTo(Op.getNode(), RV);
1215 
1216     // If operands have a use ordering, make sure we deal with
1217     // predecessor first.
1218     if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1219       std::swap(N0, N1);
1220       std::swap(NN0, NN1);
1221     }
1222 
1223     if (Replace0) {
1224       AddToWorklist(NN0.getNode());
1225       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1226     }
1227     if (Replace1) {
1228       AddToWorklist(NN1.getNode());
1229       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1230     }
1231     return Op;
1232   }
1233   return SDValue();
1234 }
1235 
1236 /// Promote the specified integer shift operation if the target indicates it is
1237 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1238 /// i32 since i16 instructions are longer.
1239 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1240   if (!LegalOperations)
1241     return SDValue();
1242 
1243   EVT VT = Op.getValueType();
1244   if (VT.isVector() || !VT.isInteger())
1245     return SDValue();
1246 
1247   // If operation type is 'undesirable', e.g. i16 on x86, consider
1248   // promoting it.
1249   unsigned Opc = Op.getOpcode();
1250   if (TLI.isTypeDesirableForOp(Opc, VT))
1251     return SDValue();
1252 
1253   EVT PVT = VT;
1254   // Consult target whether it is a good idea to promote this operation and
1255   // what's the right type to promote it to.
1256   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1257     assert(PVT != VT && "Don't know what type to promote to!");
1258 
1259     LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1260 
1261     bool Replace = false;
1262     SDValue N0 = Op.getOperand(0);
1263     SDValue N1 = Op.getOperand(1);
1264     if (Opc == ISD::SRA)
1265       N0 = SExtPromoteOperand(N0, PVT);
1266     else if (Opc == ISD::SRL)
1267       N0 = ZExtPromoteOperand(N0, PVT);
1268     else
1269       N0 = PromoteOperand(N0, PVT, Replace);
1270 
1271     if (!N0.getNode())
1272       return SDValue();
1273 
1274     SDLoc DL(Op);
1275     SDValue RV =
1276         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1277 
1278     AddToWorklist(N0.getNode());
1279     if (Replace)
1280       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1281 
1282     // Deal with Op being deleted.
1283     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1284       return RV;
1285   }
1286   return SDValue();
1287 }
1288 
1289 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1290   if (!LegalOperations)
1291     return SDValue();
1292 
1293   EVT VT = Op.getValueType();
1294   if (VT.isVector() || !VT.isInteger())
1295     return SDValue();
1296 
1297   // If operation type is 'undesirable', e.g. i16 on x86, consider
1298   // promoting it.
1299   unsigned Opc = Op.getOpcode();
1300   if (TLI.isTypeDesirableForOp(Opc, VT))
1301     return SDValue();
1302 
1303   EVT PVT = VT;
1304   // Consult target whether it is a good idea to promote this operation and
1305   // what's the right type to promote it to.
1306   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1307     assert(PVT != VT && "Don't know what type to promote to!");
1308     // fold (aext (aext x)) -> (aext x)
1309     // fold (aext (zext x)) -> (zext x)
1310     // fold (aext (sext x)) -> (sext x)
1311     LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1312     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1313   }
1314   return SDValue();
1315 }
1316 
1317 bool DAGCombiner::PromoteLoad(SDValue Op) {
1318   if (!LegalOperations)
1319     return false;
1320 
1321   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1322     return false;
1323 
1324   EVT VT = Op.getValueType();
1325   if (VT.isVector() || !VT.isInteger())
1326     return false;
1327 
1328   // If operation type is 'undesirable', e.g. i16 on x86, consider
1329   // promoting it.
1330   unsigned Opc = Op.getOpcode();
1331   if (TLI.isTypeDesirableForOp(Opc, VT))
1332     return false;
1333 
1334   EVT PVT = VT;
1335   // Consult target whether it is a good idea to promote this operation and
1336   // what's the right type to promote it to.
1337   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1338     assert(PVT != VT && "Don't know what type to promote to!");
1339 
1340     SDLoc DL(Op);
1341     SDNode *N = Op.getNode();
1342     LoadSDNode *LD = cast<LoadSDNode>(N);
1343     EVT MemVT = LD->getMemoryVT();
1344     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
1345                                                       : LD->getExtensionType();
1346     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1347                                    LD->getChain(), LD->getBasePtr(),
1348                                    MemVT, LD->getMemOperand());
1349     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1350 
1351     LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";
1352                Result.getNode()->dump(&DAG); dbgs() << '\n');
1353     WorklistRemover DeadNodes(*this);
1354     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1355     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1356     deleteAndRecombine(N);
1357     AddToWorklist(Result.getNode());
1358     return true;
1359   }
1360   return false;
1361 }
1362 
1363 /// Recursively delete a node which has no uses and any operands for
1364 /// which it is the only use.
1365 ///
1366 /// Note that this both deletes the nodes and removes them from the worklist.
1367 /// It also adds any nodes who have had a user deleted to the worklist as they
1368 /// may now have only one use and subject to other combines.
1369 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1370   if (!N->use_empty())
1371     return false;
1372 
1373   SmallSetVector<SDNode *, 16> Nodes;
1374   Nodes.insert(N);
1375   do {
1376     N = Nodes.pop_back_val();
1377     if (!N)
1378       continue;
1379 
1380     if (N->use_empty()) {
1381       for (const SDValue &ChildN : N->op_values())
1382         Nodes.insert(ChildN.getNode());
1383 
1384       removeFromWorklist(N);
1385       DAG.DeleteNode(N);
1386     } else {
1387       AddToWorklist(N);
1388     }
1389   } while (!Nodes.empty());
1390   return true;
1391 }
1392 
1393 //===----------------------------------------------------------------------===//
1394 //  Main DAG Combiner implementation
1395 //===----------------------------------------------------------------------===//
1396 
1397 void DAGCombiner::Run(CombineLevel AtLevel) {
1398   // set the instance variables, so that the various visit routines may use it.
1399   Level = AtLevel;
1400   LegalOperations = Level >= AfterLegalizeVectorOps;
1401   LegalTypes = Level >= AfterLegalizeTypes;
1402 
1403   // Add all the dag nodes to the worklist.
1404   for (SDNode &Node : DAG.allnodes())
1405     AddToWorklist(&Node);
1406 
1407   // Create a dummy node (which is not added to allnodes), that adds a reference
1408   // to the root node, preventing it from being deleted, and tracking any
1409   // changes of the root.
1410   HandleSDNode Dummy(DAG.getRoot());
1411 
1412   // While the worklist isn't empty, find a node and try to combine it.
1413   while (!WorklistMap.empty()) {
1414     SDNode *N;
1415     // The Worklist holds the SDNodes in order, but it may contain null entries.
1416     do {
1417       N = Worklist.pop_back_val();
1418     } while (!N);
1419 
1420     bool GoodWorklistEntry = WorklistMap.erase(N);
1421     (void)GoodWorklistEntry;
1422     assert(GoodWorklistEntry &&
1423            "Found a worklist entry without a corresponding map entry!");
1424 
1425     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1426     // N is deleted from the DAG, since they too may now be dead or may have a
1427     // reduced number of uses, allowing other xforms.
1428     if (recursivelyDeleteUnusedNodes(N))
1429       continue;
1430 
1431     WorklistRemover DeadNodes(*this);
1432 
1433     // If this combine is running after legalizing the DAG, re-legalize any
1434     // nodes pulled off the worklist.
1435     if (Level == AfterLegalizeDAG) {
1436       SmallSetVector<SDNode *, 16> UpdatedNodes;
1437       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1438 
1439       for (SDNode *LN : UpdatedNodes) {
1440         AddToWorklist(LN);
1441         AddUsersToWorklist(LN);
1442       }
1443       if (!NIsValid)
1444         continue;
1445     }
1446 
1447     LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1448 
1449     // Add any operands of the new node which have not yet been combined to the
1450     // worklist as well. Because the worklist uniques things already, this
1451     // won't repeatedly process the same operand.
1452     CombinedNodes.insert(N);
1453     for (const SDValue &ChildN : N->op_values())
1454       if (!CombinedNodes.count(ChildN.getNode()))
1455         AddToWorklist(ChildN.getNode());
1456 
1457     SDValue RV = combine(N);
1458 
1459     if (!RV.getNode())
1460       continue;
1461 
1462     ++NodesCombined;
1463 
1464     // If we get back the same node we passed in, rather than a new node or
1465     // zero, we know that the node must have defined multiple values and
1466     // CombineTo was used.  Since CombineTo takes care of the worklist
1467     // mechanics for us, we have no work to do in this case.
1468     if (RV.getNode() == N)
1469       continue;
1470 
1471     assert(N->getOpcode() != ISD::DELETED_NODE &&
1472            RV.getOpcode() != ISD::DELETED_NODE &&
1473            "Node was deleted but visit returned new node!");
1474 
1475     LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG));
1476 
1477     if (N->getNumValues() == RV.getNode()->getNumValues())
1478       DAG.ReplaceAllUsesWith(N, RV.getNode());
1479     else {
1480       assert(N->getValueType(0) == RV.getValueType() &&
1481              N->getNumValues() == 1 && "Type mismatch");
1482       DAG.ReplaceAllUsesWith(N, &RV);
1483     }
1484 
1485     // Push the new node and any users onto the worklist
1486     AddToWorklist(RV.getNode());
1487     AddUsersToWorklist(RV.getNode());
1488 
1489     // Finally, if the node is now dead, remove it from the graph.  The node
1490     // may not be dead if the replacement process recursively simplified to
1491     // something else needing this node. This will also take care of adding any
1492     // operands which have lost a user to the worklist.
1493     recursivelyDeleteUnusedNodes(N);
1494   }
1495 
1496   // If the root changed (e.g. it was a dead load, update the root).
1497   DAG.setRoot(Dummy.getValue());
1498   DAG.RemoveDeadNodes();
1499 }
1500 
1501 SDValue DAGCombiner::visit(SDNode *N) {
1502   switch (N->getOpcode()) {
1503   default: break;
1504   case ISD::TokenFactor:        return visitTokenFactor(N);
1505   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1506   case ISD::ADD:                return visitADD(N);
1507   case ISD::SUB:                return visitSUB(N);
1508   case ISD::ADDC:               return visitADDC(N);
1509   case ISD::UADDO:              return visitUADDO(N);
1510   case ISD::SUBC:               return visitSUBC(N);
1511   case ISD::USUBO:              return visitUSUBO(N);
1512   case ISD::ADDE:               return visitADDE(N);
1513   case ISD::ADDCARRY:           return visitADDCARRY(N);
1514   case ISD::SUBE:               return visitSUBE(N);
1515   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1516   case ISD::MUL:                return visitMUL(N);
1517   case ISD::SDIV:               return visitSDIV(N);
1518   case ISD::UDIV:               return visitUDIV(N);
1519   case ISD::SREM:
1520   case ISD::UREM:               return visitREM(N);
1521   case ISD::MULHU:              return visitMULHU(N);
1522   case ISD::MULHS:              return visitMULHS(N);
1523   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1524   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1525   case ISD::SMULO:              return visitSMULO(N);
1526   case ISD::UMULO:              return visitUMULO(N);
1527   case ISD::SMIN:
1528   case ISD::SMAX:
1529   case ISD::UMIN:
1530   case ISD::UMAX:               return visitIMINMAX(N);
1531   case ISD::AND:                return visitAND(N);
1532   case ISD::OR:                 return visitOR(N);
1533   case ISD::XOR:                return visitXOR(N);
1534   case ISD::SHL:                return visitSHL(N);
1535   case ISD::SRA:                return visitSRA(N);
1536   case ISD::SRL:                return visitSRL(N);
1537   case ISD::ROTR:
1538   case ISD::ROTL:               return visitRotate(N);
1539   case ISD::ABS:                return visitABS(N);
1540   case ISD::BSWAP:              return visitBSWAP(N);
1541   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1542   case ISD::CTLZ:               return visitCTLZ(N);
1543   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1544   case ISD::CTTZ:               return visitCTTZ(N);
1545   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1546   case ISD::CTPOP:              return visitCTPOP(N);
1547   case ISD::SELECT:             return visitSELECT(N);
1548   case ISD::VSELECT:            return visitVSELECT(N);
1549   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1550   case ISD::SETCC:              return visitSETCC(N);
1551   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1552   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1553   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1554   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1555   case ISD::AssertSext:
1556   case ISD::AssertZext:         return visitAssertExt(N);
1557   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1558   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1559   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1560   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1561   case ISD::BITCAST:            return visitBITCAST(N);
1562   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1563   case ISD::FADD:               return visitFADD(N);
1564   case ISD::FSUB:               return visitFSUB(N);
1565   case ISD::FMUL:               return visitFMUL(N);
1566   case ISD::FMA:                return visitFMA(N);
1567   case ISD::FDIV:               return visitFDIV(N);
1568   case ISD::FREM:               return visitFREM(N);
1569   case ISD::FSQRT:              return visitFSQRT(N);
1570   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1571   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1572   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1573   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1574   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1575   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1576   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1577   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1578   case ISD::FNEG:               return visitFNEG(N);
1579   case ISD::FABS:               return visitFABS(N);
1580   case ISD::FFLOOR:             return visitFFLOOR(N);
1581   case ISD::FMINNUM:            return visitFMINNUM(N);
1582   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1583   case ISD::FCEIL:              return visitFCEIL(N);
1584   case ISD::FTRUNC:             return visitFTRUNC(N);
1585   case ISD::BRCOND:             return visitBRCOND(N);
1586   case ISD::BR_CC:              return visitBR_CC(N);
1587   case ISD::LOAD:               return visitLOAD(N);
1588   case ISD::STORE:              return visitSTORE(N);
1589   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1590   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1591   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1592   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1593   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1594   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1595   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1596   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1597   case ISD::MGATHER:            return visitMGATHER(N);
1598   case ISD::MLOAD:              return visitMLOAD(N);
1599   case ISD::MSCATTER:           return visitMSCATTER(N);
1600   case ISD::MSTORE:             return visitMSTORE(N);
1601   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1602   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1603   }
1604   return SDValue();
1605 }
1606 
1607 SDValue DAGCombiner::combine(SDNode *N) {
1608   SDValue RV = visit(N);
1609 
1610   // If nothing happened, try a target-specific DAG combine.
1611   if (!RV.getNode()) {
1612     assert(N->getOpcode() != ISD::DELETED_NODE &&
1613            "Node was deleted but visit returned NULL!");
1614 
1615     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1616         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1617 
1618       // Expose the DAG combiner to the target combiner impls.
1619       TargetLowering::DAGCombinerInfo
1620         DagCombineInfo(DAG, Level, false, this);
1621 
1622       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1623     }
1624   }
1625 
1626   // If nothing happened still, try promoting the operation.
1627   if (!RV.getNode()) {
1628     switch (N->getOpcode()) {
1629     default: break;
1630     case ISD::ADD:
1631     case ISD::SUB:
1632     case ISD::MUL:
1633     case ISD::AND:
1634     case ISD::OR:
1635     case ISD::XOR:
1636       RV = PromoteIntBinOp(SDValue(N, 0));
1637       break;
1638     case ISD::SHL:
1639     case ISD::SRA:
1640     case ISD::SRL:
1641       RV = PromoteIntShiftOp(SDValue(N, 0));
1642       break;
1643     case ISD::SIGN_EXTEND:
1644     case ISD::ZERO_EXTEND:
1645     case ISD::ANY_EXTEND:
1646       RV = PromoteExtend(SDValue(N, 0));
1647       break;
1648     case ISD::LOAD:
1649       if (PromoteLoad(SDValue(N, 0)))
1650         RV = SDValue(N, 0);
1651       break;
1652     }
1653   }
1654 
1655   // If N is a commutative binary node, try eliminate it if the commuted
1656   // version is already present in the DAG.
1657   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1658       N->getNumValues() == 1) {
1659     SDValue N0 = N->getOperand(0);
1660     SDValue N1 = N->getOperand(1);
1661 
1662     // Constant operands are canonicalized to RHS.
1663     if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1664       SDValue Ops[] = {N1, N0};
1665       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1666                                             N->getFlags());
1667       if (CSENode)
1668         return SDValue(CSENode, 0);
1669     }
1670   }
1671 
1672   return RV;
1673 }
1674 
1675 /// Given a node, return its input chain if it has one, otherwise return a null
1676 /// sd operand.
1677 static SDValue getInputChainForNode(SDNode *N) {
1678   if (unsigned NumOps = N->getNumOperands()) {
1679     if (N->getOperand(0).getValueType() == MVT::Other)
1680       return N->getOperand(0);
1681     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1682       return N->getOperand(NumOps-1);
1683     for (unsigned i = 1; i < NumOps-1; ++i)
1684       if (N->getOperand(i).getValueType() == MVT::Other)
1685         return N->getOperand(i);
1686   }
1687   return SDValue();
1688 }
1689 
1690 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1691   // If N has two operands, where one has an input chain equal to the other,
1692   // the 'other' chain is redundant.
1693   if (N->getNumOperands() == 2) {
1694     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1695       return N->getOperand(0);
1696     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1697       return N->getOperand(1);
1698   }
1699 
1700   // Don't simplify token factors if optnone.
1701   if (OptLevel == CodeGenOpt::None)
1702     return SDValue();
1703 
1704   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1705   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1706   SmallPtrSet<SDNode*, 16> SeenOps;
1707   bool Changed = false;             // If we should replace this token factor.
1708 
1709   // Start out with this token factor.
1710   TFs.push_back(N);
1711 
1712   // Iterate through token factors.  The TFs grows when new token factors are
1713   // encountered.
1714   for (unsigned i = 0; i < TFs.size(); ++i) {
1715     SDNode *TF = TFs[i];
1716 
1717     // Check each of the operands.
1718     for (const SDValue &Op : TF->op_values()) {
1719       switch (Op.getOpcode()) {
1720       case ISD::EntryToken:
1721         // Entry tokens don't need to be added to the list. They are
1722         // redundant.
1723         Changed = true;
1724         break;
1725 
1726       case ISD::TokenFactor:
1727         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1728           // Queue up for processing.
1729           TFs.push_back(Op.getNode());
1730           // Clean up in case the token factor is removed.
1731           AddToWorklist(Op.getNode());
1732           Changed = true;
1733           break;
1734         }
1735         LLVM_FALLTHROUGH;
1736 
1737       default:
1738         // Only add if it isn't already in the list.
1739         if (SeenOps.insert(Op.getNode()).second)
1740           Ops.push_back(Op);
1741         else
1742           Changed = true;
1743         break;
1744       }
1745     }
1746   }
1747 
1748   // Remove Nodes that are chained to another node in the list. Do so
1749   // by walking up chains breath-first stopping when we've seen
1750   // another operand. In general we must climb to the EntryNode, but we can exit
1751   // early if we find all remaining work is associated with just one operand as
1752   // no further pruning is possible.
1753 
1754   // List of nodes to search through and original Ops from which they originate.
1755   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1756   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1757   SmallPtrSet<SDNode *, 16> SeenChains;
1758   bool DidPruneOps = false;
1759 
1760   unsigned NumLeftToConsider = 0;
1761   for (const SDValue &Op : Ops) {
1762     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1763     OpWorkCount.push_back(1);
1764   }
1765 
1766   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1767     // If this is an Op, we can remove the op from the list. Remark any
1768     // search associated with it as from the current OpNumber.
1769     if (SeenOps.count(Op) != 0) {
1770       Changed = true;
1771       DidPruneOps = true;
1772       unsigned OrigOpNumber = 0;
1773       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1774         OrigOpNumber++;
1775       assert((OrigOpNumber != Ops.size()) &&
1776              "expected to find TokenFactor Operand");
1777       // Re-mark worklist from OrigOpNumber to OpNumber
1778       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1779         if (Worklist[i].second == OrigOpNumber) {
1780           Worklist[i].second = OpNumber;
1781         }
1782       }
1783       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1784       OpWorkCount[OrigOpNumber] = 0;
1785       NumLeftToConsider--;
1786     }
1787     // Add if it's a new chain
1788     if (SeenChains.insert(Op).second) {
1789       OpWorkCount[OpNumber]++;
1790       Worklist.push_back(std::make_pair(Op, OpNumber));
1791     }
1792   };
1793 
1794   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1795     // We need at least be consider at least 2 Ops to prune.
1796     if (NumLeftToConsider <= 1)
1797       break;
1798     auto CurNode = Worklist[i].first;
1799     auto CurOpNumber = Worklist[i].second;
1800     assert((OpWorkCount[CurOpNumber] > 0) &&
1801            "Node should not appear in worklist");
1802     switch (CurNode->getOpcode()) {
1803     case ISD::EntryToken:
1804       // Hitting EntryToken is the only way for the search to terminate without
1805       // hitting
1806       // another operand's search. Prevent us from marking this operand
1807       // considered.
1808       NumLeftToConsider++;
1809       break;
1810     case ISD::TokenFactor:
1811       for (const SDValue &Op : CurNode->op_values())
1812         AddToWorklist(i, Op.getNode(), CurOpNumber);
1813       break;
1814     case ISD::CopyFromReg:
1815     case ISD::CopyToReg:
1816       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1817       break;
1818     default:
1819       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1820         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1821       break;
1822     }
1823     OpWorkCount[CurOpNumber]--;
1824     if (OpWorkCount[CurOpNumber] == 0)
1825       NumLeftToConsider--;
1826   }
1827 
1828   // If we've changed things around then replace token factor.
1829   if (Changed) {
1830     SDValue Result;
1831     if (Ops.empty()) {
1832       // The entry token is the only possible outcome.
1833       Result = DAG.getEntryNode();
1834     } else {
1835       if (DidPruneOps) {
1836         SmallVector<SDValue, 8> PrunedOps;
1837         //
1838         for (const SDValue &Op : Ops) {
1839           if (SeenChains.count(Op.getNode()) == 0)
1840             PrunedOps.push_back(Op);
1841         }
1842         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1843       } else {
1844         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1845       }
1846     }
1847     return Result;
1848   }
1849   return SDValue();
1850 }
1851 
1852 /// MERGE_VALUES can always be eliminated.
1853 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1854   WorklistRemover DeadNodes(*this);
1855   // Replacing results may cause a different MERGE_VALUES to suddenly
1856   // be CSE'd with N, and carry its uses with it. Iterate until no
1857   // uses remain, to ensure that the node can be safely deleted.
1858   // First add the users of this node to the work list so that they
1859   // can be tried again once they have new operands.
1860   AddUsersToWorklist(N);
1861   do {
1862     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1863       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1864   } while (!N->use_empty());
1865   deleteAndRecombine(N);
1866   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1867 }
1868 
1869 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1870 /// ConstantSDNode pointer else nullptr.
1871 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1872   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1873   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1874 }
1875 
1876 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1877   auto BinOpcode = BO->getOpcode();
1878   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1879           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1880           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1881           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1882           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1883           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1884           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1885           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1886           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1887          "Unexpected binary operator");
1888 
1889   // Don't do this unless the old select is going away. We want to eliminate the
1890   // binary operator, not replace a binop with a select.
1891   // TODO: Handle ISD::SELECT_CC.
1892   unsigned SelOpNo = 0;
1893   SDValue Sel = BO->getOperand(0);
1894   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
1895     SelOpNo = 1;
1896     Sel = BO->getOperand(1);
1897   }
1898 
1899   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1900     return SDValue();
1901 
1902   SDValue CT = Sel.getOperand(1);
1903   if (!isConstantOrConstantVector(CT, true) &&
1904       !isConstantFPBuildVectorOrConstantFP(CT))
1905     return SDValue();
1906 
1907   SDValue CF = Sel.getOperand(2);
1908   if (!isConstantOrConstantVector(CF, true) &&
1909       !isConstantFPBuildVectorOrConstantFP(CF))
1910     return SDValue();
1911 
1912   // Bail out if any constants are opaque because we can't constant fold those.
1913   // The exception is "and" and "or" with either 0 or -1 in which case we can
1914   // propagate non constant operands into select. I.e.:
1915   // and (select Cond, 0, -1), X --> select Cond, 0, X
1916   // or X, (select Cond, -1, 0) --> select Cond, -1, X
1917   bool CanFoldNonConst = (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
1918                          (isNullConstantOrNullSplatConstant(CT) ||
1919                           isAllOnesConstantOrAllOnesSplatConstant(CT)) &&
1920                          (isNullConstantOrNullSplatConstant(CF) ||
1921                           isAllOnesConstantOrAllOnesSplatConstant(CF));
1922 
1923   SDValue CBO = BO->getOperand(SelOpNo ^ 1);
1924   if (!CanFoldNonConst &&
1925       !isConstantOrConstantVector(CBO, true) &&
1926       !isConstantFPBuildVectorOrConstantFP(CBO))
1927     return SDValue();
1928 
1929   EVT VT = Sel.getValueType();
1930 
1931   // In case of shift value and shift amount may have different VT. For instance
1932   // on x86 shift amount is i8 regardles of LHS type. Bail out if we have
1933   // swapped operands and value types do not match. NB: x86 is fine if operands
1934   // are not swapped with shift amount VT being not bigger than shifted value.
1935   // TODO: that is possible to check for a shift operation, correct VTs and
1936   // still perform optimization on x86 if needed.
1937   if (SelOpNo && VT != CBO.getValueType())
1938     return SDValue();
1939 
1940   // We have a select-of-constants followed by a binary operator with a
1941   // constant. Eliminate the binop by pulling the constant math into the select.
1942   // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
1943   SDLoc DL(Sel);
1944   SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT)
1945                           : DAG.getNode(BinOpcode, DL, VT, CT, CBO);
1946   if (!CanFoldNonConst && !NewCT.isUndef() &&
1947       !isConstantOrConstantVector(NewCT, true) &&
1948       !isConstantFPBuildVectorOrConstantFP(NewCT))
1949     return SDValue();
1950 
1951   SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF)
1952                           : DAG.getNode(BinOpcode, DL, VT, CF, CBO);
1953   if (!CanFoldNonConst && !NewCF.isUndef() &&
1954       !isConstantOrConstantVector(NewCF, true) &&
1955       !isConstantFPBuildVectorOrConstantFP(NewCF))
1956     return SDValue();
1957 
1958   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1959 }
1960 
1961 static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) {
1962   assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
1963          "Expecting add or sub");
1964 
1965   // Match a constant operand and a zext operand for the math instruction:
1966   // add Z, C
1967   // sub C, Z
1968   bool IsAdd = N->getOpcode() == ISD::ADD;
1969   SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
1970   SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
1971   auto *CN = dyn_cast<ConstantSDNode>(C);
1972   if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
1973     return SDValue();
1974 
1975   // Match the zext operand as a setcc of a boolean.
1976   if (Z.getOperand(0).getOpcode() != ISD::SETCC ||
1977       Z.getOperand(0).getValueType() != MVT::i1)
1978     return SDValue();
1979 
1980   // Match the compare as: setcc (X & 1), 0, eq.
1981   SDValue SetCC = Z.getOperand(0);
1982   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
1983   if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) ||
1984       SetCC.getOperand(0).getOpcode() != ISD::AND ||
1985       !isOneConstant(SetCC.getOperand(0).getOperand(1)))
1986     return SDValue();
1987 
1988   // We are adding/subtracting a constant and an inverted low bit. Turn that
1989   // into a subtract/add of the low bit with incremented/decremented constant:
1990   // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
1991   // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
1992   EVT VT = C.getValueType();
1993   SDLoc DL(N);
1994   SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT);
1995   SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) :
1996                        DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
1997   return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
1998 }
1999 
2000 SDValue DAGCombiner::visitADD(SDNode *N) {
2001   SDValue N0 = N->getOperand(0);
2002   SDValue N1 = N->getOperand(1);
2003   EVT VT = N0.getValueType();
2004   SDLoc DL(N);
2005 
2006   // fold vector ops
2007   if (VT.isVector()) {
2008     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2009       return FoldedVOp;
2010 
2011     // fold (add x, 0) -> x, vector edition
2012     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2013       return N0;
2014     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2015       return N1;
2016   }
2017 
2018   // fold (add x, undef) -> undef
2019   if (N0.isUndef())
2020     return N0;
2021 
2022   if (N1.isUndef())
2023     return N1;
2024 
2025   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
2026     // canonicalize constant to RHS
2027     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
2028       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
2029     // fold (add c1, c2) -> c1+c2
2030     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
2031                                       N1.getNode());
2032   }
2033 
2034   // fold (add x, 0) -> x
2035   if (isNullConstant(N1))
2036     return N0;
2037 
2038   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
2039     // fold ((c1-A)+c2) -> (c1+c2)-A
2040     if (N0.getOpcode() == ISD::SUB &&
2041         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
2042       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
2043       return DAG.getNode(ISD::SUB, DL, VT,
2044                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
2045                          N0.getOperand(1));
2046     }
2047 
2048     // add (sext i1 X), 1 -> zext (not i1 X)
2049     // We don't transform this pattern:
2050     //   add (zext i1 X), -1 -> sext (not i1 X)
2051     // because most (?) targets generate better code for the zext form.
2052     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
2053         isOneConstantOrOneSplatConstant(N1)) {
2054       SDValue X = N0.getOperand(0);
2055       if ((!LegalOperations ||
2056            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
2057             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
2058           X.getScalarValueSizeInBits() == 1) {
2059         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
2060         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
2061       }
2062     }
2063 
2064     // Undo the add -> or combine to merge constant offsets from a frame index.
2065     if (N0.getOpcode() == ISD::OR &&
2066         isa<FrameIndexSDNode>(N0.getOperand(0)) &&
2067         isa<ConstantSDNode>(N0.getOperand(1)) &&
2068         DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
2069       SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
2070       return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
2071     }
2072   }
2073 
2074   if (SDValue NewSel = foldBinOpIntoSelect(N))
2075     return NewSel;
2076 
2077   // reassociate add
2078   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
2079     return RADD;
2080 
2081   // fold ((0-A) + B) -> B-A
2082   if (N0.getOpcode() == ISD::SUB &&
2083       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
2084     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2085 
2086   // fold (A + (0-B)) -> A-B
2087   if (N1.getOpcode() == ISD::SUB &&
2088       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
2089     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2090 
2091   // fold (A+(B-A)) -> B
2092   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2093     return N1.getOperand(0);
2094 
2095   // fold ((B-A)+A) -> B
2096   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2097     return N0.getOperand(0);
2098 
2099   // fold (A+(B-(A+C))) to (B-C)
2100   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2101       N0 == N1.getOperand(1).getOperand(0))
2102     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2103                        N1.getOperand(1).getOperand(1));
2104 
2105   // fold (A+(B-(C+A))) to (B-C)
2106   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2107       N0 == N1.getOperand(1).getOperand(1))
2108     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2109                        N1.getOperand(1).getOperand(0));
2110 
2111   // fold (A+((B-A)+or-C)) to (B+or-C)
2112   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2113       N1.getOperand(0).getOpcode() == ISD::SUB &&
2114       N0 == N1.getOperand(0).getOperand(1))
2115     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2116                        N1.getOperand(1));
2117 
2118   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2119   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2120     SDValue N00 = N0.getOperand(0);
2121     SDValue N01 = N0.getOperand(1);
2122     SDValue N10 = N1.getOperand(0);
2123     SDValue N11 = N1.getOperand(1);
2124 
2125     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2126       return DAG.getNode(ISD::SUB, DL, VT,
2127                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2128                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2129   }
2130 
2131   if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
2132     return V;
2133 
2134   if (SimplifyDemandedBits(SDValue(N, 0)))
2135     return SDValue(N, 0);
2136 
2137   // fold (a+b) -> (a|b) iff a and b share no bits.
2138   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2139       DAG.haveNoCommonBitsSet(N0, N1))
2140     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2141 
2142   // fold (add (xor a, -1), 1) -> (sub 0, a)
2143   if (isBitwiseNot(N0) && isOneConstantOrOneSplatConstant(N1))
2144     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
2145                        N0.getOperand(0));
2146 
2147   if (SDValue Combined = visitADDLike(N0, N1, N))
2148     return Combined;
2149 
2150   if (SDValue Combined = visitADDLike(N1, N0, N))
2151     return Combined;
2152 
2153   return SDValue();
2154 }
2155 
2156 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2157   bool Masked = false;
2158 
2159   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2160   while (true) {
2161     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2162       V = V.getOperand(0);
2163       continue;
2164     }
2165 
2166     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2167       Masked = true;
2168       V = V.getOperand(0);
2169       continue;
2170     }
2171 
2172     break;
2173   }
2174 
2175   // If this is not a carry, return.
2176   if (V.getResNo() != 1)
2177     return SDValue();
2178 
2179   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2180       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2181     return SDValue();
2182 
2183   // If the result is masked, then no matter what kind of bool it is we can
2184   // return. If it isn't, then we need to make sure the bool type is either 0 or
2185   // 1 and not other values.
2186   if (Masked ||
2187       TLI.getBooleanContents(V.getValueType()) ==
2188           TargetLoweringBase::ZeroOrOneBooleanContent)
2189     return V;
2190 
2191   return SDValue();
2192 }
2193 
2194 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2195   EVT VT = N0.getValueType();
2196   SDLoc DL(LocReference);
2197 
2198   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2199   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2200       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2201     return DAG.getNode(ISD::SUB, DL, VT, N0,
2202                        DAG.getNode(ISD::SHL, DL, VT,
2203                                    N1.getOperand(0).getOperand(1),
2204                                    N1.getOperand(1)));
2205 
2206   if (N1.getOpcode() == ISD::AND) {
2207     SDValue AndOp0 = N1.getOperand(0);
2208     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2209     unsigned DestBits = VT.getScalarSizeInBits();
2210 
2211     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2212     // and similar xforms where the inner op is either ~0 or 0.
2213     if (NumSignBits == DestBits &&
2214         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2215       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2216   }
2217 
2218   // add (sext i1), X -> sub X, (zext i1)
2219   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2220       N0.getOperand(0).getValueType() == MVT::i1 &&
2221       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2222     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2223     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2224   }
2225 
2226   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2227   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2228     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2229     if (TN->getVT() == MVT::i1) {
2230       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2231                                  DAG.getConstant(1, DL, VT));
2232       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2233     }
2234   }
2235 
2236   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2237   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2238       N1.getResNo() == 0)
2239     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2240                        N0, N1.getOperand(0), N1.getOperand(2));
2241 
2242   // (add X, Carry) -> (addcarry X, 0, Carry)
2243   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2244     if (SDValue Carry = getAsCarry(TLI, N1))
2245       return DAG.getNode(ISD::ADDCARRY, DL,
2246                          DAG.getVTList(VT, Carry.getValueType()), N0,
2247                          DAG.getConstant(0, DL, VT), Carry);
2248 
2249   return SDValue();
2250 }
2251 
2252 SDValue DAGCombiner::visitADDC(SDNode *N) {
2253   SDValue N0 = N->getOperand(0);
2254   SDValue N1 = N->getOperand(1);
2255   EVT VT = N0.getValueType();
2256   SDLoc DL(N);
2257 
2258   // If the flag result is dead, turn this into an ADD.
2259   if (!N->hasAnyUseOfValue(1))
2260     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2261                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2262 
2263   // canonicalize constant to RHS.
2264   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2265   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2266   if (N0C && !N1C)
2267     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2268 
2269   // fold (addc x, 0) -> x + no carry out
2270   if (isNullConstant(N1))
2271     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2272                                         DL, MVT::Glue));
2273 
2274   // If it cannot overflow, transform into an add.
2275   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2276     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2277                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2278 
2279   return SDValue();
2280 }
2281 
2282 static SDValue flipBoolean(SDValue V, const SDLoc &DL, EVT VT,
2283                            SelectionDAG &DAG, const TargetLowering &TLI) {
2284   SDValue Cst;
2285   switch (TLI.getBooleanContents(VT)) {
2286   case TargetLowering::ZeroOrOneBooleanContent:
2287   case TargetLowering::UndefinedBooleanContent:
2288     Cst = DAG.getConstant(1, DL, VT);
2289     break;
2290   case TargetLowering::ZeroOrNegativeOneBooleanContent:
2291     Cst = DAG.getConstant(-1, DL, VT);
2292     break;
2293   }
2294 
2295   return DAG.getNode(ISD::XOR, DL, VT, V, Cst);
2296 }
2297 
2298 static bool isBooleanFlip(SDValue V, EVT VT, const TargetLowering &TLI) {
2299   if (V.getOpcode() != ISD::XOR) return false;
2300   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V.getOperand(1));
2301   if (!Const) return false;
2302 
2303   switch(TLI.getBooleanContents(VT)) {
2304     case TargetLowering::ZeroOrOneBooleanContent:
2305       return Const->isOne();
2306     case TargetLowering::ZeroOrNegativeOneBooleanContent:
2307       return Const->isAllOnesValue();
2308     case TargetLowering::UndefinedBooleanContent:
2309       return (Const->getAPIntValue() & 0x01) == 1;
2310   }
2311   llvm_unreachable("Unsupported boolean content");
2312 }
2313 
2314 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2315   SDValue N0 = N->getOperand(0);
2316   SDValue N1 = N->getOperand(1);
2317   EVT VT = N0.getValueType();
2318   if (VT.isVector())
2319     return SDValue();
2320 
2321   EVT CarryVT = N->getValueType(1);
2322   SDLoc DL(N);
2323 
2324   // If the flag result is dead, turn this into an ADD.
2325   if (!N->hasAnyUseOfValue(1))
2326     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2327                      DAG.getUNDEF(CarryVT));
2328 
2329   // canonicalize constant to RHS.
2330   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2331   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2332   if (N0C && !N1C)
2333     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2334 
2335   // fold (uaddo x, 0) -> x + no carry out
2336   if (isNullConstant(N1))
2337     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2338 
2339   // If it cannot overflow, transform into an add.
2340   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2341     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2342                      DAG.getConstant(0, DL, CarryVT));
2343 
2344   // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
2345   if (isBitwiseNot(N0) && isOneConstantOrOneSplatConstant(N1)) {
2346     SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
2347                               DAG.getConstant(0, DL, VT),
2348                               N0.getOperand(0));
2349     return CombineTo(N, Sub,
2350                      flipBoolean(Sub.getValue(1), DL, CarryVT, DAG, TLI));
2351   }
2352 
2353   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2354     return Combined;
2355 
2356   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2357     return Combined;
2358 
2359   return SDValue();
2360 }
2361 
2362 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2363   auto VT = N0.getValueType();
2364 
2365   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2366   // If Y + 1 cannot overflow.
2367   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2368     SDValue Y = N1.getOperand(0);
2369     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2370     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2371       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2372                          N1.getOperand(2));
2373   }
2374 
2375   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2376   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2377     if (SDValue Carry = getAsCarry(TLI, N1))
2378       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2379                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2380 
2381   return SDValue();
2382 }
2383 
2384 SDValue DAGCombiner::visitADDE(SDNode *N) {
2385   SDValue N0 = N->getOperand(0);
2386   SDValue N1 = N->getOperand(1);
2387   SDValue CarryIn = N->getOperand(2);
2388 
2389   // canonicalize constant to RHS
2390   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2391   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2392   if (N0C && !N1C)
2393     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2394                        N1, N0, CarryIn);
2395 
2396   // fold (adde x, y, false) -> (addc x, y)
2397   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2398     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2399 
2400   return SDValue();
2401 }
2402 
2403 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2404   SDValue N0 = N->getOperand(0);
2405   SDValue N1 = N->getOperand(1);
2406   SDValue CarryIn = N->getOperand(2);
2407   SDLoc DL(N);
2408 
2409   // canonicalize constant to RHS
2410   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2411   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2412   if (N0C && !N1C)
2413     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2414 
2415   // fold (addcarry x, y, false) -> (uaddo x, y)
2416   if (isNullConstant(CarryIn)) {
2417     if (!LegalOperations ||
2418         TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0)))
2419       return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2420   }
2421 
2422   EVT CarryVT = CarryIn.getValueType();
2423 
2424   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2425   if (isNullConstant(N0) && isNullConstant(N1)) {
2426     EVT VT = N0.getValueType();
2427     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2428     AddToWorklist(CarryExt.getNode());
2429     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2430                                     DAG.getConstant(1, DL, VT)),
2431                      DAG.getConstant(0, DL, CarryVT));
2432   }
2433 
2434   // fold (addcarry (xor a, -1), 0, !b) -> (subcarry 0, a, b) and flip carry.
2435   if (isBitwiseNot(N0) && isNullConstant(N1) &&
2436       isBooleanFlip(CarryIn, CarryVT, TLI)) {
2437     SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(),
2438                               DAG.getConstant(0, DL, N0.getValueType()),
2439                               N0.getOperand(0), CarryIn.getOperand(0));
2440     return CombineTo(N, Sub,
2441                      flipBoolean(Sub.getValue(1), DL, CarryVT, DAG, TLI));
2442   }
2443 
2444   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2445     return Combined;
2446 
2447   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2448     return Combined;
2449 
2450   return SDValue();
2451 }
2452 
2453 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2454                                        SDNode *N) {
2455   // Iff the flag result is dead:
2456   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2457   if ((N0.getOpcode() == ISD::ADD ||
2458        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2459       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2460     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2461                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2462 
2463   /**
2464    * When one of the addcarry argument is itself a carry, we may be facing
2465    * a diamond carry propagation. In which case we try to transform the DAG
2466    * to ensure linear carry propagation if that is possible.
2467    *
2468    * We are trying to get:
2469    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2470    */
2471   if (auto Y = getAsCarry(TLI, N1)) {
2472     /**
2473      *            (uaddo A, B)
2474      *             /       \
2475      *          Carry      Sum
2476      *            |          \
2477      *            | (addcarry *, 0, Z)
2478      *            |       /
2479      *             \   Carry
2480      *              |   /
2481      * (addcarry X, *, *)
2482      */
2483     if (Y.getOpcode() == ISD::UADDO &&
2484         CarryIn.getResNo() == 1 &&
2485         CarryIn.getOpcode() == ISD::ADDCARRY &&
2486         isNullConstant(CarryIn.getOperand(1)) &&
2487         CarryIn.getOperand(0) == Y.getValue(0)) {
2488       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2489                               Y.getOperand(0), Y.getOperand(1),
2490                               CarryIn.getOperand(2));
2491       AddToWorklist(NewY.getNode());
2492       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2493                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2494                          NewY.getValue(1));
2495     }
2496   }
2497 
2498   return SDValue();
2499 }
2500 
2501 // Since it may not be valid to emit a fold to zero for vector initializers
2502 // check if we can before folding.
2503 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2504                              SelectionDAG &DAG, bool LegalOperations,
2505                              bool LegalTypes) {
2506   if (!VT.isVector())
2507     return DAG.getConstant(0, DL, VT);
2508   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2509     return DAG.getConstant(0, DL, VT);
2510   return SDValue();
2511 }
2512 
2513 SDValue DAGCombiner::visitSUB(SDNode *N) {
2514   SDValue N0 = N->getOperand(0);
2515   SDValue N1 = N->getOperand(1);
2516   EVT VT = N0.getValueType();
2517   SDLoc DL(N);
2518 
2519   // fold vector ops
2520   if (VT.isVector()) {
2521     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2522       return FoldedVOp;
2523 
2524     // fold (sub x, 0) -> x, vector edition
2525     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2526       return N0;
2527   }
2528 
2529   // fold (sub x, x) -> 0
2530   // FIXME: Refactor this and xor and other similar operations together.
2531   if (N0 == N1)
2532     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2533   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2534       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2535     // fold (sub c1, c2) -> c1-c2
2536     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2537                                       N1.getNode());
2538   }
2539 
2540   if (SDValue NewSel = foldBinOpIntoSelect(N))
2541     return NewSel;
2542 
2543   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2544 
2545   // fold (sub x, c) -> (add x, -c)
2546   if (N1C) {
2547     return DAG.getNode(ISD::ADD, DL, VT, N0,
2548                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2549   }
2550 
2551   if (isNullConstantOrNullSplatConstant(N0)) {
2552     unsigned BitWidth = VT.getScalarSizeInBits();
2553     // Right-shifting everything out but the sign bit followed by negation is
2554     // the same as flipping arithmetic/logical shift type without the negation:
2555     // -(X >>u 31) -> (X >>s 31)
2556     // -(X >>s 31) -> (X >>u 31)
2557     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2558       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2559       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2560         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2561         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2562           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2563       }
2564     }
2565 
2566     // 0 - X --> 0 if the sub is NUW.
2567     if (N->getFlags().hasNoUnsignedWrap())
2568       return N0;
2569 
2570     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2571       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2572       // N1 must be 0 because negating the minimum signed value is undefined.
2573       if (N->getFlags().hasNoSignedWrap())
2574         return N0;
2575 
2576       // 0 - X --> X if X is 0 or the minimum signed value.
2577       return N1;
2578     }
2579   }
2580 
2581   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2582   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2583     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2584 
2585   // fold A-(A-B) -> B
2586   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2587     return N1.getOperand(1);
2588 
2589   // fold (A+B)-A -> B
2590   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2591     return N0.getOperand(1);
2592 
2593   // fold (A+B)-B -> A
2594   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2595     return N0.getOperand(0);
2596 
2597   // fold C2-(A+C1) -> (C2-C1)-A
2598   if (N1.getOpcode() == ISD::ADD) {
2599     SDValue N11 = N1.getOperand(1);
2600     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2601         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2602       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2603       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2604     }
2605   }
2606 
2607   // fold ((A+(B+or-C))-B) -> A+or-C
2608   if (N0.getOpcode() == ISD::ADD &&
2609       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2610        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2611       N0.getOperand(1).getOperand(0) == N1)
2612     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2613                        N0.getOperand(1).getOperand(1));
2614 
2615   // fold ((A+(C+B))-B) -> A+C
2616   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2617       N0.getOperand(1).getOperand(1) == N1)
2618     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2619                        N0.getOperand(1).getOperand(0));
2620 
2621   // fold ((A-(B-C))-C) -> A-B
2622   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2623       N0.getOperand(1).getOperand(1) == N1)
2624     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2625                        N0.getOperand(1).getOperand(0));
2626 
2627   // If either operand of a sub is undef, the result is undef
2628   if (N0.isUndef())
2629     return N0;
2630   if (N1.isUndef())
2631     return N1;
2632 
2633   if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
2634     return V;
2635 
2636   // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X)
2637   if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
2638     if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) {
2639       SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1);
2640       SDValue S0 = N1.getOperand(0);
2641       if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) {
2642         unsigned OpSizeInBits = VT.getScalarSizeInBits();
2643         if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
2644           if (C->getAPIntValue() == (OpSizeInBits - 1))
2645             return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0);
2646       }
2647     }
2648   }
2649 
2650   // If the relocation model supports it, consider symbol offsets.
2651   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2652     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2653       // fold (sub Sym, c) -> Sym-c
2654       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2655         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2656                                     GA->getOffset() -
2657                                         (uint64_t)N1C->getSExtValue());
2658       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2659       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2660         if (GA->getGlobal() == GB->getGlobal())
2661           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2662                                  DL, VT);
2663     }
2664 
2665   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2666   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2667     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2668     if (TN->getVT() == MVT::i1) {
2669       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2670                                  DAG.getConstant(1, DL, VT));
2671       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2672     }
2673   }
2674 
2675   return SDValue();
2676 }
2677 
2678 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2679   SDValue N0 = N->getOperand(0);
2680   SDValue N1 = N->getOperand(1);
2681   EVT VT = N0.getValueType();
2682   SDLoc DL(N);
2683 
2684   // If the flag result is dead, turn this into an SUB.
2685   if (!N->hasAnyUseOfValue(1))
2686     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2687                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2688 
2689   // fold (subc x, x) -> 0 + no borrow
2690   if (N0 == N1)
2691     return CombineTo(N, DAG.getConstant(0, DL, VT),
2692                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2693 
2694   // fold (subc x, 0) -> x + no borrow
2695   if (isNullConstant(N1))
2696     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2697 
2698   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2699   if (isAllOnesConstant(N0))
2700     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2701                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2702 
2703   return SDValue();
2704 }
2705 
2706 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2707   SDValue N0 = N->getOperand(0);
2708   SDValue N1 = N->getOperand(1);
2709   EVT VT = N0.getValueType();
2710   if (VT.isVector())
2711     return SDValue();
2712 
2713   EVT CarryVT = N->getValueType(1);
2714   SDLoc DL(N);
2715 
2716   // If the flag result is dead, turn this into an SUB.
2717   if (!N->hasAnyUseOfValue(1))
2718     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2719                      DAG.getUNDEF(CarryVT));
2720 
2721   // fold (usubo x, x) -> 0 + no borrow
2722   if (N0 == N1)
2723     return CombineTo(N, DAG.getConstant(0, DL, VT),
2724                      DAG.getConstant(0, DL, CarryVT));
2725 
2726   // fold (usubo x, 0) -> x + no borrow
2727   if (isNullConstant(N1))
2728     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2729 
2730   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2731   if (isAllOnesConstant(N0))
2732     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2733                      DAG.getConstant(0, DL, CarryVT));
2734 
2735   return SDValue();
2736 }
2737 
2738 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2739   SDValue N0 = N->getOperand(0);
2740   SDValue N1 = N->getOperand(1);
2741   SDValue CarryIn = N->getOperand(2);
2742 
2743   // fold (sube x, y, false) -> (subc x, y)
2744   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2745     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2746 
2747   return SDValue();
2748 }
2749 
2750 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2751   SDValue N0 = N->getOperand(0);
2752   SDValue N1 = N->getOperand(1);
2753   SDValue CarryIn = N->getOperand(2);
2754 
2755   // fold (subcarry x, y, false) -> (usubo x, y)
2756   if (isNullConstant(CarryIn)) {
2757     if (!LegalOperations ||
2758         TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0)))
2759       return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2760   }
2761 
2762   return SDValue();
2763 }
2764 
2765 SDValue DAGCombiner::visitMUL(SDNode *N) {
2766   SDValue N0 = N->getOperand(0);
2767   SDValue N1 = N->getOperand(1);
2768   EVT VT = N0.getValueType();
2769 
2770   // fold (mul x, undef) -> 0
2771   if (N0.isUndef() || N1.isUndef())
2772     return DAG.getConstant(0, SDLoc(N), VT);
2773 
2774   bool N0IsConst = false;
2775   bool N1IsConst = false;
2776   bool N1IsOpaqueConst = false;
2777   bool N0IsOpaqueConst = false;
2778   APInt ConstValue0, ConstValue1;
2779   // fold vector ops
2780   if (VT.isVector()) {
2781     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2782       return FoldedVOp;
2783 
2784     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2785     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2786     assert((!N0IsConst ||
2787             ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) &&
2788            "Splat APInt should be element width");
2789     assert((!N1IsConst ||
2790             ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
2791            "Splat APInt should be element width");
2792   } else {
2793     N0IsConst = isa<ConstantSDNode>(N0);
2794     if (N0IsConst) {
2795       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2796       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2797     }
2798     N1IsConst = isa<ConstantSDNode>(N1);
2799     if (N1IsConst) {
2800       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2801       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2802     }
2803   }
2804 
2805   // fold (mul c1, c2) -> c1*c2
2806   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2807     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2808                                       N0.getNode(), N1.getNode());
2809 
2810   // canonicalize constant to RHS (vector doesn't have to splat)
2811   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2812      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2813     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2814   // fold (mul x, 0) -> 0
2815   if (N1IsConst && ConstValue1.isNullValue())
2816     return N1;
2817   // fold (mul x, 1) -> x
2818   if (N1IsConst && ConstValue1.isOneValue())
2819     return N0;
2820 
2821   if (SDValue NewSel = foldBinOpIntoSelect(N))
2822     return NewSel;
2823 
2824   // fold (mul x, -1) -> 0-x
2825   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2826     SDLoc DL(N);
2827     return DAG.getNode(ISD::SUB, DL, VT,
2828                        DAG.getConstant(0, DL, VT), N0);
2829   }
2830   // fold (mul x, (1 << c)) -> x << c
2831   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2832       DAG.isKnownToBeAPowerOfTwo(N1) &&
2833       (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
2834     SDLoc DL(N);
2835     SDValue LogBase2 = BuildLogBase2(N1, DL);
2836     AddToWorklist(LogBase2.getNode());
2837 
2838     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2839     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2840     AddToWorklist(Trunc.getNode());
2841     return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
2842   }
2843   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2844   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
2845     unsigned Log2Val = (-ConstValue1).logBase2();
2846     SDLoc DL(N);
2847     // FIXME: If the input is something that is easily negated (e.g. a
2848     // single-use add), we should put the negate there.
2849     return DAG.getNode(ISD::SUB, DL, VT,
2850                        DAG.getConstant(0, DL, VT),
2851                        DAG.getNode(ISD::SHL, DL, VT, N0,
2852                             DAG.getConstant(Log2Val, DL,
2853                                       getShiftAmountTy(N0.getValueType()))));
2854   }
2855 
2856   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2857   if (N0.getOpcode() == ISD::SHL &&
2858       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2859       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2860     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2861     if (isConstantOrConstantVector(C3))
2862       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2863   }
2864 
2865   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2866   // use.
2867   {
2868     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2869 
2870     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2871     if (N0.getOpcode() == ISD::SHL &&
2872         isConstantOrConstantVector(N0.getOperand(1)) &&
2873         N0.getNode()->hasOneUse()) {
2874       Sh = N0; Y = N1;
2875     } else if (N1.getOpcode() == ISD::SHL &&
2876                isConstantOrConstantVector(N1.getOperand(1)) &&
2877                N1.getNode()->hasOneUse()) {
2878       Sh = N1; Y = N0;
2879     }
2880 
2881     if (Sh.getNode()) {
2882       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2883       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2884     }
2885   }
2886 
2887   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2888   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2889       N0.getOpcode() == ISD::ADD &&
2890       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2891       isMulAddWithConstProfitable(N, N0, N1))
2892       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2893                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2894                                      N0.getOperand(0), N1),
2895                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2896                                      N0.getOperand(1), N1));
2897 
2898   // reassociate mul
2899   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2900     return RMUL;
2901 
2902   return SDValue();
2903 }
2904 
2905 /// Return true if divmod libcall is available.
2906 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2907                                      const TargetLowering &TLI) {
2908   RTLIB::Libcall LC;
2909   EVT NodeType = Node->getValueType(0);
2910   if (!NodeType.isSimple())
2911     return false;
2912   switch (NodeType.getSimpleVT().SimpleTy) {
2913   default: return false; // No libcall for vector types.
2914   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2915   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2916   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2917   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2918   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2919   }
2920 
2921   return TLI.getLibcallName(LC) != nullptr;
2922 }
2923 
2924 /// Issue divrem if both quotient and remainder are needed.
2925 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2926   if (Node->use_empty())
2927     return SDValue(); // This is a dead node, leave it alone.
2928 
2929   unsigned Opcode = Node->getOpcode();
2930   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2931   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2932 
2933   // DivMod lib calls can still work on non-legal types if using lib-calls.
2934   EVT VT = Node->getValueType(0);
2935   if (VT.isVector() || !VT.isInteger())
2936     return SDValue();
2937 
2938   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2939     return SDValue();
2940 
2941   // If DIVREM is going to get expanded into a libcall,
2942   // but there is no libcall available, then don't combine.
2943   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2944       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2945     return SDValue();
2946 
2947   // If div is legal, it's better to do the normal expansion
2948   unsigned OtherOpcode = 0;
2949   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2950     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2951     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2952       return SDValue();
2953   } else {
2954     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2955     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2956       return SDValue();
2957   }
2958 
2959   SDValue Op0 = Node->getOperand(0);
2960   SDValue Op1 = Node->getOperand(1);
2961   SDValue combined;
2962   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2963          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2964     SDNode *User = *UI;
2965     if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
2966         User->use_empty())
2967       continue;
2968     // Convert the other matching node(s), too;
2969     // otherwise, the DIVREM may get target-legalized into something
2970     // target-specific that we won't be able to recognize.
2971     unsigned UserOpc = User->getOpcode();
2972     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2973         User->getOperand(0) == Op0 &&
2974         User->getOperand(1) == Op1) {
2975       if (!combined) {
2976         if (UserOpc == OtherOpcode) {
2977           SDVTList VTs = DAG.getVTList(VT, VT);
2978           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2979         } else if (UserOpc == DivRemOpc) {
2980           combined = SDValue(User, 0);
2981         } else {
2982           assert(UserOpc == Opcode);
2983           continue;
2984         }
2985       }
2986       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2987         CombineTo(User, combined);
2988       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2989         CombineTo(User, combined.getValue(1));
2990     }
2991   }
2992   return combined;
2993 }
2994 
2995 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2996   SDValue N0 = N->getOperand(0);
2997   SDValue N1 = N->getOperand(1);
2998   EVT VT = N->getValueType(0);
2999   SDLoc DL(N);
3000 
3001   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
3002     return DAG.getUNDEF(VT);
3003 
3004   // undef / X -> 0
3005   // undef % X -> 0
3006   if (N0.isUndef())
3007     return DAG.getConstant(0, DL, VT);
3008 
3009   return SDValue();
3010 }
3011 
3012 SDValue DAGCombiner::visitSDIV(SDNode *N) {
3013   SDValue N0 = N->getOperand(0);
3014   SDValue N1 = N->getOperand(1);
3015   EVT VT = N->getValueType(0);
3016   EVT CCVT = getSetCCResultType(VT);
3017 
3018   // fold vector ops
3019   if (VT.isVector())
3020     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3021       return FoldedVOp;
3022 
3023   SDLoc DL(N);
3024 
3025   // fold (sdiv c1, c2) -> c1/c2
3026   ConstantSDNode *N0C = isConstOrConstSplat(N0);
3027   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3028   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
3029     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
3030   // fold (sdiv X, 1) -> X
3031   if (N1C && N1C->isOne())
3032     return N0;
3033   // fold (sdiv X, -1) -> 0-X
3034   if (N1C && N1C->isAllOnesValue())
3035     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
3036   // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
3037   if (N1C && N1C->getAPIntValue().isMinSignedValue())
3038     return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
3039                          DAG.getConstant(1, DL, VT),
3040                          DAG.getConstant(0, DL, VT));
3041 
3042   if (SDValue V = simplifyDivRem(N, DAG))
3043     return V;
3044 
3045   if (SDValue NewSel = foldBinOpIntoSelect(N))
3046     return NewSel;
3047 
3048   // If we know the sign bits of both operands are zero, strength reduce to a
3049   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
3050   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3051     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
3052 
3053   if (SDValue V = visitSDIVLike(N0, N1, N))
3054     return V;
3055 
3056   // sdiv, srem -> sdivrem
3057   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3058   // true.  Otherwise, we break the simplification logic in visitREM().
3059   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3060   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3061     if (SDValue DivRem = useDivRem(N))
3062         return DivRem;
3063 
3064   return SDValue();
3065 }
3066 
3067 SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
3068   SDLoc DL(N);
3069   EVT VT = N->getValueType(0);
3070   EVT CCVT = getSetCCResultType(VT);
3071   unsigned BitWidth = VT.getScalarSizeInBits();
3072 
3073   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3074 
3075   // Helper for determining whether a value is a power-2 constant scalar or a
3076   // vector of such elements.
3077   auto IsPowerOfTwo = [](ConstantSDNode *C) {
3078     if (C->isNullValue() || C->isOpaque())
3079       return false;
3080     if (C->getAPIntValue().isPowerOf2())
3081       return true;
3082     if ((-C->getAPIntValue()).isPowerOf2())
3083       return true;
3084     return false;
3085   };
3086 
3087   // fold (sdiv X, pow2) -> simple ops after legalize
3088   // FIXME: We check for the exact bit here because the generic lowering gives
3089   // better results in that case. The target-specific lowering should learn how
3090   // to handle exact sdivs efficiently.
3091   if (!N->getFlags().hasExact() &&
3092       ISD::matchUnaryPredicate(N1C ? SDValue(N1C, 0) : N1, IsPowerOfTwo)) {
3093     // Target-specific implementation of sdiv x, pow2.
3094     if (SDValue Res = BuildSDIVPow2(N))
3095       return Res;
3096 
3097     // Create constants that are functions of the shift amount value.
3098     EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
3099     SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
3100     SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
3101     C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
3102     SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
3103     if (!isConstantOrConstantVector(Inexact))
3104       return SDValue();
3105 
3106     // Splat the sign bit into the register
3107     SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
3108                                DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
3109     AddToWorklist(Sign.getNode());
3110 
3111     // Add (N0 < 0) ? abs2 - 1 : 0;
3112     SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
3113     AddToWorklist(Srl.getNode());
3114     SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
3115     AddToWorklist(Add.getNode());
3116     SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
3117     AddToWorklist(Sra.getNode());
3118 
3119     // Special case: (sdiv X, 1) -> X
3120     // Special Case: (sdiv X, -1) -> 0-X
3121     SDValue One = DAG.getConstant(1, DL, VT);
3122     SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
3123     SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
3124     SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
3125     SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
3126     Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
3127 
3128     // If dividing by a positive value, we're done. Otherwise, the result must
3129     // be negated.
3130     SDValue Zero = DAG.getConstant(0, DL, VT);
3131     SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
3132 
3133     // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
3134     SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
3135     SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
3136     return Res;
3137   }
3138 
3139   // If integer divide is expensive and we satisfy the requirements, emit an
3140   // alternate sequence.  Targets may check function attributes for size/speed
3141   // trade-offs.
3142   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3143   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
3144     if (SDValue Op = BuildSDIV(N))
3145       return Op;
3146 
3147   return SDValue();
3148 }
3149 
3150 SDValue DAGCombiner::visitUDIV(SDNode *N) {
3151   SDValue N0 = N->getOperand(0);
3152   SDValue N1 = N->getOperand(1);
3153   EVT VT = N->getValueType(0);
3154   EVT CCVT = getSetCCResultType(VT);
3155 
3156   // fold vector ops
3157   if (VT.isVector())
3158     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3159       return FoldedVOp;
3160 
3161   SDLoc DL(N);
3162 
3163   // fold (udiv c1, c2) -> c1/c2
3164   ConstantSDNode *N0C = isConstOrConstSplat(N0);
3165   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3166   if (N0C && N1C)
3167     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
3168                                                     N0C, N1C))
3169       return Folded;
3170   // fold (udiv X, 1) -> X
3171   if (N1C && N1C->isOne())
3172     return N0;
3173   // fold (udiv X, -1) -> select(X == -1, 1, 0)
3174   if (N1C && N1C->getAPIntValue().isAllOnesValue())
3175     return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
3176                          DAG.getConstant(1, DL, VT),
3177                          DAG.getConstant(0, DL, VT));
3178 
3179   if (SDValue V = simplifyDivRem(N, DAG))
3180     return V;
3181 
3182   if (SDValue NewSel = foldBinOpIntoSelect(N))
3183     return NewSel;
3184 
3185   if (SDValue V = visitUDIVLike(N0, N1, N))
3186     return V;
3187 
3188   // sdiv, srem -> sdivrem
3189   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3190   // true.  Otherwise, we break the simplification logic in visitREM().
3191   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3192   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3193     if (SDValue DivRem = useDivRem(N))
3194         return DivRem;
3195 
3196   return SDValue();
3197 }
3198 
3199 SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
3200   SDLoc DL(N);
3201   EVT VT = N->getValueType(0);
3202 
3203   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3204 
3205   // fold (udiv x, (1 << c)) -> x >>u c
3206   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
3207       DAG.isKnownToBeAPowerOfTwo(N1)) {
3208     SDValue LogBase2 = BuildLogBase2(N1, DL);
3209     AddToWorklist(LogBase2.getNode());
3210 
3211     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
3212     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
3213     AddToWorklist(Trunc.getNode());
3214     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
3215   }
3216 
3217   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
3218   if (N1.getOpcode() == ISD::SHL) {
3219     SDValue N10 = N1.getOperand(0);
3220     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
3221         DAG.isKnownToBeAPowerOfTwo(N10)) {
3222       SDValue LogBase2 = BuildLogBase2(N10, DL);
3223       AddToWorklist(LogBase2.getNode());
3224 
3225       EVT ADDVT = N1.getOperand(1).getValueType();
3226       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
3227       AddToWorklist(Trunc.getNode());
3228       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
3229       AddToWorklist(Add.getNode());
3230       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
3231     }
3232   }
3233 
3234   // fold (udiv x, c) -> alternate
3235   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3236   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
3237     if (SDValue Op = BuildUDIV(N))
3238       return Op;
3239 
3240   return SDValue();
3241 }
3242 
3243 // handles ISD::SREM and ISD::UREM
3244 SDValue DAGCombiner::visitREM(SDNode *N) {
3245   unsigned Opcode = N->getOpcode();
3246   SDValue N0 = N->getOperand(0);
3247   SDValue N1 = N->getOperand(1);
3248   EVT VT = N->getValueType(0);
3249   EVT CCVT = getSetCCResultType(VT);
3250 
3251   bool isSigned = (Opcode == ISD::SREM);
3252   SDLoc DL(N);
3253 
3254   // fold (rem c1, c2) -> c1%c2
3255   ConstantSDNode *N0C = isConstOrConstSplat(N0);
3256   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3257   if (N0C && N1C)
3258     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
3259       return Folded;
3260   // fold (urem X, -1) -> select(X == -1, 0, x)
3261   if (!isSigned && N1C && N1C->getAPIntValue().isAllOnesValue())
3262     return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
3263                          DAG.getConstant(0, DL, VT), N0);
3264 
3265   if (SDValue V = simplifyDivRem(N, DAG))
3266     return V;
3267 
3268   if (SDValue NewSel = foldBinOpIntoSelect(N))
3269     return NewSel;
3270 
3271   if (isSigned) {
3272     // If we know the sign bits of both operands are zero, strength reduce to a
3273     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
3274     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3275       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
3276   } else {
3277     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
3278     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
3279       // fold (urem x, pow2) -> (and x, pow2-1)
3280       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3281       AddToWorklist(Add.getNode());
3282       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3283     }
3284     if (N1.getOpcode() == ISD::SHL &&
3285         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
3286       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
3287       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3288       AddToWorklist(Add.getNode());
3289       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3290     }
3291   }
3292 
3293   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3294 
3295   // If X/C can be simplified by the division-by-constant logic, lower
3296   // X%C to the equivalent of X-X/C*C.
3297   // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
3298   // speculative DIV must not cause a DIVREM conversion.  We guard against this
3299   // by skipping the simplification if isIntDivCheap().  When div is not cheap,
3300   // combine will not return a DIVREM.  Regardless, checking cheapness here
3301   // makes sense since the simplification results in fatter code.
3302   if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
3303     SDValue OptimizedDiv =
3304         isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
3305     if (OptimizedDiv.getNode() && OptimizedDiv.getOpcode() != ISD::UDIVREM &&
3306         OptimizedDiv.getOpcode() != ISD::SDIVREM) {
3307       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
3308       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3309       AddToWorklist(OptimizedDiv.getNode());
3310       AddToWorklist(Mul.getNode());
3311       return Sub;
3312     }
3313   }
3314 
3315   // sdiv, srem -> sdivrem
3316   if (SDValue DivRem = useDivRem(N))
3317     return DivRem.getValue(1);
3318 
3319   return SDValue();
3320 }
3321 
3322 SDValue DAGCombiner::visitMULHS(SDNode *N) {
3323   SDValue N0 = N->getOperand(0);
3324   SDValue N1 = N->getOperand(1);
3325   EVT VT = N->getValueType(0);
3326   SDLoc DL(N);
3327 
3328   if (VT.isVector()) {
3329     // fold (mulhs x, 0) -> 0
3330     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3331       return N1;
3332     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3333       return N0;
3334   }
3335 
3336   // fold (mulhs x, 0) -> 0
3337   if (isNullConstant(N1))
3338     return N1;
3339   // fold (mulhs x, 1) -> (sra x, size(x)-1)
3340   if (isOneConstant(N1))
3341     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3342                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3343                                        getShiftAmountTy(N0.getValueType())));
3344 
3345   // fold (mulhs x, undef) -> 0
3346   if (N0.isUndef() || N1.isUndef())
3347     return DAG.getConstant(0, DL, VT);
3348 
3349   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3350   // plus a shift.
3351   if (VT.isSimple() && !VT.isVector()) {
3352     MVT Simple = VT.getSimpleVT();
3353     unsigned SimpleSize = Simple.getSizeInBits();
3354     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3355     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3356       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3357       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3358       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3359       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3360             DAG.getConstant(SimpleSize, DL,
3361                             getShiftAmountTy(N1.getValueType())));
3362       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3363     }
3364   }
3365 
3366   return SDValue();
3367 }
3368 
3369 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3370   SDValue N0 = N->getOperand(0);
3371   SDValue N1 = N->getOperand(1);
3372   EVT VT = N->getValueType(0);
3373   SDLoc DL(N);
3374 
3375   if (VT.isVector()) {
3376     // fold (mulhu x, 0) -> 0
3377     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3378       return N1;
3379     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3380       return N0;
3381   }
3382 
3383   // fold (mulhu x, 0) -> 0
3384   if (isNullConstant(N1))
3385     return N1;
3386   // fold (mulhu x, 1) -> 0
3387   if (isOneConstant(N1))
3388     return DAG.getConstant(0, DL, N0.getValueType());
3389   // fold (mulhu x, undef) -> 0
3390   if (N0.isUndef() || N1.isUndef())
3391     return DAG.getConstant(0, DL, VT);
3392 
3393   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3394   // plus a shift.
3395   if (VT.isSimple() && !VT.isVector()) {
3396     MVT Simple = VT.getSimpleVT();
3397     unsigned SimpleSize = Simple.getSizeInBits();
3398     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3399     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3400       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3401       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3402       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3403       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3404             DAG.getConstant(SimpleSize, DL,
3405                             getShiftAmountTy(N1.getValueType())));
3406       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3407     }
3408   }
3409 
3410   return SDValue();
3411 }
3412 
3413 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3414 /// give the opcodes for the two computations that are being performed. Return
3415 /// true if a simplification was made.
3416 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3417                                                 unsigned HiOp) {
3418   // If the high half is not needed, just compute the low half.
3419   bool HiExists = N->hasAnyUseOfValue(1);
3420   if (!HiExists &&
3421       (!LegalOperations ||
3422        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3423     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3424     return CombineTo(N, Res, Res);
3425   }
3426 
3427   // If the low half is not needed, just compute the high half.
3428   bool LoExists = N->hasAnyUseOfValue(0);
3429   if (!LoExists &&
3430       (!LegalOperations ||
3431        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3432     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3433     return CombineTo(N, Res, Res);
3434   }
3435 
3436   // If both halves are used, return as it is.
3437   if (LoExists && HiExists)
3438     return SDValue();
3439 
3440   // If the two computed results can be simplified separately, separate them.
3441   if (LoExists) {
3442     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3443     AddToWorklist(Lo.getNode());
3444     SDValue LoOpt = combine(Lo.getNode());
3445     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3446         (!LegalOperations ||
3447          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3448       return CombineTo(N, LoOpt, LoOpt);
3449   }
3450 
3451   if (HiExists) {
3452     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3453     AddToWorklist(Hi.getNode());
3454     SDValue HiOpt = combine(Hi.getNode());
3455     if (HiOpt.getNode() && HiOpt != Hi &&
3456         (!LegalOperations ||
3457          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3458       return CombineTo(N, HiOpt, HiOpt);
3459   }
3460 
3461   return SDValue();
3462 }
3463 
3464 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3465   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3466     return Res;
3467 
3468   EVT VT = N->getValueType(0);
3469   SDLoc DL(N);
3470 
3471   // If the type is twice as wide is legal, transform the mulhu to a wider
3472   // multiply plus a shift.
3473   if (VT.isSimple() && !VT.isVector()) {
3474     MVT Simple = VT.getSimpleVT();
3475     unsigned SimpleSize = Simple.getSizeInBits();
3476     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3477     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3478       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3479       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3480       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3481       // Compute the high part as N1.
3482       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3483             DAG.getConstant(SimpleSize, DL,
3484                             getShiftAmountTy(Lo.getValueType())));
3485       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3486       // Compute the low part as N0.
3487       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3488       return CombineTo(N, Lo, Hi);
3489     }
3490   }
3491 
3492   return SDValue();
3493 }
3494 
3495 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3496   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3497     return Res;
3498 
3499   EVT VT = N->getValueType(0);
3500   SDLoc DL(N);
3501 
3502   // If the type is twice as wide is legal, transform the mulhu to a wider
3503   // multiply plus a shift.
3504   if (VT.isSimple() && !VT.isVector()) {
3505     MVT Simple = VT.getSimpleVT();
3506     unsigned SimpleSize = Simple.getSizeInBits();
3507     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3508     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3509       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3510       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3511       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3512       // Compute the high part as N1.
3513       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3514             DAG.getConstant(SimpleSize, DL,
3515                             getShiftAmountTy(Lo.getValueType())));
3516       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3517       // Compute the low part as N0.
3518       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3519       return CombineTo(N, Lo, Hi);
3520     }
3521   }
3522 
3523   return SDValue();
3524 }
3525 
3526 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3527   // (smulo x, 2) -> (saddo x, x)
3528   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3529     if (C2->getAPIntValue() == 2)
3530       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3531                          N->getOperand(0), N->getOperand(0));
3532 
3533   return SDValue();
3534 }
3535 
3536 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3537   // (umulo x, 2) -> (uaddo x, x)
3538   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3539     if (C2->getAPIntValue() == 2)
3540       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3541                          N->getOperand(0), N->getOperand(0));
3542 
3543   return SDValue();
3544 }
3545 
3546 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3547   SDValue N0 = N->getOperand(0);
3548   SDValue N1 = N->getOperand(1);
3549   EVT VT = N0.getValueType();
3550 
3551   // fold vector ops
3552   if (VT.isVector())
3553     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3554       return FoldedVOp;
3555 
3556   // fold operation with constant operands.
3557   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3558   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3559   if (N0C && N1C)
3560     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3561 
3562   // canonicalize constant to RHS
3563   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3564      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3565     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3566 
3567   // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
3568   // Only do this if the current op isn't legal and the flipped is.
3569   unsigned Opcode = N->getOpcode();
3570   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3571   if (!TLI.isOperationLegal(Opcode, VT) &&
3572       (N0.isUndef() || DAG.SignBitIsZero(N0)) &&
3573       (N1.isUndef() || DAG.SignBitIsZero(N1))) {
3574     unsigned AltOpcode;
3575     switch (Opcode) {
3576     case ISD::SMIN: AltOpcode = ISD::UMIN; break;
3577     case ISD::SMAX: AltOpcode = ISD::UMAX; break;
3578     case ISD::UMIN: AltOpcode = ISD::SMIN; break;
3579     case ISD::UMAX: AltOpcode = ISD::SMAX; break;
3580     default: llvm_unreachable("Unknown MINMAX opcode");
3581     }
3582     if (TLI.isOperationLegal(AltOpcode, VT))
3583       return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1);
3584   }
3585 
3586   return SDValue();
3587 }
3588 
3589 /// If this is a binary operator with two operands of the same opcode, try to
3590 /// simplify it.
3591 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3592   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3593   EVT VT = N0.getValueType();
3594   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3595 
3596   // Bail early if none of these transforms apply.
3597   if (N0.getNumOperands() == 0) return SDValue();
3598 
3599   // For each of OP in AND/OR/XOR:
3600   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3601   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3602   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3603   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3604   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3605   //
3606   // do not sink logical op inside of a vector extend, since it may combine
3607   // into a vsetcc.
3608   EVT Op0VT = N0.getOperand(0).getValueType();
3609   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3610        N0.getOpcode() == ISD::SIGN_EXTEND ||
3611        N0.getOpcode() == ISD::BSWAP ||
3612        // Avoid infinite looping with PromoteIntBinOp.
3613        (N0.getOpcode() == ISD::ANY_EXTEND &&
3614         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3615        (N0.getOpcode() == ISD::TRUNCATE &&
3616         (!TLI.isZExtFree(VT, Op0VT) ||
3617          !TLI.isTruncateFree(Op0VT, VT)) &&
3618         TLI.isTypeLegal(Op0VT))) &&
3619       !VT.isVector() &&
3620       Op0VT == N1.getOperand(0).getValueType() &&
3621       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3622     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3623                                  N0.getOperand(0).getValueType(),
3624                                  N0.getOperand(0), N1.getOperand(0));
3625     AddToWorklist(ORNode.getNode());
3626     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3627   }
3628 
3629   // For each of OP in SHL/SRL/SRA/AND...
3630   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3631   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3632   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3633   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3634        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3635       N0.getOperand(1) == N1.getOperand(1)) {
3636     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3637                                  N0.getOperand(0).getValueType(),
3638                                  N0.getOperand(0), N1.getOperand(0));
3639     AddToWorklist(ORNode.getNode());
3640     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3641                        ORNode, N0.getOperand(1));
3642   }
3643 
3644   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3645   // Only perform this optimization up until type legalization, before
3646   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3647   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3648   // we don't want to undo this promotion.
3649   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3650   // on scalars.
3651   if ((N0.getOpcode() == ISD::BITCAST ||
3652        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3653        Level <= AfterLegalizeTypes) {
3654     SDValue In0 = N0.getOperand(0);
3655     SDValue In1 = N1.getOperand(0);
3656     EVT In0Ty = In0.getValueType();
3657     EVT In1Ty = In1.getValueType();
3658     SDLoc DL(N);
3659     // If both incoming values are integers, and the original types are the
3660     // same.
3661     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3662       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3663       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3664       AddToWorklist(Op.getNode());
3665       return BC;
3666     }
3667   }
3668 
3669   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3670   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3671   // If both shuffles use the same mask, and both shuffle within a single
3672   // vector, then it is worthwhile to move the swizzle after the operation.
3673   // The type-legalizer generates this pattern when loading illegal
3674   // vector types from memory. In many cases this allows additional shuffle
3675   // optimizations.
3676   // There are other cases where moving the shuffle after the xor/and/or
3677   // is profitable even if shuffles don't perform a swizzle.
3678   // If both shuffles use the same mask, and both shuffles have the same first
3679   // or second operand, then it might still be profitable to move the shuffle
3680   // after the xor/and/or operation.
3681   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3682     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3683     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3684 
3685     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3686            "Inputs to shuffles are not the same type");
3687 
3688     // Check that both shuffles use the same mask. The masks are known to be of
3689     // the same length because the result vector type is the same.
3690     // Check also that shuffles have only one use to avoid introducing extra
3691     // instructions.
3692     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3693         SVN0->getMask().equals(SVN1->getMask())) {
3694       SDValue ShOp = N0->getOperand(1);
3695 
3696       // Don't try to fold this node if it requires introducing a
3697       // build vector of all zeros that might be illegal at this stage.
3698       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3699         if (!LegalTypes)
3700           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3701         else
3702           ShOp = SDValue();
3703       }
3704 
3705       // (AND (shuf (A, C), shuf (B, C))) -> shuf (AND (A, B), C)
3706       // (OR  (shuf (A, C), shuf (B, C))) -> shuf (OR  (A, B), C)
3707       // (XOR (shuf (A, C), shuf (B, C))) -> shuf (XOR (A, B), V_0)
3708       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3709         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3710                                       N0->getOperand(0), N1->getOperand(0));
3711         AddToWorklist(NewNode.getNode());
3712         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3713                                     SVN0->getMask());
3714       }
3715 
3716       // Don't try to fold this node if it requires introducing a
3717       // build vector of all zeros that might be illegal at this stage.
3718       ShOp = N0->getOperand(0);
3719       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3720         if (!LegalTypes)
3721           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3722         else
3723           ShOp = SDValue();
3724       }
3725 
3726       // (AND (shuf (C, A), shuf (C, B))) -> shuf (C, AND (A, B))
3727       // (OR  (shuf (C, A), shuf (C, B))) -> shuf (C, OR  (A, B))
3728       // (XOR (shuf (C, A), shuf (C, B))) -> shuf (V_0, XOR (A, B))
3729       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3730         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3731                                       N0->getOperand(1), N1->getOperand(1));
3732         AddToWorklist(NewNode.getNode());
3733         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3734                                     SVN0->getMask());
3735       }
3736     }
3737   }
3738 
3739   return SDValue();
3740 }
3741 
3742 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3743 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3744                                        const SDLoc &DL) {
3745   SDValue LL, LR, RL, RR, N0CC, N1CC;
3746   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3747       !isSetCCEquivalent(N1, RL, RR, N1CC))
3748     return SDValue();
3749 
3750   assert(N0.getValueType() == N1.getValueType() &&
3751          "Unexpected operand types for bitwise logic op");
3752   assert(LL.getValueType() == LR.getValueType() &&
3753          RL.getValueType() == RR.getValueType() &&
3754          "Unexpected operand types for setcc");
3755 
3756   // If we're here post-legalization or the logic op type is not i1, the logic
3757   // op type must match a setcc result type. Also, all folds require new
3758   // operations on the left and right operands, so those types must match.
3759   EVT VT = N0.getValueType();
3760   EVT OpVT = LL.getValueType();
3761   if (LegalOperations || VT.getScalarType() != MVT::i1)
3762     if (VT != getSetCCResultType(OpVT))
3763       return SDValue();
3764   if (OpVT != RL.getValueType())
3765     return SDValue();
3766 
3767   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3768   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3769   bool IsInteger = OpVT.isInteger();
3770   if (LR == RR && CC0 == CC1 && IsInteger) {
3771     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3772     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3773 
3774     // All bits clear?
3775     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3776     // All sign bits clear?
3777     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3778     // Any bits set?
3779     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3780     // Any sign bits set?
3781     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3782 
3783     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3784     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3785     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3786     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3787     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3788       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3789       AddToWorklist(Or.getNode());
3790       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3791     }
3792 
3793     // All bits set?
3794     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3795     // All sign bits set?
3796     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3797     // Any bits clear?
3798     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3799     // Any sign bits clear?
3800     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3801 
3802     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3803     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3804     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3805     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3806     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3807       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3808       AddToWorklist(And.getNode());
3809       return DAG.getSetCC(DL, VT, And, LR, CC1);
3810     }
3811   }
3812 
3813   // TODO: What is the 'or' equivalent of this fold?
3814   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3815   if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
3816       IsInteger && CC0 == ISD::SETNE &&
3817       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3818        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3819     SDValue One = DAG.getConstant(1, DL, OpVT);
3820     SDValue Two = DAG.getConstant(2, DL, OpVT);
3821     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3822     AddToWorklist(Add.getNode());
3823     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3824   }
3825 
3826   // Try more general transforms if the predicates match and the only user of
3827   // the compares is the 'and' or 'or'.
3828   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3829       N0.hasOneUse() && N1.hasOneUse()) {
3830     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3831     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3832     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3833       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3834       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3835       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3836       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3837       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3838     }
3839   }
3840 
3841   // Canonicalize equivalent operands to LL == RL.
3842   if (LL == RR && LR == RL) {
3843     CC1 = ISD::getSetCCSwappedOperands(CC1);
3844     std::swap(RL, RR);
3845   }
3846 
3847   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3848   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3849   if (LL == RL && LR == RR) {
3850     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3851                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3852     if (NewCC != ISD::SETCC_INVALID &&
3853         (!LegalOperations ||
3854          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3855           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3856       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3857   }
3858 
3859   return SDValue();
3860 }
3861 
3862 /// This contains all DAGCombine rules which reduce two values combined by
3863 /// an And operation to a single value. This makes them reusable in the context
3864 /// of visitSELECT(). Rules involving constants are not included as
3865 /// visitSELECT() already handles those cases.
3866 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3867   EVT VT = N1.getValueType();
3868   SDLoc DL(N);
3869 
3870   // fold (and x, undef) -> 0
3871   if (N0.isUndef() || N1.isUndef())
3872     return DAG.getConstant(0, DL, VT);
3873 
3874   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3875     return V;
3876 
3877   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3878       VT.getSizeInBits() <= 64) {
3879     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3880       if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3881         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3882         // immediate for an add, but it is legal if its top c2 bits are set,
3883         // transform the ADD so the immediate doesn't need to be materialized
3884         // in a register.
3885         APInt ADDC = ADDI->getAPIntValue();
3886         APInt SRLC = SRLI->getAPIntValue();
3887         if (ADDC.getMinSignedBits() <= 64 &&
3888             SRLC.ult(VT.getSizeInBits()) &&
3889             !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3890           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3891                                              SRLC.getZExtValue());
3892           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3893             ADDC |= Mask;
3894             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3895               SDLoc DL0(N0);
3896               SDValue NewAdd =
3897                 DAG.getNode(ISD::ADD, DL0, VT,
3898                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3899               CombineTo(N0.getNode(), NewAdd);
3900               // Return N so it doesn't get rechecked!
3901               return SDValue(N, 0);
3902             }
3903           }
3904         }
3905       }
3906     }
3907   }
3908 
3909   // Reduce bit extract of low half of an integer to the narrower type.
3910   // (and (srl i64:x, K), KMask) ->
3911   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3912   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3913     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3914       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3915         unsigned Size = VT.getSizeInBits();
3916         const APInt &AndMask = CAnd->getAPIntValue();
3917         unsigned ShiftBits = CShift->getZExtValue();
3918 
3919         // Bail out, this node will probably disappear anyway.
3920         if (ShiftBits == 0)
3921           return SDValue();
3922 
3923         unsigned MaskBits = AndMask.countTrailingOnes();
3924         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3925 
3926         if (AndMask.isMask() &&
3927             // Required bits must not span the two halves of the integer and
3928             // must fit in the half size type.
3929             (ShiftBits + MaskBits <= Size / 2) &&
3930             TLI.isNarrowingProfitable(VT, HalfVT) &&
3931             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3932             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3933             TLI.isTruncateFree(VT, HalfVT) &&
3934             TLI.isZExtFree(HalfVT, VT)) {
3935           // The isNarrowingProfitable is to avoid regressions on PPC and
3936           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3937           // on downstream users of this. Those patterns could probably be
3938           // extended to handle extensions mixed in.
3939 
3940           SDValue SL(N0);
3941           assert(MaskBits <= Size);
3942 
3943           // Extracting the highest bit of the low half.
3944           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3945           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3946                                       N0.getOperand(0));
3947 
3948           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3949           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3950           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3951           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3952           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3953         }
3954       }
3955     }
3956   }
3957 
3958   return SDValue();
3959 }
3960 
3961 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3962                                    EVT LoadResultTy, EVT &ExtVT) {
3963   if (!AndC->getAPIntValue().isMask())
3964     return false;
3965 
3966   unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
3967 
3968   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3969   EVT LoadedVT = LoadN->getMemoryVT();
3970 
3971   if (ExtVT == LoadedVT &&
3972       (!LegalOperations ||
3973        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3974     // ZEXTLOAD will match without needing to change the size of the value being
3975     // loaded.
3976     return true;
3977   }
3978 
3979   // Do not change the width of a volatile load.
3980   if (LoadN->isVolatile())
3981     return false;
3982 
3983   // Do not generate loads of non-round integer types since these can
3984   // be expensive (and would be wrong if the type is not byte sized).
3985   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3986     return false;
3987 
3988   if (LegalOperations &&
3989       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3990     return false;
3991 
3992   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3993     return false;
3994 
3995   return true;
3996 }
3997 
3998 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
3999                                     ISD::LoadExtType ExtType, EVT &MemVT,
4000                                     unsigned ShAmt) {
4001   if (!LDST)
4002     return false;
4003   // Only allow byte offsets.
4004   if (ShAmt % 8)
4005     return false;
4006 
4007   // Do not generate loads of non-round integer types since these can
4008   // be expensive (and would be wrong if the type is not byte sized).
4009   if (!MemVT.isRound())
4010     return false;
4011 
4012   // Don't change the width of a volatile load.
4013   if (LDST->isVolatile())
4014     return false;
4015 
4016   // Verify that we are actually reducing a load width here.
4017   if (LDST->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits())
4018     return false;
4019 
4020   // Ensure that this isn't going to produce an unsupported unaligned access.
4021   if (ShAmt &&
4022       !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
4023                               LDST->getAddressSpace(), ShAmt / 8))
4024     return false;
4025 
4026   // It's not possible to generate a constant of extended or untyped type.
4027   EVT PtrType = LDST->getBasePtr().getValueType();
4028   if (PtrType == MVT::Untyped || PtrType.isExtended())
4029     return false;
4030 
4031   if (isa<LoadSDNode>(LDST)) {
4032     LoadSDNode *Load = cast<LoadSDNode>(LDST);
4033     // Don't transform one with multiple uses, this would require adding a new
4034     // load.
4035     if (!SDValue(Load, 0).hasOneUse())
4036       return false;
4037 
4038     if (LegalOperations &&
4039         !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT))
4040       return false;
4041 
4042     // For the transform to be legal, the load must produce only two values
4043     // (the value loaded and the chain).  Don't transform a pre-increment
4044     // load, for example, which produces an extra value.  Otherwise the
4045     // transformation is not equivalent, and the downstream logic to replace
4046     // uses gets things wrong.
4047     if (Load->getNumValues() > 2)
4048       return false;
4049 
4050     // If the load that we're shrinking is an extload and we're not just
4051     // discarding the extension we can't simply shrink the load. Bail.
4052     // TODO: It would be possible to merge the extensions in some cases.
4053     if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
4054         Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
4055       return false;
4056 
4057     if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT))
4058       return false;
4059   } else {
4060     assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode");
4061     StoreSDNode *Store = cast<StoreSDNode>(LDST);
4062     // Can't write outside the original store
4063     if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
4064       return false;
4065 
4066     if (LegalOperations &&
4067         !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT))
4068       return false;
4069   }
4070   return true;
4071 }
4072 
4073 bool DAGCombiner::SearchForAndLoads(SDNode *N,
4074                                     SmallPtrSetImpl<LoadSDNode*> &Loads,
4075                                     SmallPtrSetImpl<SDNode*> &NodesWithConsts,
4076                                     ConstantSDNode *Mask,
4077                                     SDNode *&NodeToMask) {
4078   // Recursively search for the operands, looking for loads which can be
4079   // narrowed.
4080   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) {
4081     SDValue Op = N->getOperand(i);
4082 
4083     if (Op.getValueType().isVector())
4084       return false;
4085 
4086     // Some constants may need fixing up later if they are too large.
4087     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4088       if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
4089           (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
4090         NodesWithConsts.insert(N);
4091       continue;
4092     }
4093 
4094     if (!Op.hasOneUse())
4095       return false;
4096 
4097     switch(Op.getOpcode()) {
4098     case ISD::LOAD: {
4099       auto *Load = cast<LoadSDNode>(Op);
4100       EVT ExtVT;
4101       if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
4102           isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
4103 
4104         // ZEXTLOAD is already small enough.
4105         if (Load->getExtensionType() == ISD::ZEXTLOAD &&
4106             ExtVT.bitsGE(Load->getMemoryVT()))
4107           continue;
4108 
4109         // Use LE to convert equal sized loads to zext.
4110         if (ExtVT.bitsLE(Load->getMemoryVT()))
4111           Loads.insert(Load);
4112 
4113         continue;
4114       }
4115       return false;
4116     }
4117     case ISD::ZERO_EXTEND:
4118     case ISD::AssertZext: {
4119       unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
4120       EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
4121       EVT VT = Op.getOpcode() == ISD::AssertZext ?
4122         cast<VTSDNode>(Op.getOperand(1))->getVT() :
4123         Op.getOperand(0).getValueType();
4124 
4125       // We can accept extending nodes if the mask is wider or an equal
4126       // width to the original type.
4127       if (ExtVT.bitsGE(VT))
4128         continue;
4129       break;
4130     }
4131     case ISD::OR:
4132     case ISD::XOR:
4133     case ISD::AND:
4134       if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
4135                              NodeToMask))
4136         return false;
4137       continue;
4138     }
4139 
4140     // Allow one node which will masked along with any loads found.
4141     if (NodeToMask)
4142       return false;
4143 
4144     // Also ensure that the node to be masked only produces one data result.
4145     NodeToMask = Op.getNode();
4146     if (NodeToMask->getNumValues() > 1) {
4147       bool HasValue = false;
4148       for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
4149         MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
4150         if (VT != MVT::Glue && VT != MVT::Other) {
4151           if (HasValue) {
4152             NodeToMask = nullptr;
4153             return false;
4154           }
4155           HasValue = true;
4156         }
4157       }
4158       assert(HasValue && "Node to be masked has no data result?");
4159     }
4160   }
4161   return true;
4162 }
4163 
4164 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) {
4165   auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
4166   if (!Mask)
4167     return false;
4168 
4169   if (!Mask->getAPIntValue().isMask())
4170     return false;
4171 
4172   // No need to do anything if the and directly uses a load.
4173   if (isa<LoadSDNode>(N->getOperand(0)))
4174     return false;
4175 
4176   SmallPtrSet<LoadSDNode*, 8> Loads;
4177   SmallPtrSet<SDNode*, 2> NodesWithConsts;
4178   SDNode *FixupNode = nullptr;
4179   if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
4180     if (Loads.size() == 0)
4181       return false;
4182 
4183     LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
4184     SDValue MaskOp = N->getOperand(1);
4185 
4186     // If it exists, fixup the single node we allow in the tree that needs
4187     // masking.
4188     if (FixupNode) {
4189       LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
4190       SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
4191                                 FixupNode->getValueType(0),
4192                                 SDValue(FixupNode, 0), MaskOp);
4193       DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
4194       DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0),
4195                              MaskOp);
4196     }
4197 
4198     // Narrow any constants that need it.
4199     for (auto *LogicN : NodesWithConsts) {
4200       SDValue Op0 = LogicN->getOperand(0);
4201       SDValue Op1 = LogicN->getOperand(1);
4202 
4203       if (isa<ConstantSDNode>(Op0))
4204           std::swap(Op0, Op1);
4205 
4206       SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(),
4207                                 Op1, MaskOp);
4208 
4209       DAG.UpdateNodeOperands(LogicN, Op0, And);
4210     }
4211 
4212     // Create narrow loads.
4213     for (auto *Load : Loads) {
4214       LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
4215       SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
4216                                 SDValue(Load, 0), MaskOp);
4217       DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
4218       DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp);
4219       SDValue NewLoad = ReduceLoadWidth(And.getNode());
4220       assert(NewLoad &&
4221              "Shouldn't be masking the load if it can't be narrowed");
4222       CombineTo(Load, NewLoad, NewLoad.getValue(1));
4223     }
4224     DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
4225     return true;
4226   }
4227   return false;
4228 }
4229 
4230 // Unfold
4231 //    x &  (-1 'logical shift' y)
4232 // To
4233 //    (x 'opposite logical shift' y) 'logical shift' y
4234 // if it is better for performance.
4235 SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
4236   assert(N->getOpcode() == ISD::AND);
4237 
4238   SDValue N0 = N->getOperand(0);
4239   SDValue N1 = N->getOperand(1);
4240 
4241   // Do we actually prefer shifts over mask?
4242   if (!TLI.preferShiftsToClearExtremeBits(N0))
4243     return SDValue();
4244 
4245   // Try to match  (-1 '[outer] logical shift' y)
4246   unsigned OuterShift;
4247   unsigned InnerShift; // The opposite direction to the OuterShift.
4248   SDValue Y;           // Shift amount.
4249   auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
4250     if (!M.hasOneUse())
4251       return false;
4252     OuterShift = M->getOpcode();
4253     if (OuterShift == ISD::SHL)
4254       InnerShift = ISD::SRL;
4255     else if (OuterShift == ISD::SRL)
4256       InnerShift = ISD::SHL;
4257     else
4258       return false;
4259     if (!isAllOnesConstant(M->getOperand(0)))
4260       return false;
4261     Y = M->getOperand(1);
4262     return true;
4263   };
4264 
4265   SDValue X;
4266   if (matchMask(N1))
4267     X = N0;
4268   else if (matchMask(N0))
4269     X = N1;
4270   else
4271     return SDValue();
4272 
4273   SDLoc DL(N);
4274   EVT VT = N->getValueType(0);
4275 
4276   //     tmp = x   'opposite logical shift' y
4277   SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
4278   //     ret = tmp 'logical shift' y
4279   SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
4280 
4281   return T1;
4282 }
4283 
4284 SDValue DAGCombiner::visitAND(SDNode *N) {
4285   SDValue N0 = N->getOperand(0);
4286   SDValue N1 = N->getOperand(1);
4287   EVT VT = N1.getValueType();
4288 
4289   // x & x --> x
4290   if (N0 == N1)
4291     return N0;
4292 
4293   // fold vector ops
4294   if (VT.isVector()) {
4295     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4296       return FoldedVOp;
4297 
4298     // fold (and x, 0) -> 0, vector edition
4299     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4300       // do not return N0, because undef node may exist in N0
4301       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
4302                              SDLoc(N), N0.getValueType());
4303     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4304       // do not return N1, because undef node may exist in N1
4305       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
4306                              SDLoc(N), N1.getValueType());
4307 
4308     // fold (and x, -1) -> x, vector edition
4309     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4310       return N1;
4311     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4312       return N0;
4313   }
4314 
4315   // fold (and c1, c2) -> c1&c2
4316   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4317   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4318   if (N0C && N1C && !N1C->isOpaque())
4319     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
4320   // canonicalize constant to RHS
4321   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4322      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4323     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
4324   // fold (and x, -1) -> x
4325   if (isAllOnesConstant(N1))
4326     return N0;
4327   // if (and x, c) is known to be zero, return 0
4328   unsigned BitWidth = VT.getScalarSizeInBits();
4329   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4330                                    APInt::getAllOnesValue(BitWidth)))
4331     return DAG.getConstant(0, SDLoc(N), VT);
4332 
4333   if (SDValue NewSel = foldBinOpIntoSelect(N))
4334     return NewSel;
4335 
4336   // reassociate and
4337   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
4338     return RAND;
4339 
4340   // Try to convert a constant mask AND into a shuffle clear mask.
4341   if (VT.isVector())
4342     if (SDValue Shuffle = XformToShuffleWithZero(N))
4343       return Shuffle;
4344 
4345   // fold (and (or x, C), D) -> D if (C & D) == D
4346   auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
4347     return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
4348   };
4349   if (N0.getOpcode() == ISD::OR &&
4350       ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
4351     return N1;
4352   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
4353   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4354     SDValue N0Op0 = N0.getOperand(0);
4355     APInt Mask = ~N1C->getAPIntValue();
4356     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
4357     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
4358       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
4359                                  N0.getValueType(), N0Op0);
4360 
4361       // Replace uses of the AND with uses of the Zero extend node.
4362       CombineTo(N, Zext);
4363 
4364       // We actually want to replace all uses of the any_extend with the
4365       // zero_extend, to avoid duplicating things.  This will later cause this
4366       // AND to be folded.
4367       CombineTo(N0.getNode(), Zext);
4368       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4369     }
4370   }
4371   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
4372   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
4373   // already be zero by virtue of the width of the base type of the load.
4374   //
4375   // the 'X' node here can either be nothing or an extract_vector_elt to catch
4376   // more cases.
4377   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4378        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
4379        N0.getOperand(0).getOpcode() == ISD::LOAD &&
4380        N0.getOperand(0).getResNo() == 0) ||
4381       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
4382     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
4383                                          N0 : N0.getOperand(0) );
4384 
4385     // Get the constant (if applicable) the zero'th operand is being ANDed with.
4386     // This can be a pure constant or a vector splat, in which case we treat the
4387     // vector as a scalar and use the splat value.
4388     APInt Constant = APInt::getNullValue(1);
4389     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
4390       Constant = C->getAPIntValue();
4391     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
4392       APInt SplatValue, SplatUndef;
4393       unsigned SplatBitSize;
4394       bool HasAnyUndefs;
4395       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
4396                                              SplatBitSize, HasAnyUndefs);
4397       if (IsSplat) {
4398         // Undef bits can contribute to a possible optimisation if set, so
4399         // set them.
4400         SplatValue |= SplatUndef;
4401 
4402         // The splat value may be something like "0x00FFFFFF", which means 0 for
4403         // the first vector value and FF for the rest, repeating. We need a mask
4404         // that will apply equally to all members of the vector, so AND all the
4405         // lanes of the constant together.
4406         EVT VT = Vector->getValueType(0);
4407         unsigned BitWidth = VT.getScalarSizeInBits();
4408 
4409         // If the splat value has been compressed to a bitlength lower
4410         // than the size of the vector lane, we need to re-expand it to
4411         // the lane size.
4412         if (BitWidth > SplatBitSize)
4413           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
4414                SplatBitSize < BitWidth;
4415                SplatBitSize = SplatBitSize * 2)
4416             SplatValue |= SplatValue.shl(SplatBitSize);
4417 
4418         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
4419         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
4420         if (SplatBitSize % BitWidth == 0) {
4421           Constant = APInt::getAllOnesValue(BitWidth);
4422           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
4423             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
4424         }
4425       }
4426     }
4427 
4428     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
4429     // actually legal and isn't going to get expanded, else this is a false
4430     // optimisation.
4431     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
4432                                                     Load->getValueType(0),
4433                                                     Load->getMemoryVT());
4434 
4435     // Resize the constant to the same size as the original memory access before
4436     // extension. If it is still the AllOnesValue then this AND is completely
4437     // unneeded.
4438     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
4439 
4440     bool B;
4441     switch (Load->getExtensionType()) {
4442     default: B = false; break;
4443     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
4444     case ISD::ZEXTLOAD:
4445     case ISD::NON_EXTLOAD: B = true; break;
4446     }
4447 
4448     if (B && Constant.isAllOnesValue()) {
4449       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
4450       // preserve semantics once we get rid of the AND.
4451       SDValue NewLoad(Load, 0);
4452 
4453       // Fold the AND away. NewLoad may get replaced immediately.
4454       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
4455 
4456       if (Load->getExtensionType() == ISD::EXTLOAD) {
4457         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
4458                               Load->getValueType(0), SDLoc(Load),
4459                               Load->getChain(), Load->getBasePtr(),
4460                               Load->getOffset(), Load->getMemoryVT(),
4461                               Load->getMemOperand());
4462         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
4463         if (Load->getNumValues() == 3) {
4464           // PRE/POST_INC loads have 3 values.
4465           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
4466                            NewLoad.getValue(2) };
4467           CombineTo(Load, To, 3, true);
4468         } else {
4469           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
4470         }
4471       }
4472 
4473       return SDValue(N, 0); // Return N so it doesn't get rechecked!
4474     }
4475   }
4476 
4477   // fold (and (load x), 255) -> (zextload x, i8)
4478   // fold (and (extload x, i16), 255) -> (zextload x, i8)
4479   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
4480   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
4481                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
4482                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
4483     if (SDValue Res = ReduceLoadWidth(N)) {
4484       LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
4485         ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
4486 
4487       AddToWorklist(N);
4488       CombineTo(LN0, Res, Res.getValue(1));
4489       return SDValue(N, 0);
4490     }
4491   }
4492 
4493   if (Level >= AfterLegalizeTypes) {
4494     // Attempt to propagate the AND back up to the leaves which, if they're
4495     // loads, can be combined to narrow loads and the AND node can be removed.
4496     // Perform after legalization so that extend nodes will already be
4497     // combined into the loads.
4498     if (BackwardsPropagateMask(N, DAG)) {
4499       return SDValue(N, 0);
4500     }
4501   }
4502 
4503   if (SDValue Combined = visitANDLike(N0, N1, N))
4504     return Combined;
4505 
4506   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
4507   if (N0.getOpcode() == N1.getOpcode())
4508     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4509       return Tmp;
4510 
4511   // Masking the negated extension of a boolean is just the zero-extended
4512   // boolean:
4513   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
4514   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
4515   //
4516   // Note: the SimplifyDemandedBits fold below can make an information-losing
4517   // transform, and then we have no way to find this better fold.
4518   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
4519     if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
4520       SDValue SubRHS = N0.getOperand(1);
4521       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
4522           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4523         return SubRHS;
4524       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
4525           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4526         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
4527     }
4528   }
4529 
4530   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
4531   // fold (and (sra)) -> (and (srl)) when possible.
4532   if (SimplifyDemandedBits(SDValue(N, 0)))
4533     return SDValue(N, 0);
4534 
4535   // fold (zext_inreg (extload x)) -> (zextload x)
4536   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
4537     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4538     EVT MemVT = LN0->getMemoryVT();
4539     // If we zero all the possible extended bits, then we can turn this into
4540     // a zextload if we are running before legalize or the operation is legal.
4541     unsigned BitWidth = N1.getScalarValueSizeInBits();
4542     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4543                            BitWidth - MemVT.getScalarSizeInBits())) &&
4544         ((!LegalOperations && !LN0->isVolatile()) ||
4545          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4546       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4547                                        LN0->getChain(), LN0->getBasePtr(),
4548                                        MemVT, LN0->getMemOperand());
4549       AddToWorklist(N);
4550       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4551       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4552     }
4553   }
4554   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
4555   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4556       N0.hasOneUse()) {
4557     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4558     EVT MemVT = LN0->getMemoryVT();
4559     // If we zero all the possible extended bits, then we can turn this into
4560     // a zextload if we are running before legalize or the operation is legal.
4561     unsigned BitWidth = N1.getScalarValueSizeInBits();
4562     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4563                            BitWidth - MemVT.getScalarSizeInBits())) &&
4564         ((!LegalOperations && !LN0->isVolatile()) ||
4565          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4566       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4567                                        LN0->getChain(), LN0->getBasePtr(),
4568                                        MemVT, LN0->getMemOperand());
4569       AddToWorklist(N);
4570       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4571       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4572     }
4573   }
4574   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
4575   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
4576     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4577                                            N0.getOperand(1), false))
4578       return BSwap;
4579   }
4580 
4581   if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N))
4582     return Shifts;
4583 
4584   return SDValue();
4585 }
4586 
4587 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
4588 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
4589                                         bool DemandHighBits) {
4590   if (!LegalOperations)
4591     return SDValue();
4592 
4593   EVT VT = N->getValueType(0);
4594   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
4595     return SDValue();
4596   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4597     return SDValue();
4598 
4599   // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
4600   bool LookPassAnd0 = false;
4601   bool LookPassAnd1 = false;
4602   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
4603       std::swap(N0, N1);
4604   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
4605       std::swap(N0, N1);
4606   if (N0.getOpcode() == ISD::AND) {
4607     if (!N0.getNode()->hasOneUse())
4608       return SDValue();
4609     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4610     // Also handle 0xffff since the LHS is guaranteed to have zeros there.
4611     // This is needed for X86.
4612     if (!N01C || (N01C->getZExtValue() != 0xFF00 &&
4613                   N01C->getZExtValue() != 0xFFFF))
4614       return SDValue();
4615     N0 = N0.getOperand(0);
4616     LookPassAnd0 = true;
4617   }
4618 
4619   if (N1.getOpcode() == ISD::AND) {
4620     if (!N1.getNode()->hasOneUse())
4621       return SDValue();
4622     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4623     if (!N11C || N11C->getZExtValue() != 0xFF)
4624       return SDValue();
4625     N1 = N1.getOperand(0);
4626     LookPassAnd1 = true;
4627   }
4628 
4629   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
4630     std::swap(N0, N1);
4631   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4632     return SDValue();
4633   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4634     return SDValue();
4635 
4636   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4637   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4638   if (!N01C || !N11C)
4639     return SDValue();
4640   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4641     return SDValue();
4642 
4643   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4644   SDValue N00 = N0->getOperand(0);
4645   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4646     if (!N00.getNode()->hasOneUse())
4647       return SDValue();
4648     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4649     if (!N001C || N001C->getZExtValue() != 0xFF)
4650       return SDValue();
4651     N00 = N00.getOperand(0);
4652     LookPassAnd0 = true;
4653   }
4654 
4655   SDValue N10 = N1->getOperand(0);
4656   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4657     if (!N10.getNode()->hasOneUse())
4658       return SDValue();
4659     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4660     // Also allow 0xFFFF since the bits will be shifted out. This is needed
4661     // for X86.
4662     if (!N101C || (N101C->getZExtValue() != 0xFF00 &&
4663                    N101C->getZExtValue() != 0xFFFF))
4664       return SDValue();
4665     N10 = N10.getOperand(0);
4666     LookPassAnd1 = true;
4667   }
4668 
4669   if (N00 != N10)
4670     return SDValue();
4671 
4672   // Make sure everything beyond the low halfword gets set to zero since the SRL
4673   // 16 will clear the top bits.
4674   unsigned OpSizeInBits = VT.getSizeInBits();
4675   if (DemandHighBits && OpSizeInBits > 16) {
4676     // If the left-shift isn't masked out then the only way this is a bswap is
4677     // if all bits beyond the low 8 are 0. In that case the entire pattern
4678     // reduces to a left shift anyway: leave it for other parts of the combiner.
4679     if (!LookPassAnd0)
4680       return SDValue();
4681 
4682     // However, if the right shift isn't masked out then it might be because
4683     // it's not needed. See if we can spot that too.
4684     if (!LookPassAnd1 &&
4685         !DAG.MaskedValueIsZero(
4686             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4687       return SDValue();
4688   }
4689 
4690   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4691   if (OpSizeInBits > 16) {
4692     SDLoc DL(N);
4693     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4694                       DAG.getConstant(OpSizeInBits - 16, DL,
4695                                       getShiftAmountTy(VT)));
4696   }
4697   return Res;
4698 }
4699 
4700 /// Return true if the specified node is an element that makes up a 32-bit
4701 /// packed halfword byteswap.
4702 /// ((x & 0x000000ff) << 8) |
4703 /// ((x & 0x0000ff00) >> 8) |
4704 /// ((x & 0x00ff0000) << 8) |
4705 /// ((x & 0xff000000) >> 8)
4706 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4707   if (!N.getNode()->hasOneUse())
4708     return false;
4709 
4710   unsigned Opc = N.getOpcode();
4711   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4712     return false;
4713 
4714   SDValue N0 = N.getOperand(0);
4715   unsigned Opc0 = N0.getOpcode();
4716   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4717     return false;
4718 
4719   ConstantSDNode *N1C = nullptr;
4720   // SHL or SRL: look upstream for AND mask operand
4721   if (Opc == ISD::AND)
4722     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4723   else if (Opc0 == ISD::AND)
4724     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4725   if (!N1C)
4726     return false;
4727 
4728   unsigned MaskByteOffset;
4729   switch (N1C->getZExtValue()) {
4730   default:
4731     return false;
4732   case 0xFF:       MaskByteOffset = 0; break;
4733   case 0xFF00:     MaskByteOffset = 1; break;
4734   case 0xFFFF:
4735     // In case demanded bits didn't clear the bits that will be shifted out.
4736     // This is needed for X86.
4737     if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) {
4738       MaskByteOffset = 1;
4739       break;
4740     }
4741     return false;
4742   case 0xFF0000:   MaskByteOffset = 2; break;
4743   case 0xFF000000: MaskByteOffset = 3; break;
4744   }
4745 
4746   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4747   if (Opc == ISD::AND) {
4748     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4749       // (x >> 8) & 0xff
4750       // (x >> 8) & 0xff0000
4751       if (Opc0 != ISD::SRL)
4752         return false;
4753       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4754       if (!C || C->getZExtValue() != 8)
4755         return false;
4756     } else {
4757       // (x << 8) & 0xff00
4758       // (x << 8) & 0xff000000
4759       if (Opc0 != ISD::SHL)
4760         return false;
4761       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4762       if (!C || C->getZExtValue() != 8)
4763         return false;
4764     }
4765   } else if (Opc == ISD::SHL) {
4766     // (x & 0xff) << 8
4767     // (x & 0xff0000) << 8
4768     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4769       return false;
4770     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4771     if (!C || C->getZExtValue() != 8)
4772       return false;
4773   } else { // Opc == ISD::SRL
4774     // (x & 0xff00) >> 8
4775     // (x & 0xff000000) >> 8
4776     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4777       return false;
4778     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4779     if (!C || C->getZExtValue() != 8)
4780       return false;
4781   }
4782 
4783   if (Parts[MaskByteOffset])
4784     return false;
4785 
4786   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4787   return true;
4788 }
4789 
4790 /// Match a 32-bit packed halfword bswap. That is
4791 /// ((x & 0x000000ff) << 8) |
4792 /// ((x & 0x0000ff00) >> 8) |
4793 /// ((x & 0x00ff0000) << 8) |
4794 /// ((x & 0xff000000) >> 8)
4795 /// => (rotl (bswap x), 16)
4796 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4797   if (!LegalOperations)
4798     return SDValue();
4799 
4800   EVT VT = N->getValueType(0);
4801   if (VT != MVT::i32)
4802     return SDValue();
4803   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4804     return SDValue();
4805 
4806   // Look for either
4807   // (or (or (and), (and)), (or (and), (and)))
4808   // (or (or (or (and), (and)), (and)), (and))
4809   if (N0.getOpcode() != ISD::OR)
4810     return SDValue();
4811   SDValue N00 = N0.getOperand(0);
4812   SDValue N01 = N0.getOperand(1);
4813   SDNode *Parts[4] = {};
4814 
4815   if (N1.getOpcode() == ISD::OR &&
4816       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4817     // (or (or (and), (and)), (or (and), (and)))
4818     if (!isBSwapHWordElement(N00, Parts))
4819       return SDValue();
4820 
4821     if (!isBSwapHWordElement(N01, Parts))
4822       return SDValue();
4823     SDValue N10 = N1.getOperand(0);
4824     if (!isBSwapHWordElement(N10, Parts))
4825       return SDValue();
4826     SDValue N11 = N1.getOperand(1);
4827     if (!isBSwapHWordElement(N11, Parts))
4828       return SDValue();
4829   } else {
4830     // (or (or (or (and), (and)), (and)), (and))
4831     if (!isBSwapHWordElement(N1, Parts))
4832       return SDValue();
4833     if (!isBSwapHWordElement(N01, Parts))
4834       return SDValue();
4835     if (N00.getOpcode() != ISD::OR)
4836       return SDValue();
4837     SDValue N000 = N00.getOperand(0);
4838     if (!isBSwapHWordElement(N000, Parts))
4839       return SDValue();
4840     SDValue N001 = N00.getOperand(1);
4841     if (!isBSwapHWordElement(N001, Parts))
4842       return SDValue();
4843   }
4844 
4845   // Make sure the parts are all coming from the same node.
4846   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4847     return SDValue();
4848 
4849   SDLoc DL(N);
4850   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4851                               SDValue(Parts[0], 0));
4852 
4853   // Result of the bswap should be rotated by 16. If it's not legal, then
4854   // do  (x << 16) | (x >> 16).
4855   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4856   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4857     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4858   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4859     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4860   return DAG.getNode(ISD::OR, DL, VT,
4861                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4862                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4863 }
4864 
4865 /// This contains all DAGCombine rules which reduce two values combined by
4866 /// an Or operation to a single value \see visitANDLike().
4867 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4868   EVT VT = N1.getValueType();
4869   SDLoc DL(N);
4870 
4871   // fold (or x, undef) -> -1
4872   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4873     return DAG.getAllOnesConstant(DL, VT);
4874 
4875   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4876     return V;
4877 
4878   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4879   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4880       // Don't increase # computations.
4881       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4882     // We can only do this xform if we know that bits from X that are set in C2
4883     // but not in C1 are already zero.  Likewise for Y.
4884     if (const ConstantSDNode *N0O1C =
4885         getAsNonOpaqueConstant(N0.getOperand(1))) {
4886       if (const ConstantSDNode *N1O1C =
4887           getAsNonOpaqueConstant(N1.getOperand(1))) {
4888         // We can only do this xform if we know that bits from X that are set in
4889         // C2 but not in C1 are already zero.  Likewise for Y.
4890         const APInt &LHSMask = N0O1C->getAPIntValue();
4891         const APInt &RHSMask = N1O1C->getAPIntValue();
4892 
4893         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4894             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4895           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4896                                   N0.getOperand(0), N1.getOperand(0));
4897           return DAG.getNode(ISD::AND, DL, VT, X,
4898                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4899         }
4900       }
4901     }
4902   }
4903 
4904   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4905   if (N0.getOpcode() == ISD::AND &&
4906       N1.getOpcode() == ISD::AND &&
4907       N0.getOperand(0) == N1.getOperand(0) &&
4908       // Don't increase # computations.
4909       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4910     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4911                             N0.getOperand(1), N1.getOperand(1));
4912     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4913   }
4914 
4915   return SDValue();
4916 }
4917 
4918 SDValue DAGCombiner::visitOR(SDNode *N) {
4919   SDValue N0 = N->getOperand(0);
4920   SDValue N1 = N->getOperand(1);
4921   EVT VT = N1.getValueType();
4922 
4923   // x | x --> x
4924   if (N0 == N1)
4925     return N0;
4926 
4927   // fold vector ops
4928   if (VT.isVector()) {
4929     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4930       return FoldedVOp;
4931 
4932     // fold (or x, 0) -> x, vector edition
4933     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4934       return N1;
4935     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4936       return N0;
4937 
4938     // fold (or x, -1) -> -1, vector edition
4939     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4940       // do not return N0, because undef node may exist in N0
4941       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4942     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4943       // do not return N1, because undef node may exist in N1
4944       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4945 
4946     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4947     // Do this only if the resulting shuffle is legal.
4948     if (isa<ShuffleVectorSDNode>(N0) &&
4949         isa<ShuffleVectorSDNode>(N1) &&
4950         // Avoid folding a node with illegal type.
4951         TLI.isTypeLegal(VT)) {
4952       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4953       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4954       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4955       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4956       // Ensure both shuffles have a zero input.
4957       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4958         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4959         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4960         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4961         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4962         bool CanFold = true;
4963         int NumElts = VT.getVectorNumElements();
4964         SmallVector<int, 4> Mask(NumElts);
4965 
4966         for (int i = 0; i != NumElts; ++i) {
4967           int M0 = SV0->getMaskElt(i);
4968           int M1 = SV1->getMaskElt(i);
4969 
4970           // Determine if either index is pointing to a zero vector.
4971           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4972           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4973 
4974           // If one element is zero and the otherside is undef, keep undef.
4975           // This also handles the case that both are undef.
4976           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4977             Mask[i] = -1;
4978             continue;
4979           }
4980 
4981           // Make sure only one of the elements is zero.
4982           if (M0Zero == M1Zero) {
4983             CanFold = false;
4984             break;
4985           }
4986 
4987           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4988 
4989           // We have a zero and non-zero element. If the non-zero came from
4990           // SV0 make the index a LHS index. If it came from SV1, make it
4991           // a RHS index. We need to mod by NumElts because we don't care
4992           // which operand it came from in the original shuffles.
4993           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4994         }
4995 
4996         if (CanFold) {
4997           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4998           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4999 
5000           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
5001           if (!LegalMask) {
5002             std::swap(NewLHS, NewRHS);
5003             ShuffleVectorSDNode::commuteMask(Mask);
5004             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
5005           }
5006 
5007           if (LegalMask)
5008             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
5009         }
5010       }
5011     }
5012   }
5013 
5014   // fold (or c1, c2) -> c1|c2
5015   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5016   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5017   if (N0C && N1C && !N1C->isOpaque())
5018     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
5019   // canonicalize constant to RHS
5020   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5021      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5022     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
5023   // fold (or x, 0) -> x
5024   if (isNullConstant(N1))
5025     return N0;
5026   // fold (or x, -1) -> -1
5027   if (isAllOnesConstant(N1))
5028     return N1;
5029 
5030   if (SDValue NewSel = foldBinOpIntoSelect(N))
5031     return NewSel;
5032 
5033   // fold (or x, c) -> c iff (x & ~c) == 0
5034   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
5035     return N1;
5036 
5037   if (SDValue Combined = visitORLike(N0, N1, N))
5038     return Combined;
5039 
5040   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
5041   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
5042     return BSwap;
5043   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
5044     return BSwap;
5045 
5046   // reassociate or
5047   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
5048     return ROR;
5049 
5050   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
5051   // iff (c1 & c2) != 0.
5052   auto MatchIntersect = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
5053     return LHS->getAPIntValue().intersects(RHS->getAPIntValue());
5054   };
5055   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5056       ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect)) {
5057     if (SDValue COR = DAG.FoldConstantArithmetic(
5058             ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) {
5059       SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
5060       AddToWorklist(IOR.getNode());
5061       return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR);
5062     }
5063   }
5064 
5065   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
5066   if (N0.getOpcode() == N1.getOpcode())
5067     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5068       return Tmp;
5069 
5070   // See if this is some rotate idiom.
5071   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
5072     return SDValue(Rot, 0);
5073 
5074   if (SDValue Load = MatchLoadCombine(N))
5075     return Load;
5076 
5077   // Simplify the operands using demanded-bits information.
5078   if (SimplifyDemandedBits(SDValue(N, 0)))
5079     return SDValue(N, 0);
5080 
5081   return SDValue();
5082 }
5083 
5084 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
5085 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
5086   if (Op.getOpcode() == ISD::AND) {
5087     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
5088       Mask = Op.getOperand(1);
5089       Op = Op.getOperand(0);
5090     } else {
5091       return false;
5092     }
5093   }
5094 
5095   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
5096     Shift = Op;
5097     return true;
5098   }
5099 
5100   return false;
5101 }
5102 
5103 // Return true if we can prove that, whenever Neg and Pos are both in the
5104 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
5105 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
5106 //
5107 //     (or (shift1 X, Neg), (shift2 X, Pos))
5108 //
5109 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
5110 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
5111 // to consider shift amounts with defined behavior.
5112 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize,
5113                            SelectionDAG &DAG) {
5114   // If EltSize is a power of 2 then:
5115   //
5116   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
5117   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
5118   //
5119   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
5120   // for the stronger condition:
5121   //
5122   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
5123   //
5124   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
5125   // we can just replace Neg with Neg' for the rest of the function.
5126   //
5127   // In other cases we check for the even stronger condition:
5128   //
5129   //     Neg == EltSize - Pos                                    [B]
5130   //
5131   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
5132   // behavior if Pos == 0 (and consequently Neg == EltSize).
5133   //
5134   // We could actually use [A] whenever EltSize is a power of 2, but the
5135   // only extra cases that it would match are those uninteresting ones
5136   // where Neg and Pos are never in range at the same time.  E.g. for
5137   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
5138   // as well as (sub 32, Pos), but:
5139   //
5140   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
5141   //
5142   // always invokes undefined behavior for 32-bit X.
5143   //
5144   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
5145   unsigned MaskLoBits = 0;
5146   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
5147     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
5148       KnownBits Known;
5149       DAG.computeKnownBits(Neg.getOperand(0), Known);
5150       unsigned Bits = Log2_64(EltSize);
5151       if (NegC->getAPIntValue().getActiveBits() <= Bits &&
5152           ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) {
5153         Neg = Neg.getOperand(0);
5154         MaskLoBits = Bits;
5155       }
5156     }
5157   }
5158 
5159   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
5160   if (Neg.getOpcode() != ISD::SUB)
5161     return false;
5162   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
5163   if (!NegC)
5164     return false;
5165   SDValue NegOp1 = Neg.getOperand(1);
5166 
5167   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
5168   // Pos'.  The truncation is redundant for the purpose of the equality.
5169   if (MaskLoBits && Pos.getOpcode() == ISD::AND) {
5170     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) {
5171       KnownBits Known;
5172       DAG.computeKnownBits(Pos.getOperand(0), Known);
5173       if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits &&
5174           ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >=
5175            MaskLoBits))
5176         Pos = Pos.getOperand(0);
5177     }
5178   }
5179 
5180   // The condition we need is now:
5181   //
5182   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
5183   //
5184   // If NegOp1 == Pos then we need:
5185   //
5186   //              EltSize & Mask == NegC & Mask
5187   //
5188   // (because "x & Mask" is a truncation and distributes through subtraction).
5189   APInt Width;
5190   if (Pos == NegOp1)
5191     Width = NegC->getAPIntValue();
5192 
5193   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
5194   // Then the condition we want to prove becomes:
5195   //
5196   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
5197   //
5198   // which, again because "x & Mask" is a truncation, becomes:
5199   //
5200   //                NegC & Mask == (EltSize - PosC) & Mask
5201   //             EltSize & Mask == (NegC + PosC) & Mask
5202   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
5203     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
5204       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
5205     else
5206       return false;
5207   } else
5208     return false;
5209 
5210   // Now we just need to check that EltSize & Mask == Width & Mask.
5211   if (MaskLoBits)
5212     // EltSize & Mask is 0 since Mask is EltSize - 1.
5213     return Width.getLoBits(MaskLoBits) == 0;
5214   return Width == EltSize;
5215 }
5216 
5217 // A subroutine of MatchRotate used once we have found an OR of two opposite
5218 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
5219 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
5220 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
5221 // Neg with outer conversions stripped away.
5222 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
5223                                        SDValue Neg, SDValue InnerPos,
5224                                        SDValue InnerNeg, unsigned PosOpcode,
5225                                        unsigned NegOpcode, const SDLoc &DL) {
5226   // fold (or (shl x, (*ext y)),
5227   //          (srl x, (*ext (sub 32, y)))) ->
5228   //   (rotl x, y) or (rotr x, (sub 32, y))
5229   //
5230   // fold (or (shl x, (*ext (sub 32, y))),
5231   //          (srl x, (*ext y))) ->
5232   //   (rotr x, y) or (rotl x, (sub 32, y))
5233   EVT VT = Shifted.getValueType();
5234   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG)) {
5235     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
5236     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
5237                        HasPos ? Pos : Neg).getNode();
5238   }
5239 
5240   return nullptr;
5241 }
5242 
5243 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
5244 // idioms for rotate, and if the target supports rotation instructions, generate
5245 // a rot[lr].
5246 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
5247   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
5248   EVT VT = LHS.getValueType();
5249   if (!TLI.isTypeLegal(VT)) return nullptr;
5250 
5251   // The target must have at least one rotate flavor.
5252   bool HasROTL = hasOperation(ISD::ROTL, VT);
5253   bool HasROTR = hasOperation(ISD::ROTR, VT);
5254   if (!HasROTL && !HasROTR) return nullptr;
5255 
5256   // Check for truncated rotate.
5257   if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
5258       LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
5259     assert(LHS.getValueType() == RHS.getValueType());
5260     if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) {
5261       return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(),
5262                          SDValue(Rot, 0)).getNode();
5263     }
5264   }
5265 
5266   // Match "(X shl/srl V1) & V2" where V2 may not be present.
5267   SDValue LHSShift;   // The shift.
5268   SDValue LHSMask;    // AND value if any.
5269   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
5270     return nullptr; // Not part of a rotate.
5271 
5272   SDValue RHSShift;   // The shift.
5273   SDValue RHSMask;    // AND value if any.
5274   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
5275     return nullptr; // Not part of a rotate.
5276 
5277   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
5278     return nullptr;   // Not shifting the same value.
5279 
5280   if (LHSShift.getOpcode() == RHSShift.getOpcode())
5281     return nullptr;   // Shifts must disagree.
5282 
5283   // Canonicalize shl to left side in a shl/srl pair.
5284   if (RHSShift.getOpcode() == ISD::SHL) {
5285     std::swap(LHS, RHS);
5286     std::swap(LHSShift, RHSShift);
5287     std::swap(LHSMask, RHSMask);
5288   }
5289 
5290   unsigned EltSizeInBits = VT.getScalarSizeInBits();
5291   SDValue LHSShiftArg = LHSShift.getOperand(0);
5292   SDValue LHSShiftAmt = LHSShift.getOperand(1);
5293   SDValue RHSShiftArg = RHSShift.getOperand(0);
5294   SDValue RHSShiftAmt = RHSShift.getOperand(1);
5295 
5296   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
5297   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
5298   auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
5299                                         ConstantSDNode *RHS) {
5300     return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
5301   };
5302   if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
5303     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
5304                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
5305 
5306     // If there is an AND of either shifted operand, apply it to the result.
5307     if (LHSMask.getNode() || RHSMask.getNode()) {
5308       SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
5309       SDValue Mask = AllOnes;
5310 
5311       if (LHSMask.getNode()) {
5312         SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
5313         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
5314                            DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
5315       }
5316       if (RHSMask.getNode()) {
5317         SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
5318         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
5319                            DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
5320       }
5321 
5322       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
5323     }
5324 
5325     return Rot.getNode();
5326   }
5327 
5328   // If there is a mask here, and we have a variable shift, we can't be sure
5329   // that we're masking out the right stuff.
5330   if (LHSMask.getNode() || RHSMask.getNode())
5331     return nullptr;
5332 
5333   // If the shift amount is sign/zext/any-extended just peel it off.
5334   SDValue LExtOp0 = LHSShiftAmt;
5335   SDValue RExtOp0 = RHSShiftAmt;
5336   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
5337        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
5338        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
5339        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
5340       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
5341        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
5342        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
5343        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
5344     LExtOp0 = LHSShiftAmt.getOperand(0);
5345     RExtOp0 = RHSShiftAmt.getOperand(0);
5346   }
5347 
5348   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
5349                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
5350   if (TryL)
5351     return TryL;
5352 
5353   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
5354                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
5355   if (TryR)
5356     return TryR;
5357 
5358   return nullptr;
5359 }
5360 
5361 namespace {
5362 
5363 /// Represents known origin of an individual byte in load combine pattern. The
5364 /// value of the byte is either constant zero or comes from memory.
5365 struct ByteProvider {
5366   // For constant zero providers Load is set to nullptr. For memory providers
5367   // Load represents the node which loads the byte from memory.
5368   // ByteOffset is the offset of the byte in the value produced by the load.
5369   LoadSDNode *Load = nullptr;
5370   unsigned ByteOffset = 0;
5371 
5372   ByteProvider() = default;
5373 
5374   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
5375     return ByteProvider(Load, ByteOffset);
5376   }
5377 
5378   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
5379 
5380   bool isConstantZero() const { return !Load; }
5381   bool isMemory() const { return Load; }
5382 
5383   bool operator==(const ByteProvider &Other) const {
5384     return Other.Load == Load && Other.ByteOffset == ByteOffset;
5385   }
5386 
5387 private:
5388   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
5389       : Load(Load), ByteOffset(ByteOffset) {}
5390 };
5391 
5392 } // end anonymous namespace
5393 
5394 /// Recursively traverses the expression calculating the origin of the requested
5395 /// byte of the given value. Returns None if the provider can't be calculated.
5396 ///
5397 /// For all the values except the root of the expression verifies that the value
5398 /// has exactly one use and if it's not true return None. This way if the origin
5399 /// of the byte is returned it's guaranteed that the values which contribute to
5400 /// the byte are not used outside of this expression.
5401 ///
5402 /// Because the parts of the expression are not allowed to have more than one
5403 /// use this function iterates over trees, not DAGs. So it never visits the same
5404 /// node more than once.
5405 static const Optional<ByteProvider>
5406 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
5407                       bool Root = false) {
5408   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
5409   if (Depth == 10)
5410     return None;
5411 
5412   if (!Root && !Op.hasOneUse())
5413     return None;
5414 
5415   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
5416   unsigned BitWidth = Op.getValueSizeInBits();
5417   if (BitWidth % 8 != 0)
5418     return None;
5419   unsigned ByteWidth = BitWidth / 8;
5420   assert(Index < ByteWidth && "invalid index requested");
5421   (void) ByteWidth;
5422 
5423   switch (Op.getOpcode()) {
5424   case ISD::OR: {
5425     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
5426     if (!LHS)
5427       return None;
5428     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
5429     if (!RHS)
5430       return None;
5431 
5432     if (LHS->isConstantZero())
5433       return RHS;
5434     if (RHS->isConstantZero())
5435       return LHS;
5436     return None;
5437   }
5438   case ISD::SHL: {
5439     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
5440     if (!ShiftOp)
5441       return None;
5442 
5443     uint64_t BitShift = ShiftOp->getZExtValue();
5444     if (BitShift % 8 != 0)
5445       return None;
5446     uint64_t ByteShift = BitShift / 8;
5447 
5448     return Index < ByteShift
5449                ? ByteProvider::getConstantZero()
5450                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
5451                                        Depth + 1);
5452   }
5453   case ISD::ANY_EXTEND:
5454   case ISD::SIGN_EXTEND:
5455   case ISD::ZERO_EXTEND: {
5456     SDValue NarrowOp = Op->getOperand(0);
5457     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
5458     if (NarrowBitWidth % 8 != 0)
5459       return None;
5460     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5461 
5462     if (Index >= NarrowByteWidth)
5463       return Op.getOpcode() == ISD::ZERO_EXTEND
5464                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5465                  : None;
5466     return calculateByteProvider(NarrowOp, Index, Depth + 1);
5467   }
5468   case ISD::BSWAP:
5469     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
5470                                  Depth + 1);
5471   case ISD::LOAD: {
5472     auto L = cast<LoadSDNode>(Op.getNode());
5473     if (L->isVolatile() || L->isIndexed())
5474       return None;
5475 
5476     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
5477     if (NarrowBitWidth % 8 != 0)
5478       return None;
5479     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5480 
5481     if (Index >= NarrowByteWidth)
5482       return L->getExtensionType() == ISD::ZEXTLOAD
5483                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5484                  : None;
5485     return ByteProvider::getMemory(L, Index);
5486   }
5487   }
5488 
5489   return None;
5490 }
5491 
5492 /// Match a pattern where a wide type scalar value is loaded by several narrow
5493 /// loads and combined by shifts and ors. Fold it into a single load or a load
5494 /// and a BSWAP if the targets supports it.
5495 ///
5496 /// Assuming little endian target:
5497 ///  i8 *a = ...
5498 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
5499 /// =>
5500 ///  i32 val = *((i32)a)
5501 ///
5502 ///  i8 *a = ...
5503 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
5504 /// =>
5505 ///  i32 val = BSWAP(*((i32)a))
5506 ///
5507 /// TODO: This rule matches complex patterns with OR node roots and doesn't
5508 /// interact well with the worklist mechanism. When a part of the pattern is
5509 /// updated (e.g. one of the loads) its direct users are put into the worklist,
5510 /// but the root node of the pattern which triggers the load combine is not
5511 /// necessarily a direct user of the changed node. For example, once the address
5512 /// of t28 load is reassociated load combine won't be triggered:
5513 ///             t25: i32 = add t4, Constant:i32<2>
5514 ///           t26: i64 = sign_extend t25
5515 ///        t27: i64 = add t2, t26
5516 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
5517 ///     t29: i32 = zero_extend t28
5518 ///   t32: i32 = shl t29, Constant:i8<8>
5519 /// t33: i32 = or t23, t32
5520 /// As a possible fix visitLoad can check if the load can be a part of a load
5521 /// combine pattern and add corresponding OR roots to the worklist.
5522 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
5523   assert(N->getOpcode() == ISD::OR &&
5524          "Can only match load combining against OR nodes");
5525 
5526   // Handles simple types only
5527   EVT VT = N->getValueType(0);
5528   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
5529     return SDValue();
5530   unsigned ByteWidth = VT.getSizeInBits() / 8;
5531 
5532   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5533   // Before legalize we can introduce too wide illegal loads which will be later
5534   // split into legal sized loads. This enables us to combine i64 load by i8
5535   // patterns to a couple of i32 loads on 32 bit targets.
5536   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
5537     return SDValue();
5538 
5539   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
5540     unsigned BW, unsigned i) { return i; };
5541   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
5542     unsigned BW, unsigned i) { return BW - i - 1; };
5543 
5544   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
5545   auto MemoryByteOffset = [&] (ByteProvider P) {
5546     assert(P.isMemory() && "Must be a memory byte provider");
5547     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
5548     assert(LoadBitWidth % 8 == 0 &&
5549            "can only analyze providers for individual bytes not bit");
5550     unsigned LoadByteWidth = LoadBitWidth / 8;
5551     return IsBigEndianTarget
5552             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
5553             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
5554   };
5555 
5556   Optional<BaseIndexOffset> Base;
5557   SDValue Chain;
5558 
5559   SmallPtrSet<LoadSDNode *, 8> Loads;
5560   Optional<ByteProvider> FirstByteProvider;
5561   int64_t FirstOffset = INT64_MAX;
5562 
5563   // Check if all the bytes of the OR we are looking at are loaded from the same
5564   // base address. Collect bytes offsets from Base address in ByteOffsets.
5565   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
5566   for (unsigned i = 0; i < ByteWidth; i++) {
5567     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
5568     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
5569       return SDValue();
5570 
5571     LoadSDNode *L = P->Load;
5572     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
5573            "Must be enforced by calculateByteProvider");
5574     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
5575 
5576     // All loads must share the same chain
5577     SDValue LChain = L->getChain();
5578     if (!Chain)
5579       Chain = LChain;
5580     else if (Chain != LChain)
5581       return SDValue();
5582 
5583     // Loads must share the same base address
5584     BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
5585     int64_t ByteOffsetFromBase = 0;
5586     if (!Base)
5587       Base = Ptr;
5588     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
5589       return SDValue();
5590 
5591     // Calculate the offset of the current byte from the base address
5592     ByteOffsetFromBase += MemoryByteOffset(*P);
5593     ByteOffsets[i] = ByteOffsetFromBase;
5594 
5595     // Remember the first byte load
5596     if (ByteOffsetFromBase < FirstOffset) {
5597       FirstByteProvider = P;
5598       FirstOffset = ByteOffsetFromBase;
5599     }
5600 
5601     Loads.insert(L);
5602   }
5603   assert(!Loads.empty() && "All the bytes of the value must be loaded from "
5604          "memory, so there must be at least one load which produces the value");
5605   assert(Base && "Base address of the accessed memory location must be set");
5606   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
5607 
5608   // Check if the bytes of the OR we are looking at match with either big or
5609   // little endian value load
5610   bool BigEndian = true, LittleEndian = true;
5611   for (unsigned i = 0; i < ByteWidth; i++) {
5612     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
5613     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
5614     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
5615     if (!BigEndian && !LittleEndian)
5616       return SDValue();
5617   }
5618   assert((BigEndian != LittleEndian) && "should be either or");
5619   assert(FirstByteProvider && "must be set");
5620 
5621   // Ensure that the first byte is loaded from zero offset of the first load.
5622   // So the combined value can be loaded from the first load address.
5623   if (MemoryByteOffset(*FirstByteProvider) != 0)
5624     return SDValue();
5625   LoadSDNode *FirstLoad = FirstByteProvider->Load;
5626 
5627   // The node we are looking at matches with the pattern, check if we can
5628   // replace it with a single load and bswap if needed.
5629 
5630   // If the load needs byte swap check if the target supports it
5631   bool NeedsBswap = IsBigEndianTarget != BigEndian;
5632 
5633   // Before legalize we can introduce illegal bswaps which will be later
5634   // converted to an explicit bswap sequence. This way we end up with a single
5635   // load and byte shuffling instead of several loads and byte shuffling.
5636   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
5637     return SDValue();
5638 
5639   // Check that a load of the wide type is both allowed and fast on the target
5640   bool Fast = false;
5641   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
5642                                         VT, FirstLoad->getAddressSpace(),
5643                                         FirstLoad->getAlignment(), &Fast);
5644   if (!Allowed || !Fast)
5645     return SDValue();
5646 
5647   SDValue NewLoad =
5648       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
5649                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5650 
5651   // Transfer chain users from old loads to the new load.
5652   for (LoadSDNode *L : Loads)
5653     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5654 
5655   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5656 }
5657 
5658 // If the target has andn, bsl, or a similar bit-select instruction,
5659 // we want to unfold masked merge, with canonical pattern of:
5660 //   |        A  |  |B|
5661 //   ((x ^ y) & m) ^ y
5662 //    |  D  |
5663 // Into:
5664 //   (x & m) | (y & ~m)
5665 // If y is a constant, and the 'andn' does not work with immediates,
5666 // we unfold into a different pattern:
5667 //   ~(~x & m) & (m | y)
5668 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at
5669 //       the very least that breaks andnpd / andnps patterns, and because those
5670 //       patterns are simplified in IR and shouldn't be created in the DAG
5671 SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) {
5672   assert(N->getOpcode() == ISD::XOR);
5673 
5674   // Don't touch 'not' (i.e. where y = -1).
5675   if (isAllOnesConstantOrAllOnesSplatConstant(N->getOperand(1)))
5676     return SDValue();
5677 
5678   EVT VT = N->getValueType(0);
5679 
5680   // There are 3 commutable operators in the pattern,
5681   // so we have to deal with 8 possible variants of the basic pattern.
5682   SDValue X, Y, M;
5683   auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) {
5684     if (And.getOpcode() != ISD::AND || !And.hasOneUse())
5685       return false;
5686     SDValue Xor = And.getOperand(XorIdx);
5687     if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse())
5688       return false;
5689     SDValue Xor0 = Xor.getOperand(0);
5690     SDValue Xor1 = Xor.getOperand(1);
5691     // Don't touch 'not' (i.e. where y = -1).
5692     if (isAllOnesConstantOrAllOnesSplatConstant(Xor1))
5693       return false;
5694     if (Other == Xor0)
5695       std::swap(Xor0, Xor1);
5696     if (Other != Xor1)
5697       return false;
5698     X = Xor0;
5699     Y = Xor1;
5700     M = And.getOperand(XorIdx ? 0 : 1);
5701     return true;
5702   };
5703 
5704   SDValue N0 = N->getOperand(0);
5705   SDValue N1 = N->getOperand(1);
5706   if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) &&
5707       !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0))
5708     return SDValue();
5709 
5710   // Don't do anything if the mask is constant. This should not be reachable.
5711   // InstCombine should have already unfolded this pattern, and DAGCombiner
5712   // probably shouldn't produce it, too.
5713   if (isa<ConstantSDNode>(M.getNode()))
5714     return SDValue();
5715 
5716   // We can transform if the target has AndNot
5717   if (!TLI.hasAndNot(M))
5718     return SDValue();
5719 
5720   SDLoc DL(N);
5721 
5722   // If Y is a constant, check that 'andn' works with immediates.
5723   if (!TLI.hasAndNot(Y)) {
5724     assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable.");
5725     // If not, we need to do a bit more work to make sure andn is still used.
5726     SDValue NotX = DAG.getNOT(DL, X, VT);
5727     SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M);
5728     SDValue NotLHS = DAG.getNOT(DL, LHS, VT);
5729     SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y);
5730     return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS);
5731   }
5732 
5733   SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M);
5734   SDValue NotM = DAG.getNOT(DL, M, VT);
5735   SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM);
5736 
5737   return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
5738 }
5739 
5740 SDValue DAGCombiner::visitXOR(SDNode *N) {
5741   SDValue N0 = N->getOperand(0);
5742   SDValue N1 = N->getOperand(1);
5743   EVT VT = N0.getValueType();
5744 
5745   // fold vector ops
5746   if (VT.isVector()) {
5747     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5748       return FoldedVOp;
5749 
5750     // fold (xor x, 0) -> x, vector edition
5751     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5752       return N1;
5753     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5754       return N0;
5755   }
5756 
5757   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5758   if (N0.isUndef() && N1.isUndef())
5759     return DAG.getConstant(0, SDLoc(N), VT);
5760   // fold (xor x, undef) -> undef
5761   if (N0.isUndef())
5762     return N0;
5763   if (N1.isUndef())
5764     return N1;
5765   // fold (xor c1, c2) -> c1^c2
5766   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5767   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5768   if (N0C && N1C)
5769     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5770   // canonicalize constant to RHS
5771   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5772      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5773     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5774   // fold (xor x, 0) -> x
5775   if (isNullConstant(N1))
5776     return N0;
5777 
5778   if (SDValue NewSel = foldBinOpIntoSelect(N))
5779     return NewSel;
5780 
5781   // reassociate xor
5782   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5783     return RXOR;
5784 
5785   // fold !(x cc y) -> (x !cc y)
5786   SDValue LHS, RHS, CC;
5787   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5788     bool isInt = LHS.getValueType().isInteger();
5789     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5790                                                isInt);
5791 
5792     if (!LegalOperations ||
5793         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5794       switch (N0.getOpcode()) {
5795       default:
5796         llvm_unreachable("Unhandled SetCC Equivalent!");
5797       case ISD::SETCC:
5798         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5799       case ISD::SELECT_CC:
5800         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5801                                N0.getOperand(3), NotCC);
5802       }
5803     }
5804   }
5805 
5806   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5807   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5808       N0.getNode()->hasOneUse() &&
5809       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5810     SDValue V = N0.getOperand(0);
5811     SDLoc DL(N0);
5812     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5813                     DAG.getConstant(1, DL, V.getValueType()));
5814     AddToWorklist(V.getNode());
5815     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5816   }
5817 
5818   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5819   if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() &&
5820       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5821     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5822     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5823       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5824       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5825       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5826       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5827       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5828     }
5829   }
5830   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5831   if (isAllOnesConstant(N1) && N0.hasOneUse() &&
5832       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5833     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5834     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5835       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5836       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5837       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5838       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5839       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5840     }
5841   }
5842   // fold (xor (and x, y), y) -> (and (not x), y)
5843   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5844       N0->getOperand(1) == N1) {
5845     SDValue X = N0->getOperand(0);
5846     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5847     AddToWorklist(NotX.getNode());
5848     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5849   }
5850 
5851   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5852   if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5853     SDValue A = N0.getOpcode() == ISD::ADD ? N0 : N1;
5854     SDValue S = N0.getOpcode() == ISD::SRA ? N0 : N1;
5855     if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) {
5856       SDValue A0 = A.getOperand(0), A1 = A.getOperand(1);
5857       SDValue S0 = S.getOperand(0);
5858       if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0)) {
5859         unsigned OpSizeInBits = VT.getScalarSizeInBits();
5860         if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1)))
5861           if (C->getAPIntValue() == (OpSizeInBits - 1))
5862             return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0);
5863       }
5864     }
5865   }
5866 
5867   // fold (xor x, x) -> 0
5868   if (N0 == N1)
5869     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5870 
5871   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5872   // Here is a concrete example of this equivalence:
5873   // i16   x ==  14
5874   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5875   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5876   //
5877   // =>
5878   //
5879   // i16     ~1      == 0b1111111111111110
5880   // i16 rol(~1, 14) == 0b1011111111111111
5881   //
5882   // Some additional tips to help conceptualize this transform:
5883   // - Try to see the operation as placing a single zero in a value of all ones.
5884   // - There exists no value for x which would allow the result to contain zero.
5885   // - Values of x larger than the bitwidth are undefined and do not require a
5886   //   consistent result.
5887   // - Pushing the zero left requires shifting one bits in from the right.
5888   // A rotate left of ~1 is a nice way of achieving the desired result.
5889   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5890       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5891     SDLoc DL(N);
5892     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5893                        N0.getOperand(1));
5894   }
5895 
5896   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5897   if (N0.getOpcode() == N1.getOpcode())
5898     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5899       return Tmp;
5900 
5901   // Unfold  ((x ^ y) & m) ^ y  into  (x & m) | (y & ~m)  if profitable
5902   if (SDValue MM = unfoldMaskedMerge(N))
5903     return MM;
5904 
5905   // Simplify the expression using non-local knowledge.
5906   if (SimplifyDemandedBits(SDValue(N, 0)))
5907     return SDValue(N, 0);
5908 
5909   return SDValue();
5910 }
5911 
5912 /// Handle transforms common to the three shifts, when the shift amount is a
5913 /// constant.
5914 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5915   SDNode *LHS = N->getOperand(0).getNode();
5916   if (!LHS->hasOneUse()) return SDValue();
5917 
5918   // We want to pull some binops through shifts, so that we have (and (shift))
5919   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5920   // thing happens with address calculations, so it's important to canonicalize
5921   // it.
5922   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5923 
5924   switch (LHS->getOpcode()) {
5925   default: return SDValue();
5926   case ISD::OR:
5927   case ISD::XOR:
5928     HighBitSet = false; // We can only transform sra if the high bit is clear.
5929     break;
5930   case ISD::AND:
5931     HighBitSet = true;  // We can only transform sra if the high bit is set.
5932     break;
5933   case ISD::ADD:
5934     if (N->getOpcode() != ISD::SHL)
5935       return SDValue(); // only shl(add) not sr[al](add).
5936     HighBitSet = false; // We can only transform sra if the high bit is clear.
5937     break;
5938   }
5939 
5940   // We require the RHS of the binop to be a constant and not opaque as well.
5941   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5942   if (!BinOpCst) return SDValue();
5943 
5944   // FIXME: disable this unless the input to the binop is a shift by a constant
5945   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5946   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5947   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5948                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5949                  BinOpLHSVal->getOpcode() == ISD::SRL;
5950   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5951                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5952 
5953   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5954       !isCopyOrSelect)
5955     return SDValue();
5956 
5957   if (isCopyOrSelect && N->hasOneUse())
5958     return SDValue();
5959 
5960   EVT VT = N->getValueType(0);
5961 
5962   // If this is a signed shift right, and the high bit is modified by the
5963   // logical operation, do not perform the transformation. The highBitSet
5964   // boolean indicates the value of the high bit of the constant which would
5965   // cause it to be modified for this operation.
5966   if (N->getOpcode() == ISD::SRA) {
5967     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5968     if (BinOpRHSSignSet != HighBitSet)
5969       return SDValue();
5970   }
5971 
5972   if (!TLI.isDesirableToCommuteWithShift(LHS))
5973     return SDValue();
5974 
5975   // Fold the constants, shifting the binop RHS by the shift amount.
5976   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5977                                N->getValueType(0),
5978                                LHS->getOperand(1), N->getOperand(1));
5979   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5980 
5981   // Create the new shift.
5982   SDValue NewShift = DAG.getNode(N->getOpcode(),
5983                                  SDLoc(LHS->getOperand(0)),
5984                                  VT, LHS->getOperand(0), N->getOperand(1));
5985 
5986   // Create the new binop.
5987   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5988 }
5989 
5990 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5991   assert(N->getOpcode() == ISD::TRUNCATE);
5992   assert(N->getOperand(0).getOpcode() == ISD::AND);
5993 
5994   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5995   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5996     SDValue N01 = N->getOperand(0).getOperand(1);
5997     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5998       SDLoc DL(N);
5999       EVT TruncVT = N->getValueType(0);
6000       SDValue N00 = N->getOperand(0).getOperand(0);
6001       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
6002       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
6003       AddToWorklist(Trunc00.getNode());
6004       AddToWorklist(Trunc01.getNode());
6005       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
6006     }
6007   }
6008 
6009   return SDValue();
6010 }
6011 
6012 SDValue DAGCombiner::visitRotate(SDNode *N) {
6013   SDLoc dl(N);
6014   SDValue N0 = N->getOperand(0);
6015   SDValue N1 = N->getOperand(1);
6016   EVT VT = N->getValueType(0);
6017   unsigned Bitsize = VT.getScalarSizeInBits();
6018 
6019   // fold (rot x, 0) -> x
6020   if (isNullConstantOrNullSplatConstant(N1))
6021     return N0;
6022 
6023   // fold (rot x, c) -> (rot x, c % BitSize)
6024   if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
6025     if (Cst->getAPIntValue().uge(Bitsize)) {
6026       uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
6027       return DAG.getNode(N->getOpcode(), dl, VT, N0,
6028                          DAG.getConstant(RotAmt, dl, N1.getValueType()));
6029     }
6030   }
6031 
6032   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
6033   if (N1.getOpcode() == ISD::TRUNCATE &&
6034       N1.getOperand(0).getOpcode() == ISD::AND) {
6035     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6036       return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
6037   }
6038 
6039   unsigned NextOp = N0.getOpcode();
6040   // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
6041   if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
6042     SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
6043     SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
6044     if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
6045       EVT ShiftVT = C1->getValueType(0);
6046       bool SameSide = (N->getOpcode() == NextOp);
6047       unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
6048       if (SDValue CombinedShift =
6049               DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
6050         SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
6051         SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
6052             ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
6053             BitsizeC.getNode());
6054         return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
6055                            CombinedShiftNorm);
6056       }
6057     }
6058   }
6059   return SDValue();
6060 }
6061 
6062 SDValue DAGCombiner::visitSHL(SDNode *N) {
6063   SDValue N0 = N->getOperand(0);
6064   SDValue N1 = N->getOperand(1);
6065   EVT VT = N0.getValueType();
6066   unsigned OpSizeInBits = VT.getScalarSizeInBits();
6067 
6068   // fold vector ops
6069   if (VT.isVector()) {
6070     if (SDValue FoldedVOp = SimplifyVBinOp(N))
6071       return FoldedVOp;
6072 
6073     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
6074     // If setcc produces all-one true value then:
6075     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
6076     if (N1CV && N1CV->isConstant()) {
6077       if (N0.getOpcode() == ISD::AND) {
6078         SDValue N00 = N0->getOperand(0);
6079         SDValue N01 = N0->getOperand(1);
6080         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
6081 
6082         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
6083             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
6084                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6085           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
6086                                                      N01CV, N1CV))
6087             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
6088         }
6089       }
6090     }
6091   }
6092 
6093   ConstantSDNode *N1C = isConstOrConstSplat(N1);
6094 
6095   // fold (shl c1, c2) -> c1<<c2
6096   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
6097   if (N0C && N1C && !N1C->isOpaque())
6098     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
6099   // fold (shl 0, x) -> 0
6100   if (isNullConstantOrNullSplatConstant(N0))
6101     return N0;
6102   // fold (shl x, c >= size(x)) -> undef
6103   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
6104   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
6105     return Val->getAPIntValue().uge(OpSizeInBits);
6106   };
6107   if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig))
6108     return DAG.getUNDEF(VT);
6109   // fold (shl x, 0) -> x
6110   if (N1C && N1C->isNullValue())
6111     return N0;
6112   // fold (shl undef, x) -> 0
6113   if (N0.isUndef())
6114     return DAG.getConstant(0, SDLoc(N), VT);
6115 
6116   if (SDValue NewSel = foldBinOpIntoSelect(N))
6117     return NewSel;
6118 
6119   // if (shl x, c) is known to be zero, return 0
6120   if (DAG.MaskedValueIsZero(SDValue(N, 0),
6121                             APInt::getAllOnesValue(OpSizeInBits)))
6122     return DAG.getConstant(0, SDLoc(N), VT);
6123   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
6124   if (N1.getOpcode() == ISD::TRUNCATE &&
6125       N1.getOperand(0).getOpcode() == ISD::AND) {
6126     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6127       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
6128   }
6129 
6130   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6131     return SDValue(N, 0);
6132 
6133   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
6134   if (N0.getOpcode() == ISD::SHL) {
6135     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
6136                                           ConstantSDNode *RHS) {
6137       APInt c1 = LHS->getAPIntValue();
6138       APInt c2 = RHS->getAPIntValue();
6139       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6140       return (c1 + c2).uge(OpSizeInBits);
6141     };
6142     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
6143       return DAG.getConstant(0, SDLoc(N), VT);
6144 
6145     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
6146                                        ConstantSDNode *RHS) {
6147       APInt c1 = LHS->getAPIntValue();
6148       APInt c2 = RHS->getAPIntValue();
6149       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6150       return (c1 + c2).ult(OpSizeInBits);
6151     };
6152     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
6153       SDLoc DL(N);
6154       EVT ShiftVT = N1.getValueType();
6155       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
6156       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
6157     }
6158   }
6159 
6160   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
6161   // For this to be valid, the second form must not preserve any of the bits
6162   // that are shifted out by the inner shift in the first form.  This means
6163   // the outer shift size must be >= the number of bits added by the ext.
6164   // As a corollary, we don't care what kind of ext it is.
6165   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
6166               N0.getOpcode() == ISD::ANY_EXTEND ||
6167               N0.getOpcode() == ISD::SIGN_EXTEND) &&
6168       N0.getOperand(0).getOpcode() == ISD::SHL) {
6169     SDValue N0Op0 = N0.getOperand(0);
6170     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
6171       APInt c1 = N0Op0C1->getAPIntValue();
6172       APInt c2 = N1C->getAPIntValue();
6173       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6174 
6175       EVT InnerShiftVT = N0Op0.getValueType();
6176       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
6177       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
6178         SDLoc DL(N0);
6179         APInt Sum = c1 + c2;
6180         if (Sum.uge(OpSizeInBits))
6181           return DAG.getConstant(0, DL, VT);
6182 
6183         return DAG.getNode(
6184             ISD::SHL, DL, VT,
6185             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
6186             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
6187       }
6188     }
6189   }
6190 
6191   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
6192   // Only fold this if the inner zext has no other uses to avoid increasing
6193   // the total number of instructions.
6194   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
6195       N0.getOperand(0).getOpcode() == ISD::SRL) {
6196     SDValue N0Op0 = N0.getOperand(0);
6197     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
6198       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
6199         uint64_t c1 = N0Op0C1->getZExtValue();
6200         uint64_t c2 = N1C->getZExtValue();
6201         if (c1 == c2) {
6202           SDValue NewOp0 = N0.getOperand(0);
6203           EVT CountVT = NewOp0.getOperand(1).getValueType();
6204           SDLoc DL(N);
6205           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
6206                                        NewOp0,
6207                                        DAG.getConstant(c2, DL, CountVT));
6208           AddToWorklist(NewSHL.getNode());
6209           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
6210         }
6211       }
6212     }
6213   }
6214 
6215   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
6216   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
6217   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
6218       N0->getFlags().hasExact()) {
6219     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
6220       uint64_t C1 = N0C1->getZExtValue();
6221       uint64_t C2 = N1C->getZExtValue();
6222       SDLoc DL(N);
6223       if (C1 <= C2)
6224         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
6225                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
6226       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
6227                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
6228     }
6229   }
6230 
6231   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
6232   //                               (and (srl x, (sub c1, c2), MASK)
6233   // Only fold this if the inner shift has no other uses -- if it does, folding
6234   // this will increase the total number of instructions.
6235   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6236     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
6237       uint64_t c1 = N0C1->getZExtValue();
6238       if (c1 < OpSizeInBits) {
6239         uint64_t c2 = N1C->getZExtValue();
6240         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
6241         SDValue Shift;
6242         if (c2 > c1) {
6243           Mask <<= c2 - c1;
6244           SDLoc DL(N);
6245           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
6246                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
6247         } else {
6248           Mask.lshrInPlace(c1 - c2);
6249           SDLoc DL(N);
6250           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
6251                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
6252         }
6253         SDLoc DL(N0);
6254         return DAG.getNode(ISD::AND, DL, VT, Shift,
6255                            DAG.getConstant(Mask, DL, VT));
6256       }
6257     }
6258   }
6259 
6260   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
6261   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
6262       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
6263     SDLoc DL(N);
6264     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
6265     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
6266     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
6267   }
6268 
6269   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
6270   // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
6271   // Variant of version done on multiply, except mul by a power of 2 is turned
6272   // into a shift.
6273   if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
6274       N0.getNode()->hasOneUse() &&
6275       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
6276       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
6277     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
6278     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
6279     AddToWorklist(Shl0.getNode());
6280     AddToWorklist(Shl1.getNode());
6281     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
6282   }
6283 
6284   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
6285   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
6286       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
6287       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
6288     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
6289     if (isConstantOrConstantVector(Shl))
6290       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
6291   }
6292 
6293   if (N1C && !N1C->isOpaque())
6294     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
6295       return NewSHL;
6296 
6297   return SDValue();
6298 }
6299 
6300 SDValue DAGCombiner::visitSRA(SDNode *N) {
6301   SDValue N0 = N->getOperand(0);
6302   SDValue N1 = N->getOperand(1);
6303   EVT VT = N0.getValueType();
6304   unsigned OpSizeInBits = VT.getScalarSizeInBits();
6305 
6306   // Arithmetic shifting an all-sign-bit value is a no-op.
6307   // fold (sra 0, x) -> 0
6308   // fold (sra -1, x) -> -1
6309   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
6310     return N0;
6311 
6312   // fold vector ops
6313   if (VT.isVector())
6314     if (SDValue FoldedVOp = SimplifyVBinOp(N))
6315       return FoldedVOp;
6316 
6317   ConstantSDNode *N1C = isConstOrConstSplat(N1);
6318 
6319   // fold (sra c1, c2) -> (sra c1, c2)
6320   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
6321   if (N0C && N1C && !N1C->isOpaque())
6322     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
6323   // fold (sra x, c >= size(x)) -> undef
6324   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
6325   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
6326     return Val->getAPIntValue().uge(OpSizeInBits);
6327   };
6328   if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig))
6329     return DAG.getUNDEF(VT);
6330   // fold (sra x, 0) -> x
6331   if (N1C && N1C->isNullValue())
6332     return N0;
6333 
6334   if (SDValue NewSel = foldBinOpIntoSelect(N))
6335     return NewSel;
6336 
6337   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
6338   // sext_inreg.
6339   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
6340     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
6341     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
6342     if (VT.isVector())
6343       ExtVT = EVT::getVectorVT(*DAG.getContext(),
6344                                ExtVT, VT.getVectorNumElements());
6345     if ((!LegalOperations ||
6346          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
6347       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6348                          N0.getOperand(0), DAG.getValueType(ExtVT));
6349   }
6350 
6351   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
6352   if (N0.getOpcode() == ISD::SRA) {
6353     SDLoc DL(N);
6354     EVT ShiftVT = N1.getValueType();
6355 
6356     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
6357                                           ConstantSDNode *RHS) {
6358       APInt c1 = LHS->getAPIntValue();
6359       APInt c2 = RHS->getAPIntValue();
6360       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6361       return (c1 + c2).uge(OpSizeInBits);
6362     };
6363     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
6364       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
6365                          DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT));
6366 
6367     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
6368                                        ConstantSDNode *RHS) {
6369       APInt c1 = LHS->getAPIntValue();
6370       APInt c2 = RHS->getAPIntValue();
6371       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6372       return (c1 + c2).ult(OpSizeInBits);
6373     };
6374     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
6375       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
6376       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum);
6377     }
6378   }
6379 
6380   // fold (sra (shl X, m), (sub result_size, n))
6381   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
6382   // result_size - n != m.
6383   // If truncate is free for the target sext(shl) is likely to result in better
6384   // code.
6385   if (N0.getOpcode() == ISD::SHL && N1C) {
6386     // Get the two constanst of the shifts, CN0 = m, CN = n.
6387     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
6388     if (N01C) {
6389       LLVMContext &Ctx = *DAG.getContext();
6390       // Determine what the truncate's result bitsize and type would be.
6391       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
6392 
6393       if (VT.isVector())
6394         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
6395 
6396       // Determine the residual right-shift amount.
6397       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
6398 
6399       // If the shift is not a no-op (in which case this should be just a sign
6400       // extend already), the truncated to type is legal, sign_extend is legal
6401       // on that type, and the truncate to that type is both legal and free,
6402       // perform the transform.
6403       if ((ShiftAmt > 0) &&
6404           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
6405           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
6406           TLI.isTruncateFree(VT, TruncVT)) {
6407         SDLoc DL(N);
6408         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
6409             getShiftAmountTy(N0.getOperand(0).getValueType()));
6410         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
6411                                     N0.getOperand(0), Amt);
6412         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
6413                                     Shift);
6414         return DAG.getNode(ISD::SIGN_EXTEND, DL,
6415                            N->getValueType(0), Trunc);
6416       }
6417     }
6418   }
6419 
6420   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
6421   if (N1.getOpcode() == ISD::TRUNCATE &&
6422       N1.getOperand(0).getOpcode() == ISD::AND) {
6423     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6424       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
6425   }
6426 
6427   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
6428   //      if c1 is equal to the number of bits the trunc removes
6429   if (N0.getOpcode() == ISD::TRUNCATE &&
6430       (N0.getOperand(0).getOpcode() == ISD::SRL ||
6431        N0.getOperand(0).getOpcode() == ISD::SRA) &&
6432       N0.getOperand(0).hasOneUse() &&
6433       N0.getOperand(0).getOperand(1).hasOneUse() &&
6434       N1C) {
6435     SDValue N0Op0 = N0.getOperand(0);
6436     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
6437       unsigned LargeShiftVal = LargeShift->getZExtValue();
6438       EVT LargeVT = N0Op0.getValueType();
6439 
6440       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
6441         SDLoc DL(N);
6442         SDValue Amt =
6443           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
6444                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
6445         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
6446                                   N0Op0.getOperand(0), Amt);
6447         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
6448       }
6449     }
6450   }
6451 
6452   // Simplify, based on bits shifted out of the LHS.
6453   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6454     return SDValue(N, 0);
6455 
6456   // If the sign bit is known to be zero, switch this to a SRL.
6457   if (DAG.SignBitIsZero(N0))
6458     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
6459 
6460   if (N1C && !N1C->isOpaque())
6461     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
6462       return NewSRA;
6463 
6464   return SDValue();
6465 }
6466 
6467 SDValue DAGCombiner::visitSRL(SDNode *N) {
6468   SDValue N0 = N->getOperand(0);
6469   SDValue N1 = N->getOperand(1);
6470   EVT VT = N0.getValueType();
6471   unsigned OpSizeInBits = VT.getScalarSizeInBits();
6472 
6473   // fold vector ops
6474   if (VT.isVector())
6475     if (SDValue FoldedVOp = SimplifyVBinOp(N))
6476       return FoldedVOp;
6477 
6478   ConstantSDNode *N1C = isConstOrConstSplat(N1);
6479 
6480   // fold (srl c1, c2) -> c1 >>u c2
6481   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
6482   if (N0C && N1C && !N1C->isOpaque())
6483     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
6484   // fold (srl 0, x) -> 0
6485   if (isNullConstantOrNullSplatConstant(N0))
6486     return N0;
6487   // fold (srl x, c >= size(x)) -> undef
6488   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
6489   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
6490     return Val->getAPIntValue().uge(OpSizeInBits);
6491   };
6492   if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig))
6493     return DAG.getUNDEF(VT);
6494   // fold (srl x, 0) -> x
6495   if (N1C && N1C->isNullValue())
6496     return N0;
6497 
6498   if (SDValue NewSel = foldBinOpIntoSelect(N))
6499     return NewSel;
6500 
6501   // if (srl x, c) is known to be zero, return 0
6502   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
6503                                    APInt::getAllOnesValue(OpSizeInBits)))
6504     return DAG.getConstant(0, SDLoc(N), VT);
6505 
6506   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
6507   if (N0.getOpcode() == ISD::SRL) {
6508     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
6509                                           ConstantSDNode *RHS) {
6510       APInt c1 = LHS->getAPIntValue();
6511       APInt c2 = RHS->getAPIntValue();
6512       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6513       return (c1 + c2).uge(OpSizeInBits);
6514     };
6515     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
6516       return DAG.getConstant(0, SDLoc(N), VT);
6517 
6518     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
6519                                        ConstantSDNode *RHS) {
6520       APInt c1 = LHS->getAPIntValue();
6521       APInt c2 = RHS->getAPIntValue();
6522       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6523       return (c1 + c2).ult(OpSizeInBits);
6524     };
6525     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
6526       SDLoc DL(N);
6527       EVT ShiftVT = N1.getValueType();
6528       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
6529       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
6530     }
6531   }
6532 
6533   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
6534   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
6535       N0.getOperand(0).getOpcode() == ISD::SRL) {
6536     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
6537       uint64_t c1 = N001C->getZExtValue();
6538       uint64_t c2 = N1C->getZExtValue();
6539       EVT InnerShiftVT = N0.getOperand(0).getValueType();
6540       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
6541       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
6542       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
6543       if (c1 + OpSizeInBits == InnerShiftSize) {
6544         SDLoc DL(N0);
6545         if (c1 + c2 >= InnerShiftSize)
6546           return DAG.getConstant(0, DL, VT);
6547         return DAG.getNode(ISD::TRUNCATE, DL, VT,
6548                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
6549                                        N0.getOperand(0).getOperand(0),
6550                                        DAG.getConstant(c1 + c2, DL,
6551                                                        ShiftCountVT)));
6552       }
6553     }
6554   }
6555 
6556   // fold (srl (shl x, c), c) -> (and x, cst2)
6557   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
6558       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
6559     SDLoc DL(N);
6560     SDValue Mask =
6561         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
6562     AddToWorklist(Mask.getNode());
6563     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
6564   }
6565 
6566   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
6567   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
6568     // Shifting in all undef bits?
6569     EVT SmallVT = N0.getOperand(0).getValueType();
6570     unsigned BitSize = SmallVT.getScalarSizeInBits();
6571     if (N1C->getZExtValue() >= BitSize)
6572       return DAG.getUNDEF(VT);
6573 
6574     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
6575       uint64_t ShiftAmt = N1C->getZExtValue();
6576       SDLoc DL0(N0);
6577       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
6578                                        N0.getOperand(0),
6579                           DAG.getConstant(ShiftAmt, DL0,
6580                                           getShiftAmountTy(SmallVT)));
6581       AddToWorklist(SmallShift.getNode());
6582       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
6583       SDLoc DL(N);
6584       return DAG.getNode(ISD::AND, DL, VT,
6585                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
6586                          DAG.getConstant(Mask, DL, VT));
6587     }
6588   }
6589 
6590   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
6591   // bit, which is unmodified by sra.
6592   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
6593     if (N0.getOpcode() == ISD::SRA)
6594       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
6595   }
6596 
6597   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
6598   if (N1C && N0.getOpcode() == ISD::CTLZ &&
6599       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
6600     KnownBits Known;
6601     DAG.computeKnownBits(N0.getOperand(0), Known);
6602 
6603     // If any of the input bits are KnownOne, then the input couldn't be all
6604     // zeros, thus the result of the srl will always be zero.
6605     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
6606 
6607     // If all of the bits input the to ctlz node are known to be zero, then
6608     // the result of the ctlz is "32" and the result of the shift is one.
6609     APInt UnknownBits = ~Known.Zero;
6610     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
6611 
6612     // Otherwise, check to see if there is exactly one bit input to the ctlz.
6613     if (UnknownBits.isPowerOf2()) {
6614       // Okay, we know that only that the single bit specified by UnknownBits
6615       // could be set on input to the CTLZ node. If this bit is set, the SRL
6616       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
6617       // to an SRL/XOR pair, which is likely to simplify more.
6618       unsigned ShAmt = UnknownBits.countTrailingZeros();
6619       SDValue Op = N0.getOperand(0);
6620 
6621       if (ShAmt) {
6622         SDLoc DL(N0);
6623         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
6624                   DAG.getConstant(ShAmt, DL,
6625                                   getShiftAmountTy(Op.getValueType())));
6626         AddToWorklist(Op.getNode());
6627       }
6628 
6629       SDLoc DL(N);
6630       return DAG.getNode(ISD::XOR, DL, VT,
6631                          Op, DAG.getConstant(1, DL, VT));
6632     }
6633   }
6634 
6635   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
6636   if (N1.getOpcode() == ISD::TRUNCATE &&
6637       N1.getOperand(0).getOpcode() == ISD::AND) {
6638     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6639       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
6640   }
6641 
6642   // fold operands of srl based on knowledge that the low bits are not
6643   // demanded.
6644   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6645     return SDValue(N, 0);
6646 
6647   if (N1C && !N1C->isOpaque())
6648     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
6649       return NewSRL;
6650 
6651   // Attempt to convert a srl of a load into a narrower zero-extending load.
6652   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6653     return NarrowLoad;
6654 
6655   // Here is a common situation. We want to optimize:
6656   //
6657   //   %a = ...
6658   //   %b = and i32 %a, 2
6659   //   %c = srl i32 %b, 1
6660   //   brcond i32 %c ...
6661   //
6662   // into
6663   //
6664   //   %a = ...
6665   //   %b = and %a, 2
6666   //   %c = setcc eq %b, 0
6667   //   brcond %c ...
6668   //
6669   // However when after the source operand of SRL is optimized into AND, the SRL
6670   // itself may not be optimized further. Look for it and add the BRCOND into
6671   // the worklist.
6672   if (N->hasOneUse()) {
6673     SDNode *Use = *N->use_begin();
6674     if (Use->getOpcode() == ISD::BRCOND)
6675       AddToWorklist(Use);
6676     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
6677       // Also look pass the truncate.
6678       Use = *Use->use_begin();
6679       if (Use->getOpcode() == ISD::BRCOND)
6680         AddToWorklist(Use);
6681     }
6682   }
6683 
6684   return SDValue();
6685 }
6686 
6687 SDValue DAGCombiner::visitABS(SDNode *N) {
6688   SDValue N0 = N->getOperand(0);
6689   EVT VT = N->getValueType(0);
6690 
6691   // fold (abs c1) -> c2
6692   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6693     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
6694   // fold (abs (abs x)) -> (abs x)
6695   if (N0.getOpcode() == ISD::ABS)
6696     return N0;
6697   // fold (abs x) -> x iff not-negative
6698   if (DAG.SignBitIsZero(N0))
6699     return N0;
6700   return SDValue();
6701 }
6702 
6703 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
6704   SDValue N0 = N->getOperand(0);
6705   EVT VT = N->getValueType(0);
6706 
6707   // fold (bswap c1) -> c2
6708   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6709     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
6710   // fold (bswap (bswap x)) -> x
6711   if (N0.getOpcode() == ISD::BSWAP)
6712     return N0->getOperand(0);
6713   return SDValue();
6714 }
6715 
6716 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
6717   SDValue N0 = N->getOperand(0);
6718   EVT VT = N->getValueType(0);
6719 
6720   // fold (bitreverse c1) -> c2
6721   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6722     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
6723   // fold (bitreverse (bitreverse x)) -> x
6724   if (N0.getOpcode() == ISD::BITREVERSE)
6725     return N0.getOperand(0);
6726   return SDValue();
6727 }
6728 
6729 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
6730   SDValue N0 = N->getOperand(0);
6731   EVT VT = N->getValueType(0);
6732 
6733   // fold (ctlz c1) -> c2
6734   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6735     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
6736 
6737   // If the value is known never to be zero, switch to the undef version.
6738   if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) {
6739     if (DAG.isKnownNeverZero(N0))
6740       return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6741   }
6742 
6743   return SDValue();
6744 }
6745 
6746 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
6747   SDValue N0 = N->getOperand(0);
6748   EVT VT = N->getValueType(0);
6749 
6750   // fold (ctlz_zero_undef c1) -> c2
6751   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6752     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6753   return SDValue();
6754 }
6755 
6756 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
6757   SDValue N0 = N->getOperand(0);
6758   EVT VT = N->getValueType(0);
6759 
6760   // fold (cttz c1) -> c2
6761   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6762     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
6763 
6764   // If the value is known never to be zero, switch to the undef version.
6765   if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) {
6766     if (DAG.isKnownNeverZero(N0))
6767       return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6768   }
6769 
6770   return SDValue();
6771 }
6772 
6773 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
6774   SDValue N0 = N->getOperand(0);
6775   EVT VT = N->getValueType(0);
6776 
6777   // fold (cttz_zero_undef c1) -> c2
6778   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6779     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6780   return SDValue();
6781 }
6782 
6783 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6784   SDValue N0 = N->getOperand(0);
6785   EVT VT = N->getValueType(0);
6786 
6787   // fold (ctpop c1) -> c2
6788   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6789     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6790   return SDValue();
6791 }
6792 
6793 /// Generate Min/Max node
6794 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6795                                    SDValue RHS, SDValue True, SDValue False,
6796                                    ISD::CondCode CC, const TargetLowering &TLI,
6797                                    SelectionDAG &DAG) {
6798   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6799     return SDValue();
6800 
6801   switch (CC) {
6802   case ISD::SETOLT:
6803   case ISD::SETOLE:
6804   case ISD::SETLT:
6805   case ISD::SETLE:
6806   case ISD::SETULT:
6807   case ISD::SETULE: {
6808     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6809     if (TLI.isOperationLegal(Opcode, VT))
6810       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6811     return SDValue();
6812   }
6813   case ISD::SETOGT:
6814   case ISD::SETOGE:
6815   case ISD::SETGT:
6816   case ISD::SETGE:
6817   case ISD::SETUGT:
6818   case ISD::SETUGE: {
6819     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6820     if (TLI.isOperationLegal(Opcode, VT))
6821       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6822     return SDValue();
6823   }
6824   default:
6825     return SDValue();
6826   }
6827 }
6828 
6829 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6830   SDValue Cond = N->getOperand(0);
6831   SDValue N1 = N->getOperand(1);
6832   SDValue N2 = N->getOperand(2);
6833   EVT VT = N->getValueType(0);
6834   EVT CondVT = Cond.getValueType();
6835   SDLoc DL(N);
6836 
6837   if (!VT.isInteger())
6838     return SDValue();
6839 
6840   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6841   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6842   if (!C1 || !C2)
6843     return SDValue();
6844 
6845   // Only do this before legalization to avoid conflicting with target-specific
6846   // transforms in the other direction (create a select from a zext/sext). There
6847   // is also a target-independent combine here in DAGCombiner in the other
6848   // direction for (select Cond, -1, 0) when the condition is not i1.
6849   if (CondVT == MVT::i1 && !LegalOperations) {
6850     if (C1->isNullValue() && C2->isOne()) {
6851       // select Cond, 0, 1 --> zext (!Cond)
6852       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6853       if (VT != MVT::i1)
6854         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6855       return NotCond;
6856     }
6857     if (C1->isNullValue() && C2->isAllOnesValue()) {
6858       // select Cond, 0, -1 --> sext (!Cond)
6859       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6860       if (VT != MVT::i1)
6861         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6862       return NotCond;
6863     }
6864     if (C1->isOne() && C2->isNullValue()) {
6865       // select Cond, 1, 0 --> zext (Cond)
6866       if (VT != MVT::i1)
6867         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6868       return Cond;
6869     }
6870     if (C1->isAllOnesValue() && C2->isNullValue()) {
6871       // select Cond, -1, 0 --> sext (Cond)
6872       if (VT != MVT::i1)
6873         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6874       return Cond;
6875     }
6876 
6877     // For any constants that differ by 1, we can transform the select into an
6878     // extend and add. Use a target hook because some targets may prefer to
6879     // transform in the other direction.
6880     if (TLI.convertSelectOfConstantsToMath(VT)) {
6881       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6882         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6883         if (VT != MVT::i1)
6884           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6885         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6886       }
6887       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6888         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6889         if (VT != MVT::i1)
6890           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6891         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6892       }
6893     }
6894 
6895     return SDValue();
6896   }
6897 
6898   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6899   // We can't do this reliably if integer based booleans have different contents
6900   // to floating point based booleans. This is because we can't tell whether we
6901   // have an integer-based boolean or a floating-point-based boolean unless we
6902   // can find the SETCC that produced it and inspect its operands. This is
6903   // fairly easy if C is the SETCC node, but it can potentially be
6904   // undiscoverable (or not reasonably discoverable). For example, it could be
6905   // in another basic block or it could require searching a complicated
6906   // expression.
6907   if (CondVT.isInteger() &&
6908       TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) ==
6909           TargetLowering::ZeroOrOneBooleanContent &&
6910       TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) ==
6911           TargetLowering::ZeroOrOneBooleanContent &&
6912       C1->isNullValue() && C2->isOne()) {
6913     SDValue NotCond =
6914         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6915     if (VT.bitsEq(CondVT))
6916       return NotCond;
6917     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6918   }
6919 
6920   return SDValue();
6921 }
6922 
6923 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6924   SDValue N0 = N->getOperand(0);
6925   SDValue N1 = N->getOperand(1);
6926   SDValue N2 = N->getOperand(2);
6927   EVT VT = N->getValueType(0);
6928   EVT VT0 = N0.getValueType();
6929   SDLoc DL(N);
6930 
6931   // fold (select C, X, X) -> X
6932   if (N1 == N2)
6933     return N1;
6934 
6935   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6936     // fold (select true, X, Y) -> X
6937     // fold (select false, X, Y) -> Y
6938     return !N0C->isNullValue() ? N1 : N2;
6939   }
6940 
6941   // fold (select X, X, Y) -> (or X, Y)
6942   // fold (select X, 1, Y) -> (or C, Y)
6943   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6944     return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6945 
6946   if (SDValue V = foldSelectOfConstants(N))
6947     return V;
6948 
6949   // fold (select C, 0, X) -> (and (not C), X)
6950   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6951     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6952     AddToWorklist(NOTNode.getNode());
6953     return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6954   }
6955   // fold (select C, X, 1) -> (or (not C), X)
6956   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6957     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6958     AddToWorklist(NOTNode.getNode());
6959     return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6960   }
6961   // fold (select X, Y, X) -> (and X, Y)
6962   // fold (select X, Y, 0) -> (and X, Y)
6963   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6964     return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6965 
6966   // If we can fold this based on the true/false value, do so.
6967   if (SimplifySelectOps(N, N1, N2))
6968     return SDValue(N, 0); // Don't revisit N.
6969 
6970   if (VT0 == MVT::i1) {
6971     // The code in this block deals with the following 2 equivalences:
6972     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6973     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6974     // The target can specify its preferred form with the
6975     // shouldNormalizeToSelectSequence() callback. However we always transform
6976     // to the right anyway if we find the inner select exists in the DAG anyway
6977     // and we always transform to the left side if we know that we can further
6978     // optimize the combination of the conditions.
6979     bool normalizeToSequence =
6980         TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6981     // select (and Cond0, Cond1), X, Y
6982     //   -> select Cond0, (select Cond1, X, Y), Y
6983     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6984       SDValue Cond0 = N0->getOperand(0);
6985       SDValue Cond1 = N0->getOperand(1);
6986       SDValue InnerSelect =
6987           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6988       if (normalizeToSequence || !InnerSelect.use_empty())
6989         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6990                            InnerSelect, N2);
6991     }
6992     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6993     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6994       SDValue Cond0 = N0->getOperand(0);
6995       SDValue Cond1 = N0->getOperand(1);
6996       SDValue InnerSelect =
6997           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6998       if (normalizeToSequence || !InnerSelect.use_empty())
6999         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
7000                            InnerSelect);
7001     }
7002 
7003     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
7004     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
7005       SDValue N1_0 = N1->getOperand(0);
7006       SDValue N1_1 = N1->getOperand(1);
7007       SDValue N1_2 = N1->getOperand(2);
7008       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
7009         // Create the actual and node if we can generate good code for it.
7010         if (!normalizeToSequence) {
7011           SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
7012           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
7013         }
7014         // Otherwise see if we can optimize the "and" to a better pattern.
7015         if (SDValue Combined = visitANDLike(N0, N1_0, N))
7016           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
7017                              N2);
7018       }
7019     }
7020     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
7021     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
7022       SDValue N2_0 = N2->getOperand(0);
7023       SDValue N2_1 = N2->getOperand(1);
7024       SDValue N2_2 = N2->getOperand(2);
7025       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
7026         // Create the actual or node if we can generate good code for it.
7027         if (!normalizeToSequence) {
7028           SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
7029           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
7030         }
7031         // Otherwise see if we can optimize to a better pattern.
7032         if (SDValue Combined = visitORLike(N0, N2_0, N))
7033           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
7034                              N2_2);
7035       }
7036     }
7037   }
7038 
7039   if (VT0 == MVT::i1) {
7040     // select (not Cond), N1, N2 -> select Cond, N2, N1
7041     if (isBitwiseNot(N0))
7042       return DAG.getNode(ISD::SELECT, DL, VT, N0->getOperand(0), N2, N1);
7043   }
7044 
7045   // fold selects based on a setcc into other things, such as min/max/abs
7046   if (N0.getOpcode() == ISD::SETCC) {
7047     // select x, y (fcmp lt x, y) -> fminnum x, y
7048     // select x, y (fcmp gt x, y) -> fmaxnum x, y
7049     //
7050     // This is OK if we don't care about what happens if either operand is a
7051     // NaN.
7052     //
7053 
7054     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
7055     // no signed zeros as well as no nans.
7056     const TargetOptions &Options = DAG.getTarget().Options;
7057     if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
7058         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
7059       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7060 
7061       if (SDValue FMinMax = combineMinNumMaxNum(
7062               DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
7063         return FMinMax;
7064     }
7065 
7066     if ((!LegalOperations &&
7067          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
7068         TLI.isOperationLegal(ISD::SELECT_CC, VT))
7069       return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
7070                          N0.getOperand(1), N1, N2, N0.getOperand(2));
7071     return SimplifySelect(DL, N0, N1, N2);
7072   }
7073 
7074   return SDValue();
7075 }
7076 
7077 static
7078 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
7079   SDLoc DL(N);
7080   EVT LoVT, HiVT;
7081   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
7082 
7083   // Split the inputs.
7084   SDValue Lo, Hi, LL, LH, RL, RH;
7085   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
7086   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
7087 
7088   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
7089   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
7090 
7091   return std::make_pair(Lo, Hi);
7092 }
7093 
7094 // This function assumes all the vselect's arguments are CONCAT_VECTOR
7095 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
7096 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
7097   SDLoc DL(N);
7098   SDValue Cond = N->getOperand(0);
7099   SDValue LHS = N->getOperand(1);
7100   SDValue RHS = N->getOperand(2);
7101   EVT VT = N->getValueType(0);
7102   int NumElems = VT.getVectorNumElements();
7103   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
7104          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
7105          Cond.getOpcode() == ISD::BUILD_VECTOR);
7106 
7107   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
7108   // binary ones here.
7109   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
7110     return SDValue();
7111 
7112   // We're sure we have an even number of elements due to the
7113   // concat_vectors we have as arguments to vselect.
7114   // Skip BV elements until we find one that's not an UNDEF
7115   // After we find an UNDEF element, keep looping until we get to half the
7116   // length of the BV and see if all the non-undef nodes are the same.
7117   ConstantSDNode *BottomHalf = nullptr;
7118   for (int i = 0; i < NumElems / 2; ++i) {
7119     if (Cond->getOperand(i)->isUndef())
7120       continue;
7121 
7122     if (BottomHalf == nullptr)
7123       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
7124     else if (Cond->getOperand(i).getNode() != BottomHalf)
7125       return SDValue();
7126   }
7127 
7128   // Do the same for the second half of the BuildVector
7129   ConstantSDNode *TopHalf = nullptr;
7130   for (int i = NumElems / 2; i < NumElems; ++i) {
7131     if (Cond->getOperand(i)->isUndef())
7132       continue;
7133 
7134     if (TopHalf == nullptr)
7135       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
7136     else if (Cond->getOperand(i).getNode() != TopHalf)
7137       return SDValue();
7138   }
7139 
7140   assert(TopHalf && BottomHalf &&
7141          "One half of the selector was all UNDEFs and the other was all the "
7142          "same value. This should have been addressed before this function.");
7143   return DAG.getNode(
7144       ISD::CONCAT_VECTORS, DL, VT,
7145       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
7146       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
7147 }
7148 
7149 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
7150   if (Level >= AfterLegalizeTypes)
7151     return SDValue();
7152 
7153   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
7154   SDValue Mask = MSC->getMask();
7155   SDValue Data  = MSC->getValue();
7156   SDLoc DL(N);
7157 
7158   // If the MSCATTER data type requires splitting and the mask is provided by a
7159   // SETCC, then split both nodes and its operands before legalization. This
7160   // prevents the type legalizer from unrolling SETCC into scalar comparisons
7161   // and enables future optimizations (e.g. min/max pattern matching on X86).
7162   if (Mask.getOpcode() != ISD::SETCC)
7163     return SDValue();
7164 
7165   // Check if any splitting is required.
7166   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
7167       TargetLowering::TypeSplitVector)
7168     return SDValue();
7169   SDValue MaskLo, MaskHi, Lo, Hi;
7170   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
7171 
7172   EVT LoVT, HiVT;
7173   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
7174 
7175   SDValue Chain = MSC->getChain();
7176 
7177   EVT MemoryVT = MSC->getMemoryVT();
7178   unsigned Alignment = MSC->getOriginalAlignment();
7179 
7180   EVT LoMemVT, HiMemVT;
7181   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
7182 
7183   SDValue DataLo, DataHi;
7184   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
7185 
7186   SDValue Scale = MSC->getScale();
7187   SDValue BasePtr = MSC->getBasePtr();
7188   SDValue IndexLo, IndexHi;
7189   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
7190 
7191   MachineMemOperand *MMO = DAG.getMachineFunction().
7192     getMachineMemOperand(MSC->getPointerInfo(),
7193                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
7194                           Alignment, MSC->getAAInfo(), MSC->getRanges());
7195 
7196   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo, Scale };
7197   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
7198                             DL, OpsLo, MMO);
7199 
7200   SDValue OpsHi[] = { Chain, DataHi, MaskHi, BasePtr, IndexHi, Scale };
7201   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
7202                             DL, OpsHi, MMO);
7203 
7204   AddToWorklist(Lo.getNode());
7205   AddToWorklist(Hi.getNode());
7206 
7207   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
7208 }
7209 
7210 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
7211   if (Level >= AfterLegalizeTypes)
7212     return SDValue();
7213 
7214   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
7215   SDValue Mask = MST->getMask();
7216   SDValue Data  = MST->getValue();
7217   EVT VT = Data.getValueType();
7218   SDLoc DL(N);
7219 
7220   // If the MSTORE data type requires splitting and the mask is provided by a
7221   // SETCC, then split both nodes and its operands before legalization. This
7222   // prevents the type legalizer from unrolling SETCC into scalar comparisons
7223   // and enables future optimizations (e.g. min/max pattern matching on X86).
7224   if (Mask.getOpcode() == ISD::SETCC) {
7225     // Check if any splitting is required.
7226     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
7227         TargetLowering::TypeSplitVector)
7228       return SDValue();
7229 
7230     SDValue MaskLo, MaskHi, Lo, Hi;
7231     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
7232 
7233     SDValue Chain = MST->getChain();
7234     SDValue Ptr   = MST->getBasePtr();
7235 
7236     EVT MemoryVT = MST->getMemoryVT();
7237     unsigned Alignment = MST->getOriginalAlignment();
7238 
7239     // if Alignment is equal to the vector size,
7240     // take the half of it for the second part
7241     unsigned SecondHalfAlignment =
7242       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
7243 
7244     EVT LoMemVT, HiMemVT;
7245     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
7246 
7247     SDValue DataLo, DataHi;
7248     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
7249 
7250     MachineMemOperand *MMO = DAG.getMachineFunction().
7251       getMachineMemOperand(MST->getPointerInfo(),
7252                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
7253                            Alignment, MST->getAAInfo(), MST->getRanges());
7254 
7255     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
7256                             MST->isTruncatingStore(),
7257                             MST->isCompressingStore());
7258 
7259     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
7260                                      MST->isCompressingStore());
7261     unsigned HiOffset = LoMemVT.getStoreSize();
7262 
7263     MMO = DAG.getMachineFunction().getMachineMemOperand(
7264         MST->getPointerInfo().getWithOffset(HiOffset),
7265         MachineMemOperand::MOStore, HiMemVT.getStoreSize(), SecondHalfAlignment,
7266         MST->getAAInfo(), MST->getRanges());
7267 
7268     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
7269                             MST->isTruncatingStore(),
7270                             MST->isCompressingStore());
7271 
7272     AddToWorklist(Lo.getNode());
7273     AddToWorklist(Hi.getNode());
7274 
7275     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
7276   }
7277   return SDValue();
7278 }
7279 
7280 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
7281   if (Level >= AfterLegalizeTypes)
7282     return SDValue();
7283 
7284   MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
7285   SDValue Mask = MGT->getMask();
7286   SDLoc DL(N);
7287 
7288   // If the MGATHER result requires splitting and the mask is provided by a
7289   // SETCC, then split both nodes and its operands before legalization. This
7290   // prevents the type legalizer from unrolling SETCC into scalar comparisons
7291   // and enables future optimizations (e.g. min/max pattern matching on X86).
7292 
7293   if (Mask.getOpcode() != ISD::SETCC)
7294     return SDValue();
7295 
7296   EVT VT = N->getValueType(0);
7297 
7298   // Check if any splitting is required.
7299   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
7300       TargetLowering::TypeSplitVector)
7301     return SDValue();
7302 
7303   SDValue MaskLo, MaskHi, Lo, Hi;
7304   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
7305 
7306   SDValue Src0 = MGT->getValue();
7307   SDValue Src0Lo, Src0Hi;
7308   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
7309 
7310   EVT LoVT, HiVT;
7311   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
7312 
7313   SDValue Chain = MGT->getChain();
7314   EVT MemoryVT = MGT->getMemoryVT();
7315   unsigned Alignment = MGT->getOriginalAlignment();
7316 
7317   EVT LoMemVT, HiMemVT;
7318   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
7319 
7320   SDValue Scale = MGT->getScale();
7321   SDValue BasePtr = MGT->getBasePtr();
7322   SDValue Index = MGT->getIndex();
7323   SDValue IndexLo, IndexHi;
7324   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
7325 
7326   MachineMemOperand *MMO = DAG.getMachineFunction().
7327     getMachineMemOperand(MGT->getPointerInfo(),
7328                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
7329                           Alignment, MGT->getAAInfo(), MGT->getRanges());
7330 
7331   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo, Scale };
7332   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
7333                            MMO);
7334 
7335   SDValue OpsHi[] = { Chain, Src0Hi, MaskHi, BasePtr, IndexHi, Scale };
7336   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
7337                            MMO);
7338 
7339   AddToWorklist(Lo.getNode());
7340   AddToWorklist(Hi.getNode());
7341 
7342   // Build a factor node to remember that this load is independent of the
7343   // other one.
7344   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
7345                       Hi.getValue(1));
7346 
7347   // Legalized the chain result - switch anything that used the old chain to
7348   // use the new one.
7349   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
7350 
7351   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
7352 
7353   SDValue RetOps[] = { GatherRes, Chain };
7354   return DAG.getMergeValues(RetOps, DL);
7355 }
7356 
7357 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
7358   if (Level >= AfterLegalizeTypes)
7359     return SDValue();
7360 
7361   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
7362   SDValue Mask = MLD->getMask();
7363   SDLoc DL(N);
7364 
7365   // If the MLOAD result requires splitting and the mask is provided by a
7366   // SETCC, then split both nodes and its operands before legalization. This
7367   // prevents the type legalizer from unrolling SETCC into scalar comparisons
7368   // and enables future optimizations (e.g. min/max pattern matching on X86).
7369   if (Mask.getOpcode() == ISD::SETCC) {
7370     EVT VT = N->getValueType(0);
7371 
7372     // Check if any splitting is required.
7373     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
7374         TargetLowering::TypeSplitVector)
7375       return SDValue();
7376 
7377     SDValue MaskLo, MaskHi, Lo, Hi;
7378     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
7379 
7380     SDValue Src0 = MLD->getSrc0();
7381     SDValue Src0Lo, Src0Hi;
7382     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
7383 
7384     EVT LoVT, HiVT;
7385     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
7386 
7387     SDValue Chain = MLD->getChain();
7388     SDValue Ptr   = MLD->getBasePtr();
7389     EVT MemoryVT = MLD->getMemoryVT();
7390     unsigned Alignment = MLD->getOriginalAlignment();
7391 
7392     // if Alignment is equal to the vector size,
7393     // take the half of it for the second part
7394     unsigned SecondHalfAlignment =
7395       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
7396          Alignment/2 : Alignment;
7397 
7398     EVT LoMemVT, HiMemVT;
7399     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
7400 
7401     MachineMemOperand *MMO = DAG.getMachineFunction().
7402     getMachineMemOperand(MLD->getPointerInfo(),
7403                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
7404                          Alignment, MLD->getAAInfo(), MLD->getRanges());
7405 
7406     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
7407                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
7408 
7409     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
7410                                      MLD->isExpandingLoad());
7411     unsigned HiOffset = LoMemVT.getStoreSize();
7412 
7413     MMO = DAG.getMachineFunction().getMachineMemOperand(
7414         MLD->getPointerInfo().getWithOffset(HiOffset),
7415         MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), SecondHalfAlignment,
7416         MLD->getAAInfo(), MLD->getRanges());
7417 
7418     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
7419                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
7420 
7421     AddToWorklist(Lo.getNode());
7422     AddToWorklist(Hi.getNode());
7423 
7424     // Build a factor node to remember that this load is independent of the
7425     // other one.
7426     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
7427                         Hi.getValue(1));
7428 
7429     // Legalized the chain result - switch anything that used the old chain to
7430     // use the new one.
7431     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
7432 
7433     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
7434 
7435     SDValue RetOps[] = { LoadRes, Chain };
7436     return DAG.getMergeValues(RetOps, DL);
7437   }
7438   return SDValue();
7439 }
7440 
7441 /// A vector select of 2 constant vectors can be simplified to math/logic to
7442 /// avoid a variable select instruction and possibly avoid constant loads.
7443 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
7444   SDValue Cond = N->getOperand(0);
7445   SDValue N1 = N->getOperand(1);
7446   SDValue N2 = N->getOperand(2);
7447   EVT VT = N->getValueType(0);
7448   if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
7449       !TLI.convertSelectOfConstantsToMath(VT) ||
7450       !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
7451       !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
7452     return SDValue();
7453 
7454   // Check if we can use the condition value to increment/decrement a single
7455   // constant value. This simplifies a select to an add and removes a constant
7456   // load/materialization from the general case.
7457   bool AllAddOne = true;
7458   bool AllSubOne = true;
7459   unsigned Elts = VT.getVectorNumElements();
7460   for (unsigned i = 0; i != Elts; ++i) {
7461     SDValue N1Elt = N1.getOperand(i);
7462     SDValue N2Elt = N2.getOperand(i);
7463     if (N1Elt.isUndef() || N2Elt.isUndef())
7464       continue;
7465 
7466     const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
7467     const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
7468     if (C1 != C2 + 1)
7469       AllAddOne = false;
7470     if (C1 != C2 - 1)
7471       AllSubOne = false;
7472   }
7473 
7474   // Further simplifications for the extra-special cases where the constants are
7475   // all 0 or all -1 should be implemented as folds of these patterns.
7476   SDLoc DL(N);
7477   if (AllAddOne || AllSubOne) {
7478     // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
7479     // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
7480     auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
7481     SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
7482     return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
7483   }
7484 
7485   // The general case for select-of-constants:
7486   // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
7487   // ...but that only makes sense if a vselect is slower than 2 logic ops, so
7488   // leave that to a machine-specific pass.
7489   return SDValue();
7490 }
7491 
7492 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
7493   SDValue N0 = N->getOperand(0);
7494   SDValue N1 = N->getOperand(1);
7495   SDValue N2 = N->getOperand(2);
7496   SDLoc DL(N);
7497 
7498   // fold (vselect C, X, X) -> X
7499   if (N1 == N2)
7500     return N1;
7501 
7502   // Canonicalize integer abs.
7503   // vselect (setg[te] X,  0),  X, -X ->
7504   // vselect (setgt    X, -1),  X, -X ->
7505   // vselect (setl[te] X,  0), -X,  X ->
7506   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7507   if (N0.getOpcode() == ISD::SETCC) {
7508     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
7509     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7510     bool isAbs = false;
7511     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
7512 
7513     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7514          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
7515         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
7516       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
7517     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
7518              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
7519       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
7520 
7521     if (isAbs) {
7522       EVT VT = LHS.getValueType();
7523       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
7524         return DAG.getNode(ISD::ABS, DL, VT, LHS);
7525 
7526       SDValue Shift = DAG.getNode(
7527           ISD::SRA, DL, VT, LHS,
7528           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
7529       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
7530       AddToWorklist(Shift.getNode());
7531       AddToWorklist(Add.getNode());
7532       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
7533     }
7534 
7535     // If this select has a condition (setcc) with narrower operands than the
7536     // select, try to widen the compare to match the select width.
7537     // TODO: This should be extended to handle any constant.
7538     // TODO: This could be extended to handle non-loading patterns, but that
7539     //       requires thorough testing to avoid regressions.
7540     if (isNullConstantOrNullSplatConstant(RHS)) {
7541       EVT NarrowVT = LHS.getValueType();
7542       EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger();
7543       EVT SetCCVT = getSetCCResultType(LHS.getValueType());
7544       unsigned SetCCWidth = SetCCVT.getScalarSizeInBits();
7545       unsigned WideWidth = WideVT.getScalarSizeInBits();
7546       bool IsSigned = isSignedIntSetCC(CC);
7547       auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7548       if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() &&
7549           SetCCWidth != 1 && SetCCWidth < WideWidth &&
7550           TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) &&
7551           TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) {
7552         // Both compare operands can be widened for free. The LHS can use an
7553         // extended load, and the RHS is a constant:
7554         //   vselect (ext (setcc load(X), C)), N1, N2 -->
7555         //   vselect (setcc extload(X), C'), N1, N2
7556         auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7557         SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS);
7558         SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS);
7559         EVT WideSetCCVT = getSetCCResultType(WideVT);
7560         SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC);
7561         return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2);
7562       }
7563     }
7564   }
7565 
7566   if (SimplifySelectOps(N, N1, N2))
7567     return SDValue(N, 0);  // Don't revisit N.
7568 
7569   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
7570   if (ISD::isBuildVectorAllOnes(N0.getNode()))
7571     return N1;
7572   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
7573   if (ISD::isBuildVectorAllZeros(N0.getNode()))
7574     return N2;
7575 
7576   // The ConvertSelectToConcatVector function is assuming both the above
7577   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
7578   // and addressed.
7579   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
7580       N2.getOpcode() == ISD::CONCAT_VECTORS &&
7581       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
7582     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
7583       return CV;
7584   }
7585 
7586   if (SDValue V = foldVSelectOfConstants(N))
7587     return V;
7588 
7589   return SDValue();
7590 }
7591 
7592 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
7593   SDValue N0 = N->getOperand(0);
7594   SDValue N1 = N->getOperand(1);
7595   SDValue N2 = N->getOperand(2);
7596   SDValue N3 = N->getOperand(3);
7597   SDValue N4 = N->getOperand(4);
7598   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
7599 
7600   // fold select_cc lhs, rhs, x, x, cc -> x
7601   if (N2 == N3)
7602     return N2;
7603 
7604   // Determine if the condition we're dealing with is constant
7605   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
7606                                   CC, SDLoc(N), false)) {
7607     AddToWorklist(SCC.getNode());
7608 
7609     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
7610       if (!SCCC->isNullValue())
7611         return N2;    // cond always true -> true val
7612       else
7613         return N3;    // cond always false -> false val
7614     } else if (SCC->isUndef()) {
7615       // When the condition is UNDEF, just return the first operand. This is
7616       // coherent the DAG creation, no setcc node is created in this case
7617       return N2;
7618     } else if (SCC.getOpcode() == ISD::SETCC) {
7619       // Fold to a simpler select_cc
7620       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
7621                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
7622                          SCC.getOperand(2));
7623     }
7624   }
7625 
7626   // If we can fold this based on the true/false value, do so.
7627   if (SimplifySelectOps(N, N2, N3))
7628     return SDValue(N, 0);  // Don't revisit N.
7629 
7630   // fold select_cc into other things, such as min/max/abs
7631   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
7632 }
7633 
7634 SDValue DAGCombiner::visitSETCC(SDNode *N) {
7635   // setcc is very commonly used as an argument to brcond. This pattern
7636   // also lend itself to numerous combines and, as a result, it is desired
7637   // we keep the argument to a brcond as a setcc as much as possible.
7638   bool PreferSetCC =
7639       N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND;
7640 
7641   SDValue Combined = SimplifySetCC(
7642       N->getValueType(0), N->getOperand(0), N->getOperand(1),
7643       cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC);
7644 
7645   if (!Combined)
7646     return SDValue();
7647 
7648   // If we prefer to have a setcc, and we don't, we'll try our best to
7649   // recreate one using rebuildSetCC.
7650   if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) {
7651     SDValue NewSetCC = rebuildSetCC(Combined);
7652 
7653     // We don't have anything interesting to combine to.
7654     if (NewSetCC.getNode() == N)
7655       return SDValue();
7656 
7657     if (NewSetCC)
7658       return NewSetCC;
7659   }
7660 
7661   return Combined;
7662 }
7663 
7664 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
7665   SDValue LHS = N->getOperand(0);
7666   SDValue RHS = N->getOperand(1);
7667   SDValue Carry = N->getOperand(2);
7668   SDValue Cond = N->getOperand(3);
7669 
7670   // If Carry is false, fold to a regular SETCC.
7671   if (isNullConstant(Carry))
7672     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7673 
7674   return SDValue();
7675 }
7676 
7677 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
7678 /// a build_vector of constants.
7679 /// This function is called by the DAGCombiner when visiting sext/zext/aext
7680 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
7681 /// Vector extends are not folded if operations are legal; this is to
7682 /// avoid introducing illegal build_vector dag nodes.
7683 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
7684                                          SelectionDAG &DAG, bool LegalTypes,
7685                                          bool LegalOperations) {
7686   unsigned Opcode = N->getOpcode();
7687   SDValue N0 = N->getOperand(0);
7688   EVT VT = N->getValueType(0);
7689 
7690   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
7691          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7692          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
7693          && "Expected EXTEND dag node in input!");
7694 
7695   // fold (sext c1) -> c1
7696   // fold (zext c1) -> c1
7697   // fold (aext c1) -> c1
7698   if (isa<ConstantSDNode>(N0))
7699     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
7700 
7701   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
7702   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
7703   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
7704   EVT SVT = VT.getScalarType();
7705   if (!(VT.isVector() &&
7706       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
7707       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
7708     return nullptr;
7709 
7710   // We can fold this node into a build_vector.
7711   unsigned VTBits = SVT.getSizeInBits();
7712   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
7713   SmallVector<SDValue, 8> Elts;
7714   unsigned NumElts = VT.getVectorNumElements();
7715   SDLoc DL(N);
7716 
7717   for (unsigned i=0; i != NumElts; ++i) {
7718     SDValue Op = N0->getOperand(i);
7719     if (Op->isUndef()) {
7720       Elts.push_back(DAG.getUNDEF(SVT));
7721       continue;
7722     }
7723 
7724     SDLoc DL(Op);
7725     // Get the constant value and if needed trunc it to the size of the type.
7726     // Nodes like build_vector might have constants wider than the scalar type.
7727     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
7728     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
7729       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
7730     else
7731       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
7732   }
7733 
7734   return DAG.getBuildVector(VT, DL, Elts).getNode();
7735 }
7736 
7737 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
7738 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
7739 // transformation. Returns true if extension are possible and the above
7740 // mentioned transformation is profitable.
7741 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0,
7742                                     unsigned ExtOpc,
7743                                     SmallVectorImpl<SDNode *> &ExtendNodes,
7744                                     const TargetLowering &TLI) {
7745   bool HasCopyToRegUses = false;
7746   bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType());
7747   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
7748                             UE = N0.getNode()->use_end();
7749        UI != UE; ++UI) {
7750     SDNode *User = *UI;
7751     if (User == N)
7752       continue;
7753     if (UI.getUse().getResNo() != N0.getResNo())
7754       continue;
7755     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
7756     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
7757       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
7758       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
7759         // Sign bits will be lost after a zext.
7760         return false;
7761       bool Add = false;
7762       for (unsigned i = 0; i != 2; ++i) {
7763         SDValue UseOp = User->getOperand(i);
7764         if (UseOp == N0)
7765           continue;
7766         if (!isa<ConstantSDNode>(UseOp))
7767           return false;
7768         Add = true;
7769       }
7770       if (Add)
7771         ExtendNodes.push_back(User);
7772       continue;
7773     }
7774     // If truncates aren't free and there are users we can't
7775     // extend, it isn't worthwhile.
7776     if (!isTruncFree)
7777       return false;
7778     // Remember if this value is live-out.
7779     if (User->getOpcode() == ISD::CopyToReg)
7780       HasCopyToRegUses = true;
7781   }
7782 
7783   if (HasCopyToRegUses) {
7784     bool BothLiveOut = false;
7785     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7786          UI != UE; ++UI) {
7787       SDUse &Use = UI.getUse();
7788       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
7789         BothLiveOut = true;
7790         break;
7791       }
7792     }
7793     if (BothLiveOut)
7794       // Both unextended and extended values are live out. There had better be
7795       // a good reason for the transformation.
7796       return ExtendNodes.size();
7797   }
7798   return true;
7799 }
7800 
7801 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
7802                                   SDValue OrigLoad, SDValue ExtLoad,
7803                                   ISD::NodeType ExtType) {
7804   // Extend SetCC uses if necessary.
7805   SDLoc DL(ExtLoad);
7806   for (SDNode *SetCC : SetCCs) {
7807     SmallVector<SDValue, 4> Ops;
7808 
7809     for (unsigned j = 0; j != 2; ++j) {
7810       SDValue SOp = SetCC->getOperand(j);
7811       if (SOp == OrigLoad)
7812         Ops.push_back(ExtLoad);
7813       else
7814         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
7815     }
7816 
7817     Ops.push_back(SetCC->getOperand(2));
7818     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7819   }
7820 }
7821 
7822 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
7823 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
7824   SDValue N0 = N->getOperand(0);
7825   EVT DstVT = N->getValueType(0);
7826   EVT SrcVT = N0.getValueType();
7827 
7828   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
7829           N->getOpcode() == ISD::ZERO_EXTEND) &&
7830          "Unexpected node type (not an extend)!");
7831 
7832   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
7833   // For example, on a target with legal v4i32, but illegal v8i32, turn:
7834   //   (v8i32 (sext (v8i16 (load x))))
7835   // into:
7836   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
7837   //                          (v4i32 (sextload (x + 16)))))
7838   // Where uses of the original load, i.e.:
7839   //   (v8i16 (load x))
7840   // are replaced with:
7841   //   (v8i16 (truncate
7842   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
7843   //                            (v4i32 (sextload (x + 16)))))))
7844   //
7845   // This combine is only applicable to illegal, but splittable, vectors.
7846   // All legal types, and illegal non-vector types, are handled elsewhere.
7847   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
7848   //
7849   if (N0->getOpcode() != ISD::LOAD)
7850     return SDValue();
7851 
7852   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7853 
7854   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
7855       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
7856       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
7857     return SDValue();
7858 
7859   SmallVector<SDNode *, 4> SetCCs;
7860   if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI))
7861     return SDValue();
7862 
7863   ISD::LoadExtType ExtType =
7864       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7865 
7866   // Try to split the vector types to get down to legal types.
7867   EVT SplitSrcVT = SrcVT;
7868   EVT SplitDstVT = DstVT;
7869   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7870          SplitSrcVT.getVectorNumElements() > 1) {
7871     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7872     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7873   }
7874 
7875   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7876     return SDValue();
7877 
7878   SDLoc DL(N);
7879   const unsigned NumSplits =
7880       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7881   const unsigned Stride = SplitSrcVT.getStoreSize();
7882   SmallVector<SDValue, 4> Loads;
7883   SmallVector<SDValue, 4> Chains;
7884 
7885   SDValue BasePtr = LN0->getBasePtr();
7886   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7887     const unsigned Offset = Idx * Stride;
7888     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7889 
7890     SDValue SplitLoad = DAG.getExtLoad(
7891         ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr,
7892         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7893         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7894 
7895     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7896                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7897 
7898     Loads.push_back(SplitLoad.getValue(0));
7899     Chains.push_back(SplitLoad.getValue(1));
7900   }
7901 
7902   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7903   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7904 
7905   // Simplify TF.
7906   AddToWorklist(NewChain.getNode());
7907 
7908   CombineTo(N, NewValue);
7909 
7910   // Replace uses of the original load (before extension)
7911   // with a truncate of the concatenated sextloaded vectors.
7912   SDValue Trunc =
7913       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7914   ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode());
7915   CombineTo(N0.getNode(), Trunc, NewChain);
7916   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7917 }
7918 
7919 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
7920 //      (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
7921 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) {
7922   assert(N->getOpcode() == ISD::ZERO_EXTEND);
7923   EVT VT = N->getValueType(0);
7924 
7925   // and/or/xor
7926   SDValue N0 = N->getOperand(0);
7927   if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7928         N0.getOpcode() == ISD::XOR) ||
7929       N0.getOperand(1).getOpcode() != ISD::Constant ||
7930       (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT)))
7931     return SDValue();
7932 
7933   // shl/shr
7934   SDValue N1 = N0->getOperand(0);
7935   if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) ||
7936       N1.getOperand(1).getOpcode() != ISD::Constant ||
7937       (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT)))
7938     return SDValue();
7939 
7940   // load
7941   if (!isa<LoadSDNode>(N1.getOperand(0)))
7942     return SDValue();
7943   LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0));
7944   EVT MemVT = Load->getMemoryVT();
7945   if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) ||
7946       Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed())
7947     return SDValue();
7948 
7949 
7950   // If the shift op is SHL, the logic op must be AND, otherwise the result
7951   // will be wrong.
7952   if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND)
7953     return SDValue();
7954 
7955   if (!N0.hasOneUse() || !N1.hasOneUse())
7956     return SDValue();
7957 
7958   SmallVector<SDNode*, 4> SetCCs;
7959   if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0),
7960                                ISD::ZERO_EXTEND, SetCCs, TLI))
7961     return SDValue();
7962 
7963   // Actually do the transformation.
7964   SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT,
7965                                    Load->getChain(), Load->getBasePtr(),
7966                                    Load->getMemoryVT(), Load->getMemOperand());
7967 
7968   SDLoc DL1(N1);
7969   SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad,
7970                               N1.getOperand(1));
7971 
7972   APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7973   Mask = Mask.zext(VT.getSizeInBits());
7974   SDLoc DL0(N0);
7975   SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift,
7976                             DAG.getConstant(Mask, DL0, VT));
7977 
7978   ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
7979   CombineTo(N, And);
7980   if (SDValue(Load, 0).hasOneUse()) {
7981     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
7982   } else {
7983     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load),
7984                                 Load->getValueType(0), ExtLoad);
7985     CombineTo(Load, Trunc, ExtLoad.getValue(1));
7986   }
7987   return SDValue(N,0); // Return N so it doesn't get rechecked!
7988 }
7989 
7990 /// If we're narrowing or widening the result of a vector select and the final
7991 /// size is the same size as a setcc (compare) feeding the select, then try to
7992 /// apply the cast operation to the select's operands because matching vector
7993 /// sizes for a select condition and other operands should be more efficient.
7994 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7995   unsigned CastOpcode = Cast->getOpcode();
7996   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7997           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7998           CastOpcode == ISD::FP_ROUND) &&
7999          "Unexpected opcode for vector select narrowing/widening");
8000 
8001   // We only do this transform before legal ops because the pattern may be
8002   // obfuscated by target-specific operations after legalization. Do not create
8003   // an illegal select op, however, because that may be difficult to lower.
8004   EVT VT = Cast->getValueType(0);
8005   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
8006     return SDValue();
8007 
8008   SDValue VSel = Cast->getOperand(0);
8009   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
8010       VSel.getOperand(0).getOpcode() != ISD::SETCC)
8011     return SDValue();
8012 
8013   // Does the setcc have the same vector size as the casted select?
8014   SDValue SetCC = VSel.getOperand(0);
8015   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
8016   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
8017     return SDValue();
8018 
8019   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
8020   SDValue A = VSel.getOperand(1);
8021   SDValue B = VSel.getOperand(2);
8022   SDValue CastA, CastB;
8023   SDLoc DL(Cast);
8024   if (CastOpcode == ISD::FP_ROUND) {
8025     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
8026     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
8027     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
8028   } else {
8029     CastA = DAG.getNode(CastOpcode, DL, VT, A);
8030     CastB = DAG.getNode(CastOpcode, DL, VT, B);
8031   }
8032   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
8033 }
8034 
8035 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
8036 // fold ([s|z]ext (     extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
8037 static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner,
8038                                      const TargetLowering &TLI, EVT VT,
8039                                      bool LegalOperations, SDNode *N,
8040                                      SDValue N0, ISD::LoadExtType ExtLoadType) {
8041   SDNode *N0Node = N0.getNode();
8042   bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node)
8043                                                    : ISD::isZEXTLoad(N0Node);
8044   if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) ||
8045       !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse())
8046     return {};
8047 
8048   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8049   EVT MemVT = LN0->getMemoryVT();
8050   if ((LegalOperations || LN0->isVolatile()) &&
8051       !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT))
8052     return {};
8053 
8054   SDValue ExtLoad =
8055       DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
8056                      LN0->getBasePtr(), MemVT, LN0->getMemOperand());
8057   Combiner.CombineTo(N, ExtLoad);
8058   DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8059   return SDValue(N, 0); // Return N so it doesn't get rechecked!
8060 }
8061 
8062 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x)))
8063 // Only generate vector extloads when 1) they're legal, and 2) they are
8064 // deemed desirable by the target.
8065 static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner,
8066                                   const TargetLowering &TLI, EVT VT,
8067                                   bool LegalOperations, SDNode *N, SDValue N0,
8068                                   ISD::LoadExtType ExtLoadType,
8069                                   ISD::NodeType ExtOpc) {
8070   if (!ISD::isNON_EXTLoad(N0.getNode()) ||
8071       !ISD::isUNINDEXEDLoad(N0.getNode()) ||
8072       ((LegalOperations || VT.isVector() ||
8073         cast<LoadSDNode>(N0)->isVolatile()) &&
8074        !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType())))
8075     return {};
8076 
8077   bool DoXform = true;
8078   SmallVector<SDNode *, 4> SetCCs;
8079   if (!N0.hasOneUse())
8080     DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI);
8081   if (VT.isVector())
8082     DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
8083   if (!DoXform)
8084     return {};
8085 
8086   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8087   SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
8088                                    LN0->getBasePtr(), N0.getValueType(),
8089                                    LN0->getMemOperand());
8090   Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc);
8091   // If the load value is used only by N, replace it via CombineTo N.
8092   bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
8093   Combiner.CombineTo(N, ExtLoad);
8094   if (NoReplaceTrunc) {
8095     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8096   } else {
8097     SDValue Trunc =
8098         DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad);
8099     Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1));
8100   }
8101   return SDValue(N, 0); // Return N so it doesn't get rechecked!
8102 }
8103 
8104 static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG,
8105                                        bool LegalOperations) {
8106   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
8107           N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext");
8108 
8109   SDValue SetCC = N->getOperand(0);
8110   if (LegalOperations || SetCC.getOpcode() != ISD::SETCC ||
8111       !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1)
8112     return SDValue();
8113 
8114   SDValue X = SetCC.getOperand(0);
8115   SDValue Ones = SetCC.getOperand(1);
8116   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
8117   EVT VT = N->getValueType(0);
8118   EVT XVT = X.getValueType();
8119   // setge X, C is canonicalized to setgt, so we do not need to match that
8120   // pattern. The setlt sibling is folded in SimplifySelectCC() because it does
8121   // not require the 'not' op.
8122   if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) {
8123     // Invert and smear/shift the sign bit:
8124     // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1)
8125     // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1)
8126     SDLoc DL(N);
8127     SDValue NotX = DAG.getNOT(DL, X, VT);
8128     SDValue ShiftAmount = DAG.getConstant(VT.getSizeInBits() - 1, DL, VT);
8129     auto ShiftOpcode = N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL;
8130     return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount);
8131   }
8132   return SDValue();
8133 }
8134 
8135 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
8136   SDValue N0 = N->getOperand(0);
8137   EVT VT = N->getValueType(0);
8138   SDLoc DL(N);
8139 
8140   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8141                                               LegalOperations))
8142     return SDValue(Res, 0);
8143 
8144   // fold (sext (sext x)) -> (sext x)
8145   // fold (sext (aext x)) -> (sext x)
8146   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
8147     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
8148 
8149   if (N0.getOpcode() == ISD::TRUNCATE) {
8150     // fold (sext (truncate (load x))) -> (sext (smaller load x))
8151     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
8152     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
8153       SDNode *oye = N0.getOperand(0).getNode();
8154       if (NarrowLoad.getNode() != N0.getNode()) {
8155         CombineTo(N0.getNode(), NarrowLoad);
8156         // CombineTo deleted the truncate, if needed, but not what's under it.
8157         AddToWorklist(oye);
8158       }
8159       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8160     }
8161 
8162     // See if the value being truncated is already sign extended.  If so, just
8163     // eliminate the trunc/sext pair.
8164     SDValue Op = N0.getOperand(0);
8165     unsigned OpBits   = Op.getScalarValueSizeInBits();
8166     unsigned MidBits  = N0.getScalarValueSizeInBits();
8167     unsigned DestBits = VT.getScalarSizeInBits();
8168     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
8169 
8170     if (OpBits == DestBits) {
8171       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8172       // bits, it is already ready.
8173       if (NumSignBits > DestBits-MidBits)
8174         return Op;
8175     } else if (OpBits < DestBits) {
8176       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8177       // bits, just sext from i32.
8178       if (NumSignBits > OpBits-MidBits)
8179         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
8180     } else {
8181       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8182       // bits, just truncate to i32.
8183       if (NumSignBits > OpBits-MidBits)
8184         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
8185     }
8186 
8187     // fold (sext (truncate x)) -> (sextinreg x).
8188     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
8189                                                  N0.getValueType())) {
8190       if (OpBits < DestBits)
8191         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
8192       else if (OpBits > DestBits)
8193         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
8194       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
8195                          DAG.getValueType(N0.getValueType()));
8196     }
8197   }
8198 
8199   // Try to simplify (sext (load x)).
8200   if (SDValue foldedExt =
8201           tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
8202                              ISD::SEXTLOAD, ISD::SIGN_EXTEND))
8203     return foldedExt;
8204 
8205   // fold (sext (load x)) to multiple smaller sextloads.
8206   // Only on illegal but splittable vectors.
8207   if (SDValue ExtLoad = CombineExtLoad(N))
8208     return ExtLoad;
8209 
8210   // Try to simplify (sext (sextload x)).
8211   if (SDValue foldedExt = tryToFoldExtOfExtload(
8212           DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD))
8213     return foldedExt;
8214 
8215   // fold (sext (and/or/xor (load x), cst)) ->
8216   //      (and/or/xor (sextload x), (sext cst))
8217   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
8218        N0.getOpcode() == ISD::XOR) &&
8219       isa<LoadSDNode>(N0.getOperand(0)) &&
8220       N0.getOperand(1).getOpcode() == ISD::Constant &&
8221       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
8222     LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
8223     EVT MemVT = LN00->getMemoryVT();
8224     if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) &&
8225       LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) {
8226       SmallVector<SDNode*, 4> SetCCs;
8227       bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
8228                                              ISD::SIGN_EXTEND, SetCCs, TLI);
8229       if (DoXform) {
8230         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT,
8231                                          LN00->getChain(), LN00->getBasePtr(),
8232                                          LN00->getMemoryVT(),
8233                                          LN00->getMemOperand());
8234         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8235         Mask = Mask.sext(VT.getSizeInBits());
8236         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
8237                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
8238         ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND);
8239         bool NoReplaceTruncAnd = !N0.hasOneUse();
8240         bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
8241         CombineTo(N, And);
8242         // If N0 has multiple uses, change other uses as well.
8243         if (NoReplaceTruncAnd) {
8244           SDValue TruncAnd =
8245               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
8246           CombineTo(N0.getNode(), TruncAnd);
8247         }
8248         if (NoReplaceTrunc) {
8249           DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
8250         } else {
8251           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
8252                                       LN00->getValueType(0), ExtLoad);
8253           CombineTo(LN00, Trunc, ExtLoad.getValue(1));
8254         }
8255         return SDValue(N,0); // Return N so it doesn't get rechecked!
8256       }
8257     }
8258   }
8259 
8260   if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
8261     return V;
8262 
8263   if (N0.getOpcode() == ISD::SETCC) {
8264     SDValue N00 = N0.getOperand(0);
8265     SDValue N01 = N0.getOperand(1);
8266     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
8267     EVT N00VT = N0.getOperand(0).getValueType();
8268 
8269     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
8270     // Only do this before legalize for now.
8271     if (VT.isVector() && !LegalOperations &&
8272         TLI.getBooleanContents(N00VT) ==
8273             TargetLowering::ZeroOrNegativeOneBooleanContent) {
8274       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
8275       // of the same size as the compared operands. Only optimize sext(setcc())
8276       // if this is the case.
8277       EVT SVT = getSetCCResultType(N00VT);
8278 
8279       // We know that the # elements of the results is the same as the
8280       // # elements of the compare (and the # elements of the compare result
8281       // for that matter).  Check to see that they are the same size.  If so,
8282       // we know that the element size of the sext'd result matches the
8283       // element size of the compare operands.
8284       if (VT.getSizeInBits() == SVT.getSizeInBits())
8285         return DAG.getSetCC(DL, VT, N00, N01, CC);
8286 
8287       // If the desired elements are smaller or larger than the source
8288       // elements, we can use a matching integer vector type and then
8289       // truncate/sign extend.
8290       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
8291       if (SVT == MatchingVecType) {
8292         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
8293         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
8294       }
8295     }
8296 
8297     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
8298     // Here, T can be 1 or -1, depending on the type of the setcc and
8299     // getBooleanContents().
8300     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
8301 
8302     // To determine the "true" side of the select, we need to know the high bit
8303     // of the value returned by the setcc if it evaluates to true.
8304     // If the type of the setcc is i1, then the true case of the select is just
8305     // sext(i1 1), that is, -1.
8306     // If the type of the setcc is larger (say, i8) then the value of the high
8307     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
8308     // of the appropriate width.
8309     SDValue ExtTrueVal = (SetCCWidth == 1)
8310                              ? DAG.getAllOnesConstant(DL, VT)
8311                              : DAG.getBoolConstant(true, DL, VT, N00VT);
8312     SDValue Zero = DAG.getConstant(0, DL, VT);
8313     if (SDValue SCC =
8314             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
8315       return SCC;
8316 
8317     if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
8318       EVT SetCCVT = getSetCCResultType(N00VT);
8319       // Don't do this transform for i1 because there's a select transform
8320       // that would reverse it.
8321       // TODO: We should not do this transform at all without a target hook
8322       // because a sext is likely cheaper than a select?
8323       if (SetCCVT.getScalarSizeInBits() != 1 &&
8324           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
8325         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
8326         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
8327       }
8328     }
8329   }
8330 
8331   // fold (sext x) -> (zext x) if the sign bit is known zero.
8332   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
8333       DAG.SignBitIsZero(N0))
8334     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
8335 
8336   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8337     return NewVSel;
8338 
8339   return SDValue();
8340 }
8341 
8342 // isTruncateOf - If N is a truncate of some other value, return true, record
8343 // the value being truncated in Op and which of Op's bits are zero/one in Known.
8344 // This function computes KnownBits to avoid a duplicated call to
8345 // computeKnownBits in the caller.
8346 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
8347                          KnownBits &Known) {
8348   if (N->getOpcode() == ISD::TRUNCATE) {
8349     Op = N->getOperand(0);
8350     DAG.computeKnownBits(Op, Known);
8351     return true;
8352   }
8353 
8354   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
8355       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
8356     return false;
8357 
8358   SDValue Op0 = N->getOperand(0);
8359   SDValue Op1 = N->getOperand(1);
8360   assert(Op0.getValueType() == Op1.getValueType());
8361 
8362   if (isNullConstant(Op0))
8363     Op = Op1;
8364   else if (isNullConstant(Op1))
8365     Op = Op0;
8366   else
8367     return false;
8368 
8369   DAG.computeKnownBits(Op, Known);
8370 
8371   if (!(Known.Zero | 1).isAllOnesValue())
8372     return false;
8373 
8374   return true;
8375 }
8376 
8377 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
8378   SDValue N0 = N->getOperand(0);
8379   EVT VT = N->getValueType(0);
8380 
8381   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8382                                               LegalOperations))
8383     return SDValue(Res, 0);
8384 
8385   // fold (zext (zext x)) -> (zext x)
8386   // fold (zext (aext x)) -> (zext x)
8387   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
8388     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
8389                        N0.getOperand(0));
8390 
8391   // fold (zext (truncate x)) -> (zext x) or
8392   //      (zext (truncate x)) -> (truncate x)
8393   // This is valid when the truncated bits of x are already zero.
8394   // FIXME: We should extend this to work for vectors too.
8395   SDValue Op;
8396   KnownBits Known;
8397   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
8398     APInt TruncatedBits =
8399       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
8400       APInt(Op.getValueSizeInBits(), 0) :
8401       APInt::getBitsSet(Op.getValueSizeInBits(),
8402                         N0.getValueSizeInBits(),
8403                         std::min(Op.getValueSizeInBits(),
8404                                  VT.getSizeInBits()));
8405     if (TruncatedBits.isSubsetOf(Known.Zero))
8406       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
8407   }
8408 
8409   // fold (zext (truncate x)) -> (and x, mask)
8410   if (N0.getOpcode() == ISD::TRUNCATE) {
8411     // fold (zext (truncate (load x))) -> (zext (smaller load x))
8412     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
8413     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
8414       SDNode *oye = N0.getOperand(0).getNode();
8415       if (NarrowLoad.getNode() != N0.getNode()) {
8416         CombineTo(N0.getNode(), NarrowLoad);
8417         // CombineTo deleted the truncate, if needed, but not what's under it.
8418         AddToWorklist(oye);
8419       }
8420       return SDValue(N, 0); // Return N so it doesn't get rechecked!
8421     }
8422 
8423     EVT SrcVT = N0.getOperand(0).getValueType();
8424     EVT MinVT = N0.getValueType();
8425 
8426     // Try to mask before the extension to avoid having to generate a larger mask,
8427     // possibly over several sub-vectors.
8428     if (SrcVT.bitsLT(VT) && VT.isVector()) {
8429       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
8430                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
8431         SDValue Op = N0.getOperand(0);
8432         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
8433         AddToWorklist(Op.getNode());
8434         SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
8435         // Transfer the debug info; the new node is equivalent to N0.
8436         DAG.transferDbgValues(N0, ZExtOrTrunc);
8437         return ZExtOrTrunc;
8438       }
8439     }
8440 
8441     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
8442       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
8443       AddToWorklist(Op.getNode());
8444       SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
8445       // We may safely transfer the debug info describing the truncate node over
8446       // to the equivalent and operation.
8447       DAG.transferDbgValues(N0, And);
8448       return And;
8449     }
8450   }
8451 
8452   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
8453   // if either of the casts is not free.
8454   if (N0.getOpcode() == ISD::AND &&
8455       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
8456       N0.getOperand(1).getOpcode() == ISD::Constant &&
8457       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
8458                            N0.getValueType()) ||
8459        !TLI.isZExtFree(N0.getValueType(), VT))) {
8460     SDValue X = N0.getOperand(0).getOperand(0);
8461     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
8462     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8463     Mask = Mask.zext(VT.getSizeInBits());
8464     SDLoc DL(N);
8465     return DAG.getNode(ISD::AND, DL, VT,
8466                        X, DAG.getConstant(Mask, DL, VT));
8467   }
8468 
8469   // Try to simplify (zext (load x)).
8470   if (SDValue foldedExt =
8471           tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
8472                              ISD::ZEXTLOAD, ISD::ZERO_EXTEND))
8473     return foldedExt;
8474 
8475   // fold (zext (load x)) to multiple smaller zextloads.
8476   // Only on illegal but splittable vectors.
8477   if (SDValue ExtLoad = CombineExtLoad(N))
8478     return ExtLoad;
8479 
8480   // fold (zext (and/or/xor (load x), cst)) ->
8481   //      (and/or/xor (zextload x), (zext cst))
8482   // Unless (and (load x) cst) will match as a zextload already and has
8483   // additional users.
8484   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
8485        N0.getOpcode() == ISD::XOR) &&
8486       isa<LoadSDNode>(N0.getOperand(0)) &&
8487       N0.getOperand(1).getOpcode() == ISD::Constant &&
8488       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
8489     LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
8490     EVT MemVT = LN00->getMemoryVT();
8491     if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) &&
8492         LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) {
8493       bool DoXform = true;
8494       SmallVector<SDNode*, 4> SetCCs;
8495       if (!N0.hasOneUse()) {
8496         if (N0.getOpcode() == ISD::AND) {
8497           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
8498           EVT LoadResultTy = AndC->getValueType(0);
8499           EVT ExtVT;
8500           if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
8501             DoXform = false;
8502         }
8503       }
8504       if (DoXform)
8505         DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
8506                                           ISD::ZERO_EXTEND, SetCCs, TLI);
8507       if (DoXform) {
8508         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT,
8509                                          LN00->getChain(), LN00->getBasePtr(),
8510                                          LN00->getMemoryVT(),
8511                                          LN00->getMemOperand());
8512         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8513         Mask = Mask.zext(VT.getSizeInBits());
8514         SDLoc DL(N);
8515         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
8516                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
8517         ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
8518         bool NoReplaceTruncAnd = !N0.hasOneUse();
8519         bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
8520         CombineTo(N, And);
8521         // If N0 has multiple uses, change other uses as well.
8522         if (NoReplaceTruncAnd) {
8523           SDValue TruncAnd =
8524               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
8525           CombineTo(N0.getNode(), TruncAnd);
8526         }
8527         if (NoReplaceTrunc) {
8528           DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
8529         } else {
8530           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
8531                                       LN00->getValueType(0), ExtLoad);
8532           CombineTo(LN00, Trunc, ExtLoad.getValue(1));
8533         }
8534         return SDValue(N,0); // Return N so it doesn't get rechecked!
8535       }
8536     }
8537   }
8538 
8539   // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
8540   //      (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
8541   if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N))
8542     return ZExtLoad;
8543 
8544   // Try to simplify (zext (zextload x)).
8545   if (SDValue foldedExt = tryToFoldExtOfExtload(
8546           DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD))
8547     return foldedExt;
8548 
8549   if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
8550     return V;
8551 
8552   if (N0.getOpcode() == ISD::SETCC) {
8553     // Only do this before legalize for now.
8554     if (!LegalOperations && VT.isVector() &&
8555         N0.getValueType().getVectorElementType() == MVT::i1) {
8556       EVT N00VT = N0.getOperand(0).getValueType();
8557       if (getSetCCResultType(N00VT) == N0.getValueType())
8558         return SDValue();
8559 
8560       // We know that the # elements of the results is the same as the #
8561       // elements of the compare (and the # elements of the compare result for
8562       // that matter). Check to see that they are the same size. If so, we know
8563       // that the element size of the sext'd result matches the element size of
8564       // the compare operands.
8565       SDLoc DL(N);
8566       SDValue VecOnes = DAG.getConstant(1, DL, VT);
8567       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
8568         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
8569         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
8570                                      N0.getOperand(1), N0.getOperand(2));
8571         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
8572       }
8573 
8574       // If the desired elements are smaller or larger than the source
8575       // elements we can use a matching integer vector type and then
8576       // truncate/sign extend.
8577       EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
8578       SDValue VsetCC =
8579           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
8580                       N0.getOperand(1), N0.getOperand(2));
8581       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
8582                          VecOnes);
8583     }
8584 
8585     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
8586     SDLoc DL(N);
8587     if (SDValue SCC = SimplifySelectCC(
8588             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
8589             DAG.getConstant(0, DL, VT),
8590             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
8591       return SCC;
8592   }
8593 
8594   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
8595   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
8596       isa<ConstantSDNode>(N0.getOperand(1)) &&
8597       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
8598       N0.hasOneUse()) {
8599     SDValue ShAmt = N0.getOperand(1);
8600     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8601     if (N0.getOpcode() == ISD::SHL) {
8602       SDValue InnerZExt = N0.getOperand(0);
8603       // If the original shl may be shifting out bits, do not perform this
8604       // transformation.
8605       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
8606         InnerZExt.getOperand(0).getValueSizeInBits();
8607       if (ShAmtVal > KnownZeroBits)
8608         return SDValue();
8609     }
8610 
8611     SDLoc DL(N);
8612 
8613     // Ensure that the shift amount is wide enough for the shifted value.
8614     if (VT.getSizeInBits() >= 256)
8615       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
8616 
8617     return DAG.getNode(N0.getOpcode(), DL, VT,
8618                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
8619                        ShAmt);
8620   }
8621 
8622   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8623     return NewVSel;
8624 
8625   return SDValue();
8626 }
8627 
8628 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
8629   SDValue N0 = N->getOperand(0);
8630   EVT VT = N->getValueType(0);
8631 
8632   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8633                                               LegalOperations))
8634     return SDValue(Res, 0);
8635 
8636   // fold (aext (aext x)) -> (aext x)
8637   // fold (aext (zext x)) -> (zext x)
8638   // fold (aext (sext x)) -> (sext x)
8639   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
8640       N0.getOpcode() == ISD::ZERO_EXTEND ||
8641       N0.getOpcode() == ISD::SIGN_EXTEND)
8642     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8643 
8644   // fold (aext (truncate (load x))) -> (aext (smaller load x))
8645   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
8646   if (N0.getOpcode() == ISD::TRUNCATE) {
8647     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
8648       SDNode *oye = N0.getOperand(0).getNode();
8649       if (NarrowLoad.getNode() != N0.getNode()) {
8650         CombineTo(N0.getNode(), NarrowLoad);
8651         // CombineTo deleted the truncate, if needed, but not what's under it.
8652         AddToWorklist(oye);
8653       }
8654       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8655     }
8656   }
8657 
8658   // fold (aext (truncate x))
8659   if (N0.getOpcode() == ISD::TRUNCATE)
8660     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
8661 
8662   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
8663   // if the trunc is not free.
8664   if (N0.getOpcode() == ISD::AND &&
8665       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
8666       N0.getOperand(1).getOpcode() == ISD::Constant &&
8667       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
8668                           N0.getValueType())) {
8669     SDLoc DL(N);
8670     SDValue X = N0.getOperand(0).getOperand(0);
8671     X = DAG.getAnyExtOrTrunc(X, DL, VT);
8672     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8673     Mask = Mask.zext(VT.getSizeInBits());
8674     return DAG.getNode(ISD::AND, DL, VT,
8675                        X, DAG.getConstant(Mask, DL, VT));
8676   }
8677 
8678   // fold (aext (load x)) -> (aext (truncate (extload x)))
8679   // None of the supported targets knows how to perform load and any_ext
8680   // on vectors in one instruction.  We only perform this transformation on
8681   // scalars.
8682   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
8683       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8684       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8685     bool DoXform = true;
8686     SmallVector<SDNode*, 4> SetCCs;
8687     if (!N0.hasOneUse())
8688       DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs,
8689                                         TLI);
8690     if (DoXform) {
8691       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8692       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8693                                        LN0->getChain(),
8694                                        LN0->getBasePtr(), N0.getValueType(),
8695                                        LN0->getMemOperand());
8696       ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND);
8697       // If the load value is used only by N, replace it via CombineTo N.
8698       bool NoReplaceTrunc = N0.hasOneUse();
8699       CombineTo(N, ExtLoad);
8700       if (NoReplaceTrunc) {
8701         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8702       } else {
8703         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
8704                                     N0.getValueType(), ExtLoad);
8705         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
8706       }
8707       return SDValue(N, 0); // Return N so it doesn't get rechecked!
8708     }
8709   }
8710 
8711   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
8712   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
8713   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
8714   if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) &&
8715       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
8716     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8717     ISD::LoadExtType ExtType = LN0->getExtensionType();
8718     EVT MemVT = LN0->getMemoryVT();
8719     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
8720       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
8721                                        VT, LN0->getChain(), LN0->getBasePtr(),
8722                                        MemVT, LN0->getMemOperand());
8723       CombineTo(N, ExtLoad);
8724       DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8725       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8726     }
8727   }
8728 
8729   if (N0.getOpcode() == ISD::SETCC) {
8730     // For vectors:
8731     // aext(setcc) -> vsetcc
8732     // aext(setcc) -> truncate(vsetcc)
8733     // aext(setcc) -> aext(vsetcc)
8734     // Only do this before legalize for now.
8735     if (VT.isVector() && !LegalOperations) {
8736       EVT N00VT = N0.getOperand(0).getValueType();
8737       if (getSetCCResultType(N00VT) == N0.getValueType())
8738         return SDValue();
8739 
8740       // We know that the # elements of the results is the same as the
8741       // # elements of the compare (and the # elements of the compare result
8742       // for that matter).  Check to see that they are the same size.  If so,
8743       // we know that the element size of the sext'd result matches the
8744       // element size of the compare operands.
8745       if (VT.getSizeInBits() == N00VT.getSizeInBits())
8746         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
8747                              N0.getOperand(1),
8748                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
8749       // If the desired elements are smaller or larger than the source
8750       // elements we can use a matching integer vector type and then
8751       // truncate/any extend
8752       else {
8753         EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
8754         SDValue VsetCC =
8755           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
8756                         N0.getOperand(1),
8757                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
8758         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
8759       }
8760     }
8761 
8762     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
8763     SDLoc DL(N);
8764     if (SDValue SCC = SimplifySelectCC(
8765             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
8766             DAG.getConstant(0, DL, VT),
8767             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
8768       return SCC;
8769   }
8770 
8771   return SDValue();
8772 }
8773 
8774 SDValue DAGCombiner::visitAssertExt(SDNode *N) {
8775   unsigned Opcode = N->getOpcode();
8776   SDValue N0 = N->getOperand(0);
8777   SDValue N1 = N->getOperand(1);
8778   EVT AssertVT = cast<VTSDNode>(N1)->getVT();
8779 
8780   // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
8781   if (N0.getOpcode() == Opcode &&
8782       AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
8783     return N0;
8784 
8785   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
8786       N0.getOperand(0).getOpcode() == Opcode) {
8787     // We have an assert, truncate, assert sandwich. Make one stronger assert
8788     // by asserting on the smallest asserted type to the larger source type.
8789     // This eliminates the later assert:
8790     // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
8791     // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
8792     SDValue BigA = N0.getOperand(0);
8793     EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
8794     assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
8795            "Asserting zero/sign-extended bits to a type larger than the "
8796            "truncated destination does not provide information");
8797 
8798     SDLoc DL(N);
8799     EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
8800     SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
8801     SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
8802                                     BigA.getOperand(0), MinAssertVTVal);
8803     return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
8804   }
8805 
8806   return SDValue();
8807 }
8808 
8809 /// If the result of a wider load is shifted to right of N  bits and then
8810 /// truncated to a narrower type and where N is a multiple of number of bits of
8811 /// the narrower type, transform it to a narrower load from address + N / num of
8812 /// bits of new type. Also narrow the load if the result is masked with an AND
8813 /// to effectively produce a smaller type. If the result is to be extended, also
8814 /// fold the extension to form a extending load.
8815 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
8816   unsigned Opc = N->getOpcode();
8817 
8818   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
8819   SDValue N0 = N->getOperand(0);
8820   EVT VT = N->getValueType(0);
8821   EVT ExtVT = VT;
8822 
8823   // This transformation isn't valid for vector loads.
8824   if (VT.isVector())
8825     return SDValue();
8826 
8827   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
8828   // extended to VT.
8829   if (Opc == ISD::SIGN_EXTEND_INREG) {
8830     ExtType = ISD::SEXTLOAD;
8831     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8832   } else if (Opc == ISD::SRL) {
8833     // Another special-case: SRL is basically zero-extending a narrower value,
8834     // or it maybe shifting a higher subword, half or byte into the lowest
8835     // bits.
8836     ExtType = ISD::ZEXTLOAD;
8837     N0 = SDValue(N, 0);
8838 
8839     auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0));
8840     auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8841     if (!N01 || !LN0)
8842       return SDValue();
8843 
8844     uint64_t ShiftAmt = N01->getZExtValue();
8845     uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits();
8846     if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt)
8847       ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt);
8848     else
8849       ExtVT = EVT::getIntegerVT(*DAG.getContext(),
8850                                 VT.getSizeInBits() - ShiftAmt);
8851   } else if (Opc == ISD::AND) {
8852     // An AND with a constant mask is the same as a truncate + zero-extend.
8853     auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
8854     if (!AndC || !AndC->getAPIntValue().isMask())
8855       return SDValue();
8856 
8857     unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
8858     ExtType = ISD::ZEXTLOAD;
8859     ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
8860   }
8861 
8862   unsigned ShAmt = 0;
8863   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
8864     SDValue SRL = N0;
8865     if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) {
8866       ShAmt = ConstShift->getZExtValue();
8867       unsigned EVTBits = ExtVT.getSizeInBits();
8868       // Is the shift amount a multiple of size of VT?
8869       if ((ShAmt & (EVTBits-1)) == 0) {
8870         N0 = N0.getOperand(0);
8871         // Is the load width a multiple of size of VT?
8872         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
8873           return SDValue();
8874       }
8875 
8876       // At this point, we must have a load or else we can't do the transform.
8877       if (!isa<LoadSDNode>(N0)) return SDValue();
8878 
8879       auto *LN0 = cast<LoadSDNode>(N0);
8880 
8881       // Because a SRL must be assumed to *need* to zero-extend the high bits
8882       // (as opposed to anyext the high bits), we can't combine the zextload
8883       // lowering of SRL and an sextload.
8884       if (LN0->getExtensionType() == ISD::SEXTLOAD)
8885         return SDValue();
8886 
8887       // If the shift amount is larger than the input type then we're not
8888       // accessing any of the loaded bytes.  If the load was a zextload/extload
8889       // then the result of the shift+trunc is zero/undef (handled elsewhere).
8890       if (ShAmt >= LN0->getMemoryVT().getSizeInBits())
8891         return SDValue();
8892 
8893       // If the SRL is only used by a masking AND, we may be able to adjust
8894       // the ExtVT to make the AND redundant.
8895       SDNode *Mask = *(SRL->use_begin());
8896       if (Mask->getOpcode() == ISD::AND &&
8897           isa<ConstantSDNode>(Mask->getOperand(1))) {
8898         const APInt &ShiftMask =
8899           cast<ConstantSDNode>(Mask->getOperand(1))->getAPIntValue();
8900         if (ShiftMask.isMask()) {
8901           EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(),
8902                                            ShiftMask.countTrailingOnes());
8903           // If the mask is smaller, recompute the type.
8904           if ((ExtVT.getSizeInBits() > MaskedVT.getSizeInBits()) &&
8905               TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT))
8906             ExtVT = MaskedVT;
8907         }
8908       }
8909     }
8910   }
8911 
8912   // If the load is shifted left (and the result isn't shifted back right),
8913   // we can fold the truncate through the shift.
8914   unsigned ShLeftAmt = 0;
8915   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8916       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
8917     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8918       ShLeftAmt = N01->getZExtValue();
8919       N0 = N0.getOperand(0);
8920     }
8921   }
8922 
8923   // If we haven't found a load, we can't narrow it.
8924   if (!isa<LoadSDNode>(N0))
8925     return SDValue();
8926 
8927   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8928   if (!isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt))
8929     return SDValue();
8930 
8931   // For big endian targets, we need to adjust the offset to the pointer to
8932   // load the correct bytes.
8933   if (DAG.getDataLayout().isBigEndian()) {
8934     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
8935     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
8936     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
8937   }
8938 
8939   EVT PtrType = N0.getOperand(1).getValueType();
8940   uint64_t PtrOff = ShAmt / 8;
8941   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8942   SDLoc DL(LN0);
8943   // The original load itself didn't wrap, so an offset within it doesn't.
8944   SDNodeFlags Flags;
8945   Flags.setNoUnsignedWrap(true);
8946   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8947                                PtrType, LN0->getBasePtr(),
8948                                DAG.getConstant(PtrOff, DL, PtrType),
8949                                Flags);
8950   AddToWorklist(NewPtr.getNode());
8951 
8952   SDValue Load;
8953   if (ExtType == ISD::NON_EXTLOAD)
8954     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8955                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8956                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8957   else
8958     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8959                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8960                           NewAlign, LN0->getMemOperand()->getFlags(),
8961                           LN0->getAAInfo());
8962 
8963   // Replace the old load's chain with the new load's chain.
8964   WorklistRemover DeadNodes(*this);
8965   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8966 
8967   // Shift the result left, if we've swallowed a left shift.
8968   SDValue Result = Load;
8969   if (ShLeftAmt != 0) {
8970     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8971     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8972       ShImmTy = VT;
8973     // If the shift amount is as large as the result size (but, presumably,
8974     // no larger than the source) then the useful bits of the result are
8975     // zero; we can't simply return the shortened shift, because the result
8976     // of that operation is undefined.
8977     SDLoc DL(N0);
8978     if (ShLeftAmt >= VT.getSizeInBits())
8979       Result = DAG.getConstant(0, DL, VT);
8980     else
8981       Result = DAG.getNode(ISD::SHL, DL, VT,
8982                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8983   }
8984 
8985   // Return the new loaded value.
8986   return Result;
8987 }
8988 
8989 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8990   SDValue N0 = N->getOperand(0);
8991   SDValue N1 = N->getOperand(1);
8992   EVT VT = N->getValueType(0);
8993   EVT EVT = cast<VTSDNode>(N1)->getVT();
8994   unsigned VTBits = VT.getScalarSizeInBits();
8995   unsigned EVTBits = EVT.getScalarSizeInBits();
8996 
8997   if (N0.isUndef())
8998     return DAG.getUNDEF(VT);
8999 
9000   // fold (sext_in_reg c1) -> c1
9001   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
9002     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
9003 
9004   // If the input is already sign extended, just drop the extension.
9005   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
9006     return N0;
9007 
9008   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
9009   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9010       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
9011     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
9012                        N0.getOperand(0), N1);
9013 
9014   // fold (sext_in_reg (sext x)) -> (sext x)
9015   // fold (sext_in_reg (aext x)) -> (sext x)
9016   // if x is small enough.
9017   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
9018     SDValue N00 = N0.getOperand(0);
9019     if (N00.getScalarValueSizeInBits() <= EVTBits &&
9020         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
9021       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
9022   }
9023 
9024   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
9025   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
9026        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
9027        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
9028       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
9029     if (!LegalOperations ||
9030         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
9031       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
9032   }
9033 
9034   // fold (sext_in_reg (zext x)) -> (sext x)
9035   // iff we are extending the source sign bit.
9036   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
9037     SDValue N00 = N0.getOperand(0);
9038     if (N00.getScalarValueSizeInBits() == EVTBits &&
9039         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
9040       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
9041   }
9042 
9043   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
9044   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
9045     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
9046 
9047   // fold operands of sext_in_reg based on knowledge that the top bits are not
9048   // demanded.
9049   if (SimplifyDemandedBits(SDValue(N, 0)))
9050     return SDValue(N, 0);
9051 
9052   // fold (sext_in_reg (load x)) -> (smaller sextload x)
9053   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
9054   if (SDValue NarrowLoad = ReduceLoadWidth(N))
9055     return NarrowLoad;
9056 
9057   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
9058   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
9059   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
9060   if (N0.getOpcode() == ISD::SRL) {
9061     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
9062       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
9063         // We can turn this into an SRA iff the input to the SRL is already sign
9064         // extended enough.
9065         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
9066         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
9067           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
9068                              N0.getOperand(0), N0.getOperand(1));
9069       }
9070   }
9071 
9072   // fold (sext_inreg (extload x)) -> (sextload x)
9073   // If sextload is not supported by target, we can only do the combine when
9074   // load has one use. Doing otherwise can block folding the extload with other
9075   // extends that the target does support.
9076   if (ISD::isEXTLoad(N0.getNode()) &&
9077       ISD::isUNINDEXEDLoad(N0.getNode()) &&
9078       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
9079       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() &&
9080         N0.hasOneUse()) ||
9081        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
9082     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9083     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
9084                                      LN0->getChain(),
9085                                      LN0->getBasePtr(), EVT,
9086                                      LN0->getMemOperand());
9087     CombineTo(N, ExtLoad);
9088     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
9089     AddToWorklist(ExtLoad.getNode());
9090     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9091   }
9092   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
9093   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
9094       N0.hasOneUse() &&
9095       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
9096       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
9097        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
9098     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9099     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
9100                                      LN0->getChain(),
9101                                      LN0->getBasePtr(), EVT,
9102                                      LN0->getMemOperand());
9103     CombineTo(N, ExtLoad);
9104     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
9105     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9106   }
9107 
9108   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
9109   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
9110     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
9111                                            N0.getOperand(1), false))
9112       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
9113                          BSwap, N1);
9114   }
9115 
9116   return SDValue();
9117 }
9118 
9119 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
9120   SDValue N0 = N->getOperand(0);
9121   EVT VT = N->getValueType(0);
9122 
9123   if (N0.isUndef())
9124     return DAG.getUNDEF(VT);
9125 
9126   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
9127                                               LegalOperations))
9128     return SDValue(Res, 0);
9129 
9130   return SDValue();
9131 }
9132 
9133 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
9134   SDValue N0 = N->getOperand(0);
9135   EVT VT = N->getValueType(0);
9136 
9137   if (N0.isUndef())
9138     return DAG.getUNDEF(VT);
9139 
9140   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
9141                                               LegalOperations))
9142     return SDValue(Res, 0);
9143 
9144   return SDValue();
9145 }
9146 
9147 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
9148   SDValue N0 = N->getOperand(0);
9149   EVT VT = N->getValueType(0);
9150   bool isLE = DAG.getDataLayout().isLittleEndian();
9151 
9152   // noop truncate
9153   if (N0.getValueType() == N->getValueType(0))
9154     return N0;
9155 
9156   // fold (truncate (truncate x)) -> (truncate x)
9157   if (N0.getOpcode() == ISD::TRUNCATE)
9158     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
9159 
9160   // fold (truncate c1) -> c1
9161   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
9162     SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
9163     if (C.getNode() != N)
9164       return C;
9165   }
9166 
9167   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
9168   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
9169       N0.getOpcode() == ISD::SIGN_EXTEND ||
9170       N0.getOpcode() == ISD::ANY_EXTEND) {
9171     // if the source is smaller than the dest, we still need an extend.
9172     if (N0.getOperand(0).getValueType().bitsLT(VT))
9173       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
9174     // if the source is larger than the dest, than we just need the truncate.
9175     if (N0.getOperand(0).getValueType().bitsGT(VT))
9176       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
9177     // if the source and dest are the same type, we can drop both the extend
9178     // and the truncate.
9179     return N0.getOperand(0);
9180   }
9181 
9182   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
9183   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
9184     return SDValue();
9185 
9186   // Fold extract-and-trunc into a narrow extract. For example:
9187   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
9188   //   i32 y = TRUNCATE(i64 x)
9189   //        -- becomes --
9190   //   v16i8 b = BITCAST (v2i64 val)
9191   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
9192   //
9193   // Note: We only run this optimization after type legalization (which often
9194   // creates this pattern) and before operation legalization after which
9195   // we need to be more careful about the vector instructions that we generate.
9196   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9197       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
9198     EVT VecTy = N0.getOperand(0).getValueType();
9199     EVT ExTy = N0.getValueType();
9200     EVT TrTy = N->getValueType(0);
9201 
9202     unsigned NumElem = VecTy.getVectorNumElements();
9203     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
9204 
9205     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
9206     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
9207 
9208     SDValue EltNo = N0->getOperand(1);
9209     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
9210       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9211       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
9212       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
9213 
9214       SDLoc DL(N);
9215       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
9216                          DAG.getBitcast(NVT, N0.getOperand(0)),
9217                          DAG.getConstant(Index, DL, IndexTy));
9218     }
9219   }
9220 
9221   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
9222   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
9223     EVT SrcVT = N0.getValueType();
9224     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
9225         TLI.isTruncateFree(SrcVT, VT)) {
9226       SDLoc SL(N0);
9227       SDValue Cond = N0.getOperand(0);
9228       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
9229       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
9230       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
9231     }
9232   }
9233 
9234   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
9235   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
9236       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
9237       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
9238     SDValue Amt = N0.getOperand(1);
9239     KnownBits Known;
9240     DAG.computeKnownBits(Amt, Known);
9241     unsigned Size = VT.getScalarSizeInBits();
9242     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
9243       SDLoc SL(N);
9244       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
9245 
9246       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
9247       if (AmtVT != Amt.getValueType()) {
9248         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
9249         AddToWorklist(Amt.getNode());
9250       }
9251       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
9252     }
9253   }
9254 
9255   // Fold a series of buildvector, bitcast, and truncate if possible.
9256   // For example fold
9257   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
9258   //   (2xi32 (buildvector x, y)).
9259   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
9260       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
9261       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
9262       N0.getOperand(0).hasOneUse()) {
9263     SDValue BuildVect = N0.getOperand(0);
9264     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
9265     EVT TruncVecEltTy = VT.getVectorElementType();
9266 
9267     // Check that the element types match.
9268     if (BuildVectEltTy == TruncVecEltTy) {
9269       // Now we only need to compute the offset of the truncated elements.
9270       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
9271       unsigned TruncVecNumElts = VT.getVectorNumElements();
9272       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
9273 
9274       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
9275              "Invalid number of elements");
9276 
9277       SmallVector<SDValue, 8> Opnds;
9278       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
9279         Opnds.push_back(BuildVect.getOperand(i));
9280 
9281       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
9282     }
9283   }
9284 
9285   // See if we can simplify the input to this truncate through knowledge that
9286   // only the low bits are being used.
9287   // For example "trunc (or (shl x, 8), y)" // -> trunc y
9288   // Currently we only perform this optimization on scalars because vectors
9289   // may have different active low bits.
9290   if (!VT.isVector()) {
9291     APInt Mask =
9292         APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
9293     if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
9294       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
9295   }
9296 
9297   // fold (truncate (load x)) -> (smaller load x)
9298   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
9299   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
9300     if (SDValue Reduced = ReduceLoadWidth(N))
9301       return Reduced;
9302 
9303     // Handle the case where the load remains an extending load even
9304     // after truncation.
9305     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
9306       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9307       if (!LN0->isVolatile() &&
9308           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
9309         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
9310                                          VT, LN0->getChain(), LN0->getBasePtr(),
9311                                          LN0->getMemoryVT(),
9312                                          LN0->getMemOperand());
9313         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
9314         return NewLoad;
9315       }
9316     }
9317   }
9318 
9319   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
9320   // where ... are all 'undef'.
9321   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
9322     SmallVector<EVT, 8> VTs;
9323     SDValue V;
9324     unsigned Idx = 0;
9325     unsigned NumDefs = 0;
9326 
9327     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9328       SDValue X = N0.getOperand(i);
9329       if (!X.isUndef()) {
9330         V = X;
9331         Idx = i;
9332         NumDefs++;
9333       }
9334       // Stop if more than one members are non-undef.
9335       if (NumDefs > 1)
9336         break;
9337       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
9338                                      VT.getVectorElementType(),
9339                                      X.getValueType().getVectorNumElements()));
9340     }
9341 
9342     if (NumDefs == 0)
9343       return DAG.getUNDEF(VT);
9344 
9345     if (NumDefs == 1) {
9346       assert(V.getNode() && "The single defined operand is empty!");
9347       SmallVector<SDValue, 8> Opnds;
9348       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
9349         if (i != Idx) {
9350           Opnds.push_back(DAG.getUNDEF(VTs[i]));
9351           continue;
9352         }
9353         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
9354         AddToWorklist(NV.getNode());
9355         Opnds.push_back(NV);
9356       }
9357       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
9358     }
9359   }
9360 
9361   // Fold truncate of a bitcast of a vector to an extract of the low vector
9362   // element.
9363   //
9364   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
9365   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
9366     SDValue VecSrc = N0.getOperand(0);
9367     EVT SrcVT = VecSrc.getValueType();
9368     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
9369         (!LegalOperations ||
9370          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
9371       SDLoc SL(N);
9372 
9373       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
9374       unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1;
9375       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
9376                          VecSrc, DAG.getConstant(Idx, SL, IdxVT));
9377     }
9378   }
9379 
9380   // Simplify the operands using demanded-bits information.
9381   if (!VT.isVector() &&
9382       SimplifyDemandedBits(SDValue(N, 0)))
9383     return SDValue(N, 0);
9384 
9385   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
9386   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
9387   // When the adde's carry is not used.
9388   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
9389       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
9390       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
9391     SDLoc SL(N);
9392     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
9393     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
9394     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
9395     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
9396   }
9397 
9398   // fold (truncate (extract_subvector(ext x))) ->
9399   //      (extract_subvector x)
9400   // TODO: This can be generalized to cover cases where the truncate and extract
9401   // do not fully cancel each other out.
9402   if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9403     SDValue N00 = N0.getOperand(0);
9404     if (N00.getOpcode() == ISD::SIGN_EXTEND ||
9405         N00.getOpcode() == ISD::ZERO_EXTEND ||
9406         N00.getOpcode() == ISD::ANY_EXTEND) {
9407       if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
9408           VT.getVectorElementType())
9409         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
9410                            N00.getOperand(0), N0.getOperand(1));
9411     }
9412   }
9413 
9414   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
9415     return NewVSel;
9416 
9417   return SDValue();
9418 }
9419 
9420 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
9421   SDValue Elt = N->getOperand(i);
9422   if (Elt.getOpcode() != ISD::MERGE_VALUES)
9423     return Elt.getNode();
9424   return Elt.getOperand(Elt.getResNo()).getNode();
9425 }
9426 
9427 /// build_pair (load, load) -> load
9428 /// if load locations are consecutive.
9429 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
9430   assert(N->getOpcode() == ISD::BUILD_PAIR);
9431 
9432   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
9433   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
9434 
9435   // A BUILD_PAIR is always having the least significant part in elt 0 and the
9436   // most significant part in elt 1. So when combining into one large load, we
9437   // need to consider the endianness.
9438   if (DAG.getDataLayout().isBigEndian())
9439     std::swap(LD1, LD2);
9440 
9441   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
9442       LD1->getAddressSpace() != LD2->getAddressSpace())
9443     return SDValue();
9444   EVT LD1VT = LD1->getValueType(0);
9445   unsigned LD1Bytes = LD1VT.getStoreSize();
9446   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
9447       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
9448     unsigned Align = LD1->getAlignment();
9449     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
9450         VT.getTypeForEVT(*DAG.getContext()));
9451 
9452     if (NewAlign <= Align &&
9453         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
9454       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
9455                          LD1->getPointerInfo(), Align);
9456   }
9457 
9458   return SDValue();
9459 }
9460 
9461 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
9462   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
9463   // and Lo parts; on big-endian machines it doesn't.
9464   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
9465 }
9466 
9467 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
9468                                     const TargetLowering &TLI) {
9469   // If this is not a bitcast to an FP type or if the target doesn't have
9470   // IEEE754-compliant FP logic, we're done.
9471   EVT VT = N->getValueType(0);
9472   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
9473     return SDValue();
9474 
9475   // TODO: Use splat values for the constant-checking below and remove this
9476   // restriction.
9477   SDValue N0 = N->getOperand(0);
9478   EVT SourceVT = N0.getValueType();
9479   if (SourceVT.isVector())
9480     return SDValue();
9481 
9482   unsigned FPOpcode;
9483   APInt SignMask;
9484   switch (N0.getOpcode()) {
9485   case ISD::AND:
9486     FPOpcode = ISD::FABS;
9487     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
9488     break;
9489   case ISD::XOR:
9490     FPOpcode = ISD::FNEG;
9491     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
9492     break;
9493   // TODO: ISD::OR --> ISD::FNABS?
9494   default:
9495     return SDValue();
9496   }
9497 
9498   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
9499   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
9500   SDValue LogicOp0 = N0.getOperand(0);
9501   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9502   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
9503       LogicOp0.getOpcode() == ISD::BITCAST &&
9504       LogicOp0->getOperand(0).getValueType() == VT)
9505     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
9506 
9507   return SDValue();
9508 }
9509 
9510 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
9511   SDValue N0 = N->getOperand(0);
9512   EVT VT = N->getValueType(0);
9513 
9514   if (N0.isUndef())
9515     return DAG.getUNDEF(VT);
9516 
9517   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
9518   // Only do this before legalize, since afterward the target may be depending
9519   // on the bitconvert.
9520   // First check to see if this is all constant.
9521   if (!LegalTypes &&
9522       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
9523       VT.isVector()) {
9524     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
9525 
9526     EVT DestEltVT = N->getValueType(0).getVectorElementType();
9527     assert(!DestEltVT.isVector() &&
9528            "Element type of vector ValueType must not be vector!");
9529     if (isSimple)
9530       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
9531   }
9532 
9533   // If the input is a constant, let getNode fold it.
9534   // We always need to check that this is just a fp -> int or int -> conversion
9535   // otherwise we will get back N which will confuse the caller into thinking
9536   // we used CombineTo. This can block target combines from running. If we can't
9537   // allowed legal operations, we need to ensure the resulting operation will be
9538   // legal.
9539   // TODO: Maybe we should check that the return value isn't N explicitly?
9540   if ((isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
9541        (!LegalOperations || TLI.isOperationLegal(ISD::ConstantFP, VT))) ||
9542       (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
9543        (!LegalOperations || TLI.isOperationLegal(ISD::Constant, VT))))
9544     return DAG.getBitcast(VT, N0);
9545 
9546   // (conv (conv x, t1), t2) -> (conv x, t2)
9547   if (N0.getOpcode() == ISD::BITCAST)
9548     return DAG.getBitcast(VT, N0.getOperand(0));
9549 
9550   // fold (conv (load x)) -> (load (conv*)x)
9551   // If the resultant load doesn't need a higher alignment than the original!
9552   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9553       // Do not change the width of a volatile load.
9554       !cast<LoadSDNode>(N0)->isVolatile() &&
9555       // Do not remove the cast if the types differ in endian layout.
9556       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
9557           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
9558       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
9559       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
9560     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9561     unsigned OrigAlign = LN0->getAlignment();
9562 
9563     bool Fast = false;
9564     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
9565                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
9566         Fast) {
9567       SDValue Load =
9568           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9569                       LN0->getPointerInfo(), OrigAlign,
9570                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
9571       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
9572       return Load;
9573     }
9574   }
9575 
9576   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
9577     return V;
9578 
9579   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
9580   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
9581   //
9582   // For ppc_fp128:
9583   // fold (bitcast (fneg x)) ->
9584   //     flipbit = signbit
9585   //     (xor (bitcast x) (build_pair flipbit, flipbit))
9586   //
9587   // fold (bitcast (fabs x)) ->
9588   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
9589   //     (xor (bitcast x) (build_pair flipbit, flipbit))
9590   // This often reduces constant pool loads.
9591   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
9592        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
9593       N0.getNode()->hasOneUse() && VT.isInteger() &&
9594       !VT.isVector() && !N0.getValueType().isVector()) {
9595     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
9596     AddToWorklist(NewConv.getNode());
9597 
9598     SDLoc DL(N);
9599     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
9600       assert(VT.getSizeInBits() == 128);
9601       SDValue SignBit = DAG.getConstant(
9602           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
9603       SDValue FlipBit;
9604       if (N0.getOpcode() == ISD::FNEG) {
9605         FlipBit = SignBit;
9606         AddToWorklist(FlipBit.getNode());
9607       } else {
9608         assert(N0.getOpcode() == ISD::FABS);
9609         SDValue Hi =
9610             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
9611                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
9612                                               SDLoc(NewConv)));
9613         AddToWorklist(Hi.getNode());
9614         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
9615         AddToWorklist(FlipBit.getNode());
9616       }
9617       SDValue FlipBits =
9618           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9619       AddToWorklist(FlipBits.getNode());
9620       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
9621     }
9622     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9623     if (N0.getOpcode() == ISD::FNEG)
9624       return DAG.getNode(ISD::XOR, DL, VT,
9625                          NewConv, DAG.getConstant(SignBit, DL, VT));
9626     assert(N0.getOpcode() == ISD::FABS);
9627     return DAG.getNode(ISD::AND, DL, VT,
9628                        NewConv, DAG.getConstant(~SignBit, DL, VT));
9629   }
9630 
9631   // fold (bitconvert (fcopysign cst, x)) ->
9632   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
9633   // Note that we don't handle (copysign x, cst) because this can always be
9634   // folded to an fneg or fabs.
9635   //
9636   // For ppc_fp128:
9637   // fold (bitcast (fcopysign cst, x)) ->
9638   //     flipbit = (and (extract_element
9639   //                     (xor (bitcast cst), (bitcast x)), 0),
9640   //                    signbit)
9641   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
9642   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
9643       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
9644       VT.isInteger() && !VT.isVector()) {
9645     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
9646     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
9647     if (isTypeLegal(IntXVT)) {
9648       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
9649       AddToWorklist(X.getNode());
9650 
9651       // If X has a different width than the result/lhs, sext it or truncate it.
9652       unsigned VTWidth = VT.getSizeInBits();
9653       if (OrigXWidth < VTWidth) {
9654         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
9655         AddToWorklist(X.getNode());
9656       } else if (OrigXWidth > VTWidth) {
9657         // To get the sign bit in the right place, we have to shift it right
9658         // before truncating.
9659         SDLoc DL(X);
9660         X = DAG.getNode(ISD::SRL, DL,
9661                         X.getValueType(), X,
9662                         DAG.getConstant(OrigXWidth-VTWidth, DL,
9663                                         X.getValueType()));
9664         AddToWorklist(X.getNode());
9665         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
9666         AddToWorklist(X.getNode());
9667       }
9668 
9669       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
9670         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
9671         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9672         AddToWorklist(Cst.getNode());
9673         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
9674         AddToWorklist(X.getNode());
9675         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
9676         AddToWorklist(XorResult.getNode());
9677         SDValue XorResult64 = DAG.getNode(
9678             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
9679             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
9680                                   SDLoc(XorResult)));
9681         AddToWorklist(XorResult64.getNode());
9682         SDValue FlipBit =
9683             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
9684                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
9685         AddToWorklist(FlipBit.getNode());
9686         SDValue FlipBits =
9687             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9688         AddToWorklist(FlipBits.getNode());
9689         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
9690       }
9691       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9692       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
9693                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
9694       AddToWorklist(X.getNode());
9695 
9696       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9697       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
9698                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
9699       AddToWorklist(Cst.getNode());
9700 
9701       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
9702     }
9703   }
9704 
9705   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
9706   if (N0.getOpcode() == ISD::BUILD_PAIR)
9707     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
9708       return CombineLD;
9709 
9710   // Remove double bitcasts from shuffles - this is often a legacy of
9711   // XformToShuffleWithZero being used to combine bitmaskings (of
9712   // float vectors bitcast to integer vectors) into shuffles.
9713   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
9714   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
9715       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
9716       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
9717       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
9718     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
9719 
9720     // If operands are a bitcast, peek through if it casts the original VT.
9721     // If operands are a constant, just bitcast back to original VT.
9722     auto PeekThroughBitcast = [&](SDValue Op) {
9723       if (Op.getOpcode() == ISD::BITCAST &&
9724           Op.getOperand(0).getValueType() == VT)
9725         return SDValue(Op.getOperand(0));
9726       if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
9727           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
9728         return DAG.getBitcast(VT, Op);
9729       return SDValue();
9730     };
9731 
9732     // FIXME: If either input vector is bitcast, try to convert the shuffle to
9733     // the result type of this bitcast. This would eliminate at least one
9734     // bitcast. See the transform in InstCombine.
9735     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
9736     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
9737     if (!(SV0 && SV1))
9738       return SDValue();
9739 
9740     int MaskScale =
9741         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
9742     SmallVector<int, 8> NewMask;
9743     for (int M : SVN->getMask())
9744       for (int i = 0; i != MaskScale; ++i)
9745         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
9746 
9747     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9748     if (!LegalMask) {
9749       std::swap(SV0, SV1);
9750       ShuffleVectorSDNode::commuteMask(NewMask);
9751       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9752     }
9753 
9754     if (LegalMask)
9755       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
9756   }
9757 
9758   return SDValue();
9759 }
9760 
9761 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
9762   EVT VT = N->getValueType(0);
9763   return CombineConsecutiveLoads(N, VT);
9764 }
9765 
9766 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
9767 /// operands. DstEltVT indicates the destination element value type.
9768 SDValue DAGCombiner::
9769 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
9770   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
9771 
9772   // If this is already the right type, we're done.
9773   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
9774 
9775   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
9776   unsigned DstBitSize = DstEltVT.getSizeInBits();
9777 
9778   // If this is a conversion of N elements of one type to N elements of another
9779   // type, convert each element.  This handles FP<->INT cases.
9780   if (SrcBitSize == DstBitSize) {
9781     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9782                               BV->getValueType(0).getVectorNumElements());
9783 
9784     // Due to the FP element handling below calling this routine recursively,
9785     // we can end up with a scalar-to-vector node here.
9786     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
9787       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
9788                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
9789 
9790     SmallVector<SDValue, 8> Ops;
9791     for (SDValue Op : BV->op_values()) {
9792       // If the vector element type is not legal, the BUILD_VECTOR operands
9793       // are promoted and implicitly truncated.  Make that explicit here.
9794       if (Op.getValueType() != SrcEltVT)
9795         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
9796       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
9797       AddToWorklist(Ops.back().getNode());
9798     }
9799     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
9800   }
9801 
9802   // Otherwise, we're growing or shrinking the elements.  To avoid having to
9803   // handle annoying details of growing/shrinking FP values, we convert them to
9804   // int first.
9805   if (SrcEltVT.isFloatingPoint()) {
9806     // Convert the input float vector to a int vector where the elements are the
9807     // same sizes.
9808     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
9809     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
9810     SrcEltVT = IntVT;
9811   }
9812 
9813   // Now we know the input is an integer vector.  If the output is a FP type,
9814   // convert to integer first, then to FP of the right size.
9815   if (DstEltVT.isFloatingPoint()) {
9816     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
9817     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
9818 
9819     // Next, convert to FP elements of the same size.
9820     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
9821   }
9822 
9823   SDLoc DL(BV);
9824 
9825   // Okay, we know the src/dst types are both integers of differing types.
9826   // Handling growing first.
9827   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
9828   if (SrcBitSize < DstBitSize) {
9829     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
9830 
9831     SmallVector<SDValue, 8> Ops;
9832     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
9833          i += NumInputsPerOutput) {
9834       bool isLE = DAG.getDataLayout().isLittleEndian();
9835       APInt NewBits = APInt(DstBitSize, 0);
9836       bool EltIsUndef = true;
9837       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
9838         // Shift the previously computed bits over.
9839         NewBits <<= SrcBitSize;
9840         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
9841         if (Op.isUndef()) continue;
9842         EltIsUndef = false;
9843 
9844         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
9845                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
9846       }
9847 
9848       if (EltIsUndef)
9849         Ops.push_back(DAG.getUNDEF(DstEltVT));
9850       else
9851         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
9852     }
9853 
9854     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
9855     return DAG.getBuildVector(VT, DL, Ops);
9856   }
9857 
9858   // Finally, this must be the case where we are shrinking elements: each input
9859   // turns into multiple outputs.
9860   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
9861   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9862                             NumOutputsPerInput*BV->getNumOperands());
9863   SmallVector<SDValue, 8> Ops;
9864 
9865   for (const SDValue &Op : BV->op_values()) {
9866     if (Op.isUndef()) {
9867       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
9868       continue;
9869     }
9870 
9871     APInt OpVal = cast<ConstantSDNode>(Op)->
9872                   getAPIntValue().zextOrTrunc(SrcBitSize);
9873 
9874     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
9875       APInt ThisVal = OpVal.trunc(DstBitSize);
9876       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
9877       OpVal.lshrInPlace(DstBitSize);
9878     }
9879 
9880     // For big endian targets, swap the order of the pieces of each element.
9881     if (DAG.getDataLayout().isBigEndian())
9882       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
9883   }
9884 
9885   return DAG.getBuildVector(VT, DL, Ops);
9886 }
9887 
9888 static bool isContractable(SDNode *N) {
9889   SDNodeFlags F = N->getFlags();
9890   return F.hasAllowContract() || F.hasAllowReassociation();
9891 }
9892 
9893 /// Try to perform FMA combining on a given FADD node.
9894 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
9895   SDValue N0 = N->getOperand(0);
9896   SDValue N1 = N->getOperand(1);
9897   EVT VT = N->getValueType(0);
9898   SDLoc SL(N);
9899 
9900   const TargetOptions &Options = DAG.getTarget().Options;
9901 
9902   // Floating-point multiply-add with intermediate rounding.
9903   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9904 
9905   // Floating-point multiply-add without intermediate rounding.
9906   bool HasFMA =
9907       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9908       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9909 
9910   // No valid opcode, do not combine.
9911   if (!HasFMAD && !HasFMA)
9912     return SDValue();
9913 
9914   SDNodeFlags Flags = N->getFlags();
9915   bool CanFuse = Options.UnsafeFPMath || isContractable(N);
9916   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9917                               CanFuse || HasFMAD);
9918   // If the addition is not contractable, do not combine.
9919   if (!AllowFusionGlobally && !isContractable(N))
9920     return SDValue();
9921 
9922   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9923   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9924     return SDValue();
9925 
9926   // Always prefer FMAD to FMA for precision.
9927   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9928   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9929 
9930   // Is the node an FMUL and contractable either due to global flags or
9931   // SDNodeFlags.
9932   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9933     if (N.getOpcode() != ISD::FMUL)
9934       return false;
9935     return AllowFusionGlobally || isContractable(N.getNode());
9936   };
9937   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
9938   // prefer to fold the multiply with fewer uses.
9939   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
9940     if (N0.getNode()->use_size() > N1.getNode()->use_size())
9941       std::swap(N0, N1);
9942   }
9943 
9944   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
9945   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9946     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9947                        N0.getOperand(0), N0.getOperand(1), N1, Flags);
9948   }
9949 
9950   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
9951   // Note: Commutes FADD operands.
9952   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
9953     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9954                        N1.getOperand(0), N1.getOperand(1), N0, Flags);
9955   }
9956 
9957   // Look through FP_EXTEND nodes to do more combining.
9958 
9959   // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
9960   if (N0.getOpcode() == ISD::FP_EXTEND) {
9961     SDValue N00 = N0.getOperand(0);
9962     if (isContractableFMUL(N00) &&
9963         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9964       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9965                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9966                                      N00.getOperand(0)),
9967                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9968                                      N00.getOperand(1)), N1, Flags);
9969     }
9970   }
9971 
9972   // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
9973   // Note: Commutes FADD operands.
9974   if (N1.getOpcode() == ISD::FP_EXTEND) {
9975     SDValue N10 = N1.getOperand(0);
9976     if (isContractableFMUL(N10) &&
9977         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9978       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9979                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9980                                      N10.getOperand(0)),
9981                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9982                                      N10.getOperand(1)), N0, Flags);
9983     }
9984   }
9985 
9986   // More folding opportunities when target permits.
9987   if (Aggressive) {
9988     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9989     if (CanFuse &&
9990         N0.getOpcode() == PreferredFusedOpcode &&
9991         N0.getOperand(2).getOpcode() == ISD::FMUL &&
9992         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9993       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9994                          N0.getOperand(0), N0.getOperand(1),
9995                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9996                                      N0.getOperand(2).getOperand(0),
9997                                      N0.getOperand(2).getOperand(1),
9998                                      N1, Flags), Flags);
9999     }
10000 
10001     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
10002     if (CanFuse &&
10003         N1->getOpcode() == PreferredFusedOpcode &&
10004         N1.getOperand(2).getOpcode() == ISD::FMUL &&
10005         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
10006       return DAG.getNode(PreferredFusedOpcode, SL, VT,
10007                          N1.getOperand(0), N1.getOperand(1),
10008                          DAG.getNode(PreferredFusedOpcode, SL, VT,
10009                                      N1.getOperand(2).getOperand(0),
10010                                      N1.getOperand(2).getOperand(1),
10011                                      N0, Flags), Flags);
10012     }
10013 
10014 
10015     // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
10016     //   -> (fma x, y, (fma (fpext u), (fpext v), z))
10017     auto FoldFAddFMAFPExtFMul = [&] (
10018       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z,
10019       SDNodeFlags Flags) {
10020       return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
10021                          DAG.getNode(PreferredFusedOpcode, SL, VT,
10022                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
10023                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
10024                                      Z, Flags), Flags);
10025     };
10026     if (N0.getOpcode() == PreferredFusedOpcode) {
10027       SDValue N02 = N0.getOperand(2);
10028       if (N02.getOpcode() == ISD::FP_EXTEND) {
10029         SDValue N020 = N02.getOperand(0);
10030         if (isContractableFMUL(N020) &&
10031             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
10032           return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
10033                                       N020.getOperand(0), N020.getOperand(1),
10034                                       N1, Flags);
10035         }
10036       }
10037     }
10038 
10039     // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
10040     //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
10041     // FIXME: This turns two single-precision and one double-precision
10042     // operation into two double-precision operations, which might not be
10043     // interesting for all targets, especially GPUs.
10044     auto FoldFAddFPExtFMAFMul = [&] (
10045       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z,
10046       SDNodeFlags Flags) {
10047       return DAG.getNode(PreferredFusedOpcode, SL, VT,
10048                          DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
10049                          DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
10050                          DAG.getNode(PreferredFusedOpcode, SL, VT,
10051                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
10052                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
10053                                      Z, Flags), Flags);
10054     };
10055     if (N0.getOpcode() == ISD::FP_EXTEND) {
10056       SDValue N00 = N0.getOperand(0);
10057       if (N00.getOpcode() == PreferredFusedOpcode) {
10058         SDValue N002 = N00.getOperand(2);
10059         if (isContractableFMUL(N002) &&
10060             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
10061           return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
10062                                       N002.getOperand(0), N002.getOperand(1),
10063                                       N1, Flags);
10064         }
10065       }
10066     }
10067 
10068     // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
10069     //   -> (fma y, z, (fma (fpext u), (fpext v), x))
10070     if (N1.getOpcode() == PreferredFusedOpcode) {
10071       SDValue N12 = N1.getOperand(2);
10072       if (N12.getOpcode() == ISD::FP_EXTEND) {
10073         SDValue N120 = N12.getOperand(0);
10074         if (isContractableFMUL(N120) &&
10075             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
10076           return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
10077                                       N120.getOperand(0), N120.getOperand(1),
10078                                       N0, Flags);
10079         }
10080       }
10081     }
10082 
10083     // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
10084     //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
10085     // FIXME: This turns two single-precision and one double-precision
10086     // operation into two double-precision operations, which might not be
10087     // interesting for all targets, especially GPUs.
10088     if (N1.getOpcode() == ISD::FP_EXTEND) {
10089       SDValue N10 = N1.getOperand(0);
10090       if (N10.getOpcode() == PreferredFusedOpcode) {
10091         SDValue N102 = N10.getOperand(2);
10092         if (isContractableFMUL(N102) &&
10093             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
10094           return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
10095                                       N102.getOperand(0), N102.getOperand(1),
10096                                       N0, Flags);
10097         }
10098       }
10099     }
10100   }
10101 
10102   return SDValue();
10103 }
10104 
10105 /// Try to perform FMA combining on a given FSUB node.
10106 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
10107   SDValue N0 = N->getOperand(0);
10108   SDValue N1 = N->getOperand(1);
10109   EVT VT = N->getValueType(0);
10110   SDLoc SL(N);
10111 
10112   const TargetOptions &Options = DAG.getTarget().Options;
10113   // Floating-point multiply-add with intermediate rounding.
10114   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
10115 
10116   // Floating-point multiply-add without intermediate rounding.
10117   bool HasFMA =
10118       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
10119       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
10120 
10121   // No valid opcode, do not combine.
10122   if (!HasFMAD && !HasFMA)
10123     return SDValue();
10124 
10125   const SDNodeFlags Flags = N->getFlags();
10126   bool CanFuse = Options.UnsafeFPMath || isContractable(N);
10127   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
10128                               CanFuse || HasFMAD);
10129 
10130   // If the subtraction is not contractable, do not combine.
10131   if (!AllowFusionGlobally && !isContractable(N))
10132     return SDValue();
10133 
10134   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
10135   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
10136     return SDValue();
10137 
10138   // Always prefer FMAD to FMA for precision.
10139   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
10140   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
10141 
10142   // Is the node an FMUL and contractable either due to global flags or
10143   // SDNodeFlags.
10144   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
10145     if (N.getOpcode() != ISD::FMUL)
10146       return false;
10147     return AllowFusionGlobally || isContractable(N.getNode());
10148   };
10149 
10150   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
10151   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
10152     return DAG.getNode(PreferredFusedOpcode, SL, VT,
10153                        N0.getOperand(0), N0.getOperand(1),
10154                        DAG.getNode(ISD::FNEG, SL, VT, N1), Flags);
10155   }
10156 
10157   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
10158   // Note: Commutes FSUB operands.
10159   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
10160     return DAG.getNode(PreferredFusedOpcode, SL, VT,
10161                        DAG.getNode(ISD::FNEG, SL, VT,
10162                                    N1.getOperand(0)),
10163                        N1.getOperand(1), N0, Flags);
10164   }
10165 
10166   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
10167   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
10168       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
10169     SDValue N00 = N0.getOperand(0).getOperand(0);
10170     SDValue N01 = N0.getOperand(0).getOperand(1);
10171     return DAG.getNode(PreferredFusedOpcode, SL, VT,
10172                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
10173                        DAG.getNode(ISD::FNEG, SL, VT, N1), Flags);
10174   }
10175 
10176   // Look through FP_EXTEND nodes to do more combining.
10177 
10178   // fold (fsub (fpext (fmul x, y)), z)
10179   //   -> (fma (fpext x), (fpext y), (fneg z))
10180   if (N0.getOpcode() == ISD::FP_EXTEND) {
10181     SDValue N00 = N0.getOperand(0);
10182     if (isContractableFMUL(N00) &&
10183         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
10184       return DAG.getNode(PreferredFusedOpcode, SL, VT,
10185                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
10186                                      N00.getOperand(0)),
10187                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
10188                                      N00.getOperand(1)),
10189                          DAG.getNode(ISD::FNEG, SL, VT, N1), Flags);
10190     }
10191   }
10192 
10193   // fold (fsub x, (fpext (fmul y, z)))
10194   //   -> (fma (fneg (fpext y)), (fpext z), x)
10195   // Note: Commutes FSUB operands.
10196   if (N1.getOpcode() == ISD::FP_EXTEND) {
10197     SDValue N10 = N1.getOperand(0);
10198     if (isContractableFMUL(N10) &&
10199         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
10200       return DAG.getNode(PreferredFusedOpcode, SL, VT,
10201                          DAG.getNode(ISD::FNEG, SL, VT,
10202                                      DAG.getNode(ISD::FP_EXTEND, SL, VT,
10203                                                  N10.getOperand(0))),
10204                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
10205                                      N10.getOperand(1)),
10206                          N0, Flags);
10207     }
10208   }
10209 
10210   // fold (fsub (fpext (fneg (fmul, x, y))), z)
10211   //   -> (fneg (fma (fpext x), (fpext y), z))
10212   // Note: This could be removed with appropriate canonicalization of the
10213   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
10214   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
10215   // from implementing the canonicalization in visitFSUB.
10216   if (N0.getOpcode() == ISD::FP_EXTEND) {
10217     SDValue N00 = N0.getOperand(0);
10218     if (N00.getOpcode() == ISD::FNEG) {
10219       SDValue N000 = N00.getOperand(0);
10220       if (isContractableFMUL(N000) &&
10221           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
10222         return DAG.getNode(ISD::FNEG, SL, VT,
10223                            DAG.getNode(PreferredFusedOpcode, SL, VT,
10224                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
10225                                                    N000.getOperand(0)),
10226                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
10227                                                    N000.getOperand(1)),
10228                                        N1, Flags));
10229       }
10230     }
10231   }
10232 
10233   // fold (fsub (fneg (fpext (fmul, x, y))), z)
10234   //   -> (fneg (fma (fpext x)), (fpext y), z)
10235   // Note: This could be removed with appropriate canonicalization of the
10236   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
10237   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
10238   // from implementing the canonicalization in visitFSUB.
10239   if (N0.getOpcode() == ISD::FNEG) {
10240     SDValue N00 = N0.getOperand(0);
10241     if (N00.getOpcode() == ISD::FP_EXTEND) {
10242       SDValue N000 = N00.getOperand(0);
10243       if (isContractableFMUL(N000) &&
10244           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) {
10245         return DAG.getNode(ISD::FNEG, SL, VT,
10246                            DAG.getNode(PreferredFusedOpcode, SL, VT,
10247                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
10248                                                    N000.getOperand(0)),
10249                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
10250                                                    N000.getOperand(1)),
10251                                        N1, Flags));
10252       }
10253     }
10254   }
10255 
10256   // More folding opportunities when target permits.
10257   if (Aggressive) {
10258     // fold (fsub (fma x, y, (fmul u, v)), z)
10259     //   -> (fma x, y (fma u, v, (fneg z)))
10260     if (CanFuse && N0.getOpcode() == PreferredFusedOpcode &&
10261         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
10262         N0.getOperand(2)->hasOneUse()) {
10263       return DAG.getNode(PreferredFusedOpcode, SL, VT,
10264                          N0.getOperand(0), N0.getOperand(1),
10265                          DAG.getNode(PreferredFusedOpcode, SL, VT,
10266                                      N0.getOperand(2).getOperand(0),
10267                                      N0.getOperand(2).getOperand(1),
10268                                      DAG.getNode(ISD::FNEG, SL, VT,
10269                                                  N1), Flags), Flags);
10270     }
10271 
10272     // fold (fsub x, (fma y, z, (fmul u, v)))
10273     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
10274     if (CanFuse && N1.getOpcode() == PreferredFusedOpcode &&
10275         isContractableFMUL(N1.getOperand(2))) {
10276       SDValue N20 = N1.getOperand(2).getOperand(0);
10277       SDValue N21 = N1.getOperand(2).getOperand(1);
10278       return DAG.getNode(PreferredFusedOpcode, SL, VT,
10279                          DAG.getNode(ISD::FNEG, SL, VT,
10280                                      N1.getOperand(0)),
10281                          N1.getOperand(1),
10282                          DAG.getNode(PreferredFusedOpcode, SL, VT,
10283                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
10284                                      N21, N0, Flags), Flags);
10285     }
10286 
10287 
10288     // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
10289     //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
10290     if (N0.getOpcode() == PreferredFusedOpcode) {
10291       SDValue N02 = N0.getOperand(2);
10292       if (N02.getOpcode() == ISD::FP_EXTEND) {
10293         SDValue N020 = N02.getOperand(0);
10294         if (isContractableFMUL(N020) &&
10295             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
10296           return DAG.getNode(PreferredFusedOpcode, SL, VT,
10297                              N0.getOperand(0), N0.getOperand(1),
10298                              DAG.getNode(PreferredFusedOpcode, SL, VT,
10299                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
10300                                                      N020.getOperand(0)),
10301                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
10302                                                      N020.getOperand(1)),
10303                                          DAG.getNode(ISD::FNEG, SL, VT,
10304                                                      N1), Flags), Flags);
10305         }
10306       }
10307     }
10308 
10309     // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
10310     //   -> (fma (fpext x), (fpext y),
10311     //           (fma (fpext u), (fpext v), (fneg z)))
10312     // FIXME: This turns two single-precision and one double-precision
10313     // operation into two double-precision operations, which might not be
10314     // interesting for all targets, especially GPUs.
10315     if (N0.getOpcode() == ISD::FP_EXTEND) {
10316       SDValue N00 = N0.getOperand(0);
10317       if (N00.getOpcode() == PreferredFusedOpcode) {
10318         SDValue N002 = N00.getOperand(2);
10319         if (isContractableFMUL(N002) &&
10320             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
10321           return DAG.getNode(PreferredFusedOpcode, SL, VT,
10322                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
10323                                          N00.getOperand(0)),
10324                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
10325                                          N00.getOperand(1)),
10326                              DAG.getNode(PreferredFusedOpcode, SL, VT,
10327                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
10328                                                      N002.getOperand(0)),
10329                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
10330                                                      N002.getOperand(1)),
10331                                          DAG.getNode(ISD::FNEG, SL, VT,
10332                                                      N1), Flags), Flags);
10333         }
10334       }
10335     }
10336 
10337     // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
10338     //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
10339     if (N1.getOpcode() == PreferredFusedOpcode &&
10340         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
10341       SDValue N120 = N1.getOperand(2).getOperand(0);
10342       if (isContractableFMUL(N120) &&
10343           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
10344         SDValue N1200 = N120.getOperand(0);
10345         SDValue N1201 = N120.getOperand(1);
10346         return DAG.getNode(PreferredFusedOpcode, SL, VT,
10347                            DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
10348                            N1.getOperand(1),
10349                            DAG.getNode(PreferredFusedOpcode, SL, VT,
10350                                        DAG.getNode(ISD::FNEG, SL, VT,
10351                                                    DAG.getNode(ISD::FP_EXTEND, SL,
10352                                                                VT, N1200)),
10353                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
10354                                                    N1201),
10355                                        N0, Flags), Flags);
10356       }
10357     }
10358 
10359     // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
10360     //   -> (fma (fneg (fpext y)), (fpext z),
10361     //           (fma (fneg (fpext u)), (fpext v), x))
10362     // FIXME: This turns two single-precision and one double-precision
10363     // operation into two double-precision operations, which might not be
10364     // interesting for all targets, especially GPUs.
10365     if (N1.getOpcode() == ISD::FP_EXTEND &&
10366         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
10367       SDValue CvtSrc = N1.getOperand(0);
10368       SDValue N100 = CvtSrc.getOperand(0);
10369       SDValue N101 = CvtSrc.getOperand(1);
10370       SDValue N102 = CvtSrc.getOperand(2);
10371       if (isContractableFMUL(N102) &&
10372           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) {
10373         SDValue N1020 = N102.getOperand(0);
10374         SDValue N1021 = N102.getOperand(1);
10375         return DAG.getNode(PreferredFusedOpcode, SL, VT,
10376                            DAG.getNode(ISD::FNEG, SL, VT,
10377                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
10378                                                    N100)),
10379                            DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
10380                            DAG.getNode(PreferredFusedOpcode, SL, VT,
10381                                        DAG.getNode(ISD::FNEG, SL, VT,
10382                                                    DAG.getNode(ISD::FP_EXTEND, SL,
10383                                                                VT, N1020)),
10384                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
10385                                                    N1021),
10386                                        N0, Flags), Flags);
10387       }
10388     }
10389   }
10390 
10391   return SDValue();
10392 }
10393 
10394 /// Try to perform FMA combining on a given FMUL node based on the distributive
10395 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
10396 /// subtraction instead of addition).
10397 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
10398   SDValue N0 = N->getOperand(0);
10399   SDValue N1 = N->getOperand(1);
10400   EVT VT = N->getValueType(0);
10401   SDLoc SL(N);
10402   const SDNodeFlags Flags = N->getFlags();
10403 
10404   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
10405 
10406   const TargetOptions &Options = DAG.getTarget().Options;
10407 
10408   // The transforms below are incorrect when x == 0 and y == inf, because the
10409   // intermediate multiplication produces a nan.
10410   if (!Options.NoInfsFPMath)
10411     return SDValue();
10412 
10413   // Floating-point multiply-add without intermediate rounding.
10414   bool HasFMA =
10415       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
10416       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
10417       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
10418 
10419   // Floating-point multiply-add with intermediate rounding. This can result
10420   // in a less precise result due to the changed rounding order.
10421   bool HasFMAD = Options.UnsafeFPMath &&
10422                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
10423 
10424   // No valid opcode, do not combine.
10425   if (!HasFMAD && !HasFMA)
10426     return SDValue();
10427 
10428   // Always prefer FMAD to FMA for precision.
10429   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
10430   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
10431 
10432   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
10433   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
10434   auto FuseFADD = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) {
10435     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
10436       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
10437       if (XC1 && XC1->isExactlyValue(+1.0))
10438         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
10439                            Y, Flags);
10440       if (XC1 && XC1->isExactlyValue(-1.0))
10441         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
10442                            DAG.getNode(ISD::FNEG, SL, VT, Y), Flags);
10443     }
10444     return SDValue();
10445   };
10446 
10447   if (SDValue FMA = FuseFADD(N0, N1, Flags))
10448     return FMA;
10449   if (SDValue FMA = FuseFADD(N1, N0, Flags))
10450     return FMA;
10451 
10452   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
10453   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
10454   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
10455   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
10456   auto FuseFSUB = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) {
10457     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
10458       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
10459       if (XC0 && XC0->isExactlyValue(+1.0))
10460         return DAG.getNode(PreferredFusedOpcode, SL, VT,
10461                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
10462                            Y, Flags);
10463       if (XC0 && XC0->isExactlyValue(-1.0))
10464         return DAG.getNode(PreferredFusedOpcode, SL, VT,
10465                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
10466                            DAG.getNode(ISD::FNEG, SL, VT, Y), Flags);
10467 
10468       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
10469       if (XC1 && XC1->isExactlyValue(+1.0))
10470         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
10471                            DAG.getNode(ISD::FNEG, SL, VT, Y), Flags);
10472       if (XC1 && XC1->isExactlyValue(-1.0))
10473         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
10474                            Y, Flags);
10475     }
10476     return SDValue();
10477   };
10478 
10479   if (SDValue FMA = FuseFSUB(N0, N1, Flags))
10480     return FMA;
10481   if (SDValue FMA = FuseFSUB(N1, N0, Flags))
10482     return FMA;
10483 
10484   return SDValue();
10485 }
10486 
10487 static bool isFMulNegTwo(SDValue &N) {
10488   if (N.getOpcode() != ISD::FMUL)
10489     return false;
10490   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
10491     return CFP->isExactlyValue(-2.0);
10492   return false;
10493 }
10494 
10495 SDValue DAGCombiner::visitFADD(SDNode *N) {
10496   SDValue N0 = N->getOperand(0);
10497   SDValue N1 = N->getOperand(1);
10498   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
10499   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
10500   EVT VT = N->getValueType(0);
10501   SDLoc DL(N);
10502   const TargetOptions &Options = DAG.getTarget().Options;
10503   const SDNodeFlags Flags = N->getFlags();
10504 
10505   // fold vector ops
10506   if (VT.isVector())
10507     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10508       return FoldedVOp;
10509 
10510   // fold (fadd c1, c2) -> c1 + c2
10511   if (N0CFP && N1CFP)
10512     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
10513 
10514   // canonicalize constant to RHS
10515   if (N0CFP && !N1CFP)
10516     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
10517 
10518   if (SDValue NewSel = foldBinOpIntoSelect(N))
10519     return NewSel;
10520 
10521   // fold (fadd A, (fneg B)) -> (fsub A, B)
10522   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
10523       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
10524     return DAG.getNode(ISD::FSUB, DL, VT, N0,
10525                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
10526 
10527   // fold (fadd (fneg A), B) -> (fsub B, A)
10528   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
10529       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
10530     return DAG.getNode(ISD::FSUB, DL, VT, N1,
10531                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
10532 
10533   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
10534   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
10535   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
10536       (isFMulNegTwo(N1) && N1.hasOneUse())) {
10537     bool N1IsFMul = isFMulNegTwo(N1);
10538     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
10539     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
10540     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
10541   }
10542 
10543   ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1);
10544   if (N1C && N1C->isZero()) {
10545     if (N1C->isNegative() || Options.UnsafeFPMath ||
10546         Flags.hasNoSignedZeros()) {
10547       // fold (fadd A, 0) -> A
10548       return N0;
10549     }
10550   }
10551 
10552   // No FP constant should be created after legalization as Instruction
10553   // Selection pass has a hard time dealing with FP constants.
10554   bool AllowNewConst = (Level < AfterLegalizeDAG);
10555 
10556   // If 'unsafe math' or nnan is enabled, fold lots of things.
10557   if ((Options.UnsafeFPMath || Flags.hasNoNaNs()) && AllowNewConst) {
10558     // If allowed, fold (fadd (fneg x), x) -> 0.0
10559     if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
10560       return DAG.getConstantFP(0.0, DL, VT);
10561 
10562     // If allowed, fold (fadd x, (fneg x)) -> 0.0
10563     if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
10564       return DAG.getConstantFP(0.0, DL, VT);
10565   }
10566 
10567   // If 'unsafe math' or reassoc and nsz, fold lots of things.
10568   // TODO: break out portions of the transformations below for which Unsafe is
10569   //       considered and which do not require both nsz and reassoc
10570   if ((Options.UnsafeFPMath ||
10571        (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) &&
10572       AllowNewConst) {
10573     // fadd (fadd x, c1), c2 -> fadd x, c1 + c2
10574     if (N1CFP && N0.getOpcode() == ISD::FADD &&
10575         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
10576       SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, Flags);
10577       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC, Flags);
10578     }
10579 
10580     // We can fold chains of FADD's of the same value into multiplications.
10581     // This transform is not safe in general because we are reducing the number
10582     // of rounding steps.
10583     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
10584       if (N0.getOpcode() == ISD::FMUL) {
10585         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
10586         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
10587 
10588         // (fadd (fmul x, c), x) -> (fmul x, c+1)
10589         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
10590           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
10591                                        DAG.getConstantFP(1.0, DL, VT), Flags);
10592           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
10593         }
10594 
10595         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
10596         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
10597             N1.getOperand(0) == N1.getOperand(1) &&
10598             N0.getOperand(0) == N1.getOperand(0)) {
10599           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
10600                                        DAG.getConstantFP(2.0, DL, VT), Flags);
10601           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
10602         }
10603       }
10604 
10605       if (N1.getOpcode() == ISD::FMUL) {
10606         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
10607         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
10608 
10609         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
10610         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
10611           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
10612                                        DAG.getConstantFP(1.0, DL, VT), Flags);
10613           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
10614         }
10615 
10616         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
10617         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
10618             N0.getOperand(0) == N0.getOperand(1) &&
10619             N1.getOperand(0) == N0.getOperand(0)) {
10620           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
10621                                        DAG.getConstantFP(2.0, DL, VT), Flags);
10622           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
10623         }
10624       }
10625 
10626       if (N0.getOpcode() == ISD::FADD) {
10627         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
10628         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
10629         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
10630             (N0.getOperand(0) == N1)) {
10631           return DAG.getNode(ISD::FMUL, DL, VT,
10632                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
10633         }
10634       }
10635 
10636       if (N1.getOpcode() == ISD::FADD) {
10637         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
10638         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
10639         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
10640             N1.getOperand(0) == N0) {
10641           return DAG.getNode(ISD::FMUL, DL, VT,
10642                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
10643         }
10644       }
10645 
10646       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
10647       if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
10648           N0.getOperand(0) == N0.getOperand(1) &&
10649           N1.getOperand(0) == N1.getOperand(1) &&
10650           N0.getOperand(0) == N1.getOperand(0)) {
10651         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
10652                            DAG.getConstantFP(4.0, DL, VT), Flags);
10653       }
10654     }
10655   } // enable-unsafe-fp-math
10656 
10657   // FADD -> FMA combines:
10658   if (SDValue Fused = visitFADDForFMACombine(N)) {
10659     AddToWorklist(Fused.getNode());
10660     return Fused;
10661   }
10662   return SDValue();
10663 }
10664 
10665 SDValue DAGCombiner::visitFSUB(SDNode *N) {
10666   SDValue N0 = N->getOperand(0);
10667   SDValue N1 = N->getOperand(1);
10668   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10669   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10670   EVT VT = N->getValueType(0);
10671   SDLoc DL(N);
10672   const TargetOptions &Options = DAG.getTarget().Options;
10673   const SDNodeFlags Flags = N->getFlags();
10674 
10675   // fold vector ops
10676   if (VT.isVector())
10677     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10678       return FoldedVOp;
10679 
10680   // fold (fsub c1, c2) -> c1-c2
10681   if (N0CFP && N1CFP)
10682     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
10683 
10684   if (SDValue NewSel = foldBinOpIntoSelect(N))
10685     return NewSel;
10686 
10687   // (fsub A, 0) -> A
10688   if (N1CFP && N1CFP->isZero()) {
10689     if (!N1CFP->isNegative() || Options.UnsafeFPMath ||
10690         Flags.hasNoSignedZeros()) {
10691       return N0;
10692     }
10693   }
10694 
10695   if (N0 == N1) {
10696     // (fsub x, x) -> 0.0
10697     if (Options.UnsafeFPMath || Flags.hasNoNaNs())
10698       return DAG.getConstantFP(0.0f, DL, VT);
10699   }
10700 
10701   // (fsub 0, B) -> -B
10702   if (N0CFP && N0CFP->isZero()) {
10703     if (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) {
10704       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10705         return GetNegatedExpression(N1, DAG, LegalOperations);
10706       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10707         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
10708     }
10709   }
10710 
10711   // fold (fsub A, (fneg B)) -> (fadd A, B)
10712   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10713     return DAG.getNode(ISD::FADD, DL, VT, N0,
10714                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
10715 
10716   // If 'unsafe math' is enabled, fold lots of things.
10717   if (Options.UnsafeFPMath) {
10718     // (fsub x, (fadd x, y)) -> (fneg y)
10719     // (fsub x, (fadd y, x)) -> (fneg y)
10720     if (N1.getOpcode() == ISD::FADD) {
10721       SDValue N10 = N1->getOperand(0);
10722       SDValue N11 = N1->getOperand(1);
10723 
10724       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
10725         return GetNegatedExpression(N11, DAG, LegalOperations);
10726 
10727       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
10728         return GetNegatedExpression(N10, DAG, LegalOperations);
10729     }
10730   }
10731 
10732   // FSUB -> FMA combines:
10733   if (SDValue Fused = visitFSUBForFMACombine(N)) {
10734     AddToWorklist(Fused.getNode());
10735     return Fused;
10736   }
10737 
10738   return SDValue();
10739 }
10740 
10741 SDValue DAGCombiner::visitFMUL(SDNode *N) {
10742   SDValue N0 = N->getOperand(0);
10743   SDValue N1 = N->getOperand(1);
10744   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10745   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10746   EVT VT = N->getValueType(0);
10747   SDLoc DL(N);
10748   const TargetOptions &Options = DAG.getTarget().Options;
10749   const SDNodeFlags Flags = N->getFlags();
10750 
10751   // fold vector ops
10752   if (VT.isVector()) {
10753     // This just handles C1 * C2 for vectors. Other vector folds are below.
10754     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10755       return FoldedVOp;
10756   }
10757 
10758   // fold (fmul c1, c2) -> c1*c2
10759   if (N0CFP && N1CFP)
10760     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
10761 
10762   // canonicalize constant to RHS
10763   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10764      !isConstantFPBuildVectorOrConstantFP(N1))
10765     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
10766 
10767   // fold (fmul A, 1.0) -> A
10768   if (N1CFP && N1CFP->isExactlyValue(1.0))
10769     return N0;
10770 
10771   if (SDValue NewSel = foldBinOpIntoSelect(N))
10772     return NewSel;
10773 
10774   if (Options.UnsafeFPMath ||
10775       (Flags.hasNoNaNs() && Flags.hasNoSignedZeros())) {
10776     // fold (fmul A, 0) -> 0
10777     if (N1CFP && N1CFP->isZero())
10778       return N1;
10779   }
10780 
10781   if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) {
10782     // fmul (fmul X, C1), C2 -> fmul X, C1 * C2
10783     if (N0.getOpcode() == ISD::FMUL) {
10784       // Fold scalars or any vector constants (not just splats).
10785       // This fold is done in general by InstCombine, but extra fmul insts
10786       // may have been generated during lowering.
10787       SDValue N00 = N0.getOperand(0);
10788       SDValue N01 = N0.getOperand(1);
10789       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
10790       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
10791       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
10792 
10793       // Check 1: Make sure that the first operand of the inner multiply is NOT
10794       // a constant. Otherwise, we may induce infinite looping.
10795       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
10796         // Check 2: Make sure that the second operand of the inner multiply and
10797         // the second operand of the outer multiply are constants.
10798         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
10799             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
10800           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
10801           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
10802         }
10803       }
10804     }
10805 
10806     // Match a special-case: we convert X * 2.0 into fadd.
10807     // fmul (fadd X, X), C -> fmul X, 2.0 * C
10808     if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() &&
10809         N0.getOperand(0) == N0.getOperand(1)) {
10810       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
10811       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
10812       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
10813     }
10814   }
10815 
10816   // fold (fmul X, 2.0) -> (fadd X, X)
10817   if (N1CFP && N1CFP->isExactlyValue(+2.0))
10818     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
10819 
10820   // fold (fmul X, -1.0) -> (fneg X)
10821   if (N1CFP && N1CFP->isExactlyValue(-1.0))
10822     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10823       return DAG.getNode(ISD::FNEG, DL, VT, N0);
10824 
10825   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
10826   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10827     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10828       // Both can be negated for free, check to see if at least one is cheaper
10829       // negated.
10830       if (LHSNeg == 2 || RHSNeg == 2)
10831         return DAG.getNode(ISD::FMUL, DL, VT,
10832                            GetNegatedExpression(N0, DAG, LegalOperations),
10833                            GetNegatedExpression(N1, DAG, LegalOperations),
10834                            Flags);
10835     }
10836   }
10837 
10838   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
10839   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
10840   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
10841       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
10842       TLI.isOperationLegal(ISD::FABS, VT)) {
10843     SDValue Select = N0, X = N1;
10844     if (Select.getOpcode() != ISD::SELECT)
10845       std::swap(Select, X);
10846 
10847     SDValue Cond = Select.getOperand(0);
10848     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
10849     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
10850 
10851     if (TrueOpnd && FalseOpnd &&
10852         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
10853         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
10854         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
10855       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10856       switch (CC) {
10857       default: break;
10858       case ISD::SETOLT:
10859       case ISD::SETULT:
10860       case ISD::SETOLE:
10861       case ISD::SETULE:
10862       case ISD::SETLT:
10863       case ISD::SETLE:
10864         std::swap(TrueOpnd, FalseOpnd);
10865         LLVM_FALLTHROUGH;
10866       case ISD::SETOGT:
10867       case ISD::SETUGT:
10868       case ISD::SETOGE:
10869       case ISD::SETUGE:
10870       case ISD::SETGT:
10871       case ISD::SETGE:
10872         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
10873             TLI.isOperationLegal(ISD::FNEG, VT))
10874           return DAG.getNode(ISD::FNEG, DL, VT,
10875                    DAG.getNode(ISD::FABS, DL, VT, X));
10876         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
10877           return DAG.getNode(ISD::FABS, DL, VT, X);
10878 
10879         break;
10880       }
10881     }
10882   }
10883 
10884   // FMUL -> FMA combines:
10885   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
10886     AddToWorklist(Fused.getNode());
10887     return Fused;
10888   }
10889 
10890   return SDValue();
10891 }
10892 
10893 SDValue DAGCombiner::visitFMA(SDNode *N) {
10894   SDValue N0 = N->getOperand(0);
10895   SDValue N1 = N->getOperand(1);
10896   SDValue N2 = N->getOperand(2);
10897   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10898   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10899   EVT VT = N->getValueType(0);
10900   SDLoc DL(N);
10901   const TargetOptions &Options = DAG.getTarget().Options;
10902 
10903   // FMA nodes have flags that propagate to the created nodes.
10904   const SDNodeFlags Flags = N->getFlags();
10905   bool UnsafeFPMath = Options.UnsafeFPMath || isContractable(N);
10906 
10907   // Constant fold FMA.
10908   if (isa<ConstantFPSDNode>(N0) &&
10909       isa<ConstantFPSDNode>(N1) &&
10910       isa<ConstantFPSDNode>(N2)) {
10911     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
10912   }
10913 
10914   if (UnsafeFPMath) {
10915     if (N0CFP && N0CFP->isZero())
10916       return N2;
10917     if (N1CFP && N1CFP->isZero())
10918       return N2;
10919   }
10920   // TODO: The FMA node should have flags that propagate to these nodes.
10921   if (N0CFP && N0CFP->isExactlyValue(1.0))
10922     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
10923   if (N1CFP && N1CFP->isExactlyValue(1.0))
10924     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
10925 
10926   // Canonicalize (fma c, x, y) -> (fma x, c, y)
10927   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10928      !isConstantFPBuildVectorOrConstantFP(N1))
10929     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
10930 
10931   if (UnsafeFPMath) {
10932     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
10933     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
10934         isConstantFPBuildVectorOrConstantFP(N1) &&
10935         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
10936       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10937                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
10938                                      Flags), Flags);
10939     }
10940 
10941     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
10942     if (N0.getOpcode() == ISD::FMUL &&
10943         isConstantFPBuildVectorOrConstantFP(N1) &&
10944         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
10945       return DAG.getNode(ISD::FMA, DL, VT,
10946                          N0.getOperand(0),
10947                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
10948                                      Flags),
10949                          N2);
10950     }
10951   }
10952 
10953   // (fma x, 1, y) -> (fadd x, y)
10954   // (fma x, -1, y) -> (fadd (fneg x), y)
10955   if (N1CFP) {
10956     if (N1CFP->isExactlyValue(1.0))
10957       // TODO: The FMA node should have flags that propagate to this node.
10958       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
10959 
10960     if (N1CFP->isExactlyValue(-1.0) &&
10961         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
10962       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
10963       AddToWorklist(RHSNeg.getNode());
10964       // TODO: The FMA node should have flags that propagate to this node.
10965       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
10966     }
10967 
10968     // fma (fneg x), K, y -> fma x -K, y
10969     if (N0.getOpcode() == ISD::FNEG &&
10970         (TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10971          (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) {
10972       return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
10973                          DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2);
10974     }
10975   }
10976 
10977   if (UnsafeFPMath) {
10978     // (fma x, c, x) -> (fmul x, (c+1))
10979     if (N1CFP && N0 == N2) {
10980       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10981                          DAG.getNode(ISD::FADD, DL, VT, N1,
10982                                      DAG.getConstantFP(1.0, DL, VT), Flags),
10983                          Flags);
10984     }
10985 
10986     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
10987     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
10988       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10989                          DAG.getNode(ISD::FADD, DL, VT, N1,
10990                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
10991                          Flags);
10992     }
10993   }
10994 
10995   return SDValue();
10996 }
10997 
10998 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10999 // reciprocal.
11000 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
11001 // Notice that this is not always beneficial. One reason is different targets
11002 // may have different costs for FDIV and FMUL, so sometimes the cost of two
11003 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
11004 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
11005 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
11006   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
11007   const SDNodeFlags Flags = N->getFlags();
11008   if (!UnsafeMath && !Flags.hasAllowReciprocal())
11009     return SDValue();
11010 
11011   // Skip if current node is a reciprocal.
11012   SDValue N0 = N->getOperand(0);
11013   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
11014   if (N0CFP && N0CFP->isExactlyValue(1.0))
11015     return SDValue();
11016 
11017   // Exit early if the target does not want this transform or if there can't
11018   // possibly be enough uses of the divisor to make the transform worthwhile.
11019   SDValue N1 = N->getOperand(1);
11020   unsigned MinUses = TLI.combineRepeatedFPDivisors();
11021   if (!MinUses || N1->use_size() < MinUses)
11022     return SDValue();
11023 
11024   // Find all FDIV users of the same divisor.
11025   // Use a set because duplicates may be present in the user list.
11026   SetVector<SDNode *> Users;
11027   for (auto *U : N1->uses()) {
11028     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
11029       // This division is eligible for optimization only if global unsafe math
11030       // is enabled or if this division allows reciprocal formation.
11031       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
11032         Users.insert(U);
11033     }
11034   }
11035 
11036   // Now that we have the actual number of divisor uses, make sure it meets
11037   // the minimum threshold specified by the target.
11038   if (Users.size() < MinUses)
11039     return SDValue();
11040 
11041   EVT VT = N->getValueType(0);
11042   SDLoc DL(N);
11043   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
11044   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
11045 
11046   // Dividend / Divisor -> Dividend * Reciprocal
11047   for (auto *U : Users) {
11048     SDValue Dividend = U->getOperand(0);
11049     if (Dividend != FPOne) {
11050       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
11051                                     Reciprocal, Flags);
11052       CombineTo(U, NewNode);
11053     } else if (U != Reciprocal.getNode()) {
11054       // In the absence of fast-math-flags, this user node is always the
11055       // same node as Reciprocal, but with FMF they may be different nodes.
11056       CombineTo(U, Reciprocal);
11057     }
11058   }
11059   return SDValue(N, 0);  // N was replaced.
11060 }
11061 
11062 SDValue DAGCombiner::visitFDIV(SDNode *N) {
11063   SDValue N0 = N->getOperand(0);
11064   SDValue N1 = N->getOperand(1);
11065   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
11066   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
11067   EVT VT = N->getValueType(0);
11068   SDLoc DL(N);
11069   const TargetOptions &Options = DAG.getTarget().Options;
11070   SDNodeFlags Flags = N->getFlags();
11071 
11072   // fold vector ops
11073   if (VT.isVector())
11074     if (SDValue FoldedVOp = SimplifyVBinOp(N))
11075       return FoldedVOp;
11076 
11077   // fold (fdiv c1, c2) -> c1/c2
11078   if (N0CFP && N1CFP)
11079     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
11080 
11081   if (SDValue NewSel = foldBinOpIntoSelect(N))
11082     return NewSel;
11083 
11084   if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) {
11085     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
11086     if (N1CFP) {
11087       // Compute the reciprocal 1.0 / c2.
11088       const APFloat &N1APF = N1CFP->getValueAPF();
11089       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
11090       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
11091       // Only do the transform if the reciprocal is a legal fp immediate that
11092       // isn't too nasty (eg NaN, denormal, ...).
11093       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
11094           (!LegalOperations ||
11095            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
11096            // backend)... we should handle this gracefully after Legalize.
11097            // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
11098            TLI.isOperationLegal(ISD::ConstantFP, VT) ||
11099            TLI.isFPImmLegal(Recip, VT)))
11100         return DAG.getNode(ISD::FMUL, DL, VT, N0,
11101                            DAG.getConstantFP(Recip, DL, VT), Flags);
11102     }
11103 
11104     // If this FDIV is part of a reciprocal square root, it may be folded
11105     // into a target-specific square root estimate instruction.
11106     if (N1.getOpcode() == ISD::FSQRT) {
11107       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
11108         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
11109       }
11110     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
11111                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
11112       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
11113                                           Flags)) {
11114         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
11115         AddToWorklist(RV.getNode());
11116         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
11117       }
11118     } else if (N1.getOpcode() == ISD::FP_ROUND &&
11119                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
11120       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
11121                                           Flags)) {
11122         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
11123         AddToWorklist(RV.getNode());
11124         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
11125       }
11126     } else if (N1.getOpcode() == ISD::FMUL) {
11127       // Look through an FMUL. Even though this won't remove the FDIV directly,
11128       // it's still worthwhile to get rid of the FSQRT if possible.
11129       SDValue SqrtOp;
11130       SDValue OtherOp;
11131       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
11132         SqrtOp = N1.getOperand(0);
11133         OtherOp = N1.getOperand(1);
11134       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
11135         SqrtOp = N1.getOperand(1);
11136         OtherOp = N1.getOperand(0);
11137       }
11138       if (SqrtOp.getNode()) {
11139         // We found a FSQRT, so try to make this fold:
11140         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
11141         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
11142           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
11143           AddToWorklist(RV.getNode());
11144           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
11145         }
11146       }
11147     }
11148 
11149     // Fold into a reciprocal estimate and multiply instead of a real divide.
11150     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
11151       AddToWorklist(RV.getNode());
11152       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
11153     }
11154   }
11155 
11156   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
11157   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
11158     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
11159       // Both can be negated for free, check to see if at least one is cheaper
11160       // negated.
11161       if (LHSNeg == 2 || RHSNeg == 2)
11162         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
11163                            GetNegatedExpression(N0, DAG, LegalOperations),
11164                            GetNegatedExpression(N1, DAG, LegalOperations),
11165                            Flags);
11166     }
11167   }
11168 
11169   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
11170     return CombineRepeatedDivisors;
11171 
11172   return SDValue();
11173 }
11174 
11175 SDValue DAGCombiner::visitFREM(SDNode *N) {
11176   SDValue N0 = N->getOperand(0);
11177   SDValue N1 = N->getOperand(1);
11178   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
11179   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
11180   EVT VT = N->getValueType(0);
11181 
11182   // fold (frem c1, c2) -> fmod(c1,c2)
11183   if (N0CFP && N1CFP)
11184     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
11185 
11186   if (SDValue NewSel = foldBinOpIntoSelect(N))
11187     return NewSel;
11188 
11189   return SDValue();
11190 }
11191 
11192 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
11193   SDNodeFlags Flags = N->getFlags();
11194   if (!DAG.getTarget().Options.UnsafeFPMath &&
11195       !Flags.hasApproximateFuncs())
11196     return SDValue();
11197 
11198   SDValue N0 = N->getOperand(0);
11199   if (TLI.isFsqrtCheap(N0, DAG))
11200     return SDValue();
11201 
11202   // FSQRT nodes have flags that propagate to the created nodes.
11203   return buildSqrtEstimate(N0, Flags);
11204 }
11205 
11206 /// copysign(x, fp_extend(y)) -> copysign(x, y)
11207 /// copysign(x, fp_round(y)) -> copysign(x, y)
11208 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
11209   SDValue N1 = N->getOperand(1);
11210   if ((N1.getOpcode() == ISD::FP_EXTEND ||
11211        N1.getOpcode() == ISD::FP_ROUND)) {
11212     // Do not optimize out type conversion of f128 type yet.
11213     // For some targets like x86_64, configuration is changed to keep one f128
11214     // value in one SSE register, but instruction selection cannot handle
11215     // FCOPYSIGN on SSE registers yet.
11216     EVT N1VT = N1->getValueType(0);
11217     EVT N1Op0VT = N1->getOperand(0).getValueType();
11218     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
11219   }
11220   return false;
11221 }
11222 
11223 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
11224   SDValue N0 = N->getOperand(0);
11225   SDValue N1 = N->getOperand(1);
11226   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
11227   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
11228   EVT VT = N->getValueType(0);
11229 
11230   if (N0CFP && N1CFP) // Constant fold
11231     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
11232 
11233   if (N1CFP) {
11234     const APFloat &V = N1CFP->getValueAPF();
11235     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
11236     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
11237     if (!V.isNegative()) {
11238       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
11239         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
11240     } else {
11241       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
11242         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
11243                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
11244     }
11245   }
11246 
11247   // copysign(fabs(x), y) -> copysign(x, y)
11248   // copysign(fneg(x), y) -> copysign(x, y)
11249   // copysign(copysign(x,z), y) -> copysign(x, y)
11250   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
11251       N0.getOpcode() == ISD::FCOPYSIGN)
11252     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
11253 
11254   // copysign(x, abs(y)) -> abs(x)
11255   if (N1.getOpcode() == ISD::FABS)
11256     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
11257 
11258   // copysign(x, copysign(y,z)) -> copysign(x, z)
11259   if (N1.getOpcode() == ISD::FCOPYSIGN)
11260     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
11261 
11262   // copysign(x, fp_extend(y)) -> copysign(x, y)
11263   // copysign(x, fp_round(y)) -> copysign(x, y)
11264   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
11265     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
11266 
11267   return SDValue();
11268 }
11269 
11270 static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG,
11271                                const TargetLowering &TLI) {
11272   // This optimization is guarded by a function attribute because it may produce
11273   // unexpected results. Ie, programs may be relying on the platform-specific
11274   // undefined behavior when the float-to-int conversion overflows.
11275   const Function &F = DAG.getMachineFunction().getFunction();
11276   Attribute StrictOverflow = F.getFnAttribute("strict-float-cast-overflow");
11277   if (StrictOverflow.getValueAsString().equals("false"))
11278     return SDValue();
11279 
11280   // We only do this if the target has legal ftrunc. Otherwise, we'd likely be
11281   // replacing casts with a libcall. We also must be allowed to ignore -0.0
11282   // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer
11283   // conversions would return +0.0.
11284   // FIXME: We should be able to use node-level FMF here.
11285   // TODO: If strict math, should we use FABS (+ range check for signed cast)?
11286   EVT VT = N->getValueType(0);
11287   if (!TLI.isOperationLegal(ISD::FTRUNC, VT) ||
11288       !DAG.getTarget().Options.NoSignedZerosFPMath)
11289     return SDValue();
11290 
11291   // fptosi/fptoui round towards zero, so converting from FP to integer and
11292   // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X
11293   SDValue N0 = N->getOperand(0);
11294   if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT &&
11295       N0.getOperand(0).getValueType() == VT)
11296     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
11297 
11298   if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT &&
11299       N0.getOperand(0).getValueType() == VT)
11300     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
11301 
11302   return SDValue();
11303 }
11304 
11305 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
11306   SDValue N0 = N->getOperand(0);
11307   EVT VT = N->getValueType(0);
11308   EVT OpVT = N0.getValueType();
11309 
11310   // fold (sint_to_fp c1) -> c1fp
11311   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
11312       // ...but only if the target supports immediate floating-point values
11313       (!LegalOperations ||
11314        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
11315     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
11316 
11317   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
11318   // but UINT_TO_FP is legal on this target, try to convert.
11319   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
11320       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
11321     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
11322     if (DAG.SignBitIsZero(N0))
11323       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
11324   }
11325 
11326   // The next optimizations are desirable only if SELECT_CC can be lowered.
11327   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
11328     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
11329     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
11330         !VT.isVector() &&
11331         (!LegalOperations ||
11332          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
11333       SDLoc DL(N);
11334       SDValue Ops[] =
11335         { N0.getOperand(0), N0.getOperand(1),
11336           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
11337           N0.getOperand(2) };
11338       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
11339     }
11340 
11341     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
11342     //      (select_cc x, y, 1.0, 0.0,, cc)
11343     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
11344         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
11345         (!LegalOperations ||
11346          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
11347       SDLoc DL(N);
11348       SDValue Ops[] =
11349         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
11350           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
11351           N0.getOperand(0).getOperand(2) };
11352       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
11353     }
11354   }
11355 
11356   if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
11357     return FTrunc;
11358 
11359   return SDValue();
11360 }
11361 
11362 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
11363   SDValue N0 = N->getOperand(0);
11364   EVT VT = N->getValueType(0);
11365   EVT OpVT = N0.getValueType();
11366 
11367   // fold (uint_to_fp c1) -> c1fp
11368   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
11369       // ...but only if the target supports immediate floating-point values
11370       (!LegalOperations ||
11371        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
11372     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
11373 
11374   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
11375   // but SINT_TO_FP is legal on this target, try to convert.
11376   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
11377       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
11378     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
11379     if (DAG.SignBitIsZero(N0))
11380       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
11381   }
11382 
11383   // The next optimizations are desirable only if SELECT_CC can be lowered.
11384   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
11385     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
11386     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
11387         (!LegalOperations ||
11388          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
11389       SDLoc DL(N);
11390       SDValue Ops[] =
11391         { N0.getOperand(0), N0.getOperand(1),
11392           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
11393           N0.getOperand(2) };
11394       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
11395     }
11396   }
11397 
11398   if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
11399     return FTrunc;
11400 
11401   return SDValue();
11402 }
11403 
11404 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
11405 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
11406   SDValue N0 = N->getOperand(0);
11407   EVT VT = N->getValueType(0);
11408 
11409   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
11410     return SDValue();
11411 
11412   SDValue Src = N0.getOperand(0);
11413   EVT SrcVT = Src.getValueType();
11414   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
11415   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
11416 
11417   // We can safely assume the conversion won't overflow the output range,
11418   // because (for example) (uint8_t)18293.f is undefined behavior.
11419 
11420   // Since we can assume the conversion won't overflow, our decision as to
11421   // whether the input will fit in the float should depend on the minimum
11422   // of the input range and output range.
11423 
11424   // This means this is also safe for a signed input and unsigned output, since
11425   // a negative input would lead to undefined behavior.
11426   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
11427   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
11428   unsigned ActualSize = std::min(InputSize, OutputSize);
11429   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
11430 
11431   // We can only fold away the float conversion if the input range can be
11432   // represented exactly in the float range.
11433   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
11434     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
11435       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
11436                                                        : ISD::ZERO_EXTEND;
11437       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
11438     }
11439     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
11440       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
11441     return DAG.getBitcast(VT, Src);
11442   }
11443   return SDValue();
11444 }
11445 
11446 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
11447   SDValue N0 = N->getOperand(0);
11448   EVT VT = N->getValueType(0);
11449 
11450   // fold (fp_to_sint c1fp) -> c1
11451   if (isConstantFPBuildVectorOrConstantFP(N0))
11452     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
11453 
11454   return FoldIntToFPToInt(N, DAG);
11455 }
11456 
11457 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
11458   SDValue N0 = N->getOperand(0);
11459   EVT VT = N->getValueType(0);
11460 
11461   // fold (fp_to_uint c1fp) -> c1
11462   if (isConstantFPBuildVectorOrConstantFP(N0))
11463     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
11464 
11465   return FoldIntToFPToInt(N, DAG);
11466 }
11467 
11468 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
11469   SDValue N0 = N->getOperand(0);
11470   SDValue N1 = N->getOperand(1);
11471   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
11472   EVT VT = N->getValueType(0);
11473 
11474   // fold (fp_round c1fp) -> c1fp
11475   if (N0CFP)
11476     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
11477 
11478   // fold (fp_round (fp_extend x)) -> x
11479   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
11480     return N0.getOperand(0);
11481 
11482   // fold (fp_round (fp_round x)) -> (fp_round x)
11483   if (N0.getOpcode() == ISD::FP_ROUND) {
11484     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
11485     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
11486 
11487     // Skip this folding if it results in an fp_round from f80 to f16.
11488     //
11489     // f80 to f16 always generates an expensive (and as yet, unimplemented)
11490     // libcall to __truncxfhf2 instead of selecting native f16 conversion
11491     // instructions from f32 or f64.  Moreover, the first (value-preserving)
11492     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
11493     // x86.
11494     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
11495       return SDValue();
11496 
11497     // If the first fp_round isn't a value preserving truncation, it might
11498     // introduce a tie in the second fp_round, that wouldn't occur in the
11499     // single-step fp_round we want to fold to.
11500     // In other words, double rounding isn't the same as rounding.
11501     // Also, this is a value preserving truncation iff both fp_round's are.
11502     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
11503       SDLoc DL(N);
11504       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
11505                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
11506     }
11507   }
11508 
11509   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
11510   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
11511     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
11512                               N0.getOperand(0), N1);
11513     AddToWorklist(Tmp.getNode());
11514     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
11515                        Tmp, N0.getOperand(1));
11516   }
11517 
11518   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
11519     return NewVSel;
11520 
11521   return SDValue();
11522 }
11523 
11524 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
11525   SDValue N0 = N->getOperand(0);
11526   EVT VT = N->getValueType(0);
11527   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
11528   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
11529 
11530   // fold (fp_round_inreg c1fp) -> c1fp
11531   if (N0CFP && isTypeLegal(EVT)) {
11532     SDLoc DL(N);
11533     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
11534     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
11535   }
11536 
11537   return SDValue();
11538 }
11539 
11540 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
11541   SDValue N0 = N->getOperand(0);
11542   EVT VT = N->getValueType(0);
11543 
11544   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
11545   if (N->hasOneUse() &&
11546       N->use_begin()->getOpcode() == ISD::FP_ROUND)
11547     return SDValue();
11548 
11549   // fold (fp_extend c1fp) -> c1fp
11550   if (isConstantFPBuildVectorOrConstantFP(N0))
11551     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
11552 
11553   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
11554   if (N0.getOpcode() == ISD::FP16_TO_FP &&
11555       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
11556     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
11557 
11558   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
11559   // value of X.
11560   if (N0.getOpcode() == ISD::FP_ROUND
11561       && N0.getConstantOperandVal(1) == 1) {
11562     SDValue In = N0.getOperand(0);
11563     if (In.getValueType() == VT) return In;
11564     if (VT.bitsLT(In.getValueType()))
11565       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
11566                          In, N0.getOperand(1));
11567     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
11568   }
11569 
11570   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
11571   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11572        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
11573     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
11574     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
11575                                      LN0->getChain(),
11576                                      LN0->getBasePtr(), N0.getValueType(),
11577                                      LN0->getMemOperand());
11578     CombineTo(N, ExtLoad);
11579     CombineTo(N0.getNode(),
11580               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
11581                           N0.getValueType(), ExtLoad,
11582                           DAG.getIntPtrConstant(1, SDLoc(N0))),
11583               ExtLoad.getValue(1));
11584     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11585   }
11586 
11587   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
11588     return NewVSel;
11589 
11590   return SDValue();
11591 }
11592 
11593 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
11594   SDValue N0 = N->getOperand(0);
11595   EVT VT = N->getValueType(0);
11596 
11597   // fold (fceil c1) -> fceil(c1)
11598   if (isConstantFPBuildVectorOrConstantFP(N0))
11599     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
11600 
11601   return SDValue();
11602 }
11603 
11604 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
11605   SDValue N0 = N->getOperand(0);
11606   EVT VT = N->getValueType(0);
11607 
11608   // fold (ftrunc c1) -> ftrunc(c1)
11609   if (isConstantFPBuildVectorOrConstantFP(N0))
11610     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
11611 
11612   // fold ftrunc (known rounded int x) -> x
11613   // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
11614   // likely to be generated to extract integer from a rounded floating value.
11615   switch (N0.getOpcode()) {
11616   default: break;
11617   case ISD::FRINT:
11618   case ISD::FTRUNC:
11619   case ISD::FNEARBYINT:
11620   case ISD::FFLOOR:
11621   case ISD::FCEIL:
11622     return N0;
11623   }
11624 
11625   return SDValue();
11626 }
11627 
11628 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
11629   SDValue N0 = N->getOperand(0);
11630   EVT VT = N->getValueType(0);
11631 
11632   // fold (ffloor c1) -> ffloor(c1)
11633   if (isConstantFPBuildVectorOrConstantFP(N0))
11634     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
11635 
11636   return SDValue();
11637 }
11638 
11639 // FIXME: FNEG and FABS have a lot in common; refactor.
11640 SDValue DAGCombiner::visitFNEG(SDNode *N) {
11641   SDValue N0 = N->getOperand(0);
11642   EVT VT = N->getValueType(0);
11643 
11644   // Constant fold FNEG.
11645   if (isConstantFPBuildVectorOrConstantFP(N0))
11646     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
11647 
11648   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
11649                          &DAG.getTarget().Options))
11650     return GetNegatedExpression(N0, DAG, LegalOperations);
11651 
11652   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
11653   // constant pool values.
11654   if (!TLI.isFNegFree(VT) &&
11655       N0.getOpcode() == ISD::BITCAST &&
11656       N0.getNode()->hasOneUse()) {
11657     SDValue Int = N0.getOperand(0);
11658     EVT IntVT = Int.getValueType();
11659     if (IntVT.isInteger() && !IntVT.isVector()) {
11660       APInt SignMask;
11661       if (N0.getValueType().isVector()) {
11662         // For a vector, get a mask such as 0x80... per scalar element
11663         // and splat it.
11664         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
11665         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11666       } else {
11667         // For a scalar, just generate 0x80...
11668         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
11669       }
11670       SDLoc DL0(N0);
11671       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
11672                         DAG.getConstant(SignMask, DL0, IntVT));
11673       AddToWorklist(Int.getNode());
11674       return DAG.getBitcast(VT, Int);
11675     }
11676   }
11677 
11678   // (fneg (fmul c, x)) -> (fmul -c, x)
11679   if (N0.getOpcode() == ISD::FMUL &&
11680       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
11681     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
11682     if (CFP1) {
11683       APFloat CVal = CFP1->getValueAPF();
11684       CVal.changeSign();
11685       if (Level >= AfterLegalizeDAG &&
11686           (TLI.isFPImmLegal(CVal, VT) ||
11687            TLI.isOperationLegal(ISD::ConstantFP, VT)))
11688         return DAG.getNode(
11689             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
11690             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
11691             N0->getFlags());
11692     }
11693   }
11694 
11695   return SDValue();
11696 }
11697 
11698 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
11699   SDValue N0 = N->getOperand(0);
11700   SDValue N1 = N->getOperand(1);
11701   EVT VT = N->getValueType(0);
11702   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11703   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11704 
11705   if (N0CFP && N1CFP) {
11706     const APFloat &C0 = N0CFP->getValueAPF();
11707     const APFloat &C1 = N1CFP->getValueAPF();
11708     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
11709   }
11710 
11711   // Canonicalize to constant on RHS.
11712   if (isConstantFPBuildVectorOrConstantFP(N0) &&
11713      !isConstantFPBuildVectorOrConstantFP(N1))
11714     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
11715 
11716   return SDValue();
11717 }
11718 
11719 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
11720   SDValue N0 = N->getOperand(0);
11721   SDValue N1 = N->getOperand(1);
11722   EVT VT = N->getValueType(0);
11723   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11724   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11725 
11726   if (N0CFP && N1CFP) {
11727     const APFloat &C0 = N0CFP->getValueAPF();
11728     const APFloat &C1 = N1CFP->getValueAPF();
11729     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
11730   }
11731 
11732   // Canonicalize to constant on RHS.
11733   if (isConstantFPBuildVectorOrConstantFP(N0) &&
11734      !isConstantFPBuildVectorOrConstantFP(N1))
11735     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
11736 
11737   return SDValue();
11738 }
11739 
11740 SDValue DAGCombiner::visitFABS(SDNode *N) {
11741   SDValue N0 = N->getOperand(0);
11742   EVT VT = N->getValueType(0);
11743 
11744   // fold (fabs c1) -> fabs(c1)
11745   if (isConstantFPBuildVectorOrConstantFP(N0))
11746     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
11747 
11748   // fold (fabs (fabs x)) -> (fabs x)
11749   if (N0.getOpcode() == ISD::FABS)
11750     return N->getOperand(0);
11751 
11752   // fold (fabs (fneg x)) -> (fabs x)
11753   // fold (fabs (fcopysign x, y)) -> (fabs x)
11754   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
11755     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
11756 
11757   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
11758   // constant pool values.
11759   if (!TLI.isFAbsFree(VT) &&
11760       N0.getOpcode() == ISD::BITCAST &&
11761       N0.getNode()->hasOneUse()) {
11762     SDValue Int = N0.getOperand(0);
11763     EVT IntVT = Int.getValueType();
11764     if (IntVT.isInteger() && !IntVT.isVector()) {
11765       APInt SignMask;
11766       if (N0.getValueType().isVector()) {
11767         // For a vector, get a mask such as 0x7f... per scalar element
11768         // and splat it.
11769         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
11770         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11771       } else {
11772         // For a scalar, just generate 0x7f...
11773         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
11774       }
11775       SDLoc DL(N0);
11776       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
11777                         DAG.getConstant(SignMask, DL, IntVT));
11778       AddToWorklist(Int.getNode());
11779       return DAG.getBitcast(N->getValueType(0), Int);
11780     }
11781   }
11782 
11783   return SDValue();
11784 }
11785 
11786 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
11787   SDValue Chain = N->getOperand(0);
11788   SDValue N1 = N->getOperand(1);
11789   SDValue N2 = N->getOperand(2);
11790 
11791   // If N is a constant we could fold this into a fallthrough or unconditional
11792   // branch. However that doesn't happen very often in normal code, because
11793   // Instcombine/SimplifyCFG should have handled the available opportunities.
11794   // If we did this folding here, it would be necessary to update the
11795   // MachineBasicBlock CFG, which is awkward.
11796 
11797   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
11798   // on the target.
11799   if (N1.getOpcode() == ISD::SETCC &&
11800       TLI.isOperationLegalOrCustom(ISD::BR_CC,
11801                                    N1.getOperand(0).getValueType())) {
11802     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11803                        Chain, N1.getOperand(2),
11804                        N1.getOperand(0), N1.getOperand(1), N2);
11805   }
11806 
11807   if (N1.hasOneUse()) {
11808     if (SDValue NewN1 = rebuildSetCC(N1))
11809       return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, NewN1, N2);
11810   }
11811 
11812   return SDValue();
11813 }
11814 
11815 SDValue DAGCombiner::rebuildSetCC(SDValue N) {
11816   if (N.getOpcode() == ISD::SRL ||
11817       (N.getOpcode() == ISD::TRUNCATE &&
11818        (N.getOperand(0).hasOneUse() &&
11819         N.getOperand(0).getOpcode() == ISD::SRL))) {
11820     // Look pass the truncate.
11821     if (N.getOpcode() == ISD::TRUNCATE)
11822       N = N.getOperand(0);
11823 
11824     // Match this pattern so that we can generate simpler code:
11825     //
11826     //   %a = ...
11827     //   %b = and i32 %a, 2
11828     //   %c = srl i32 %b, 1
11829     //   brcond i32 %c ...
11830     //
11831     // into
11832     //
11833     //   %a = ...
11834     //   %b = and i32 %a, 2
11835     //   %c = setcc eq %b, 0
11836     //   brcond %c ...
11837     //
11838     // This applies only when the AND constant value has one bit set and the
11839     // SRL constant is equal to the log2 of the AND constant. The back-end is
11840     // smart enough to convert the result into a TEST/JMP sequence.
11841     SDValue Op0 = N.getOperand(0);
11842     SDValue Op1 = N.getOperand(1);
11843 
11844     if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) {
11845       SDValue AndOp1 = Op0.getOperand(1);
11846 
11847       if (AndOp1.getOpcode() == ISD::Constant) {
11848         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
11849 
11850         if (AndConst.isPowerOf2() &&
11851             cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) {
11852           SDLoc DL(N);
11853           return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()),
11854                               Op0, DAG.getConstant(0, DL, Op0.getValueType()),
11855                               ISD::SETNE);
11856         }
11857       }
11858     }
11859   }
11860 
11861   // Transform br(xor(x, y)) -> br(x != y)
11862   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
11863   if (N.getOpcode() == ISD::XOR) {
11864     // Because we may call this on a speculatively constructed
11865     // SimplifiedSetCC Node, we need to simplify this node first.
11866     // Ideally this should be folded into SimplifySetCC and not
11867     // here. For now, grab a handle to N so we don't lose it from
11868     // replacements interal to the visit.
11869     HandleSDNode XORHandle(N);
11870     while (N.getOpcode() == ISD::XOR) {
11871       SDValue Tmp = visitXOR(N.getNode());
11872       // No simplification done.
11873       if (!Tmp.getNode())
11874         break;
11875       // Returning N is form in-visit replacement that may invalidated
11876       // N. Grab value from Handle.
11877       if (Tmp.getNode() == N.getNode())
11878         N = XORHandle.getValue();
11879       else // Node simplified. Try simplifying again.
11880         N = Tmp;
11881     }
11882 
11883     if (N.getOpcode() != ISD::XOR)
11884       return N;
11885 
11886     SDNode *TheXor = N.getNode();
11887 
11888     SDValue Op0 = TheXor->getOperand(0);
11889     SDValue Op1 = TheXor->getOperand(1);
11890 
11891     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
11892       bool Equal = false;
11893       if (isOneConstant(Op0) && Op0.hasOneUse() &&
11894           Op0.getOpcode() == ISD::XOR) {
11895         TheXor = Op0.getNode();
11896         Equal = true;
11897       }
11898 
11899       EVT SetCCVT = N.getValueType();
11900       if (LegalTypes)
11901         SetCCVT = getSetCCResultType(SetCCVT);
11902       // Replace the uses of XOR with SETCC
11903       return DAG.getSetCC(SDLoc(TheXor), SetCCVT, Op0, Op1,
11904                           Equal ? ISD::SETEQ : ISD::SETNE);
11905     }
11906   }
11907 
11908   return SDValue();
11909 }
11910 
11911 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
11912 //
11913 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
11914   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
11915   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
11916 
11917   // If N is a constant we could fold this into a fallthrough or unconditional
11918   // branch. However that doesn't happen very often in normal code, because
11919   // Instcombine/SimplifyCFG should have handled the available opportunities.
11920   // If we did this folding here, it would be necessary to update the
11921   // MachineBasicBlock CFG, which is awkward.
11922 
11923   // Use SimplifySetCC to simplify SETCC's.
11924   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
11925                                CondLHS, CondRHS, CC->get(), SDLoc(N),
11926                                false);
11927   if (Simp.getNode()) AddToWorklist(Simp.getNode());
11928 
11929   // fold to a simpler setcc
11930   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
11931     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11932                        N->getOperand(0), Simp.getOperand(2),
11933                        Simp.getOperand(0), Simp.getOperand(1),
11934                        N->getOperand(4));
11935 
11936   return SDValue();
11937 }
11938 
11939 /// Return true if 'Use' is a load or a store that uses N as its base pointer
11940 /// and that N may be folded in the load / store addressing mode.
11941 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
11942                                     SelectionDAG &DAG,
11943                                     const TargetLowering &TLI) {
11944   EVT VT;
11945   unsigned AS;
11946 
11947   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
11948     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
11949       return false;
11950     VT = LD->getMemoryVT();
11951     AS = LD->getAddressSpace();
11952   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
11953     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
11954       return false;
11955     VT = ST->getMemoryVT();
11956     AS = ST->getAddressSpace();
11957   } else
11958     return false;
11959 
11960   TargetLowering::AddrMode AM;
11961   if (N->getOpcode() == ISD::ADD) {
11962     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11963     if (Offset)
11964       // [reg +/- imm]
11965       AM.BaseOffs = Offset->getSExtValue();
11966     else
11967       // [reg +/- reg]
11968       AM.Scale = 1;
11969   } else if (N->getOpcode() == ISD::SUB) {
11970     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11971     if (Offset)
11972       // [reg +/- imm]
11973       AM.BaseOffs = -Offset->getSExtValue();
11974     else
11975       // [reg +/- reg]
11976       AM.Scale = 1;
11977   } else
11978     return false;
11979 
11980   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
11981                                    VT.getTypeForEVT(*DAG.getContext()), AS);
11982 }
11983 
11984 /// Try turning a load/store into a pre-indexed load/store when the base
11985 /// pointer is an add or subtract and it has other uses besides the load/store.
11986 /// After the transformation, the new indexed load/store has effectively folded
11987 /// the add/subtract in and all of its other uses are redirected to the
11988 /// new load/store.
11989 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
11990   if (Level < AfterLegalizeDAG)
11991     return false;
11992 
11993   bool isLoad = true;
11994   SDValue Ptr;
11995   EVT VT;
11996   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11997     if (LD->isIndexed())
11998       return false;
11999     VT = LD->getMemoryVT();
12000     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
12001         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
12002       return false;
12003     Ptr = LD->getBasePtr();
12004   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
12005     if (ST->isIndexed())
12006       return false;
12007     VT = ST->getMemoryVT();
12008     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
12009         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
12010       return false;
12011     Ptr = ST->getBasePtr();
12012     isLoad = false;
12013   } else {
12014     return false;
12015   }
12016 
12017   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
12018   // out.  There is no reason to make this a preinc/predec.
12019   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
12020       Ptr.getNode()->hasOneUse())
12021     return false;
12022 
12023   // Ask the target to do addressing mode selection.
12024   SDValue BasePtr;
12025   SDValue Offset;
12026   ISD::MemIndexedMode AM = ISD::UNINDEXED;
12027   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
12028     return false;
12029 
12030   // Backends without true r+i pre-indexed forms may need to pass a
12031   // constant base with a variable offset so that constant coercion
12032   // will work with the patterns in canonical form.
12033   bool Swapped = false;
12034   if (isa<ConstantSDNode>(BasePtr)) {
12035     std::swap(BasePtr, Offset);
12036     Swapped = true;
12037   }
12038 
12039   // Don't create a indexed load / store with zero offset.
12040   if (isNullConstant(Offset))
12041     return false;
12042 
12043   // Try turning it into a pre-indexed load / store except when:
12044   // 1) The new base ptr is a frame index.
12045   // 2) If N is a store and the new base ptr is either the same as or is a
12046   //    predecessor of the value being stored.
12047   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
12048   //    that would create a cycle.
12049   // 4) All uses are load / store ops that use it as old base ptr.
12050 
12051   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
12052   // (plus the implicit offset) to a register to preinc anyway.
12053   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
12054     return false;
12055 
12056   // Check #2.
12057   if (!isLoad) {
12058     SDValue Val = cast<StoreSDNode>(N)->getValue();
12059     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
12060       return false;
12061   }
12062 
12063   // Caches for hasPredecessorHelper.
12064   SmallPtrSet<const SDNode *, 32> Visited;
12065   SmallVector<const SDNode *, 16> Worklist;
12066   Worklist.push_back(N);
12067 
12068   // If the offset is a constant, there may be other adds of constants that
12069   // can be folded with this one. We should do this to avoid having to keep
12070   // a copy of the original base pointer.
12071   SmallVector<SDNode *, 16> OtherUses;
12072   if (isa<ConstantSDNode>(Offset))
12073     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
12074                               UE = BasePtr.getNode()->use_end();
12075          UI != UE; ++UI) {
12076       SDUse &Use = UI.getUse();
12077       // Skip the use that is Ptr and uses of other results from BasePtr's
12078       // node (important for nodes that return multiple results).
12079       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
12080         continue;
12081 
12082       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
12083         continue;
12084 
12085       if (Use.getUser()->getOpcode() != ISD::ADD &&
12086           Use.getUser()->getOpcode() != ISD::SUB) {
12087         OtherUses.clear();
12088         break;
12089       }
12090 
12091       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
12092       if (!isa<ConstantSDNode>(Op1)) {
12093         OtherUses.clear();
12094         break;
12095       }
12096 
12097       // FIXME: In some cases, we can be smarter about this.
12098       if (Op1.getValueType() != Offset.getValueType()) {
12099         OtherUses.clear();
12100         break;
12101       }
12102 
12103       OtherUses.push_back(Use.getUser());
12104     }
12105 
12106   if (Swapped)
12107     std::swap(BasePtr, Offset);
12108 
12109   // Now check for #3 and #4.
12110   bool RealUse = false;
12111 
12112   for (SDNode *Use : Ptr.getNode()->uses()) {
12113     if (Use == N)
12114       continue;
12115     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
12116       return false;
12117 
12118     // If Ptr may be folded in addressing mode of other use, then it's
12119     // not profitable to do this transformation.
12120     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
12121       RealUse = true;
12122   }
12123 
12124   if (!RealUse)
12125     return false;
12126 
12127   SDValue Result;
12128   if (isLoad)
12129     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
12130                                 BasePtr, Offset, AM);
12131   else
12132     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
12133                                  BasePtr, Offset, AM);
12134   ++PreIndexedNodes;
12135   ++NodesCombined;
12136   LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: ";
12137              Result.getNode()->dump(&DAG); dbgs() << '\n');
12138   WorklistRemover DeadNodes(*this);
12139   if (isLoad) {
12140     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
12141     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
12142   } else {
12143     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
12144   }
12145 
12146   // Finally, since the node is now dead, remove it from the graph.
12147   deleteAndRecombine(N);
12148 
12149   if (Swapped)
12150     std::swap(BasePtr, Offset);
12151 
12152   // Replace other uses of BasePtr that can be updated to use Ptr
12153   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
12154     unsigned OffsetIdx = 1;
12155     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
12156       OffsetIdx = 0;
12157     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
12158            BasePtr.getNode() && "Expected BasePtr operand");
12159 
12160     // We need to replace ptr0 in the following expression:
12161     //   x0 * offset0 + y0 * ptr0 = t0
12162     // knowing that
12163     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
12164     //
12165     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
12166     // indexed load/store and the expression that needs to be re-written.
12167     //
12168     // Therefore, we have:
12169     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
12170 
12171     ConstantSDNode *CN =
12172       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
12173     int X0, X1, Y0, Y1;
12174     const APInt &Offset0 = CN->getAPIntValue();
12175     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
12176 
12177     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
12178     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
12179     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
12180     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
12181 
12182     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
12183 
12184     APInt CNV = Offset0;
12185     if (X0 < 0) CNV = -CNV;
12186     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
12187     else CNV = CNV - Offset1;
12188 
12189     SDLoc DL(OtherUses[i]);
12190 
12191     // We can now generate the new expression.
12192     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
12193     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
12194 
12195     SDValue NewUse = DAG.getNode(Opcode,
12196                                  DL,
12197                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
12198     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
12199     deleteAndRecombine(OtherUses[i]);
12200   }
12201 
12202   // Replace the uses of Ptr with uses of the updated base value.
12203   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
12204   deleteAndRecombine(Ptr.getNode());
12205   AddToWorklist(Result.getNode());
12206 
12207   return true;
12208 }
12209 
12210 /// Try to combine a load/store with a add/sub of the base pointer node into a
12211 /// post-indexed load/store. The transformation folded the add/subtract into the
12212 /// new indexed load/store effectively and all of its uses are redirected to the
12213 /// new load/store.
12214 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
12215   if (Level < AfterLegalizeDAG)
12216     return false;
12217 
12218   bool isLoad = true;
12219   SDValue Ptr;
12220   EVT VT;
12221   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
12222     if (LD->isIndexed())
12223       return false;
12224     VT = LD->getMemoryVT();
12225     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
12226         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
12227       return false;
12228     Ptr = LD->getBasePtr();
12229   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
12230     if (ST->isIndexed())
12231       return false;
12232     VT = ST->getMemoryVT();
12233     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
12234         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
12235       return false;
12236     Ptr = ST->getBasePtr();
12237     isLoad = false;
12238   } else {
12239     return false;
12240   }
12241 
12242   if (Ptr.getNode()->hasOneUse())
12243     return false;
12244 
12245   for (SDNode *Op : Ptr.getNode()->uses()) {
12246     if (Op == N ||
12247         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
12248       continue;
12249 
12250     SDValue BasePtr;
12251     SDValue Offset;
12252     ISD::MemIndexedMode AM = ISD::UNINDEXED;
12253     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
12254       // Don't create a indexed load / store with zero offset.
12255       if (isNullConstant(Offset))
12256         continue;
12257 
12258       // Try turning it into a post-indexed load / store except when
12259       // 1) All uses are load / store ops that use it as base ptr (and
12260       //    it may be folded as addressing mmode).
12261       // 2) Op must be independent of N, i.e. Op is neither a predecessor
12262       //    nor a successor of N. Otherwise, if Op is folded that would
12263       //    create a cycle.
12264 
12265       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
12266         continue;
12267 
12268       // Check for #1.
12269       bool TryNext = false;
12270       for (SDNode *Use : BasePtr.getNode()->uses()) {
12271         if (Use == Ptr.getNode())
12272           continue;
12273 
12274         // If all the uses are load / store addresses, then don't do the
12275         // transformation.
12276         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
12277           bool RealUse = false;
12278           for (SDNode *UseUse : Use->uses()) {
12279             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
12280               RealUse = true;
12281           }
12282 
12283           if (!RealUse) {
12284             TryNext = true;
12285             break;
12286           }
12287         }
12288       }
12289 
12290       if (TryNext)
12291         continue;
12292 
12293       // Check for #2
12294       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
12295         SDValue Result = isLoad
12296           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
12297                                BasePtr, Offset, AM)
12298           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
12299                                 BasePtr, Offset, AM);
12300         ++PostIndexedNodes;
12301         ++NodesCombined;
12302         LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG);
12303                    dbgs() << "\nWith: "; Result.getNode()->dump(&DAG);
12304                    dbgs() << '\n');
12305         WorklistRemover DeadNodes(*this);
12306         if (isLoad) {
12307           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
12308           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
12309         } else {
12310           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
12311         }
12312 
12313         // Finally, since the node is now dead, remove it from the graph.
12314         deleteAndRecombine(N);
12315 
12316         // Replace the uses of Use with uses of the updated base value.
12317         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
12318                                       Result.getValue(isLoad ? 1 : 0));
12319         deleteAndRecombine(Op);
12320         return true;
12321       }
12322     }
12323   }
12324 
12325   return false;
12326 }
12327 
12328 /// Return the base-pointer arithmetic from an indexed \p LD.
12329 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
12330   ISD::MemIndexedMode AM = LD->getAddressingMode();
12331   assert(AM != ISD::UNINDEXED);
12332   SDValue BP = LD->getOperand(1);
12333   SDValue Inc = LD->getOperand(2);
12334 
12335   // Some backends use TargetConstants for load offsets, but don't expect
12336   // TargetConstants in general ADD nodes. We can convert these constants into
12337   // regular Constants (if the constant is not opaque).
12338   assert((Inc.getOpcode() != ISD::TargetConstant ||
12339           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
12340          "Cannot split out indexing using opaque target constants");
12341   if (Inc.getOpcode() == ISD::TargetConstant) {
12342     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
12343     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
12344                           ConstInc->getValueType(0));
12345   }
12346 
12347   unsigned Opc =
12348       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
12349   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
12350 }
12351 
12352 SDValue DAGCombiner::visitLOAD(SDNode *N) {
12353   LoadSDNode *LD  = cast<LoadSDNode>(N);
12354   SDValue Chain = LD->getChain();
12355   SDValue Ptr   = LD->getBasePtr();
12356 
12357   // If load is not volatile and there are no uses of the loaded value (and
12358   // the updated indexed value in case of indexed loads), change uses of the
12359   // chain value into uses of the chain input (i.e. delete the dead load).
12360   if (!LD->isVolatile()) {
12361     if (N->getValueType(1) == MVT::Other) {
12362       // Unindexed loads.
12363       if (!N->hasAnyUseOfValue(0)) {
12364         // It's not safe to use the two value CombineTo variant here. e.g.
12365         // v1, chain2 = load chain1, loc
12366         // v2, chain3 = load chain2, loc
12367         // v3         = add v2, c
12368         // Now we replace use of chain2 with chain1.  This makes the second load
12369         // isomorphic to the one we are deleting, and thus makes this load live.
12370         LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG);
12371                    dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG);
12372                    dbgs() << "\n");
12373         WorklistRemover DeadNodes(*this);
12374         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
12375         AddUsersToWorklist(Chain.getNode());
12376         if (N->use_empty())
12377           deleteAndRecombine(N);
12378 
12379         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
12380       }
12381     } else {
12382       // Indexed loads.
12383       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
12384 
12385       // If this load has an opaque TargetConstant offset, then we cannot split
12386       // the indexing into an add/sub directly (that TargetConstant may not be
12387       // valid for a different type of node, and we cannot convert an opaque
12388       // target constant into a regular constant).
12389       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
12390                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
12391 
12392       if (!N->hasAnyUseOfValue(0) &&
12393           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
12394         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
12395         SDValue Index;
12396         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
12397           Index = SplitIndexingFromLoad(LD);
12398           // Try to fold the base pointer arithmetic into subsequent loads and
12399           // stores.
12400           AddUsersToWorklist(N);
12401         } else
12402           Index = DAG.getUNDEF(N->getValueType(1));
12403         LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG);
12404                    dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG);
12405                    dbgs() << " and 2 other values\n");
12406         WorklistRemover DeadNodes(*this);
12407         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
12408         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
12409         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
12410         deleteAndRecombine(N);
12411         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
12412       }
12413     }
12414   }
12415 
12416   // If this load is directly stored, replace the load value with the stored
12417   // value.
12418   // TODO: Handle store large -> read small portion.
12419   // TODO: Handle TRUNCSTORE/LOADEXT
12420   if (OptLevel != CodeGenOpt::None &&
12421       ISD::isNormalLoad(N) && !LD->isVolatile()) {
12422     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
12423       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
12424       if (PrevST->getBasePtr() == Ptr &&
12425           PrevST->getValue().getValueType() == N->getValueType(0))
12426         return CombineTo(N, PrevST->getOperand(1), Chain);
12427     }
12428   }
12429 
12430   // Try to infer better alignment information than the load already has.
12431   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
12432     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12433       if (Align > LD->getAlignment() && LD->getSrcValueOffset() % Align == 0) {
12434         SDValue NewLoad = DAG.getExtLoad(
12435             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
12436             LD->getPointerInfo(), LD->getMemoryVT(), Align,
12437             LD->getMemOperand()->getFlags(), LD->getAAInfo());
12438         // NewLoad will always be N as we are only refining the alignment
12439         assert(NewLoad.getNode() == N);
12440         (void)NewLoad;
12441       }
12442     }
12443   }
12444 
12445   if (LD->isUnindexed()) {
12446     // Walk up chain skipping non-aliasing memory nodes.
12447     SDValue BetterChain = FindBetterChain(N, Chain);
12448 
12449     // If there is a better chain.
12450     if (Chain != BetterChain) {
12451       SDValue ReplLoad;
12452 
12453       // Replace the chain to void dependency.
12454       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
12455         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
12456                                BetterChain, Ptr, LD->getMemOperand());
12457       } else {
12458         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
12459                                   LD->getValueType(0),
12460                                   BetterChain, Ptr, LD->getMemoryVT(),
12461                                   LD->getMemOperand());
12462       }
12463 
12464       // Create token factor to keep old chain connected.
12465       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
12466                                   MVT::Other, Chain, ReplLoad.getValue(1));
12467 
12468       // Replace uses with load result and token factor
12469       return CombineTo(N, ReplLoad.getValue(0), Token);
12470     }
12471   }
12472 
12473   // Try transforming N to an indexed load.
12474   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12475     return SDValue(N, 0);
12476 
12477   // Try to slice up N to more direct loads if the slices are mapped to
12478   // different register banks or pairing can take place.
12479   if (SliceUpLoad(N))
12480     return SDValue(N, 0);
12481 
12482   return SDValue();
12483 }
12484 
12485 namespace {
12486 
12487 /// Helper structure used to slice a load in smaller loads.
12488 /// Basically a slice is obtained from the following sequence:
12489 /// Origin = load Ty1, Base
12490 /// Shift = srl Ty1 Origin, CstTy Amount
12491 /// Inst = trunc Shift to Ty2
12492 ///
12493 /// Then, it will be rewritten into:
12494 /// Slice = load SliceTy, Base + SliceOffset
12495 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
12496 ///
12497 /// SliceTy is deduced from the number of bits that are actually used to
12498 /// build Inst.
12499 struct LoadedSlice {
12500   /// Helper structure used to compute the cost of a slice.
12501   struct Cost {
12502     /// Are we optimizing for code size.
12503     bool ForCodeSize;
12504 
12505     /// Various cost.
12506     unsigned Loads = 0;
12507     unsigned Truncates = 0;
12508     unsigned CrossRegisterBanksCopies = 0;
12509     unsigned ZExts = 0;
12510     unsigned Shift = 0;
12511 
12512     Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {}
12513 
12514     /// Get the cost of one isolated slice.
12515     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
12516         : ForCodeSize(ForCodeSize), Loads(1) {
12517       EVT TruncType = LS.Inst->getValueType(0);
12518       EVT LoadedType = LS.getLoadedType();
12519       if (TruncType != LoadedType &&
12520           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
12521         ZExts = 1;
12522     }
12523 
12524     /// Account for slicing gain in the current cost.
12525     /// Slicing provide a few gains like removing a shift or a
12526     /// truncate. This method allows to grow the cost of the original
12527     /// load with the gain from this slice.
12528     void addSliceGain(const LoadedSlice &LS) {
12529       // Each slice saves a truncate.
12530       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
12531       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
12532                               LS.Inst->getValueType(0)))
12533         ++Truncates;
12534       // If there is a shift amount, this slice gets rid of it.
12535       if (LS.Shift)
12536         ++Shift;
12537       // If this slice can merge a cross register bank copy, account for it.
12538       if (LS.canMergeExpensiveCrossRegisterBankCopy())
12539         ++CrossRegisterBanksCopies;
12540     }
12541 
12542     Cost &operator+=(const Cost &RHS) {
12543       Loads += RHS.Loads;
12544       Truncates += RHS.Truncates;
12545       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
12546       ZExts += RHS.ZExts;
12547       Shift += RHS.Shift;
12548       return *this;
12549     }
12550 
12551     bool operator==(const Cost &RHS) const {
12552       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
12553              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
12554              ZExts == RHS.ZExts && Shift == RHS.Shift;
12555     }
12556 
12557     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
12558 
12559     bool operator<(const Cost &RHS) const {
12560       // Assume cross register banks copies are as expensive as loads.
12561       // FIXME: Do we want some more target hooks?
12562       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
12563       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
12564       // Unless we are optimizing for code size, consider the
12565       // expensive operation first.
12566       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
12567         return ExpensiveOpsLHS < ExpensiveOpsRHS;
12568       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
12569              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
12570     }
12571 
12572     bool operator>(const Cost &RHS) const { return RHS < *this; }
12573 
12574     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
12575 
12576     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
12577   };
12578 
12579   // The last instruction that represent the slice. This should be a
12580   // truncate instruction.
12581   SDNode *Inst;
12582 
12583   // The original load instruction.
12584   LoadSDNode *Origin;
12585 
12586   // The right shift amount in bits from the original load.
12587   unsigned Shift;
12588 
12589   // The DAG from which Origin came from.
12590   // This is used to get some contextual information about legal types, etc.
12591   SelectionDAG *DAG;
12592 
12593   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
12594               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
12595       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
12596 
12597   /// Get the bits used in a chunk of bits \p BitWidth large.
12598   /// \return Result is \p BitWidth and has used bits set to 1 and
12599   ///         not used bits set to 0.
12600   APInt getUsedBits() const {
12601     // Reproduce the trunc(lshr) sequence:
12602     // - Start from the truncated value.
12603     // - Zero extend to the desired bit width.
12604     // - Shift left.
12605     assert(Origin && "No original load to compare against.");
12606     unsigned BitWidth = Origin->getValueSizeInBits(0);
12607     assert(Inst && "This slice is not bound to an instruction");
12608     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
12609            "Extracted slice is bigger than the whole type!");
12610     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
12611     UsedBits.setAllBits();
12612     UsedBits = UsedBits.zext(BitWidth);
12613     UsedBits <<= Shift;
12614     return UsedBits;
12615   }
12616 
12617   /// Get the size of the slice to be loaded in bytes.
12618   unsigned getLoadedSize() const {
12619     unsigned SliceSize = getUsedBits().countPopulation();
12620     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
12621     return SliceSize / 8;
12622   }
12623 
12624   /// Get the type that will be loaded for this slice.
12625   /// Note: This may not be the final type for the slice.
12626   EVT getLoadedType() const {
12627     assert(DAG && "Missing context");
12628     LLVMContext &Ctxt = *DAG->getContext();
12629     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
12630   }
12631 
12632   /// Get the alignment of the load used for this slice.
12633   unsigned getAlignment() const {
12634     unsigned Alignment = Origin->getAlignment();
12635     unsigned Offset = getOffsetFromBase();
12636     if (Offset != 0)
12637       Alignment = MinAlign(Alignment, Alignment + Offset);
12638     return Alignment;
12639   }
12640 
12641   /// Check if this slice can be rewritten with legal operations.
12642   bool isLegal() const {
12643     // An invalid slice is not legal.
12644     if (!Origin || !Inst || !DAG)
12645       return false;
12646 
12647     // Offsets are for indexed load only, we do not handle that.
12648     if (!Origin->getOffset().isUndef())
12649       return false;
12650 
12651     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12652 
12653     // Check that the type is legal.
12654     EVT SliceType = getLoadedType();
12655     if (!TLI.isTypeLegal(SliceType))
12656       return false;
12657 
12658     // Check that the load is legal for this type.
12659     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
12660       return false;
12661 
12662     // Check that the offset can be computed.
12663     // 1. Check its type.
12664     EVT PtrType = Origin->getBasePtr().getValueType();
12665     if (PtrType == MVT::Untyped || PtrType.isExtended())
12666       return false;
12667 
12668     // 2. Check that it fits in the immediate.
12669     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
12670       return false;
12671 
12672     // 3. Check that the computation is legal.
12673     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
12674       return false;
12675 
12676     // Check that the zext is legal if it needs one.
12677     EVT TruncateType = Inst->getValueType(0);
12678     if (TruncateType != SliceType &&
12679         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
12680       return false;
12681 
12682     return true;
12683   }
12684 
12685   /// Get the offset in bytes of this slice in the original chunk of
12686   /// bits.
12687   /// \pre DAG != nullptr.
12688   uint64_t getOffsetFromBase() const {
12689     assert(DAG && "Missing context.");
12690     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
12691     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
12692     uint64_t Offset = Shift / 8;
12693     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
12694     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
12695            "The size of the original loaded type is not a multiple of a"
12696            " byte.");
12697     // If Offset is bigger than TySizeInBytes, it means we are loading all
12698     // zeros. This should have been optimized before in the process.
12699     assert(TySizeInBytes > Offset &&
12700            "Invalid shift amount for given loaded size");
12701     if (IsBigEndian)
12702       Offset = TySizeInBytes - Offset - getLoadedSize();
12703     return Offset;
12704   }
12705 
12706   /// Generate the sequence of instructions to load the slice
12707   /// represented by this object and redirect the uses of this slice to
12708   /// this new sequence of instructions.
12709   /// \pre this->Inst && this->Origin are valid Instructions and this
12710   /// object passed the legal check: LoadedSlice::isLegal returned true.
12711   /// \return The last instruction of the sequence used to load the slice.
12712   SDValue loadSlice() const {
12713     assert(Inst && Origin && "Unable to replace a non-existing slice.");
12714     const SDValue &OldBaseAddr = Origin->getBasePtr();
12715     SDValue BaseAddr = OldBaseAddr;
12716     // Get the offset in that chunk of bytes w.r.t. the endianness.
12717     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
12718     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
12719     if (Offset) {
12720       // BaseAddr = BaseAddr + Offset.
12721       EVT ArithType = BaseAddr.getValueType();
12722       SDLoc DL(Origin);
12723       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
12724                               DAG->getConstant(Offset, DL, ArithType));
12725     }
12726 
12727     // Create the type of the loaded slice according to its size.
12728     EVT SliceType = getLoadedType();
12729 
12730     // Create the load for the slice.
12731     SDValue LastInst =
12732         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
12733                      Origin->getPointerInfo().getWithOffset(Offset),
12734                      getAlignment(), Origin->getMemOperand()->getFlags());
12735     // If the final type is not the same as the loaded type, this means that
12736     // we have to pad with zero. Create a zero extend for that.
12737     EVT FinalType = Inst->getValueType(0);
12738     if (SliceType != FinalType)
12739       LastInst =
12740           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
12741     return LastInst;
12742   }
12743 
12744   /// Check if this slice can be merged with an expensive cross register
12745   /// bank copy. E.g.,
12746   /// i = load i32
12747   /// f = bitcast i32 i to float
12748   bool canMergeExpensiveCrossRegisterBankCopy() const {
12749     if (!Inst || !Inst->hasOneUse())
12750       return false;
12751     SDNode *Use = *Inst->use_begin();
12752     if (Use->getOpcode() != ISD::BITCAST)
12753       return false;
12754     assert(DAG && "Missing context");
12755     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12756     EVT ResVT = Use->getValueType(0);
12757     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
12758     const TargetRegisterClass *ArgRC =
12759         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
12760     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
12761       return false;
12762 
12763     // At this point, we know that we perform a cross-register-bank copy.
12764     // Check if it is expensive.
12765     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
12766     // Assume bitcasts are cheap, unless both register classes do not
12767     // explicitly share a common sub class.
12768     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
12769       return false;
12770 
12771     // Check if it will be merged with the load.
12772     // 1. Check the alignment constraint.
12773     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
12774         ResVT.getTypeForEVT(*DAG->getContext()));
12775 
12776     if (RequiredAlignment > getAlignment())
12777       return false;
12778 
12779     // 2. Check that the load is a legal operation for that type.
12780     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
12781       return false;
12782 
12783     // 3. Check that we do not have a zext in the way.
12784     if (Inst->getValueType(0) != getLoadedType())
12785       return false;
12786 
12787     return true;
12788   }
12789 };
12790 
12791 } // end anonymous namespace
12792 
12793 /// Check that all bits set in \p UsedBits form a dense region, i.e.,
12794 /// \p UsedBits looks like 0..0 1..1 0..0.
12795 static bool areUsedBitsDense(const APInt &UsedBits) {
12796   // If all the bits are one, this is dense!
12797   if (UsedBits.isAllOnesValue())
12798     return true;
12799 
12800   // Get rid of the unused bits on the right.
12801   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
12802   // Get rid of the unused bits on the left.
12803   if (NarrowedUsedBits.countLeadingZeros())
12804     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
12805   // Check that the chunk of bits is completely used.
12806   return NarrowedUsedBits.isAllOnesValue();
12807 }
12808 
12809 /// Check whether or not \p First and \p Second are next to each other
12810 /// in memory. This means that there is no hole between the bits loaded
12811 /// by \p First and the bits loaded by \p Second.
12812 static bool areSlicesNextToEachOther(const LoadedSlice &First,
12813                                      const LoadedSlice &Second) {
12814   assert(First.Origin == Second.Origin && First.Origin &&
12815          "Unable to match different memory origins.");
12816   APInt UsedBits = First.getUsedBits();
12817   assert((UsedBits & Second.getUsedBits()) == 0 &&
12818          "Slices are not supposed to overlap.");
12819   UsedBits |= Second.getUsedBits();
12820   return areUsedBitsDense(UsedBits);
12821 }
12822 
12823 /// Adjust the \p GlobalLSCost according to the target
12824 /// paring capabilities and the layout of the slices.
12825 /// \pre \p GlobalLSCost should account for at least as many loads as
12826 /// there is in the slices in \p LoadedSlices.
12827 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12828                                  LoadedSlice::Cost &GlobalLSCost) {
12829   unsigned NumberOfSlices = LoadedSlices.size();
12830   // If there is less than 2 elements, no pairing is possible.
12831   if (NumberOfSlices < 2)
12832     return;
12833 
12834   // Sort the slices so that elements that are likely to be next to each
12835   // other in memory are next to each other in the list.
12836   llvm::sort(LoadedSlices.begin(), LoadedSlices.end(),
12837              [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
12838     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
12839     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
12840   });
12841   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
12842   // First (resp. Second) is the first (resp. Second) potentially candidate
12843   // to be placed in a paired load.
12844   const LoadedSlice *First = nullptr;
12845   const LoadedSlice *Second = nullptr;
12846   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
12847                 // Set the beginning of the pair.
12848                                                            First = Second) {
12849     Second = &LoadedSlices[CurrSlice];
12850 
12851     // If First is NULL, it means we start a new pair.
12852     // Get to the next slice.
12853     if (!First)
12854       continue;
12855 
12856     EVT LoadedType = First->getLoadedType();
12857 
12858     // If the types of the slices are different, we cannot pair them.
12859     if (LoadedType != Second->getLoadedType())
12860       continue;
12861 
12862     // Check if the target supplies paired loads for this type.
12863     unsigned RequiredAlignment = 0;
12864     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
12865       // move to the next pair, this type is hopeless.
12866       Second = nullptr;
12867       continue;
12868     }
12869     // Check if we meet the alignment requirement.
12870     if (RequiredAlignment > First->getAlignment())
12871       continue;
12872 
12873     // Check that both loads are next to each other in memory.
12874     if (!areSlicesNextToEachOther(*First, *Second))
12875       continue;
12876 
12877     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
12878     --GlobalLSCost.Loads;
12879     // Move to the next pair.
12880     Second = nullptr;
12881   }
12882 }
12883 
12884 /// Check the profitability of all involved LoadedSlice.
12885 /// Currently, it is considered profitable if there is exactly two
12886 /// involved slices (1) which are (2) next to each other in memory, and
12887 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
12888 ///
12889 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
12890 /// the elements themselves.
12891 ///
12892 /// FIXME: When the cost model will be mature enough, we can relax
12893 /// constraints (1) and (2).
12894 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12895                                 const APInt &UsedBits, bool ForCodeSize) {
12896   unsigned NumberOfSlices = LoadedSlices.size();
12897   if (StressLoadSlicing)
12898     return NumberOfSlices > 1;
12899 
12900   // Check (1).
12901   if (NumberOfSlices != 2)
12902     return false;
12903 
12904   // Check (2).
12905   if (!areUsedBitsDense(UsedBits))
12906     return false;
12907 
12908   // Check (3).
12909   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
12910   // The original code has one big load.
12911   OrigCost.Loads = 1;
12912   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
12913     const LoadedSlice &LS = LoadedSlices[CurrSlice];
12914     // Accumulate the cost of all the slices.
12915     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
12916     GlobalSlicingCost += SliceCost;
12917 
12918     // Account as cost in the original configuration the gain obtained
12919     // with the current slices.
12920     OrigCost.addSliceGain(LS);
12921   }
12922 
12923   // If the target supports paired load, adjust the cost accordingly.
12924   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
12925   return OrigCost > GlobalSlicingCost;
12926 }
12927 
12928 /// If the given load, \p LI, is used only by trunc or trunc(lshr)
12929 /// operations, split it in the various pieces being extracted.
12930 ///
12931 /// This sort of thing is introduced by SROA.
12932 /// This slicing takes care not to insert overlapping loads.
12933 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
12934 bool DAGCombiner::SliceUpLoad(SDNode *N) {
12935   if (Level < AfterLegalizeDAG)
12936     return false;
12937 
12938   LoadSDNode *LD = cast<LoadSDNode>(N);
12939   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
12940       !LD->getValueType(0).isInteger())
12941     return false;
12942 
12943   // Keep track of already used bits to detect overlapping values.
12944   // In that case, we will just abort the transformation.
12945   APInt UsedBits(LD->getValueSizeInBits(0), 0);
12946 
12947   SmallVector<LoadedSlice, 4> LoadedSlices;
12948 
12949   // Check if this load is used as several smaller chunks of bits.
12950   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
12951   // of computation for each trunc.
12952   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
12953        UI != UIEnd; ++UI) {
12954     // Skip the uses of the chain.
12955     if (UI.getUse().getResNo() != 0)
12956       continue;
12957 
12958     SDNode *User = *UI;
12959     unsigned Shift = 0;
12960 
12961     // Check if this is a trunc(lshr).
12962     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
12963         isa<ConstantSDNode>(User->getOperand(1))) {
12964       Shift = User->getConstantOperandVal(1);
12965       User = *User->use_begin();
12966     }
12967 
12968     // At this point, User is a Truncate, iff we encountered, trunc or
12969     // trunc(lshr).
12970     if (User->getOpcode() != ISD::TRUNCATE)
12971       return false;
12972 
12973     // The width of the type must be a power of 2 and greater than 8-bits.
12974     // Otherwise the load cannot be represented in LLVM IR.
12975     // Moreover, if we shifted with a non-8-bits multiple, the slice
12976     // will be across several bytes. We do not support that.
12977     unsigned Width = User->getValueSizeInBits(0);
12978     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
12979       return false;
12980 
12981     // Build the slice for this chain of computations.
12982     LoadedSlice LS(User, LD, Shift, &DAG);
12983     APInt CurrentUsedBits = LS.getUsedBits();
12984 
12985     // Check if this slice overlaps with another.
12986     if ((CurrentUsedBits & UsedBits) != 0)
12987       return false;
12988     // Update the bits used globally.
12989     UsedBits |= CurrentUsedBits;
12990 
12991     // Check if the new slice would be legal.
12992     if (!LS.isLegal())
12993       return false;
12994 
12995     // Record the slice.
12996     LoadedSlices.push_back(LS);
12997   }
12998 
12999   // Abort slicing if it does not seem to be profitable.
13000   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
13001     return false;
13002 
13003   ++SlicedLoads;
13004 
13005   // Rewrite each chain to use an independent load.
13006   // By construction, each chain can be represented by a unique load.
13007 
13008   // Prepare the argument for the new token factor for all the slices.
13009   SmallVector<SDValue, 8> ArgChains;
13010   for (SmallVectorImpl<LoadedSlice>::const_iterator
13011            LSIt = LoadedSlices.begin(),
13012            LSItEnd = LoadedSlices.end();
13013        LSIt != LSItEnd; ++LSIt) {
13014     SDValue SliceInst = LSIt->loadSlice();
13015     CombineTo(LSIt->Inst, SliceInst, true);
13016     if (SliceInst.getOpcode() != ISD::LOAD)
13017       SliceInst = SliceInst.getOperand(0);
13018     assert(SliceInst->getOpcode() == ISD::LOAD &&
13019            "It takes more than a zext to get to the loaded slice!!");
13020     ArgChains.push_back(SliceInst.getValue(1));
13021   }
13022 
13023   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
13024                               ArgChains);
13025   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
13026   AddToWorklist(Chain.getNode());
13027   return true;
13028 }
13029 
13030 /// Check to see if V is (and load (ptr), imm), where the load is having
13031 /// specific bytes cleared out.  If so, return the byte size being masked out
13032 /// and the shift amount.
13033 static std::pair<unsigned, unsigned>
13034 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
13035   std::pair<unsigned, unsigned> Result(0, 0);
13036 
13037   // Check for the structure we're looking for.
13038   if (V->getOpcode() != ISD::AND ||
13039       !isa<ConstantSDNode>(V->getOperand(1)) ||
13040       !ISD::isNormalLoad(V->getOperand(0).getNode()))
13041     return Result;
13042 
13043   // Check the chain and pointer.
13044   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
13045   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
13046 
13047   // The store should be chained directly to the load or be an operand of a
13048   // tokenfactor.
13049   if (LD == Chain.getNode())
13050     ; // ok.
13051   else if (Chain->getOpcode() != ISD::TokenFactor)
13052     return Result; // Fail.
13053   else {
13054     bool isOk = false;
13055     for (const SDValue &ChainOp : Chain->op_values())
13056       if (ChainOp.getNode() == LD) {
13057         isOk = true;
13058         break;
13059       }
13060     if (!isOk) return Result;
13061   }
13062 
13063   // This only handles simple types.
13064   if (V.getValueType() != MVT::i16 &&
13065       V.getValueType() != MVT::i32 &&
13066       V.getValueType() != MVT::i64)
13067     return Result;
13068 
13069   // Check the constant mask.  Invert it so that the bits being masked out are
13070   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
13071   // follow the sign bit for uniformity.
13072   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
13073   unsigned NotMaskLZ = countLeadingZeros(NotMask);
13074   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
13075   unsigned NotMaskTZ = countTrailingZeros(NotMask);
13076   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
13077   if (NotMaskLZ == 64) return Result;  // All zero mask.
13078 
13079   // See if we have a continuous run of bits.  If so, we have 0*1+0*
13080   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
13081     return Result;
13082 
13083   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
13084   if (V.getValueType() != MVT::i64 && NotMaskLZ)
13085     NotMaskLZ -= 64-V.getValueSizeInBits();
13086 
13087   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
13088   switch (MaskedBytes) {
13089   case 1:
13090   case 2:
13091   case 4: break;
13092   default: return Result; // All one mask, or 5-byte mask.
13093   }
13094 
13095   // Verify that the first bit starts at a multiple of mask so that the access
13096   // is aligned the same as the access width.
13097   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
13098 
13099   Result.first = MaskedBytes;
13100   Result.second = NotMaskTZ/8;
13101   return Result;
13102 }
13103 
13104 /// Check to see if IVal is something that provides a value as specified by
13105 /// MaskInfo. If so, replace the specified store with a narrower store of
13106 /// truncated IVal.
13107 static SDNode *
13108 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
13109                                 SDValue IVal, StoreSDNode *St,
13110                                 DAGCombiner *DC) {
13111   unsigned NumBytes = MaskInfo.first;
13112   unsigned ByteShift = MaskInfo.second;
13113   SelectionDAG &DAG = DC->getDAG();
13114 
13115   // Check to see if IVal is all zeros in the part being masked in by the 'or'
13116   // that uses this.  If not, this is not a replacement.
13117   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
13118                                   ByteShift*8, (ByteShift+NumBytes)*8);
13119   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
13120 
13121   // Check that it is legal on the target to do this.  It is legal if the new
13122   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
13123   // legalization.
13124   MVT VT = MVT::getIntegerVT(NumBytes*8);
13125   if (!DC->isTypeLegal(VT))
13126     return nullptr;
13127 
13128   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
13129   // shifted by ByteShift and truncated down to NumBytes.
13130   if (ByteShift) {
13131     SDLoc DL(IVal);
13132     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
13133                        DAG.getConstant(ByteShift*8, DL,
13134                                     DC->getShiftAmountTy(IVal.getValueType())));
13135   }
13136 
13137   // Figure out the offset for the store and the alignment of the access.
13138   unsigned StOffset;
13139   unsigned NewAlign = St->getAlignment();
13140 
13141   if (DAG.getDataLayout().isLittleEndian())
13142     StOffset = ByteShift;
13143   else
13144     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
13145 
13146   SDValue Ptr = St->getBasePtr();
13147   if (StOffset) {
13148     SDLoc DL(IVal);
13149     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
13150                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
13151     NewAlign = MinAlign(NewAlign, StOffset);
13152   }
13153 
13154   // Truncate down to the new size.
13155   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
13156 
13157   ++OpsNarrowed;
13158   return DAG
13159       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
13160                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
13161       .getNode();
13162 }
13163 
13164 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
13165 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
13166 /// narrowing the load and store if it would end up being a win for performance
13167 /// or code size.
13168 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
13169   StoreSDNode *ST  = cast<StoreSDNode>(N);
13170   if (ST->isVolatile())
13171     return SDValue();
13172 
13173   SDValue Chain = ST->getChain();
13174   SDValue Value = ST->getValue();
13175   SDValue Ptr   = ST->getBasePtr();
13176   EVT VT = Value.getValueType();
13177 
13178   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
13179     return SDValue();
13180 
13181   unsigned Opc = Value.getOpcode();
13182 
13183   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
13184   // is a byte mask indicating a consecutive number of bytes, check to see if
13185   // Y is known to provide just those bytes.  If so, we try to replace the
13186   // load + replace + store sequence with a single (narrower) store, which makes
13187   // the load dead.
13188   if (Opc == ISD::OR) {
13189     std::pair<unsigned, unsigned> MaskedLoad;
13190     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
13191     if (MaskedLoad.first)
13192       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
13193                                                   Value.getOperand(1), ST,this))
13194         return SDValue(NewST, 0);
13195 
13196     // Or is commutative, so try swapping X and Y.
13197     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
13198     if (MaskedLoad.first)
13199       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
13200                                                   Value.getOperand(0), ST,this))
13201         return SDValue(NewST, 0);
13202   }
13203 
13204   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
13205       Value.getOperand(1).getOpcode() != ISD::Constant)
13206     return SDValue();
13207 
13208   SDValue N0 = Value.getOperand(0);
13209   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
13210       Chain == SDValue(N0.getNode(), 1)) {
13211     LoadSDNode *LD = cast<LoadSDNode>(N0);
13212     if (LD->getBasePtr() != Ptr ||
13213         LD->getPointerInfo().getAddrSpace() !=
13214         ST->getPointerInfo().getAddrSpace())
13215       return SDValue();
13216 
13217     // Find the type to narrow it the load / op / store to.
13218     SDValue N1 = Value.getOperand(1);
13219     unsigned BitWidth = N1.getValueSizeInBits();
13220     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
13221     if (Opc == ISD::AND)
13222       Imm ^= APInt::getAllOnesValue(BitWidth);
13223     if (Imm == 0 || Imm.isAllOnesValue())
13224       return SDValue();
13225     unsigned ShAmt = Imm.countTrailingZeros();
13226     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
13227     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
13228     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
13229     // The narrowing should be profitable, the load/store operation should be
13230     // legal (or custom) and the store size should be equal to the NewVT width.
13231     while (NewBW < BitWidth &&
13232            (NewVT.getStoreSizeInBits() != NewBW ||
13233             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
13234             !TLI.isNarrowingProfitable(VT, NewVT))) {
13235       NewBW = NextPowerOf2(NewBW);
13236       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
13237     }
13238     if (NewBW >= BitWidth)
13239       return SDValue();
13240 
13241     // If the lsb changed does not start at the type bitwidth boundary,
13242     // start at the previous one.
13243     if (ShAmt % NewBW)
13244       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
13245     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
13246                                    std::min(BitWidth, ShAmt + NewBW));
13247     if ((Imm & Mask) == Imm) {
13248       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
13249       if (Opc == ISD::AND)
13250         NewImm ^= APInt::getAllOnesValue(NewBW);
13251       uint64_t PtrOff = ShAmt / 8;
13252       // For big endian targets, we need to adjust the offset to the pointer to
13253       // load the correct bytes.
13254       if (DAG.getDataLayout().isBigEndian())
13255         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
13256 
13257       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
13258       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
13259       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
13260         return SDValue();
13261 
13262       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
13263                                    Ptr.getValueType(), Ptr,
13264                                    DAG.getConstant(PtrOff, SDLoc(LD),
13265                                                    Ptr.getValueType()));
13266       SDValue NewLD =
13267           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
13268                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
13269                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
13270       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
13271                                    DAG.getConstant(NewImm, SDLoc(Value),
13272                                                    NewVT));
13273       SDValue NewST =
13274           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
13275                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
13276 
13277       AddToWorklist(NewPtr.getNode());
13278       AddToWorklist(NewLD.getNode());
13279       AddToWorklist(NewVal.getNode());
13280       WorklistRemover DeadNodes(*this);
13281       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
13282       ++OpsNarrowed;
13283       return NewST;
13284     }
13285   }
13286 
13287   return SDValue();
13288 }
13289 
13290 /// For a given floating point load / store pair, if the load value isn't used
13291 /// by any other operations, then consider transforming the pair to integer
13292 /// load / store operations if the target deems the transformation profitable.
13293 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
13294   StoreSDNode *ST  = cast<StoreSDNode>(N);
13295   SDValue Chain = ST->getChain();
13296   SDValue Value = ST->getValue();
13297   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
13298       Value.hasOneUse() &&
13299       Chain == SDValue(Value.getNode(), 1)) {
13300     LoadSDNode *LD = cast<LoadSDNode>(Value);
13301     EVT VT = LD->getMemoryVT();
13302     if (!VT.isFloatingPoint() ||
13303         VT != ST->getMemoryVT() ||
13304         LD->isNonTemporal() ||
13305         ST->isNonTemporal() ||
13306         LD->getPointerInfo().getAddrSpace() != 0 ||
13307         ST->getPointerInfo().getAddrSpace() != 0)
13308       return SDValue();
13309 
13310     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
13311     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
13312         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
13313         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
13314         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
13315       return SDValue();
13316 
13317     unsigned LDAlign = LD->getAlignment();
13318     unsigned STAlign = ST->getAlignment();
13319     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
13320     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
13321     if (LDAlign < ABIAlign || STAlign < ABIAlign)
13322       return SDValue();
13323 
13324     SDValue NewLD =
13325         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
13326                     LD->getPointerInfo(), LDAlign);
13327 
13328     SDValue NewST =
13329         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
13330                      ST->getPointerInfo(), STAlign);
13331 
13332     AddToWorklist(NewLD.getNode());
13333     AddToWorklist(NewST.getNode());
13334     WorklistRemover DeadNodes(*this);
13335     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
13336     ++LdStFP2Int;
13337     return NewST;
13338   }
13339 
13340   return SDValue();
13341 }
13342 
13343 // This is a helper function for visitMUL to check the profitability
13344 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
13345 // MulNode is the original multiply, AddNode is (add x, c1),
13346 // and ConstNode is c2.
13347 //
13348 // If the (add x, c1) has multiple uses, we could increase
13349 // the number of adds if we make this transformation.
13350 // It would only be worth doing this if we can remove a
13351 // multiply in the process. Check for that here.
13352 // To illustrate:
13353 //     (A + c1) * c3
13354 //     (A + c2) * c3
13355 // We're checking for cases where we have common "c3 * A" expressions.
13356 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
13357                                               SDValue &AddNode,
13358                                               SDValue &ConstNode) {
13359   APInt Val;
13360 
13361   // If the add only has one use, this would be OK to do.
13362   if (AddNode.getNode()->hasOneUse())
13363     return true;
13364 
13365   // Walk all the users of the constant with which we're multiplying.
13366   for (SDNode *Use : ConstNode->uses()) {
13367     if (Use == MulNode) // This use is the one we're on right now. Skip it.
13368       continue;
13369 
13370     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
13371       SDNode *OtherOp;
13372       SDNode *MulVar = AddNode.getOperand(0).getNode();
13373 
13374       // OtherOp is what we're multiplying against the constant.
13375       if (Use->getOperand(0) == ConstNode)
13376         OtherOp = Use->getOperand(1).getNode();
13377       else
13378         OtherOp = Use->getOperand(0).getNode();
13379 
13380       // Check to see if multiply is with the same operand of our "add".
13381       //
13382       //     ConstNode  = CONST
13383       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
13384       //     ...
13385       //     AddNode  = (A + c1)  <-- MulVar is A.
13386       //         = AddNode * ConstNode   <-- current visiting instruction.
13387       //
13388       // If we make this transformation, we will have a common
13389       // multiply (ConstNode * A) that we can save.
13390       if (OtherOp == MulVar)
13391         return true;
13392 
13393       // Now check to see if a future expansion will give us a common
13394       // multiply.
13395       //
13396       //     ConstNode  = CONST
13397       //     AddNode    = (A + c1)
13398       //     ...   = AddNode * ConstNode <-- current visiting instruction.
13399       //     ...
13400       //     OtherOp = (A + c2)
13401       //     Use     = OtherOp * ConstNode <-- visiting Use.
13402       //
13403       // If we make this transformation, we will have a common
13404       // multiply (CONST * A) after we also do the same transformation
13405       // to the "t2" instruction.
13406       if (OtherOp->getOpcode() == ISD::ADD &&
13407           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
13408           OtherOp->getOperand(0).getNode() == MulVar)
13409         return true;
13410     }
13411   }
13412 
13413   // Didn't find a case where this would be profitable.
13414   return false;
13415 }
13416 
13417 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
13418                                          unsigned NumStores) {
13419   SmallVector<SDValue, 8> Chains;
13420   SmallPtrSet<const SDNode *, 8> Visited;
13421   SDLoc StoreDL(StoreNodes[0].MemNode);
13422 
13423   for (unsigned i = 0; i < NumStores; ++i) {
13424     Visited.insert(StoreNodes[i].MemNode);
13425   }
13426 
13427   // don't include nodes that are children
13428   for (unsigned i = 0; i < NumStores; ++i) {
13429     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
13430       Chains.push_back(StoreNodes[i].MemNode->getChain());
13431   }
13432 
13433   assert(Chains.size() > 0 && "Chain should have generated a chain");
13434   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
13435 }
13436 
13437 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
13438     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
13439     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
13440   // Make sure we have something to merge.
13441   if (NumStores < 2)
13442     return false;
13443 
13444   // The latest Node in the DAG.
13445   SDLoc DL(StoreNodes[0].MemNode);
13446 
13447   int64_t ElementSizeBits = MemVT.getStoreSizeInBits();
13448   unsigned SizeInBits = NumStores * ElementSizeBits;
13449   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
13450 
13451   EVT StoreTy;
13452   if (UseVector) {
13453     unsigned Elts = NumStores * NumMemElts;
13454     // Get the type for the merged vector store.
13455     StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
13456   } else
13457     StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
13458 
13459   SDValue StoredVal;
13460   if (UseVector) {
13461     if (IsConstantSrc) {
13462       SmallVector<SDValue, 8> BuildVector;
13463       for (unsigned I = 0; I != NumStores; ++I) {
13464         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
13465         SDValue Val = St->getValue();
13466         // If constant is of the wrong type, convert it now.
13467         if (MemVT != Val.getValueType()) {
13468           Val = peekThroughBitcast(Val);
13469           // Deal with constants of wrong size.
13470           if (ElementSizeBits != Val.getValueSizeInBits()) {
13471             EVT IntMemVT =
13472                 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
13473             if (isa<ConstantFPSDNode>(Val)) {
13474               // Not clear how to truncate FP values.
13475               return false;
13476             } else if (auto *C = dyn_cast<ConstantSDNode>(Val))
13477               Val = DAG.getConstant(C->getAPIntValue()
13478                                         .zextOrTrunc(Val.getValueSizeInBits())
13479                                         .zextOrTrunc(ElementSizeBits),
13480                                     SDLoc(C), IntMemVT);
13481           }
13482           // Make sure correctly size type is the correct type.
13483           Val = DAG.getBitcast(MemVT, Val);
13484         }
13485         BuildVector.push_back(Val);
13486       }
13487       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
13488                                                : ISD::BUILD_VECTOR,
13489                               DL, StoreTy, BuildVector);
13490     } else {
13491       SmallVector<SDValue, 8> Ops;
13492       for (unsigned i = 0; i < NumStores; ++i) {
13493         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13494         SDValue Val = peekThroughBitcast(St->getValue());
13495         // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
13496         // type MemVT. If the underlying value is not the correct
13497         // type, but it is an extraction of an appropriate vector we
13498         // can recast Val to be of the correct type. This may require
13499         // converting between EXTRACT_VECTOR_ELT and
13500         // EXTRACT_SUBVECTOR.
13501         if ((MemVT != Val.getValueType()) &&
13502             (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13503              Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
13504           SDValue Vec = Val.getOperand(0);
13505           EVT MemVTScalarTy = MemVT.getScalarType();
13506           // We may need to add a bitcast here to get types to line up.
13507           if (MemVTScalarTy != Vec.getValueType()) {
13508             unsigned Elts = Vec.getValueType().getSizeInBits() /
13509                             MemVTScalarTy.getSizeInBits();
13510             EVT NewVecTy =
13511                 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts);
13512             Vec = DAG.getBitcast(NewVecTy, Vec);
13513           }
13514           auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR
13515                                         : ISD::EXTRACT_VECTOR_ELT;
13516           Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1));
13517         }
13518         Ops.push_back(Val);
13519       }
13520 
13521       // Build the extracted vector elements back into a vector.
13522       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
13523                                                : ISD::BUILD_VECTOR,
13524                               DL, StoreTy, Ops);
13525     }
13526   } else {
13527     // We should always use a vector store when merging extracted vector
13528     // elements, so this path implies a store of constants.
13529     assert(IsConstantSrc && "Merged vector elements should use vector store");
13530 
13531     APInt StoreInt(SizeInBits, 0);
13532 
13533     // Construct a single integer constant which is made of the smaller
13534     // constant inputs.
13535     bool IsLE = DAG.getDataLayout().isLittleEndian();
13536     for (unsigned i = 0; i < NumStores; ++i) {
13537       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
13538       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
13539 
13540       SDValue Val = St->getValue();
13541       Val = peekThroughBitcast(Val);
13542       StoreInt <<= ElementSizeBits;
13543       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
13544         StoreInt |= C->getAPIntValue()
13545                         .zextOrTrunc(ElementSizeBits)
13546                         .zextOrTrunc(SizeInBits);
13547       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
13548         StoreInt |= C->getValueAPF()
13549                         .bitcastToAPInt()
13550                         .zextOrTrunc(ElementSizeBits)
13551                         .zextOrTrunc(SizeInBits);
13552         // If fp truncation is necessary give up for now.
13553         if (MemVT.getSizeInBits() != ElementSizeBits)
13554           return false;
13555       } else {
13556         llvm_unreachable("Invalid constant element type");
13557       }
13558     }
13559 
13560     // Create the new Load and Store operations.
13561     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
13562   }
13563 
13564   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13565   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
13566 
13567   // make sure we use trunc store if it's necessary to be legal.
13568   SDValue NewStore;
13569   if (!UseTrunc) {
13570     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
13571                             FirstInChain->getPointerInfo(),
13572                             FirstInChain->getAlignment());
13573   } else { // Must be realized as a trunc store
13574     EVT LegalizedStoredValTy =
13575         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
13576     unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits();
13577     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
13578     SDValue ExtendedStoreVal =
13579         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
13580                         LegalizedStoredValTy);
13581     NewStore = DAG.getTruncStore(
13582         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
13583         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
13584         FirstInChain->getAlignment(),
13585         FirstInChain->getMemOperand()->getFlags());
13586   }
13587 
13588   // Replace all merged stores with the new store.
13589   for (unsigned i = 0; i < NumStores; ++i)
13590     CombineTo(StoreNodes[i].MemNode, NewStore);
13591 
13592   AddToWorklist(NewChain.getNode());
13593   return true;
13594 }
13595 
13596 void DAGCombiner::getStoreMergeCandidates(
13597     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes,
13598     SDNode *&RootNode) {
13599   // This holds the base pointer, index, and the offset in bytes from the base
13600   // pointer.
13601   BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
13602   EVT MemVT = St->getMemoryVT();
13603 
13604   SDValue Val = peekThroughBitcast(St->getValue());
13605   // We must have a base and an offset.
13606   if (!BasePtr.getBase().getNode())
13607     return;
13608 
13609   // Do not handle stores to undef base pointers.
13610   if (BasePtr.getBase().isUndef())
13611     return;
13612 
13613   bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
13614   bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13615                           Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
13616   bool IsLoadSrc = isa<LoadSDNode>(Val);
13617   BaseIndexOffset LBasePtr;
13618   // Match on loadbaseptr if relevant.
13619   EVT LoadVT;
13620   if (IsLoadSrc) {
13621     auto *Ld = cast<LoadSDNode>(Val);
13622     LBasePtr = BaseIndexOffset::match(Ld, DAG);
13623     LoadVT = Ld->getMemoryVT();
13624     // Load and store should be the same type.
13625     if (MemVT != LoadVT)
13626       return;
13627     // Loads must only have one use.
13628     if (!Ld->hasNUsesOfValue(1, 0))
13629       return;
13630     // The memory operands must not be volatile.
13631     if (Ld->isVolatile() || Ld->isIndexed())
13632       return;
13633   }
13634   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
13635                             int64_t &Offset) -> bool {
13636     if (Other->isVolatile() || Other->isIndexed())
13637       return false;
13638     SDValue Val = peekThroughBitcast(Other->getValue());
13639     // Allow merging constants of different types as integers.
13640     bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
13641                                            : Other->getMemoryVT() != MemVT;
13642     if (IsLoadSrc) {
13643       if (NoTypeMatch)
13644         return false;
13645       // The Load's Base Ptr must also match
13646       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) {
13647         auto LPtr = BaseIndexOffset::match(OtherLd, DAG);
13648         if (LoadVT != OtherLd->getMemoryVT())
13649           return false;
13650         // Loads must only have one use.
13651         if (!OtherLd->hasNUsesOfValue(1, 0))
13652           return false;
13653         // The memory operands must not be volatile.
13654         if (OtherLd->isVolatile() || OtherLd->isIndexed())
13655           return false;
13656         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
13657           return false;
13658       } else
13659         return false;
13660     }
13661     if (IsConstantSrc) {
13662       if (NoTypeMatch)
13663         return false;
13664       if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val)))
13665         return false;
13666     }
13667     if (IsExtractVecSrc) {
13668       // Do not merge truncated stores here.
13669       if (Other->isTruncatingStore())
13670         return false;
13671       if (!MemVT.bitsEq(Val.getValueType()))
13672         return false;
13673       if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13674           Val.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13675         return false;
13676     }
13677     Ptr = BaseIndexOffset::match(Other, DAG);
13678     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
13679   };
13680 
13681   // We looking for a root node which is an ancestor to all mergable
13682   // stores. We search up through a load, to our root and then down
13683   // through all children. For instance we will find Store{1,2,3} if
13684   // St is Store1, Store2. or Store3 where the root is not a load
13685   // which always true for nonvolatile ops. TODO: Expand
13686   // the search to find all valid candidates through multiple layers of loads.
13687   //
13688   // Root
13689   // |-------|-------|
13690   // Load    Load    Store3
13691   // |       |
13692   // Store1   Store2
13693   //
13694   // FIXME: We should be able to climb and
13695   // descend TokenFactors to find candidates as well.
13696 
13697   RootNode = St->getChain().getNode();
13698 
13699   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
13700     RootNode = Ldn->getChain().getNode();
13701     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13702       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
13703         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
13704           if (I2.getOperandNo() == 0)
13705             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
13706               BaseIndexOffset Ptr;
13707               int64_t PtrDiff;
13708               if (CandidateMatch(OtherST, Ptr, PtrDiff))
13709                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13710             }
13711   } else
13712     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13713       if (I.getOperandNo() == 0)
13714         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
13715           BaseIndexOffset Ptr;
13716           int64_t PtrDiff;
13717           if (CandidateMatch(OtherST, Ptr, PtrDiff))
13718             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13719         }
13720 }
13721 
13722 // We need to check that merging these stores does not cause a loop in
13723 // the DAG. Any store candidate may depend on another candidate
13724 // indirectly through its operand (we already consider dependencies
13725 // through the chain). Check in parallel by searching up from
13726 // non-chain operands of candidates.
13727 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
13728     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
13729     SDNode *RootNode) {
13730   // FIXME: We should be able to truncate a full search of
13731   // predecessors by doing a BFS and keeping tabs the originating
13732   // stores from which worklist nodes come from in a similar way to
13733   // TokenFactor simplfication.
13734 
13735   SmallPtrSet<const SDNode *, 32> Visited;
13736   SmallVector<const SDNode *, 8> Worklist;
13737 
13738   // RootNode is a predecessor to all candidates so we need not search
13739   // past it. Add RootNode (peeking through TokenFactors). Do not count
13740   // these towards size check.
13741 
13742   Worklist.push_back(RootNode);
13743   while (!Worklist.empty()) {
13744     auto N = Worklist.pop_back_val();
13745     if (N->getOpcode() == ISD::TokenFactor) {
13746       for (SDValue Op : N->ops())
13747         Worklist.push_back(Op.getNode());
13748     }
13749     Visited.insert(N);
13750   }
13751 
13752   // Don't count pruning nodes towards max.
13753   unsigned int Max = 1024 + Visited.size();
13754   // Search Ops of store candidates.
13755   for (unsigned i = 0; i < NumStores; ++i) {
13756     SDNode *N = StoreNodes[i].MemNode;
13757     // Of the 4 Store Operands:
13758     //   * Chain (Op 0) -> We have already considered these
13759     //                    in candidate selection and can be
13760     //                    safely ignored
13761     //   * Value (Op 1) -> Cycles may happen (e.g. through load chains)
13762     //   * Address (Op 2) -> Merged addresses may only vary by a fixed constant
13763     //                      and so no cycles are possible.
13764     //   * (Op 3) -> appears to always be undef. Cannot be source of cycle.
13765     //
13766     // Thus we need only check predecessors of the value operands.
13767     auto *Op = N->getOperand(1).getNode();
13768     if (Visited.insert(Op).second)
13769       Worklist.push_back(Op);
13770   }
13771   // Search through DAG. We can stop early if we find a store node.
13772   for (unsigned i = 0; i < NumStores; ++i)
13773     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
13774                                      Max))
13775       return false;
13776   return true;
13777 }
13778 
13779 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
13780   if (OptLevel == CodeGenOpt::None)
13781     return false;
13782 
13783   EVT MemVT = St->getMemoryVT();
13784   int64_t ElementSizeBytes = MemVT.getStoreSize();
13785   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
13786 
13787   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
13788     return false;
13789 
13790   bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute(
13791       Attribute::NoImplicitFloat);
13792 
13793   // This function cannot currently deal with non-byte-sized memory sizes.
13794   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
13795     return false;
13796 
13797   if (!MemVT.isSimple())
13798     return false;
13799 
13800   // Perform an early exit check. Do not bother looking at stored values that
13801   // are not constants, loads, or extracted vector elements.
13802   SDValue StoredVal = peekThroughBitcast(St->getValue());
13803   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
13804   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
13805                        isa<ConstantFPSDNode>(StoredVal);
13806   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13807                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
13808 
13809   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
13810     return false;
13811 
13812   SmallVector<MemOpLink, 8> StoreNodes;
13813   SDNode *RootNode;
13814   // Find potential store merge candidates by searching through chain sub-DAG
13815   getStoreMergeCandidates(St, StoreNodes, RootNode);
13816 
13817   // Check if there is anything to merge.
13818   if (StoreNodes.size() < 2)
13819     return false;
13820 
13821   // Sort the memory operands according to their distance from the
13822   // base pointer.
13823   llvm::sort(StoreNodes.begin(), StoreNodes.end(),
13824              [](MemOpLink LHS, MemOpLink RHS) {
13825                return LHS.OffsetFromBase < RHS.OffsetFromBase;
13826              });
13827 
13828   // Store Merge attempts to merge the lowest stores. This generally
13829   // works out as if successful, as the remaining stores are checked
13830   // after the first collection of stores is merged. However, in the
13831   // case that a non-mergeable store is found first, e.g., {p[-2],
13832   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
13833   // mergeable cases. To prevent this, we prune such stores from the
13834   // front of StoreNodes here.
13835 
13836   bool RV = false;
13837   while (StoreNodes.size() > 1) {
13838     unsigned StartIdx = 0;
13839     while ((StartIdx + 1 < StoreNodes.size()) &&
13840            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
13841                StoreNodes[StartIdx + 1].OffsetFromBase)
13842       ++StartIdx;
13843 
13844     // Bail if we don't have enough candidates to merge.
13845     if (StartIdx + 1 >= StoreNodes.size())
13846       return RV;
13847 
13848     if (StartIdx)
13849       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
13850 
13851     // Scan the memory operations on the chain and find the first
13852     // non-consecutive store memory address.
13853     unsigned NumConsecutiveStores = 1;
13854     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
13855     // Check that the addresses are consecutive starting from the second
13856     // element in the list of stores.
13857     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
13858       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
13859       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13860         break;
13861       NumConsecutiveStores = i + 1;
13862     }
13863 
13864     if (NumConsecutiveStores < 2) {
13865       StoreNodes.erase(StoreNodes.begin(),
13866                        StoreNodes.begin() + NumConsecutiveStores);
13867       continue;
13868     }
13869 
13870     // The node with the lowest store address.
13871     LLVMContext &Context = *DAG.getContext();
13872     const DataLayout &DL = DAG.getDataLayout();
13873 
13874     // Store the constants into memory as one consecutive store.
13875     if (IsConstantSrc) {
13876       while (NumConsecutiveStores >= 2) {
13877         LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13878         unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13879         unsigned FirstStoreAlign = FirstInChain->getAlignment();
13880         unsigned LastLegalType = 1;
13881         unsigned LastLegalVectorType = 1;
13882         bool LastIntegerTrunc = false;
13883         bool NonZero = false;
13884         unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
13885         for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13886           StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
13887           SDValue StoredVal = ST->getValue();
13888           bool IsElementZero = false;
13889           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
13890             IsElementZero = C->isNullValue();
13891           else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
13892             IsElementZero = C->getConstantFPValue()->isNullValue();
13893           if (IsElementZero) {
13894             if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
13895               FirstZeroAfterNonZero = i;
13896           }
13897           NonZero |= !IsElementZero;
13898 
13899           // Find a legal type for the constant store.
13900           unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13901           EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13902           bool IsFast = false;
13903 
13904           // Break early when size is too large to be legal.
13905           if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits)
13906             break;
13907 
13908           if (TLI.isTypeLegal(StoreTy) &&
13909               TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13910               TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13911                                      FirstStoreAlign, &IsFast) &&
13912               IsFast) {
13913             LastIntegerTrunc = false;
13914             LastLegalType = i + 1;
13915             // Or check whether a truncstore is legal.
13916           } else if (TLI.getTypeAction(Context, StoreTy) ==
13917                      TargetLowering::TypePromoteInteger) {
13918             EVT LegalizedStoredValTy =
13919                 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
13920             if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) &&
13921                 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) &&
13922                 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13923                                        FirstStoreAlign, &IsFast) &&
13924                 IsFast) {
13925               LastIntegerTrunc = true;
13926               LastLegalType = i + 1;
13927             }
13928           }
13929 
13930           // We only use vectors if the constant is known to be zero or the
13931           // target allows it and the function is not marked with the
13932           // noimplicitfloat attribute.
13933           if ((!NonZero ||
13934                TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
13935               !NoVectors) {
13936             // Find a legal type for the vector store.
13937             unsigned Elts = (i + 1) * NumMemElts;
13938             EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13939             if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) &&
13940                 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13941                 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13942                                        FirstStoreAlign, &IsFast) &&
13943                 IsFast)
13944               LastLegalVectorType = i + 1;
13945           }
13946         }
13947 
13948         bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
13949         unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
13950 
13951         // Check if we found a legal integer type that creates a meaningful
13952         // merge.
13953         if (NumElem < 2) {
13954           // We know that candidate stores are in order and of correct
13955           // shape. While there is no mergeable sequence from the
13956           // beginning one may start later in the sequence. The only
13957           // reason a merge of size N could have failed where another of
13958           // the same size would not have, is if the alignment has
13959           // improved or we've dropped a non-zero value. Drop as many
13960           // candidates as we can here.
13961           unsigned NumSkip = 1;
13962           while (
13963               (NumSkip < NumConsecutiveStores) &&
13964               (NumSkip < FirstZeroAfterNonZero) &&
13965               (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13966             NumSkip++;
13967 
13968           StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13969           NumConsecutiveStores -= NumSkip;
13970           continue;
13971         }
13972 
13973         // Check that we can merge these candidates without causing a cycle.
13974         if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
13975                                                       RootNode)) {
13976           StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13977           NumConsecutiveStores -= NumElem;
13978           continue;
13979         }
13980 
13981         RV |= MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, true,
13982                                               UseVector, LastIntegerTrunc);
13983 
13984         // Remove merged stores for next iteration.
13985         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13986         NumConsecutiveStores -= NumElem;
13987       }
13988       continue;
13989     }
13990 
13991     // When extracting multiple vector elements, try to store them
13992     // in one vector store rather than a sequence of scalar stores.
13993     if (IsExtractVecSrc) {
13994       // Loop on Consecutive Stores on success.
13995       while (NumConsecutiveStores >= 2) {
13996         LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13997         unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13998         unsigned FirstStoreAlign = FirstInChain->getAlignment();
13999         unsigned NumStoresToMerge = 1;
14000         for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
14001           // Find a legal type for the vector store.
14002           unsigned Elts = (i + 1) * NumMemElts;
14003           EVT Ty =
14004               EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
14005           bool IsFast;
14006 
14007           // Break early when size is too large to be legal.
14008           if (Ty.getSizeInBits() > MaximumLegalStoreInBits)
14009             break;
14010 
14011           if (TLI.isTypeLegal(Ty) &&
14012               TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
14013               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
14014                                      FirstStoreAlign, &IsFast) &&
14015               IsFast)
14016             NumStoresToMerge = i + 1;
14017         }
14018 
14019         // Check if we found a legal integer type creating a meaningful
14020         // merge.
14021         if (NumStoresToMerge < 2) {
14022           // We know that candidate stores are in order and of correct
14023           // shape. While there is no mergeable sequence from the
14024           // beginning one may start later in the sequence. The only
14025           // reason a merge of size N could have failed where another of
14026           // the same size would not have, is if the alignment has
14027           // improved. Drop as many candidates as we can here.
14028           unsigned NumSkip = 1;
14029           while (
14030               (NumSkip < NumConsecutiveStores) &&
14031               (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
14032             NumSkip++;
14033 
14034           StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
14035           NumConsecutiveStores -= NumSkip;
14036           continue;
14037         }
14038 
14039         // Check that we can merge these candidates without causing a cycle.
14040         if (!checkMergeStoreCandidatesForDependencies(
14041                 StoreNodes, NumStoresToMerge, RootNode)) {
14042           StoreNodes.erase(StoreNodes.begin(),
14043                            StoreNodes.begin() + NumStoresToMerge);
14044           NumConsecutiveStores -= NumStoresToMerge;
14045           continue;
14046         }
14047 
14048         RV |= MergeStoresOfConstantsOrVecElts(
14049             StoreNodes, MemVT, NumStoresToMerge, false, true, false);
14050 
14051         StoreNodes.erase(StoreNodes.begin(),
14052                          StoreNodes.begin() + NumStoresToMerge);
14053         NumConsecutiveStores -= NumStoresToMerge;
14054       }
14055       continue;
14056     }
14057 
14058     // Below we handle the case of multiple consecutive stores that
14059     // come from multiple consecutive loads. We merge them into a single
14060     // wide load and a single wide store.
14061 
14062     // Look for load nodes which are used by the stored values.
14063     SmallVector<MemOpLink, 8> LoadNodes;
14064 
14065     // Find acceptable loads. Loads need to have the same chain (token factor),
14066     // must not be zext, volatile, indexed, and they must be consecutive.
14067     BaseIndexOffset LdBasePtr;
14068 
14069     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
14070       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
14071       SDValue Val = peekThroughBitcast(St->getValue());
14072       LoadSDNode *Ld = cast<LoadSDNode>(Val);
14073 
14074       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG);
14075       // If this is not the first ptr that we check.
14076       int64_t LdOffset = 0;
14077       if (LdBasePtr.getBase().getNode()) {
14078         // The base ptr must be the same.
14079         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
14080           break;
14081       } else {
14082         // Check that all other base pointers are the same as this one.
14083         LdBasePtr = LdPtr;
14084       }
14085 
14086       // We found a potential memory operand to merge.
14087       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
14088     }
14089 
14090     while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) {
14091       // If we have load/store pair instructions and we only have two values,
14092       // don't bother merging.
14093       unsigned RequiredAlignment;
14094       if (LoadNodes.size() == 2 &&
14095           TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
14096           StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
14097         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
14098         LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2);
14099         break;
14100       }
14101       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
14102       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
14103       unsigned FirstStoreAlign = FirstInChain->getAlignment();
14104       LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
14105       unsigned FirstLoadAS = FirstLoad->getAddressSpace();
14106       unsigned FirstLoadAlign = FirstLoad->getAlignment();
14107 
14108       // Scan the memory operations on the chain and find the first
14109       // non-consecutive load memory address. These variables hold the index in
14110       // the store node array.
14111 
14112       unsigned LastConsecutiveLoad = 1;
14113 
14114       // This variable refers to the size and not index in the array.
14115       unsigned LastLegalVectorType = 1;
14116       unsigned LastLegalIntegerType = 1;
14117       bool isDereferenceable = true;
14118       bool DoIntegerTruncate = false;
14119       StartAddress = LoadNodes[0].OffsetFromBase;
14120       SDValue FirstChain = FirstLoad->getChain();
14121       for (unsigned i = 1; i < LoadNodes.size(); ++i) {
14122         // All loads must share the same chain.
14123         if (LoadNodes[i].MemNode->getChain() != FirstChain)
14124           break;
14125 
14126         int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
14127         if (CurrAddress - StartAddress != (ElementSizeBytes * i))
14128           break;
14129         LastConsecutiveLoad = i;
14130 
14131         if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
14132           isDereferenceable = false;
14133 
14134         // Find a legal type for the vector store.
14135         unsigned Elts = (i + 1) * NumMemElts;
14136         EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
14137 
14138         // Break early when size is too large to be legal.
14139         if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits)
14140           break;
14141 
14142         bool IsFastSt, IsFastLd;
14143         if (TLI.isTypeLegal(StoreTy) &&
14144             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
14145             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
14146                                    FirstStoreAlign, &IsFastSt) &&
14147             IsFastSt &&
14148             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
14149                                    FirstLoadAlign, &IsFastLd) &&
14150             IsFastLd) {
14151           LastLegalVectorType = i + 1;
14152         }
14153 
14154         // Find a legal type for the integer store.
14155         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
14156         StoreTy = EVT::getIntegerVT(Context, SizeInBits);
14157         if (TLI.isTypeLegal(StoreTy) &&
14158             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
14159             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
14160                                    FirstStoreAlign, &IsFastSt) &&
14161             IsFastSt &&
14162             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
14163                                    FirstLoadAlign, &IsFastLd) &&
14164             IsFastLd) {
14165           LastLegalIntegerType = i + 1;
14166           DoIntegerTruncate = false;
14167           // Or check whether a truncstore and extload is legal.
14168         } else if (TLI.getTypeAction(Context, StoreTy) ==
14169                    TargetLowering::TypePromoteInteger) {
14170           EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy);
14171           if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) &&
14172               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) &&
14173               TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy,
14174                                  StoreTy) &&
14175               TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy,
14176                                  StoreTy) &&
14177               TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) &&
14178               TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
14179                                      FirstStoreAlign, &IsFastSt) &&
14180               IsFastSt &&
14181               TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
14182                                      FirstLoadAlign, &IsFastLd) &&
14183               IsFastLd) {
14184             LastLegalIntegerType = i + 1;
14185             DoIntegerTruncate = true;
14186           }
14187         }
14188       }
14189 
14190       // Only use vector types if the vector type is larger than the integer
14191       // type. If they are the same, use integers.
14192       bool UseVectorTy =
14193           LastLegalVectorType > LastLegalIntegerType && !NoVectors;
14194       unsigned LastLegalType =
14195           std::max(LastLegalVectorType, LastLegalIntegerType);
14196 
14197       // We add +1 here because the LastXXX variables refer to location while
14198       // the NumElem refers to array/index size.
14199       unsigned NumElem =
14200           std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
14201       NumElem = std::min(LastLegalType, NumElem);
14202 
14203       if (NumElem < 2) {
14204         // We know that candidate stores are in order and of correct
14205         // shape. While there is no mergeable sequence from the
14206         // beginning one may start later in the sequence. The only
14207         // reason a merge of size N could have failed where another of
14208         // the same size would not have is if the alignment or either
14209         // the load or store has improved. Drop as many candidates as we
14210         // can here.
14211         unsigned NumSkip = 1;
14212         while ((NumSkip < LoadNodes.size()) &&
14213                (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
14214                (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
14215           NumSkip++;
14216         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
14217         LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip);
14218         NumConsecutiveStores -= NumSkip;
14219         continue;
14220       }
14221 
14222       // Check that we can merge these candidates without causing a cycle.
14223       if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
14224                                                     RootNode)) {
14225         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
14226         LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem);
14227         NumConsecutiveStores -= NumElem;
14228         continue;
14229       }
14230 
14231       // Find if it is better to use vectors or integers to load and store
14232       // to memory.
14233       EVT JointMemOpVT;
14234       if (UseVectorTy) {
14235         // Find a legal type for the vector store.
14236         unsigned Elts = NumElem * NumMemElts;
14237         JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
14238       } else {
14239         unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
14240         JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
14241       }
14242 
14243       SDLoc LoadDL(LoadNodes[0].MemNode);
14244       SDLoc StoreDL(StoreNodes[0].MemNode);
14245 
14246       // The merged loads are required to have the same incoming chain, so
14247       // using the first's chain is acceptable.
14248 
14249       SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
14250       AddToWorklist(NewStoreChain.getNode());
14251 
14252       MachineMemOperand::Flags MMOFlags =
14253           isDereferenceable ? MachineMemOperand::MODereferenceable
14254                             : MachineMemOperand::MONone;
14255 
14256       SDValue NewLoad, NewStore;
14257       if (UseVectorTy || !DoIntegerTruncate) {
14258         NewLoad =
14259             DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
14260                         FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
14261                         FirstLoadAlign, MMOFlags);
14262         NewStore = DAG.getStore(
14263             NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
14264             FirstInChain->getPointerInfo(), FirstStoreAlign);
14265       } else { // This must be the truncstore/extload case
14266         EVT ExtendedTy =
14267             TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
14268         NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy,
14269                                  FirstLoad->getChain(), FirstLoad->getBasePtr(),
14270                                  FirstLoad->getPointerInfo(), JointMemOpVT,
14271                                  FirstLoadAlign, MMOFlags);
14272         NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
14273                                      FirstInChain->getBasePtr(),
14274                                      FirstInChain->getPointerInfo(),
14275                                      JointMemOpVT, FirstInChain->getAlignment(),
14276                                      FirstInChain->getMemOperand()->getFlags());
14277       }
14278 
14279       // Transfer chain users from old loads to the new load.
14280       for (unsigned i = 0; i < NumElem; ++i) {
14281         LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
14282         DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
14283                                       SDValue(NewLoad.getNode(), 1));
14284       }
14285 
14286       // Replace the all stores with the new store. Recursively remove
14287       // corresponding value if its no longer used.
14288       for (unsigned i = 0; i < NumElem; ++i) {
14289         SDValue Val = StoreNodes[i].MemNode->getOperand(1);
14290         CombineTo(StoreNodes[i].MemNode, NewStore);
14291         if (Val.getNode()->use_empty())
14292           recursivelyDeleteUnusedNodes(Val.getNode());
14293       }
14294 
14295       RV = true;
14296       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
14297       LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem);
14298       NumConsecutiveStores -= NumElem;
14299     }
14300   }
14301   return RV;
14302 }
14303 
14304 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
14305   SDLoc SL(ST);
14306   SDValue ReplStore;
14307 
14308   // Replace the chain to avoid dependency.
14309   if (ST->isTruncatingStore()) {
14310     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
14311                                   ST->getBasePtr(), ST->getMemoryVT(),
14312                                   ST->getMemOperand());
14313   } else {
14314     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
14315                              ST->getMemOperand());
14316   }
14317 
14318   // Create token to keep both nodes around.
14319   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
14320                               MVT::Other, ST->getChain(), ReplStore);
14321 
14322   // Make sure the new and old chains are cleaned up.
14323   AddToWorklist(Token.getNode());
14324 
14325   // Don't add users to work list.
14326   return CombineTo(ST, Token, false);
14327 }
14328 
14329 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
14330   SDValue Value = ST->getValue();
14331   if (Value.getOpcode() == ISD::TargetConstantFP)
14332     return SDValue();
14333 
14334   SDLoc DL(ST);
14335 
14336   SDValue Chain = ST->getChain();
14337   SDValue Ptr = ST->getBasePtr();
14338 
14339   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
14340 
14341   // NOTE: If the original store is volatile, this transform must not increase
14342   // the number of stores.  For example, on x86-32 an f64 can be stored in one
14343   // processor operation but an i64 (which is not legal) requires two.  So the
14344   // transform should not be done in this case.
14345 
14346   SDValue Tmp;
14347   switch (CFP->getSimpleValueType(0).SimpleTy) {
14348   default:
14349     llvm_unreachable("Unknown FP type");
14350   case MVT::f16:    // We don't do this for these yet.
14351   case MVT::f80:
14352   case MVT::f128:
14353   case MVT::ppcf128:
14354     return SDValue();
14355   case MVT::f32:
14356     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
14357         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
14358       ;
14359       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
14360                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
14361                             MVT::i32);
14362       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
14363     }
14364 
14365     return SDValue();
14366   case MVT::f64:
14367     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
14368          !ST->isVolatile()) ||
14369         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
14370       ;
14371       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
14372                             getZExtValue(), SDLoc(CFP), MVT::i64);
14373       return DAG.getStore(Chain, DL, Tmp,
14374                           Ptr, ST->getMemOperand());
14375     }
14376 
14377     if (!ST->isVolatile() &&
14378         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
14379       // Many FP stores are not made apparent until after legalize, e.g. for
14380       // argument passing.  Since this is so common, custom legalize the
14381       // 64-bit integer store into two 32-bit stores.
14382       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
14383       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
14384       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
14385       if (DAG.getDataLayout().isBigEndian())
14386         std::swap(Lo, Hi);
14387 
14388       unsigned Alignment = ST->getAlignment();
14389       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
14390       AAMDNodes AAInfo = ST->getAAInfo();
14391 
14392       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
14393                                  ST->getAlignment(), MMOFlags, AAInfo);
14394       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
14395                         DAG.getConstant(4, DL, Ptr.getValueType()));
14396       Alignment = MinAlign(Alignment, 4U);
14397       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
14398                                  ST->getPointerInfo().getWithOffset(4),
14399                                  Alignment, MMOFlags, AAInfo);
14400       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14401                          St0, St1);
14402     }
14403 
14404     return SDValue();
14405   }
14406 }
14407 
14408 SDValue DAGCombiner::visitSTORE(SDNode *N) {
14409   StoreSDNode *ST  = cast<StoreSDNode>(N);
14410   SDValue Chain = ST->getChain();
14411   SDValue Value = ST->getValue();
14412   SDValue Ptr   = ST->getBasePtr();
14413 
14414   // If this is a store of a bit convert, store the input value if the
14415   // resultant store does not need a higher alignment than the original.
14416   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
14417       ST->isUnindexed()) {
14418     EVT SVT = Value.getOperand(0).getValueType();
14419     if (((!LegalOperations && !ST->isVolatile()) ||
14420          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
14421         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
14422       unsigned OrigAlign = ST->getAlignment();
14423       bool Fast = false;
14424       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
14425                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
14426           Fast) {
14427         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
14428                             ST->getPointerInfo(), OrigAlign,
14429                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
14430       }
14431     }
14432   }
14433 
14434   // Turn 'store undef, Ptr' -> nothing.
14435   if (Value.isUndef() && ST->isUnindexed())
14436     return Chain;
14437 
14438   // Try to infer better alignment information than the store already has.
14439   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
14440     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
14441       if (Align > ST->getAlignment() && ST->getSrcValueOffset() % Align == 0) {
14442         SDValue NewStore =
14443             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
14444                               ST->getMemoryVT(), Align,
14445                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
14446         // NewStore will always be N as we are only refining the alignment
14447         assert(NewStore.getNode() == N);
14448         (void)NewStore;
14449       }
14450     }
14451   }
14452 
14453   // Try transforming a pair floating point load / store ops to integer
14454   // load / store ops.
14455   if (SDValue NewST = TransformFPLoadStorePair(N))
14456     return NewST;
14457 
14458   if (ST->isUnindexed()) {
14459     // Walk up chain skipping non-aliasing memory nodes, on this store and any
14460     // adjacent stores.
14461     if (findBetterNeighborChains(ST)) {
14462       // replaceStoreChain uses CombineTo, which handled all of the worklist
14463       // manipulation. Return the original node to not do anything else.
14464       return SDValue(ST, 0);
14465     }
14466     Chain = ST->getChain();
14467   }
14468 
14469   // FIXME: is there such a thing as a truncating indexed store?
14470   if (ST->isTruncatingStore() && ST->isUnindexed() &&
14471       Value.getValueType().isInteger()) {
14472     // See if we can simplify the input to this truncstore with knowledge that
14473     // only the low bits are being used.  For example:
14474     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
14475     SDValue Shorter = DAG.GetDemandedBits(
14476         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
14477                                     ST->getMemoryVT().getScalarSizeInBits()));
14478     AddToWorklist(Value.getNode());
14479     if (Shorter.getNode())
14480       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
14481                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
14482 
14483     // Otherwise, see if we can simplify the operation with
14484     // SimplifyDemandedBits, which only works if the value has a single use.
14485     if (SimplifyDemandedBits(
14486             Value,
14487             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
14488                                  ST->getMemoryVT().getScalarSizeInBits()))) {
14489       // Re-visit the store if anything changed and the store hasn't been merged
14490       // with another node (N is deleted) SimplifyDemandedBits will add Value's
14491       // node back to the worklist if necessary, but we also need to re-visit
14492       // the Store node itself.
14493       if (N->getOpcode() != ISD::DELETED_NODE)
14494         AddToWorklist(N);
14495       return SDValue(N, 0);
14496     }
14497   }
14498 
14499   // If this is a load followed by a store to the same location, then the store
14500   // is dead/noop.
14501   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
14502     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
14503         ST->isUnindexed() && !ST->isVolatile() &&
14504         // There can't be any side effects between the load and store, such as
14505         // a call or store.
14506         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
14507       // The store is dead, remove it.
14508       return Chain;
14509     }
14510   }
14511 
14512   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
14513     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
14514         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
14515         ST->getMemoryVT() == ST1->getMemoryVT()) {
14516       // If this is a store followed by a store with the same value to the same
14517       // location, then the store is dead/noop.
14518       if (ST1->getValue() == Value) {
14519         // The store is dead, remove it.
14520         return Chain;
14521       }
14522 
14523       // If this is a store who's preceeding store to the same location
14524       // and no one other node is chained to that store we can effectively
14525       // drop the store. Do not remove stores to undef as they may be used as
14526       // data sinks.
14527       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
14528           !ST1->getBasePtr().isUndef()) {
14529         // ST1 is fully overwritten and can be elided. Combine with it's chain
14530         // value.
14531         CombineTo(ST1, ST1->getChain());
14532         return SDValue();
14533       }
14534     }
14535   }
14536 
14537   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
14538   // truncating store.  We can do this even if this is already a truncstore.
14539   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
14540       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
14541       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
14542                             ST->getMemoryVT())) {
14543     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
14544                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
14545   }
14546 
14547   // Always perform this optimization before types are legal. If the target
14548   // prefers, also try this after legalization to catch stores that were created
14549   // by intrinsics or other nodes.
14550   if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) {
14551     while (true) {
14552       // There can be multiple store sequences on the same chain.
14553       // Keep trying to merge store sequences until we are unable to do so
14554       // or until we merge the last store on the chain.
14555       bool Changed = MergeConsecutiveStores(ST);
14556       if (!Changed) break;
14557       // Return N as merge only uses CombineTo and no worklist clean
14558       // up is necessary.
14559       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
14560         return SDValue(N, 0);
14561     }
14562   }
14563 
14564   // Try transforming N to an indexed store.
14565   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
14566     return SDValue(N, 0);
14567 
14568   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
14569   //
14570   // Make sure to do this only after attempting to merge stores in order to
14571   //  avoid changing the types of some subset of stores due to visit order,
14572   //  preventing their merging.
14573   if (isa<ConstantFPSDNode>(ST->getValue())) {
14574     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
14575       return NewSt;
14576   }
14577 
14578   if (SDValue NewSt = splitMergedValStore(ST))
14579     return NewSt;
14580 
14581   return ReduceLoadOpStoreWidth(N);
14582 }
14583 
14584 /// For the instruction sequence of store below, F and I values
14585 /// are bundled together as an i64 value before being stored into memory.
14586 /// Sometimes it is more efficent to generate separate stores for F and I,
14587 /// which can remove the bitwise instructions or sink them to colder places.
14588 ///
14589 ///   (store (or (zext (bitcast F to i32) to i64),
14590 ///              (shl (zext I to i64), 32)), addr)  -->
14591 ///   (store F, addr) and (store I, addr+4)
14592 ///
14593 /// Similarly, splitting for other merged store can also be beneficial, like:
14594 /// For pair of {i32, i32}, i64 store --> two i32 stores.
14595 /// For pair of {i32, i16}, i64 store --> two i32 stores.
14596 /// For pair of {i16, i16}, i32 store --> two i16 stores.
14597 /// For pair of {i16, i8},  i32 store --> two i16 stores.
14598 /// For pair of {i8, i8},   i16 store --> two i8 stores.
14599 ///
14600 /// We allow each target to determine specifically which kind of splitting is
14601 /// supported.
14602 ///
14603 /// The store patterns are commonly seen from the simple code snippet below
14604 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
14605 ///   void goo(const std::pair<int, float> &);
14606 ///   hoo() {
14607 ///     ...
14608 ///     goo(std::make_pair(tmp, ftmp));
14609 ///     ...
14610 ///   }
14611 ///
14612 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
14613   if (OptLevel == CodeGenOpt::None)
14614     return SDValue();
14615 
14616   SDValue Val = ST->getValue();
14617   SDLoc DL(ST);
14618 
14619   // Match OR operand.
14620   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
14621     return SDValue();
14622 
14623   // Match SHL operand and get Lower and Higher parts of Val.
14624   SDValue Op1 = Val.getOperand(0);
14625   SDValue Op2 = Val.getOperand(1);
14626   SDValue Lo, Hi;
14627   if (Op1.getOpcode() != ISD::SHL) {
14628     std::swap(Op1, Op2);
14629     if (Op1.getOpcode() != ISD::SHL)
14630       return SDValue();
14631   }
14632   Lo = Op2;
14633   Hi = Op1.getOperand(0);
14634   if (!Op1.hasOneUse())
14635     return SDValue();
14636 
14637   // Match shift amount to HalfValBitSize.
14638   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
14639   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
14640   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
14641     return SDValue();
14642 
14643   // Lo and Hi are zero-extended from int with size less equal than 32
14644   // to i64.
14645   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
14646       !Lo.getOperand(0).getValueType().isScalarInteger() ||
14647       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
14648       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
14649       !Hi.getOperand(0).getValueType().isScalarInteger() ||
14650       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
14651     return SDValue();
14652 
14653   // Use the EVT of low and high parts before bitcast as the input
14654   // of target query.
14655   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
14656                   ? Lo.getOperand(0).getValueType()
14657                   : Lo.getValueType();
14658   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
14659                    ? Hi.getOperand(0).getValueType()
14660                    : Hi.getValueType();
14661   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
14662     return SDValue();
14663 
14664   // Start to split store.
14665   unsigned Alignment = ST->getAlignment();
14666   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
14667   AAMDNodes AAInfo = ST->getAAInfo();
14668 
14669   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
14670   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
14671   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
14672   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
14673 
14674   SDValue Chain = ST->getChain();
14675   SDValue Ptr = ST->getBasePtr();
14676   // Lower value store.
14677   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
14678                              ST->getAlignment(), MMOFlags, AAInfo);
14679   Ptr =
14680       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
14681                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
14682   // Higher value store.
14683   SDValue St1 =
14684       DAG.getStore(St0, DL, Hi, Ptr,
14685                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
14686                    Alignment / 2, MMOFlags, AAInfo);
14687   return St1;
14688 }
14689 
14690 /// Convert a disguised subvector insertion into a shuffle:
14691 /// insert_vector_elt V, (bitcast X from vector type), IdxC -->
14692 /// bitcast(shuffle (bitcast V), (extended X), Mask)
14693 /// Note: We do not use an insert_subvector node because that requires a legal
14694 /// subvector type.
14695 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) {
14696   SDValue InsertVal = N->getOperand(1);
14697   if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() ||
14698       !InsertVal.getOperand(0).getValueType().isVector())
14699     return SDValue();
14700 
14701   SDValue SubVec = InsertVal.getOperand(0);
14702   SDValue DestVec = N->getOperand(0);
14703   EVT SubVecVT = SubVec.getValueType();
14704   EVT VT = DestVec.getValueType();
14705   unsigned NumSrcElts = SubVecVT.getVectorNumElements();
14706   unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits();
14707   unsigned NumMaskVals = ExtendRatio * NumSrcElts;
14708 
14709   // Step 1: Create a shuffle mask that implements this insert operation. The
14710   // vector that we are inserting into will be operand 0 of the shuffle, so
14711   // those elements are just 'i'. The inserted subvector is in the first
14712   // positions of operand 1 of the shuffle. Example:
14713   // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
14714   SmallVector<int, 16> Mask(NumMaskVals);
14715   for (unsigned i = 0; i != NumMaskVals; ++i) {
14716     if (i / NumSrcElts == InsIndex)
14717       Mask[i] = (i % NumSrcElts) + NumMaskVals;
14718     else
14719       Mask[i] = i;
14720   }
14721 
14722   // Bail out if the target can not handle the shuffle we want to create.
14723   EVT SubVecEltVT = SubVecVT.getVectorElementType();
14724   EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals);
14725   if (!TLI.isShuffleMaskLegal(Mask, ShufVT))
14726     return SDValue();
14727 
14728   // Step 2: Create a wide vector from the inserted source vector by appending
14729   // undefined elements. This is the same size as our destination vector.
14730   SDLoc DL(N);
14731   SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT));
14732   ConcatOps[0] = SubVec;
14733   SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps);
14734 
14735   // Step 3: Shuffle in the padded subvector.
14736   SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec);
14737   SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask);
14738   AddToWorklist(PaddedSubV.getNode());
14739   AddToWorklist(DestVecBC.getNode());
14740   AddToWorklist(Shuf.getNode());
14741   return DAG.getBitcast(VT, Shuf);
14742 }
14743 
14744 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
14745   SDValue InVec = N->getOperand(0);
14746   SDValue InVal = N->getOperand(1);
14747   SDValue EltNo = N->getOperand(2);
14748   SDLoc DL(N);
14749 
14750   // If the inserted element is an UNDEF, just use the input vector.
14751   if (InVal.isUndef())
14752     return InVec;
14753 
14754   EVT VT = InVec.getValueType();
14755 
14756   // Remove redundant insertions:
14757   // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
14758   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14759       InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
14760     return InVec;
14761 
14762   // We must know which element is being inserted for folds below here.
14763   auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14764   if (!IndexC)
14765     return SDValue();
14766   unsigned Elt = IndexC->getZExtValue();
14767 
14768   if (SDValue Shuf = combineInsertEltToShuffle(N, Elt))
14769     return Shuf;
14770 
14771   // Canonicalize insert_vector_elt dag nodes.
14772   // Example:
14773   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
14774   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
14775   //
14776   // Do this only if the child insert_vector node has one use; also
14777   // do this only if indices are both constants and Idx1 < Idx0.
14778   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
14779       && isa<ConstantSDNode>(InVec.getOperand(2))) {
14780     unsigned OtherElt = InVec.getConstantOperandVal(2);
14781     if (Elt < OtherElt) {
14782       // Swap nodes.
14783       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
14784                                   InVec.getOperand(0), InVal, EltNo);
14785       AddToWorklist(NewOp.getNode());
14786       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
14787                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
14788     }
14789   }
14790 
14791   // If we can't generate a legal BUILD_VECTOR, exit
14792   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
14793     return SDValue();
14794 
14795   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
14796   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
14797   // vector elements.
14798   SmallVector<SDValue, 8> Ops;
14799   // Do not combine these two vectors if the output vector will not replace
14800   // the input vector.
14801   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
14802     Ops.append(InVec.getNode()->op_begin(),
14803                InVec.getNode()->op_end());
14804   } else if (InVec.isUndef()) {
14805     unsigned NElts = VT.getVectorNumElements();
14806     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
14807   } else {
14808     return SDValue();
14809   }
14810 
14811   // Insert the element
14812   if (Elt < Ops.size()) {
14813     // All the operands of BUILD_VECTOR must have the same type;
14814     // we enforce that here.
14815     EVT OpVT = Ops[0].getValueType();
14816     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
14817   }
14818 
14819   // Return the new vector
14820   return DAG.getBuildVector(VT, DL, Ops);
14821 }
14822 
14823 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
14824     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
14825   assert(!OriginalLoad->isVolatile());
14826 
14827   EVT ResultVT = EVE->getValueType(0);
14828   EVT VecEltVT = InVecVT.getVectorElementType();
14829   unsigned Align = OriginalLoad->getAlignment();
14830   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
14831       VecEltVT.getTypeForEVT(*DAG.getContext()));
14832 
14833   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14834     return SDValue();
14835 
14836   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
14837     ISD::NON_EXTLOAD : ISD::EXTLOAD;
14838   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
14839     return SDValue();
14840 
14841   Align = NewAlign;
14842 
14843   SDValue NewPtr = OriginalLoad->getBasePtr();
14844   SDValue Offset;
14845   EVT PtrType = NewPtr.getValueType();
14846   MachinePointerInfo MPI;
14847   SDLoc DL(EVE);
14848   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14849     int Elt = ConstEltNo->getZExtValue();
14850     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
14851     Offset = DAG.getConstant(PtrOff, DL, PtrType);
14852     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
14853   } else {
14854     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
14855     Offset = DAG.getNode(
14856         ISD::MUL, DL, PtrType, Offset,
14857         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
14858     MPI = OriginalLoad->getPointerInfo();
14859   }
14860   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
14861 
14862   // The replacement we need to do here is a little tricky: we need to
14863   // replace an extractelement of a load with a load.
14864   // Use ReplaceAllUsesOfValuesWith to do the replacement.
14865   // Note that this replacement assumes that the extractvalue is the only
14866   // use of the load; that's okay because we don't want to perform this
14867   // transformation in other cases anyway.
14868   SDValue Load;
14869   SDValue Chain;
14870   if (ResultVT.bitsGT(VecEltVT)) {
14871     // If the result type of vextract is wider than the load, then issue an
14872     // extending load instead.
14873     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
14874                                                   VecEltVT)
14875                                    ? ISD::ZEXTLOAD
14876                                    : ISD::EXTLOAD;
14877     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
14878                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
14879                           Align, OriginalLoad->getMemOperand()->getFlags(),
14880                           OriginalLoad->getAAInfo());
14881     Chain = Load.getValue(1);
14882   } else {
14883     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
14884                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
14885                        OriginalLoad->getAAInfo());
14886     Chain = Load.getValue(1);
14887     if (ResultVT.bitsLT(VecEltVT))
14888       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
14889     else
14890       Load = DAG.getBitcast(ResultVT, Load);
14891   }
14892   WorklistRemover DeadNodes(*this);
14893   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
14894   SDValue To[] = { Load, Chain };
14895   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
14896   // Since we're explicitly calling ReplaceAllUses, add the new node to the
14897   // worklist explicitly as well.
14898   AddToWorklist(Load.getNode());
14899   AddUsersToWorklist(Load.getNode()); // Add users too
14900   // Make sure to revisit this node to clean it up; it will usually be dead.
14901   AddToWorklist(EVE);
14902   ++OpsNarrowed;
14903   return SDValue(EVE, 0);
14904 }
14905 
14906 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
14907   // (vextract (scalar_to_vector val, 0) -> val
14908   SDValue InVec = N->getOperand(0);
14909   EVT VT = InVec.getValueType();
14910   EVT NVT = N->getValueType(0);
14911 
14912   if (InVec.isUndef())
14913     return DAG.getUNDEF(NVT);
14914 
14915   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14916     // Check if the result type doesn't match the inserted element type. A
14917     // SCALAR_TO_VECTOR may truncate the inserted element and the
14918     // EXTRACT_VECTOR_ELT may widen the extracted vector.
14919     SDValue InOp = InVec.getOperand(0);
14920     if (InOp.getValueType() != NVT) {
14921       assert(InOp.getValueType().isInteger() && NVT.isInteger());
14922       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
14923     }
14924     return InOp;
14925   }
14926 
14927   SDValue EltNo = N->getOperand(1);
14928   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
14929 
14930   // extract_vector_elt of out-of-bounds element -> UNDEF
14931   if (ConstEltNo && ConstEltNo->getAPIntValue().uge(VT.getVectorNumElements()))
14932     return DAG.getUNDEF(NVT);
14933 
14934   // extract_vector_elt (build_vector x, y), 1 -> y
14935   if (ConstEltNo &&
14936       InVec.getOpcode() == ISD::BUILD_VECTOR &&
14937       TLI.isTypeLegal(VT) &&
14938       (InVec.hasOneUse() ||
14939        TLI.aggressivelyPreferBuildVectorSources(VT))) {
14940     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
14941     EVT InEltVT = Elt.getValueType();
14942 
14943     // Sometimes build_vector's scalar input types do not match result type.
14944     if (NVT == InEltVT)
14945       return Elt;
14946 
14947     // TODO: It may be useful to truncate if free if the build_vector implicitly
14948     // converts.
14949   }
14950 
14951   // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x)
14952   bool isLE = DAG.getDataLayout().isLittleEndian();
14953   unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1;
14954   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
14955       ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) {
14956     SDValue BCSrc = InVec.getOperand(0);
14957     if (BCSrc.getValueType().isScalarInteger())
14958       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
14959   }
14960 
14961   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
14962   //
14963   // This only really matters if the index is non-constant since other combines
14964   // on the constant elements already work.
14965   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
14966       EltNo == InVec.getOperand(2)) {
14967     SDValue Elt = InVec.getOperand(1);
14968     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
14969   }
14970 
14971   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
14972   // We only perform this optimization before the op legalization phase because
14973   // we may introduce new vector instructions which are not backed by TD
14974   // patterns. For example on AVX, extracting elements from a wide vector
14975   // without using extract_subvector. However, if we can find an underlying
14976   // scalar value, then we can always use that.
14977   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
14978     int NumElem = VT.getVectorNumElements();
14979     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
14980     // Find the new index to extract from.
14981     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
14982 
14983     // Extracting an undef index is undef.
14984     if (OrigElt == -1)
14985       return DAG.getUNDEF(NVT);
14986 
14987     // Select the right vector half to extract from.
14988     SDValue SVInVec;
14989     if (OrigElt < NumElem) {
14990       SVInVec = InVec->getOperand(0);
14991     } else {
14992       SVInVec = InVec->getOperand(1);
14993       OrigElt -= NumElem;
14994     }
14995 
14996     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
14997       SDValue InOp = SVInVec.getOperand(OrigElt);
14998       if (InOp.getValueType() != NVT) {
14999         assert(InOp.getValueType().isInteger() && NVT.isInteger());
15000         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
15001       }
15002 
15003       return InOp;
15004     }
15005 
15006     // FIXME: We should handle recursing on other vector shuffles and
15007     // scalar_to_vector here as well.
15008 
15009     if (!LegalOperations ||
15010         // FIXME: Should really be just isOperationLegalOrCustom.
15011         TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) ||
15012         TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) {
15013       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
15014       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
15015                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
15016     }
15017   }
15018 
15019   // If only EXTRACT_VECTOR_ELT nodes use the source vector we can
15020   // simplify it based on the (valid) extraction indices.
15021   if (llvm::all_of(InVec->uses(), [&](SDNode *Use) {
15022         return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15023                Use->getOperand(0) == InVec &&
15024                isa<ConstantSDNode>(Use->getOperand(1));
15025       })) {
15026     APInt DemandedElts = APInt::getNullValue(VT.getVectorNumElements());
15027     for (SDNode *Use : InVec->uses()) {
15028       auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1));
15029       if (CstElt->getAPIntValue().ult(VT.getVectorNumElements()))
15030         DemandedElts.setBit(CstElt->getZExtValue());
15031     }
15032     if (SimplifyDemandedVectorElts(InVec, DemandedElts, true))
15033       return SDValue(N, 0);
15034   }
15035 
15036   bool BCNumEltsChanged = false;
15037   EVT ExtVT = VT.getVectorElementType();
15038   EVT LVT = ExtVT;
15039 
15040   // If the result of load has to be truncated, then it's not necessarily
15041   // profitable.
15042   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
15043     return SDValue();
15044 
15045   if (InVec.getOpcode() == ISD::BITCAST) {
15046     // Don't duplicate a load with other uses.
15047     if (!InVec.hasOneUse())
15048       return SDValue();
15049 
15050     EVT BCVT = InVec.getOperand(0).getValueType();
15051     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
15052       return SDValue();
15053     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
15054       BCNumEltsChanged = true;
15055     InVec = InVec.getOperand(0);
15056     ExtVT = BCVT.getVectorElementType();
15057   }
15058 
15059   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
15060   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
15061       ISD::isNormalLoad(InVec.getNode()) &&
15062       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
15063     SDValue Index = N->getOperand(1);
15064     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
15065       if (!OrigLoad->isVolatile()) {
15066         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
15067                                                              OrigLoad);
15068       }
15069     }
15070   }
15071 
15072   // Perform only after legalization to ensure build_vector / vector_shuffle
15073   // optimizations have already been done.
15074   if (!LegalOperations) return SDValue();
15075 
15076   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
15077   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
15078   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
15079 
15080   if (ConstEltNo) {
15081     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15082 
15083     LoadSDNode *LN0 = nullptr;
15084     const ShuffleVectorSDNode *SVN = nullptr;
15085     if (ISD::isNormalLoad(InVec.getNode())) {
15086       LN0 = cast<LoadSDNode>(InVec);
15087     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
15088                InVec.getOperand(0).getValueType() == ExtVT &&
15089                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
15090       // Don't duplicate a load with other uses.
15091       if (!InVec.hasOneUse())
15092         return SDValue();
15093 
15094       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
15095     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
15096       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
15097       // =>
15098       // (load $addr+1*size)
15099 
15100       // Don't duplicate a load with other uses.
15101       if (!InVec.hasOneUse())
15102         return SDValue();
15103 
15104       // If the bit convert changed the number of elements, it is unsafe
15105       // to examine the mask.
15106       if (BCNumEltsChanged)
15107         return SDValue();
15108 
15109       // Select the input vector, guarding against out of range extract vector.
15110       unsigned NumElems = VT.getVectorNumElements();
15111       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
15112       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
15113 
15114       if (InVec.getOpcode() == ISD::BITCAST) {
15115         // Don't duplicate a load with other uses.
15116         if (!InVec.hasOneUse())
15117           return SDValue();
15118 
15119         InVec = InVec.getOperand(0);
15120       }
15121       if (ISD::isNormalLoad(InVec.getNode())) {
15122         LN0 = cast<LoadSDNode>(InVec);
15123         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
15124         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
15125       }
15126     }
15127 
15128     // Make sure we found a non-volatile load and the extractelement is
15129     // the only use.
15130     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
15131       return SDValue();
15132 
15133     // If Idx was -1 above, Elt is going to be -1, so just return undef.
15134     if (Elt == -1)
15135       return DAG.getUNDEF(LVT);
15136 
15137     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
15138   }
15139 
15140   return SDValue();
15141 }
15142 
15143 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
15144 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
15145   // We perform this optimization post type-legalization because
15146   // the type-legalizer often scalarizes integer-promoted vectors.
15147   // Performing this optimization before may create bit-casts which
15148   // will be type-legalized to complex code sequences.
15149   // We perform this optimization only before the operation legalizer because we
15150   // may introduce illegal operations.
15151   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
15152     return SDValue();
15153 
15154   unsigned NumInScalars = N->getNumOperands();
15155   SDLoc DL(N);
15156   EVT VT = N->getValueType(0);
15157 
15158   // Check to see if this is a BUILD_VECTOR of a bunch of values
15159   // which come from any_extend or zero_extend nodes. If so, we can create
15160   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
15161   // optimizations. We do not handle sign-extend because we can't fill the sign
15162   // using shuffles.
15163   EVT SourceType = MVT::Other;
15164   bool AllAnyExt = true;
15165 
15166   for (unsigned i = 0; i != NumInScalars; ++i) {
15167     SDValue In = N->getOperand(i);
15168     // Ignore undef inputs.
15169     if (In.isUndef()) continue;
15170 
15171     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
15172     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
15173 
15174     // Abort if the element is not an extension.
15175     if (!ZeroExt && !AnyExt) {
15176       SourceType = MVT::Other;
15177       break;
15178     }
15179 
15180     // The input is a ZeroExt or AnyExt. Check the original type.
15181     EVT InTy = In.getOperand(0).getValueType();
15182 
15183     // Check that all of the widened source types are the same.
15184     if (SourceType == MVT::Other)
15185       // First time.
15186       SourceType = InTy;
15187     else if (InTy != SourceType) {
15188       // Multiple income types. Abort.
15189       SourceType = MVT::Other;
15190       break;
15191     }
15192 
15193     // Check if all of the extends are ANY_EXTENDs.
15194     AllAnyExt &= AnyExt;
15195   }
15196 
15197   // In order to have valid types, all of the inputs must be extended from the
15198   // same source type and all of the inputs must be any or zero extend.
15199   // Scalar sizes must be a power of two.
15200   EVT OutScalarTy = VT.getScalarType();
15201   bool ValidTypes = SourceType != MVT::Other &&
15202                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
15203                  isPowerOf2_32(SourceType.getSizeInBits());
15204 
15205   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
15206   // turn into a single shuffle instruction.
15207   if (!ValidTypes)
15208     return SDValue();
15209 
15210   bool isLE = DAG.getDataLayout().isLittleEndian();
15211   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
15212   assert(ElemRatio > 1 && "Invalid element size ratio");
15213   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
15214                                DAG.getConstant(0, DL, SourceType);
15215 
15216   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
15217   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
15218 
15219   // Populate the new build_vector
15220   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15221     SDValue Cast = N->getOperand(i);
15222     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
15223             Cast.getOpcode() == ISD::ZERO_EXTEND ||
15224             Cast.isUndef()) && "Invalid cast opcode");
15225     SDValue In;
15226     if (Cast.isUndef())
15227       In = DAG.getUNDEF(SourceType);
15228     else
15229       In = Cast->getOperand(0);
15230     unsigned Index = isLE ? (i * ElemRatio) :
15231                             (i * ElemRatio + (ElemRatio - 1));
15232 
15233     assert(Index < Ops.size() && "Invalid index");
15234     Ops[Index] = In;
15235   }
15236 
15237   // The type of the new BUILD_VECTOR node.
15238   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
15239   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
15240          "Invalid vector size");
15241   // Check if the new vector type is legal.
15242   if (!isTypeLegal(VecVT) ||
15243       (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) &&
15244        TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)))
15245     return SDValue();
15246 
15247   // Make the new BUILD_VECTOR.
15248   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
15249 
15250   // The new BUILD_VECTOR node has the potential to be further optimized.
15251   AddToWorklist(BV.getNode());
15252   // Bitcast to the desired type.
15253   return DAG.getBitcast(VT, BV);
15254 }
15255 
15256 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
15257   EVT VT = N->getValueType(0);
15258 
15259   unsigned NumInScalars = N->getNumOperands();
15260   SDLoc DL(N);
15261 
15262   EVT SrcVT = MVT::Other;
15263   unsigned Opcode = ISD::DELETED_NODE;
15264   unsigned NumDefs = 0;
15265 
15266   for (unsigned i = 0; i != NumInScalars; ++i) {
15267     SDValue In = N->getOperand(i);
15268     unsigned Opc = In.getOpcode();
15269 
15270     if (Opc == ISD::UNDEF)
15271       continue;
15272 
15273     // If all scalar values are floats and converted from integers.
15274     if (Opcode == ISD::DELETED_NODE &&
15275         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
15276       Opcode = Opc;
15277     }
15278 
15279     if (Opc != Opcode)
15280       return SDValue();
15281 
15282     EVT InVT = In.getOperand(0).getValueType();
15283 
15284     // If all scalar values are typed differently, bail out. It's chosen to
15285     // simplify BUILD_VECTOR of integer types.
15286     if (SrcVT == MVT::Other)
15287       SrcVT = InVT;
15288     if (SrcVT != InVT)
15289       return SDValue();
15290     NumDefs++;
15291   }
15292 
15293   // If the vector has just one element defined, it's not worth to fold it into
15294   // a vectorized one.
15295   if (NumDefs < 2)
15296     return SDValue();
15297 
15298   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
15299          && "Should only handle conversion from integer to float.");
15300   assert(SrcVT != MVT::Other && "Cannot determine source type!");
15301 
15302   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
15303 
15304   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
15305     return SDValue();
15306 
15307   // Just because the floating-point vector type is legal does not necessarily
15308   // mean that the corresponding integer vector type is.
15309   if (!isTypeLegal(NVT))
15310     return SDValue();
15311 
15312   SmallVector<SDValue, 8> Opnds;
15313   for (unsigned i = 0; i != NumInScalars; ++i) {
15314     SDValue In = N->getOperand(i);
15315 
15316     if (In.isUndef())
15317       Opnds.push_back(DAG.getUNDEF(SrcVT));
15318     else
15319       Opnds.push_back(In.getOperand(0));
15320   }
15321   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
15322   AddToWorklist(BV.getNode());
15323 
15324   return DAG.getNode(Opcode, DL, VT, BV);
15325 }
15326 
15327 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
15328                                            ArrayRef<int> VectorMask,
15329                                            SDValue VecIn1, SDValue VecIn2,
15330                                            unsigned LeftIdx) {
15331   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
15332   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
15333 
15334   EVT VT = N->getValueType(0);
15335   EVT InVT1 = VecIn1.getValueType();
15336   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
15337 
15338   unsigned Vec2Offset = 0;
15339   unsigned NumElems = VT.getVectorNumElements();
15340   unsigned ShuffleNumElems = NumElems;
15341 
15342   // In case both the input vectors are extracted from same base
15343   // vector we do not need extra addend (Vec2Offset) while
15344   // computing shuffle mask.
15345   if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
15346       !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
15347       !(VecIn1.getOperand(0) == VecIn2.getOperand(0)))
15348     Vec2Offset = InVT1.getVectorNumElements();
15349 
15350   // We can't generate a shuffle node with mismatched input and output types.
15351   // Try to make the types match the type of the output.
15352   if (InVT1 != VT || InVT2 != VT) {
15353     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
15354       // If the output vector length is a multiple of both input lengths,
15355       // we can concatenate them and pad the rest with undefs.
15356       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
15357       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
15358       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
15359       ConcatOps[0] = VecIn1;
15360       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
15361       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
15362       VecIn2 = SDValue();
15363     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
15364       if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
15365         return SDValue();
15366 
15367       if (!VecIn2.getNode()) {
15368         // If we only have one input vector, and it's twice the size of the
15369         // output, split it in two.
15370         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
15371                              DAG.getConstant(NumElems, DL, IdxTy));
15372         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
15373         // Since we now have shorter input vectors, adjust the offset of the
15374         // second vector's start.
15375         Vec2Offset = NumElems;
15376       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
15377         // VecIn1 is wider than the output, and we have another, possibly
15378         // smaller input. Pad the smaller input with undefs, shuffle at the
15379         // input vector width, and extract the output.
15380         // The shuffle type is different than VT, so check legality again.
15381         if (LegalOperations &&
15382             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
15383           return SDValue();
15384 
15385         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
15386         // lower it back into a BUILD_VECTOR. So if the inserted type is
15387         // illegal, don't even try.
15388         if (InVT1 != InVT2) {
15389           if (!TLI.isTypeLegal(InVT2))
15390             return SDValue();
15391           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
15392                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
15393         }
15394         ShuffleNumElems = NumElems * 2;
15395       } else {
15396         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
15397         // than VecIn1. We can't handle this for now - this case will disappear
15398         // when we start sorting the vectors by type.
15399         return SDValue();
15400       }
15401     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
15402                InVT1.getSizeInBits() == VT.getSizeInBits()) {
15403       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
15404       ConcatOps[0] = VecIn2;
15405       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
15406     } else {
15407       // TODO: Support cases where the length mismatch isn't exactly by a
15408       // factor of 2.
15409       // TODO: Move this check upwards, so that if we have bad type
15410       // mismatches, we don't create any DAG nodes.
15411       return SDValue();
15412     }
15413   }
15414 
15415   // Initialize mask to undef.
15416   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
15417 
15418   // Only need to run up to the number of elements actually used, not the
15419   // total number of elements in the shuffle - if we are shuffling a wider
15420   // vector, the high lanes should be set to undef.
15421   for (unsigned i = 0; i != NumElems; ++i) {
15422     if (VectorMask[i] <= 0)
15423       continue;
15424 
15425     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
15426     if (VectorMask[i] == (int)LeftIdx) {
15427       Mask[i] = ExtIndex;
15428     } else if (VectorMask[i] == (int)LeftIdx + 1) {
15429       Mask[i] = Vec2Offset + ExtIndex;
15430     }
15431   }
15432 
15433   // The type the input vectors may have changed above.
15434   InVT1 = VecIn1.getValueType();
15435 
15436   // If we already have a VecIn2, it should have the same type as VecIn1.
15437   // If we don't, get an undef/zero vector of the appropriate type.
15438   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
15439   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
15440 
15441   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
15442   if (ShuffleNumElems > NumElems)
15443     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
15444 
15445   return Shuffle;
15446 }
15447 
15448 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
15449 // operations. If the types of the vectors we're extracting from allow it,
15450 // turn this into a vector_shuffle node.
15451 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
15452   SDLoc DL(N);
15453   EVT VT = N->getValueType(0);
15454 
15455   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
15456   if (!isTypeLegal(VT))
15457     return SDValue();
15458 
15459   // May only combine to shuffle after legalize if shuffle is legal.
15460   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
15461     return SDValue();
15462 
15463   bool UsesZeroVector = false;
15464   unsigned NumElems = N->getNumOperands();
15465 
15466   // Record, for each element of the newly built vector, which input vector
15467   // that element comes from. -1 stands for undef, 0 for the zero vector,
15468   // and positive values for the input vectors.
15469   // VectorMask maps each element to its vector number, and VecIn maps vector
15470   // numbers to their initial SDValues.
15471 
15472   SmallVector<int, 8> VectorMask(NumElems, -1);
15473   SmallVector<SDValue, 8> VecIn;
15474   VecIn.push_back(SDValue());
15475 
15476   for (unsigned i = 0; i != NumElems; ++i) {
15477     SDValue Op = N->getOperand(i);
15478 
15479     if (Op.isUndef())
15480       continue;
15481 
15482     // See if we can use a blend with a zero vector.
15483     // TODO: Should we generalize this to a blend with an arbitrary constant
15484     // vector?
15485     if (isNullConstant(Op) || isNullFPConstant(Op)) {
15486       UsesZeroVector = true;
15487       VectorMask[i] = 0;
15488       continue;
15489     }
15490 
15491     // Not an undef or zero. If the input is something other than an
15492     // EXTRACT_VECTOR_ELT with an in-range constant index, bail out.
15493     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
15494         !isa<ConstantSDNode>(Op.getOperand(1)))
15495       return SDValue();
15496     SDValue ExtractedFromVec = Op.getOperand(0);
15497 
15498     APInt ExtractIdx = cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue();
15499     if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements()))
15500       return SDValue();
15501 
15502     // All inputs must have the same element type as the output.
15503     if (VT.getVectorElementType() !=
15504         ExtractedFromVec.getValueType().getVectorElementType())
15505       return SDValue();
15506 
15507     // Have we seen this input vector before?
15508     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
15509     // a map back from SDValues to numbers isn't worth it.
15510     unsigned Idx = std::distance(
15511         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
15512     if (Idx == VecIn.size())
15513       VecIn.push_back(ExtractedFromVec);
15514 
15515     VectorMask[i] = Idx;
15516   }
15517 
15518   // If we didn't find at least one input vector, bail out.
15519   if (VecIn.size() < 2)
15520     return SDValue();
15521 
15522   // If all the Operands of BUILD_VECTOR extract from same
15523   // vector, then split the vector efficiently based on the maximum
15524   // vector access index and adjust the VectorMask and
15525   // VecIn accordingly.
15526   if (VecIn.size() == 2) {
15527     unsigned MaxIndex = 0;
15528     unsigned NearestPow2 = 0;
15529     SDValue Vec = VecIn.back();
15530     EVT InVT = Vec.getValueType();
15531     MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
15532     SmallVector<unsigned, 8> IndexVec(NumElems, 0);
15533 
15534     for (unsigned i = 0; i < NumElems; i++) {
15535       if (VectorMask[i] <= 0)
15536         continue;
15537       unsigned Index = N->getOperand(i).getConstantOperandVal(1);
15538       IndexVec[i] = Index;
15539       MaxIndex = std::max(MaxIndex, Index);
15540     }
15541 
15542     NearestPow2 = PowerOf2Ceil(MaxIndex);
15543     if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
15544         NumElems * 2 < NearestPow2) {
15545       unsigned SplitSize = NearestPow2 / 2;
15546       EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
15547                                      InVT.getVectorElementType(), SplitSize);
15548       if (TLI.isTypeLegal(SplitVT)) {
15549         SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
15550                                      DAG.getConstant(SplitSize, DL, IdxTy));
15551         SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
15552                                      DAG.getConstant(0, DL, IdxTy));
15553         VecIn.pop_back();
15554         VecIn.push_back(VecIn1);
15555         VecIn.push_back(VecIn2);
15556 
15557         for (unsigned i = 0; i < NumElems; i++) {
15558           if (VectorMask[i] <= 0)
15559             continue;
15560           VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
15561         }
15562       }
15563     }
15564   }
15565 
15566   // TODO: We want to sort the vectors by descending length, so that adjacent
15567   // pairs have similar length, and the longer vector is always first in the
15568   // pair.
15569 
15570   // TODO: Should this fire if some of the input vectors has illegal type (like
15571   // it does now), or should we let legalization run its course first?
15572 
15573   // Shuffle phase:
15574   // Take pairs of vectors, and shuffle them so that the result has elements
15575   // from these vectors in the correct places.
15576   // For example, given:
15577   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
15578   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
15579   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
15580   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
15581   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
15582   // We will generate:
15583   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
15584   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
15585   SmallVector<SDValue, 4> Shuffles;
15586   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
15587     unsigned LeftIdx = 2 * In + 1;
15588     SDValue VecLeft = VecIn[LeftIdx];
15589     SDValue VecRight =
15590         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
15591 
15592     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
15593                                                 VecRight, LeftIdx))
15594       Shuffles.push_back(Shuffle);
15595     else
15596       return SDValue();
15597   }
15598 
15599   // If we need the zero vector as an "ingredient" in the blend tree, add it
15600   // to the list of shuffles.
15601   if (UsesZeroVector)
15602     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
15603                                       : DAG.getConstantFP(0.0, DL, VT));
15604 
15605   // If we only have one shuffle, we're done.
15606   if (Shuffles.size() == 1)
15607     return Shuffles[0];
15608 
15609   // Update the vector mask to point to the post-shuffle vectors.
15610   for (int &Vec : VectorMask)
15611     if (Vec == 0)
15612       Vec = Shuffles.size() - 1;
15613     else
15614       Vec = (Vec - 1) / 2;
15615 
15616   // More than one shuffle. Generate a binary tree of blends, e.g. if from
15617   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
15618   // generate:
15619   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
15620   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
15621   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
15622   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
15623   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
15624   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
15625   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
15626 
15627   // Make sure the initial size of the shuffle list is even.
15628   if (Shuffles.size() % 2)
15629     Shuffles.push_back(DAG.getUNDEF(VT));
15630 
15631   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
15632     if (CurSize % 2) {
15633       Shuffles[CurSize] = DAG.getUNDEF(VT);
15634       CurSize++;
15635     }
15636     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
15637       int Left = 2 * In;
15638       int Right = 2 * In + 1;
15639       SmallVector<int, 8> Mask(NumElems, -1);
15640       for (unsigned i = 0; i != NumElems; ++i) {
15641         if (VectorMask[i] == Left) {
15642           Mask[i] = i;
15643           VectorMask[i] = In;
15644         } else if (VectorMask[i] == Right) {
15645           Mask[i] = i + NumElems;
15646           VectorMask[i] = In;
15647         }
15648       }
15649 
15650       Shuffles[In] =
15651           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
15652     }
15653   }
15654   return Shuffles[0];
15655 }
15656 
15657 // Try to turn a build vector of zero extends of extract vector elts into a
15658 // a vector zero extend and possibly an extract subvector.
15659 // TODO: Support sign extend or any extend?
15660 // TODO: Allow undef elements?
15661 // TODO: Don't require the extracts to start at element 0.
15662 SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) {
15663   if (LegalOperations)
15664     return SDValue();
15665 
15666   EVT VT = N->getValueType(0);
15667 
15668   SDValue Op0 = N->getOperand(0);
15669   auto checkElem = [&](SDValue Op) -> int64_t {
15670     if (Op.getOpcode() == ISD::ZERO_EXTEND &&
15671         Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15672         Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0))
15673       if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1)))
15674         return C->getZExtValue();
15675     return -1;
15676   };
15677 
15678   // Make sure the first element matches
15679   // (zext (extract_vector_elt X, C))
15680   int64_t Offset = checkElem(Op0);
15681   if (Offset < 0)
15682     return SDValue();
15683 
15684   unsigned NumElems = N->getNumOperands();
15685   SDValue In = Op0.getOperand(0).getOperand(0);
15686   EVT InSVT = In.getValueType().getScalarType();
15687   EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems);
15688 
15689   // Don't create an illegal input type after type legalization.
15690   if (LegalTypes && !TLI.isTypeLegal(InVT))
15691     return SDValue();
15692 
15693   // Ensure all the elements come from the same vector and are adjacent.
15694   for (unsigned i = 1; i != NumElems; ++i) {
15695     if ((Offset + i) != checkElem(N->getOperand(i)))
15696       return SDValue();
15697   }
15698 
15699   SDLoc DL(N);
15700   In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In,
15701                    Op0.getOperand(0).getOperand(1));
15702   return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, In);
15703 }
15704 
15705 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
15706   EVT VT = N->getValueType(0);
15707 
15708   // A vector built entirely of undefs is undef.
15709   if (ISD::allOperandsUndef(N))
15710     return DAG.getUNDEF(VT);
15711 
15712   // If this is a splat of a bitcast from another vector, change to a
15713   // concat_vector.
15714   // For example:
15715   //   (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) ->
15716   //     (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X))))
15717   //
15718   // If X is a build_vector itself, the concat can become a larger build_vector.
15719   // TODO: Maybe this is useful for non-splat too?
15720   if (!LegalOperations) {
15721     if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) {
15722       Splat = peekThroughBitcast(Splat);
15723       EVT SrcVT = Splat.getValueType();
15724       if (SrcVT.isVector()) {
15725         unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements();
15726         EVT NewVT = EVT::getVectorVT(*DAG.getContext(),
15727                                      SrcVT.getVectorElementType(), NumElts);
15728         if (!LegalTypes || TLI.isTypeLegal(NewVT)) {
15729           SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat);
15730           SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N),
15731                                        NewVT, Ops);
15732           return DAG.getBitcast(VT, Concat);
15733         }
15734       }
15735     }
15736   }
15737 
15738   // Check if we can express BUILD VECTOR via subvector extract.
15739   if (!LegalTypes && (N->getNumOperands() > 1)) {
15740     SDValue Op0 = N->getOperand(0);
15741     auto checkElem = [&](SDValue Op) -> uint64_t {
15742       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
15743           (Op0.getOperand(0) == Op.getOperand(0)))
15744         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
15745           return CNode->getZExtValue();
15746       return -1;
15747     };
15748 
15749     int Offset = checkElem(Op0);
15750     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
15751       if (Offset + i != checkElem(N->getOperand(i))) {
15752         Offset = -1;
15753         break;
15754       }
15755     }
15756 
15757     if ((Offset == 0) &&
15758         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
15759       return Op0.getOperand(0);
15760     if ((Offset != -1) &&
15761         ((Offset % N->getValueType(0).getVectorNumElements()) ==
15762          0)) // IDX must be multiple of output size.
15763       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
15764                          Op0.getOperand(0), Op0.getOperand(1));
15765   }
15766 
15767   if (SDValue V = convertBuildVecZextToZext(N))
15768     return V;
15769 
15770   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
15771     return V;
15772 
15773   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
15774     return V;
15775 
15776   if (SDValue V = reduceBuildVecToShuffle(N))
15777     return V;
15778 
15779   return SDValue();
15780 }
15781 
15782 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
15783   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15784   EVT OpVT = N->getOperand(0).getValueType();
15785 
15786   // If the operands are legal vectors, leave them alone.
15787   if (TLI.isTypeLegal(OpVT))
15788     return SDValue();
15789 
15790   SDLoc DL(N);
15791   EVT VT = N->getValueType(0);
15792   SmallVector<SDValue, 8> Ops;
15793 
15794   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
15795   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
15796 
15797   // Keep track of what we encounter.
15798   bool AnyInteger = false;
15799   bool AnyFP = false;
15800   for (const SDValue &Op : N->ops()) {
15801     if (ISD::BITCAST == Op.getOpcode() &&
15802         !Op.getOperand(0).getValueType().isVector())
15803       Ops.push_back(Op.getOperand(0));
15804     else if (ISD::UNDEF == Op.getOpcode())
15805       Ops.push_back(ScalarUndef);
15806     else
15807       return SDValue();
15808 
15809     // Note whether we encounter an integer or floating point scalar.
15810     // If it's neither, bail out, it could be something weird like x86mmx.
15811     EVT LastOpVT = Ops.back().getValueType();
15812     if (LastOpVT.isFloatingPoint())
15813       AnyFP = true;
15814     else if (LastOpVT.isInteger())
15815       AnyInteger = true;
15816     else
15817       return SDValue();
15818   }
15819 
15820   // If any of the operands is a floating point scalar bitcast to a vector,
15821   // use floating point types throughout, and bitcast everything.
15822   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
15823   if (AnyFP) {
15824     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
15825     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
15826     if (AnyInteger) {
15827       for (SDValue &Op : Ops) {
15828         if (Op.getValueType() == SVT)
15829           continue;
15830         if (Op.isUndef())
15831           Op = ScalarUndef;
15832         else
15833           Op = DAG.getBitcast(SVT, Op);
15834       }
15835     }
15836   }
15837 
15838   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
15839                                VT.getSizeInBits() / SVT.getSizeInBits());
15840   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
15841 }
15842 
15843 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
15844 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
15845 // most two distinct vectors the same size as the result, attempt to turn this
15846 // into a legal shuffle.
15847 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
15848   EVT VT = N->getValueType(0);
15849   EVT OpVT = N->getOperand(0).getValueType();
15850   int NumElts = VT.getVectorNumElements();
15851   int NumOpElts = OpVT.getVectorNumElements();
15852 
15853   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
15854   SmallVector<int, 8> Mask;
15855 
15856   for (SDValue Op : N->ops()) {
15857     // Peek through any bitcast.
15858     Op = peekThroughBitcast(Op);
15859 
15860     // UNDEF nodes convert to UNDEF shuffle mask values.
15861     if (Op.isUndef()) {
15862       Mask.append((unsigned)NumOpElts, -1);
15863       continue;
15864     }
15865 
15866     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15867       return SDValue();
15868 
15869     // What vector are we extracting the subvector from and at what index?
15870     SDValue ExtVec = Op.getOperand(0);
15871 
15872     // We want the EVT of the original extraction to correctly scale the
15873     // extraction index.
15874     EVT ExtVT = ExtVec.getValueType();
15875 
15876     // Peek through any bitcast.
15877     ExtVec = peekThroughBitcast(ExtVec);
15878 
15879     // UNDEF nodes convert to UNDEF shuffle mask values.
15880     if (ExtVec.isUndef()) {
15881       Mask.append((unsigned)NumOpElts, -1);
15882       continue;
15883     }
15884 
15885     if (!isa<ConstantSDNode>(Op.getOperand(1)))
15886       return SDValue();
15887     int ExtIdx = Op.getConstantOperandVal(1);
15888 
15889     // Ensure that we are extracting a subvector from a vector the same
15890     // size as the result.
15891     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
15892       return SDValue();
15893 
15894     // Scale the subvector index to account for any bitcast.
15895     int NumExtElts = ExtVT.getVectorNumElements();
15896     if (0 == (NumExtElts % NumElts))
15897       ExtIdx /= (NumExtElts / NumElts);
15898     else if (0 == (NumElts % NumExtElts))
15899       ExtIdx *= (NumElts / NumExtElts);
15900     else
15901       return SDValue();
15902 
15903     // At most we can reference 2 inputs in the final shuffle.
15904     if (SV0.isUndef() || SV0 == ExtVec) {
15905       SV0 = ExtVec;
15906       for (int i = 0; i != NumOpElts; ++i)
15907         Mask.push_back(i + ExtIdx);
15908     } else if (SV1.isUndef() || SV1 == ExtVec) {
15909       SV1 = ExtVec;
15910       for (int i = 0; i != NumOpElts; ++i)
15911         Mask.push_back(i + ExtIdx + NumElts);
15912     } else {
15913       return SDValue();
15914     }
15915   }
15916 
15917   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
15918     return SDValue();
15919 
15920   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
15921                               DAG.getBitcast(VT, SV1), Mask);
15922 }
15923 
15924 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
15925   // If we only have one input vector, we don't need to do any concatenation.
15926   if (N->getNumOperands() == 1)
15927     return N->getOperand(0);
15928 
15929   // Check if all of the operands are undefs.
15930   EVT VT = N->getValueType(0);
15931   if (ISD::allOperandsUndef(N))
15932     return DAG.getUNDEF(VT);
15933 
15934   // Optimize concat_vectors where all but the first of the vectors are undef.
15935   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
15936         return Op.isUndef();
15937       })) {
15938     SDValue In = N->getOperand(0);
15939     assert(In.getValueType().isVector() && "Must concat vectors");
15940 
15941     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
15942     if (In->getOpcode() == ISD::BITCAST &&
15943         !In->getOperand(0).getValueType().isVector()) {
15944       SDValue Scalar = In->getOperand(0);
15945 
15946       // If the bitcast type isn't legal, it might be a trunc of a legal type;
15947       // look through the trunc so we can still do the transform:
15948       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
15949       if (Scalar->getOpcode() == ISD::TRUNCATE &&
15950           !TLI.isTypeLegal(Scalar.getValueType()) &&
15951           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
15952         Scalar = Scalar->getOperand(0);
15953 
15954       EVT SclTy = Scalar->getValueType(0);
15955 
15956       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
15957         return SDValue();
15958 
15959       // Bail out if the vector size is not a multiple of the scalar size.
15960       if (VT.getSizeInBits() % SclTy.getSizeInBits())
15961         return SDValue();
15962 
15963       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
15964       if (VNTNumElms < 2)
15965         return SDValue();
15966 
15967       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
15968       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
15969         return SDValue();
15970 
15971       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
15972       return DAG.getBitcast(VT, Res);
15973     }
15974   }
15975 
15976   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
15977   // We have already tested above for an UNDEF only concatenation.
15978   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
15979   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
15980   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
15981     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
15982   };
15983   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
15984     SmallVector<SDValue, 8> Opnds;
15985     EVT SVT = VT.getScalarType();
15986 
15987     EVT MinVT = SVT;
15988     if (!SVT.isFloatingPoint()) {
15989       // If BUILD_VECTOR are from built from integer, they may have different
15990       // operand types. Get the smallest type and truncate all operands to it.
15991       bool FoundMinVT = false;
15992       for (const SDValue &Op : N->ops())
15993         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15994           EVT OpSVT = Op.getOperand(0).getValueType();
15995           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
15996           FoundMinVT = true;
15997         }
15998       assert(FoundMinVT && "Concat vector type mismatch");
15999     }
16000 
16001     for (const SDValue &Op : N->ops()) {
16002       EVT OpVT = Op.getValueType();
16003       unsigned NumElts = OpVT.getVectorNumElements();
16004 
16005       if (ISD::UNDEF == Op.getOpcode())
16006         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
16007 
16008       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
16009         if (SVT.isFloatingPoint()) {
16010           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
16011           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
16012         } else {
16013           for (unsigned i = 0; i != NumElts; ++i)
16014             Opnds.push_back(
16015                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
16016         }
16017       }
16018     }
16019 
16020     assert(VT.getVectorNumElements() == Opnds.size() &&
16021            "Concat vector type mismatch");
16022     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
16023   }
16024 
16025   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
16026   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
16027     return V;
16028 
16029   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
16030   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
16031     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
16032       return V;
16033 
16034   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
16035   // nodes often generate nop CONCAT_VECTOR nodes.
16036   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
16037   // place the incoming vectors at the exact same location.
16038   SDValue SingleSource = SDValue();
16039   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
16040 
16041   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
16042     SDValue Op = N->getOperand(i);
16043 
16044     if (Op.isUndef())
16045       continue;
16046 
16047     // Check if this is the identity extract:
16048     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
16049       return SDValue();
16050 
16051     // Find the single incoming vector for the extract_subvector.
16052     if (SingleSource.getNode()) {
16053       if (Op.getOperand(0) != SingleSource)
16054         return SDValue();
16055     } else {
16056       SingleSource = Op.getOperand(0);
16057 
16058       // Check the source type is the same as the type of the result.
16059       // If not, this concat may extend the vector, so we can not
16060       // optimize it away.
16061       if (SingleSource.getValueType() != N->getValueType(0))
16062         return SDValue();
16063     }
16064 
16065     unsigned IdentityIndex = i * PartNumElem;
16066     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
16067     // The extract index must be constant.
16068     if (!CS)
16069       return SDValue();
16070 
16071     // Check that we are reading from the identity index.
16072     if (CS->getZExtValue() != IdentityIndex)
16073       return SDValue();
16074   }
16075 
16076   if (SingleSource.getNode())
16077     return SingleSource;
16078 
16079   return SDValue();
16080 }
16081 
16082 /// If we are extracting a subvector produced by a wide binary operator with at
16083 /// at least one operand that was the result of a vector concatenation, then try
16084 /// to use the narrow vector operands directly to avoid the concatenation and
16085 /// extraction.
16086 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
16087   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
16088   // some of these bailouts with other transforms.
16089 
16090   // The extract index must be a constant, so we can map it to a concat operand.
16091   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
16092   if (!ExtractIndex)
16093     return SDValue();
16094 
16095   // Only handle the case where we are doubling and then halving. A larger ratio
16096   // may require more than two narrow binops to replace the wide binop.
16097   EVT VT = Extract->getValueType(0);
16098   unsigned NumElems = VT.getVectorNumElements();
16099   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
16100          "Extract index is not a multiple of the vector length.");
16101   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
16102     return SDValue();
16103 
16104   // We are looking for an optionally bitcasted wide vector binary operator
16105   // feeding an extract subvector.
16106   SDValue BinOp = peekThroughBitcast(Extract->getOperand(0));
16107 
16108   // TODO: The motivating case for this transform is an x86 AVX1 target. That
16109   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
16110   // flavors, but no other 256-bit integer support. This could be extended to
16111   // handle any binop, but that may require fixing/adding other folds to avoid
16112   // codegen regressions.
16113   unsigned BOpcode = BinOp.getOpcode();
16114   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
16115     return SDValue();
16116 
16117   // The binop must be a vector type, so we can chop it in half.
16118   EVT WideBVT = BinOp.getValueType();
16119   if (!WideBVT.isVector())
16120     return SDValue();
16121 
16122   // Bail out if the target does not support a narrower version of the binop.
16123   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
16124                                    WideBVT.getVectorNumElements() / 2);
16125   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16126   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
16127     return SDValue();
16128 
16129   // Peek through bitcasts of the binary operator operands if needed.
16130   SDValue LHS = peekThroughBitcast(BinOp.getOperand(0));
16131   SDValue RHS = peekThroughBitcast(BinOp.getOperand(1));
16132 
16133   // We need at least one concatenation operation of a binop operand to make
16134   // this transform worthwhile. The concat must double the input vector sizes.
16135   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
16136   bool ConcatL =
16137       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
16138   bool ConcatR =
16139       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
16140   if (!ConcatL && !ConcatR)
16141     return SDValue();
16142 
16143   // If one of the binop operands was not the result of a concat, we must
16144   // extract a half-sized operand for our new narrow binop. We can't just reuse
16145   // the original extract index operand because we may have bitcasted.
16146   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
16147   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
16148   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
16149   SDLoc DL(Extract);
16150 
16151   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
16152   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
16153   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
16154   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
16155                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
16156                                     BinOp.getOperand(0),
16157                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
16158 
16159   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
16160                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
16161                                     BinOp.getOperand(1),
16162                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
16163 
16164   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
16165   return DAG.getBitcast(VT, NarrowBinOp);
16166 }
16167 
16168 /// If we are extracting a subvector from a wide vector load, convert to a
16169 /// narrow load to eliminate the extraction:
16170 /// (extract_subvector (load wide vector)) --> (load narrow vector)
16171 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
16172   // TODO: Add support for big-endian. The offset calculation must be adjusted.
16173   if (DAG.getDataLayout().isBigEndian())
16174     return SDValue();
16175 
16176   // TODO: The one-use check is overly conservative. Check the cost of the
16177   // extract instead or remove that condition entirely.
16178   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
16179   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
16180   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
16181       !ExtIdx)
16182     return SDValue();
16183 
16184   // The narrow load will be offset from the base address of the old load if
16185   // we are extracting from something besides index 0 (little-endian).
16186   EVT VT = Extract->getValueType(0);
16187   SDLoc DL(Extract);
16188   SDValue BaseAddr = Ld->getOperand(1);
16189   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
16190 
16191   // TODO: Use "BaseIndexOffset" to make this more effective.
16192   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
16193   MachineFunction &MF = DAG.getMachineFunction();
16194   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
16195                                                    VT.getStoreSize());
16196   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
16197   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
16198   return NewLd;
16199 }
16200 
16201 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
16202   EVT NVT = N->getValueType(0);
16203   SDValue V = N->getOperand(0);
16204 
16205   // Extract from UNDEF is UNDEF.
16206   if (V.isUndef())
16207     return DAG.getUNDEF(NVT);
16208 
16209   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
16210     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
16211       return NarrowLoad;
16212 
16213   // Combine:
16214   //    (extract_subvec (concat V1, V2, ...), i)
16215   // Into:
16216   //    Vi if possible
16217   // Only operand 0 is checked as 'concat' assumes all inputs of the same
16218   // type.
16219   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
16220       isa<ConstantSDNode>(N->getOperand(1)) &&
16221       V->getOperand(0).getValueType() == NVT) {
16222     unsigned Idx = N->getConstantOperandVal(1);
16223     unsigned NumElems = NVT.getVectorNumElements();
16224     assert((Idx % NumElems) == 0 &&
16225            "IDX in concat is not a multiple of the result vector length.");
16226     return V->getOperand(Idx / NumElems);
16227   }
16228 
16229   // Skip bitcasting
16230   V = peekThroughBitcast(V);
16231 
16232   // If the input is a build vector. Try to make a smaller build vector.
16233   if (V->getOpcode() == ISD::BUILD_VECTOR) {
16234     if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
16235       EVT InVT = V->getValueType(0);
16236       unsigned ExtractSize = NVT.getSizeInBits();
16237       unsigned EltSize = InVT.getScalarSizeInBits();
16238       // Only do this if we won't split any elements.
16239       if (ExtractSize % EltSize == 0) {
16240         unsigned NumElems = ExtractSize / EltSize;
16241         EVT EltVT = InVT.getVectorElementType();
16242         EVT ExtractVT = NumElems == 1 ? EltVT :
16243           EVT::getVectorVT(*DAG.getContext(), EltVT, NumElems);
16244         if ((Level < AfterLegalizeDAG ||
16245              (NumElems == 1 ||
16246               TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) &&
16247             (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
16248           unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) /
16249                             EltSize;
16250           if (NumElems == 1) {
16251             SDValue Src = V->getOperand(IdxVal);
16252             if (EltVT != Src.getValueType())
16253               Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src);
16254 
16255             return DAG.getBitcast(NVT, Src);
16256           }
16257 
16258           // Extract the pieces from the original build_vector.
16259           SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N),
16260                                             makeArrayRef(V->op_begin() + IdxVal,
16261                                                          NumElems));
16262           return DAG.getBitcast(NVT, BuildVec);
16263         }
16264       }
16265     }
16266   }
16267 
16268   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
16269     // Handle only simple case where vector being inserted and vector
16270     // being extracted are of same size.
16271     EVT SmallVT = V->getOperand(1).getValueType();
16272     if (!NVT.bitsEq(SmallVT))
16273       return SDValue();
16274 
16275     // Only handle cases where both indexes are constants.
16276     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
16277     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
16278 
16279     if (InsIdx && ExtIdx) {
16280       // Combine:
16281       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
16282       // Into:
16283       //    indices are equal or bit offsets are equal => V1
16284       //    otherwise => (extract_subvec V1, ExtIdx)
16285       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
16286           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
16287         return DAG.getBitcast(NVT, V->getOperand(1));
16288       return DAG.getNode(
16289           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
16290           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
16291           N->getOperand(1));
16292     }
16293   }
16294 
16295   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
16296     return NarrowBOp;
16297 
16298   if (SimplifyDemandedVectorElts(SDValue(N, 0)))
16299     return SDValue(N, 0);
16300 
16301   return SDValue();
16302 }
16303 
16304 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
16305 // or turn a shuffle of a single concat into simpler shuffle then concat.
16306 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
16307   EVT VT = N->getValueType(0);
16308   unsigned NumElts = VT.getVectorNumElements();
16309 
16310   SDValue N0 = N->getOperand(0);
16311   SDValue N1 = N->getOperand(1);
16312   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
16313 
16314   SmallVector<SDValue, 4> Ops;
16315   EVT ConcatVT = N0.getOperand(0).getValueType();
16316   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
16317   unsigned NumConcats = NumElts / NumElemsPerConcat;
16318 
16319   // Special case: shuffle(concat(A,B)) can be more efficiently represented
16320   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
16321   // half vector elements.
16322   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
16323       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
16324                   SVN->getMask().end(), [](int i) { return i == -1; })) {
16325     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
16326                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
16327     N1 = DAG.getUNDEF(ConcatVT);
16328     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
16329   }
16330 
16331   // Look at every vector that's inserted. We're looking for exact
16332   // subvector-sized copies from a concatenated vector
16333   for (unsigned I = 0; I != NumConcats; ++I) {
16334     // Make sure we're dealing with a copy.
16335     unsigned Begin = I * NumElemsPerConcat;
16336     bool AllUndef = true, NoUndef = true;
16337     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
16338       if (SVN->getMaskElt(J) >= 0)
16339         AllUndef = false;
16340       else
16341         NoUndef = false;
16342     }
16343 
16344     if (NoUndef) {
16345       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
16346         return SDValue();
16347 
16348       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
16349         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
16350           return SDValue();
16351 
16352       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
16353       if (FirstElt < N0.getNumOperands())
16354         Ops.push_back(N0.getOperand(FirstElt));
16355       else
16356         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
16357 
16358     } else if (AllUndef) {
16359       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
16360     } else { // Mixed with general masks and undefs, can't do optimization.
16361       return SDValue();
16362     }
16363   }
16364 
16365   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
16366 }
16367 
16368 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
16369 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
16370 //
16371 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
16372 // a simplification in some sense, but it isn't appropriate in general: some
16373 // BUILD_VECTORs are substantially cheaper than others. The general case
16374 // of a BUILD_VECTOR requires inserting each element individually (or
16375 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
16376 // all constants is a single constant pool load.  A BUILD_VECTOR where each
16377 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
16378 // are undef lowers to a small number of element insertions.
16379 //
16380 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
16381 // We don't fold shuffles where one side is a non-zero constant, and we don't
16382 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
16383 // non-constant operands. This seems to work out reasonably well in practice.
16384 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
16385                                        SelectionDAG &DAG,
16386                                        const TargetLowering &TLI) {
16387   EVT VT = SVN->getValueType(0);
16388   unsigned NumElts = VT.getVectorNumElements();
16389   SDValue N0 = SVN->getOperand(0);
16390   SDValue N1 = SVN->getOperand(1);
16391 
16392   if (!N0->hasOneUse() || !N1->hasOneUse())
16393     return SDValue();
16394 
16395   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
16396   // discussed above.
16397   if (!N1.isUndef()) {
16398     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
16399     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
16400     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
16401       return SDValue();
16402     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
16403       return SDValue();
16404   }
16405 
16406   // If both inputs are splats of the same value then we can safely merge this
16407   // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
16408   bool IsSplat = false;
16409   auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
16410   auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
16411   if (BV0 && BV1)
16412     if (SDValue Splat0 = BV0->getSplatValue())
16413       IsSplat = (Splat0 == BV1->getSplatValue());
16414 
16415   SmallVector<SDValue, 8> Ops;
16416   SmallSet<SDValue, 16> DuplicateOps;
16417   for (int M : SVN->getMask()) {
16418     SDValue Op = DAG.getUNDEF(VT.getScalarType());
16419     if (M >= 0) {
16420       int Idx = M < (int)NumElts ? M : M - NumElts;
16421       SDValue &S = (M < (int)NumElts ? N0 : N1);
16422       if (S.getOpcode() == ISD::BUILD_VECTOR) {
16423         Op = S.getOperand(Idx);
16424       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
16425         assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index.");
16426         Op = S.getOperand(0);
16427       } else {
16428         // Operand can't be combined - bail out.
16429         return SDValue();
16430       }
16431     }
16432 
16433     // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
16434     // generating a splat; semantically, this is fine, but it's likely to
16435     // generate low-quality code if the target can't reconstruct an appropriate
16436     // shuffle.
16437     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
16438       if (!IsSplat && !DuplicateOps.insert(Op).second)
16439         return SDValue();
16440 
16441     Ops.push_back(Op);
16442   }
16443 
16444   // BUILD_VECTOR requires all inputs to be of the same type, find the
16445   // maximum type and extend them all.
16446   EVT SVT = VT.getScalarType();
16447   if (SVT.isInteger())
16448     for (SDValue &Op : Ops)
16449       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
16450   if (SVT != VT.getScalarType())
16451     for (SDValue &Op : Ops)
16452       Op = TLI.isZExtFree(Op.getValueType(), SVT)
16453                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
16454                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
16455   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
16456 }
16457 
16458 // Match shuffles that can be converted to any_vector_extend_in_reg.
16459 // This is often generated during legalization.
16460 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
16461 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
16462 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
16463                                             SelectionDAG &DAG,
16464                                             const TargetLowering &TLI,
16465                                             bool LegalOperations,
16466                                             bool LegalTypes) {
16467   EVT VT = SVN->getValueType(0);
16468   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
16469 
16470   // TODO Add support for big-endian when we have a test case.
16471   if (!VT.isInteger() || IsBigEndian)
16472     return SDValue();
16473 
16474   unsigned NumElts = VT.getVectorNumElements();
16475   unsigned EltSizeInBits = VT.getScalarSizeInBits();
16476   ArrayRef<int> Mask = SVN->getMask();
16477   SDValue N0 = SVN->getOperand(0);
16478 
16479   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
16480   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
16481     for (unsigned i = 0; i != NumElts; ++i) {
16482       if (Mask[i] < 0)
16483         continue;
16484       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
16485         continue;
16486       return false;
16487     }
16488     return true;
16489   };
16490 
16491   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
16492   // power-of-2 extensions as they are the most likely.
16493   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
16494     // Check for non power of 2 vector sizes
16495     if (NumElts % Scale != 0)
16496       continue;
16497     if (!isAnyExtend(Scale))
16498       continue;
16499 
16500     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
16501     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
16502     if (!LegalTypes || TLI.isTypeLegal(OutVT))
16503       if (!LegalOperations ||
16504           TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
16505         return DAG.getBitcast(VT,
16506                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
16507   }
16508 
16509   return SDValue();
16510 }
16511 
16512 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
16513 // each source element of a large type into the lowest elements of a smaller
16514 // destination type. This is often generated during legalization.
16515 // If the source node itself was a '*_extend_vector_inreg' node then we should
16516 // then be able to remove it.
16517 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
16518                                         SelectionDAG &DAG) {
16519   EVT VT = SVN->getValueType(0);
16520   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
16521 
16522   // TODO Add support for big-endian when we have a test case.
16523   if (!VT.isInteger() || IsBigEndian)
16524     return SDValue();
16525 
16526   SDValue N0 = peekThroughBitcast(SVN->getOperand(0));
16527 
16528   unsigned Opcode = N0.getOpcode();
16529   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
16530       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
16531       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
16532     return SDValue();
16533 
16534   SDValue N00 = N0.getOperand(0);
16535   ArrayRef<int> Mask = SVN->getMask();
16536   unsigned NumElts = VT.getVectorNumElements();
16537   unsigned EltSizeInBits = VT.getScalarSizeInBits();
16538   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
16539   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
16540 
16541   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
16542     return SDValue();
16543   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
16544 
16545   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
16546   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
16547   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
16548   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
16549     for (unsigned i = 0; i != NumElts; ++i) {
16550       if (Mask[i] < 0)
16551         continue;
16552       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
16553         continue;
16554       return false;
16555     }
16556     return true;
16557   };
16558 
16559   // At the moment we just handle the case where we've truncated back to the
16560   // same size as before the extension.
16561   // TODO: handle more extension/truncation cases as cases arise.
16562   if (EltSizeInBits != ExtSrcSizeInBits)
16563     return SDValue();
16564 
16565   // We can remove *extend_vector_inreg only if the truncation happens at
16566   // the same scale as the extension.
16567   if (isTruncate(ExtScale))
16568     return DAG.getBitcast(VT, N00);
16569 
16570   return SDValue();
16571 }
16572 
16573 // Combine shuffles of splat-shuffles of the form:
16574 // shuffle (shuffle V, undef, splat-mask), undef, M
16575 // If splat-mask contains undef elements, we need to be careful about
16576 // introducing undef's in the folded mask which are not the result of composing
16577 // the masks of the shuffles.
16578 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
16579                                      ShuffleVectorSDNode *Splat,
16580                                      SelectionDAG &DAG) {
16581   ArrayRef<int> SplatMask = Splat->getMask();
16582   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
16583 
16584   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
16585   // every undef mask element in the splat-shuffle has a corresponding undef
16586   // element in the user-shuffle's mask or if the composition of mask elements
16587   // would result in undef.
16588   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
16589   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
16590   //   In this case it is not legal to simplify to the splat-shuffle because we
16591   //   may be exposing the users of the shuffle an undef element at index 1
16592   //   which was not there before the combine.
16593   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
16594   //   In this case the composition of masks yields SplatMask, so it's ok to
16595   //   simplify to the splat-shuffle.
16596   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
16597   //   In this case the composed mask includes all undef elements of SplatMask
16598   //   and in addition sets element zero to undef. It is safe to simplify to
16599   //   the splat-shuffle.
16600   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
16601                                        ArrayRef<int> SplatMask) {
16602     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
16603       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
16604           SplatMask[UserMask[i]] != -1)
16605         return false;
16606     return true;
16607   };
16608   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
16609     return SDValue(Splat, 0);
16610 
16611   // Create a new shuffle with a mask that is composed of the two shuffles'
16612   // masks.
16613   SmallVector<int, 32> NewMask;
16614   for (int Idx : UserMask)
16615     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
16616 
16617   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
16618                               Splat->getOperand(0), Splat->getOperand(1),
16619                               NewMask);
16620 }
16621 
16622 /// If the shuffle mask is taking exactly one element from the first vector
16623 /// operand and passing through all other elements from the second vector
16624 /// operand, return the index of the mask element that is choosing an element
16625 /// from the first operand. Otherwise, return -1.
16626 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {
16627   int MaskSize = Mask.size();
16628   int EltFromOp0 = -1;
16629   // TODO: This does not match if there are undef elements in the shuffle mask.
16630   // Should we ignore undefs in the shuffle mask instead? The trade-off is
16631   // removing an instruction (a shuffle), but losing the knowledge that some
16632   // vector lanes are not needed.
16633   for (int i = 0; i != MaskSize; ++i) {
16634     if (Mask[i] >= 0 && Mask[i] < MaskSize) {
16635       // We're looking for a shuffle of exactly one element from operand 0.
16636       if (EltFromOp0 != -1)
16637         return -1;
16638       EltFromOp0 = i;
16639     } else if (Mask[i] != i + MaskSize) {
16640       // Nothing from operand 1 can change lanes.
16641       return -1;
16642     }
16643   }
16644   return EltFromOp0;
16645 }
16646 
16647 /// If a shuffle inserts exactly one element from a source vector operand into
16648 /// another vector operand and we can access the specified element as a scalar,
16649 /// then we can eliminate the shuffle.
16650 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf,
16651                                       SelectionDAG &DAG) {
16652   // First, check if we are taking one element of a vector and shuffling that
16653   // element into another vector.
16654   ArrayRef<int> Mask = Shuf->getMask();
16655   SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end());
16656   SDValue Op0 = Shuf->getOperand(0);
16657   SDValue Op1 = Shuf->getOperand(1);
16658   int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);
16659   if (ShufOp0Index == -1) {
16660     // Commute mask and check again.
16661     ShuffleVectorSDNode::commuteMask(CommutedMask);
16662     ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);
16663     if (ShufOp0Index == -1)
16664       return SDValue();
16665     // Commute operands to match the commuted shuffle mask.
16666     std::swap(Op0, Op1);
16667     Mask = CommutedMask;
16668   }
16669 
16670   // The shuffle inserts exactly one element from operand 0 into operand 1.
16671   // Now see if we can access that element as a scalar via a real insert element
16672   // instruction.
16673   // TODO: We can try harder to locate the element as a scalar. Examples: it
16674   // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
16675   assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&
16676          "Shuffle mask value must be from operand 0");
16677   if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT)
16678     return SDValue();
16679 
16680   auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2));
16681   if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
16682     return SDValue();
16683 
16684   // There's an existing insertelement with constant insertion index, so we
16685   // don't need to check the legality/profitability of a replacement operation
16686   // that differs at most in the constant value. The target should be able to
16687   // lower any of those in a similar way. If not, legalization will expand this
16688   // to a scalar-to-vector plus shuffle.
16689   //
16690   // Note that the shuffle may move the scalar from the position that the insert
16691   // element used. Therefore, our new insert element occurs at the shuffle's
16692   // mask index value, not the insert's index value.
16693   // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
16694   SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf),
16695                                         Op0.getOperand(2).getValueType());
16696   return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(),
16697                      Op1, Op0.getOperand(1), NewInsIndex);
16698 }
16699 
16700 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
16701   EVT VT = N->getValueType(0);
16702   unsigned NumElts = VT.getVectorNumElements();
16703 
16704   SDValue N0 = N->getOperand(0);
16705   SDValue N1 = N->getOperand(1);
16706 
16707   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
16708 
16709   // Canonicalize shuffle undef, undef -> undef
16710   if (N0.isUndef() && N1.isUndef())
16711     return DAG.getUNDEF(VT);
16712 
16713   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
16714 
16715   // Canonicalize shuffle v, v -> v, undef
16716   if (N0 == N1) {
16717     SmallVector<int, 8> NewMask;
16718     for (unsigned i = 0; i != NumElts; ++i) {
16719       int Idx = SVN->getMaskElt(i);
16720       if (Idx >= (int)NumElts) Idx -= NumElts;
16721       NewMask.push_back(Idx);
16722     }
16723     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
16724   }
16725 
16726   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
16727   if (N0.isUndef())
16728     return DAG.getCommutedVectorShuffle(*SVN);
16729 
16730   // Remove references to rhs if it is undef
16731   if (N1.isUndef()) {
16732     bool Changed = false;
16733     SmallVector<int, 8> NewMask;
16734     for (unsigned i = 0; i != NumElts; ++i) {
16735       int Idx = SVN->getMaskElt(i);
16736       if (Idx >= (int)NumElts) {
16737         Idx = -1;
16738         Changed = true;
16739       }
16740       NewMask.push_back(Idx);
16741     }
16742     if (Changed)
16743       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
16744   }
16745 
16746   if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG))
16747     return InsElt;
16748 
16749   // A shuffle of a single vector that is a splat can always be folded.
16750   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
16751     if (N1->isUndef() && N0Shuf->isSplat())
16752       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
16753 
16754   // If it is a splat, check if the argument vector is another splat or a
16755   // build_vector.
16756   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
16757     SDNode *V = N0.getNode();
16758 
16759     // If this is a bit convert that changes the element type of the vector but
16760     // not the number of vector elements, look through it.  Be careful not to
16761     // look though conversions that change things like v4f32 to v2f64.
16762     if (V->getOpcode() == ISD::BITCAST) {
16763       SDValue ConvInput = V->getOperand(0);
16764       if (ConvInput.getValueType().isVector() &&
16765           ConvInput.getValueType().getVectorNumElements() == NumElts)
16766         V = ConvInput.getNode();
16767     }
16768 
16769     if (V->getOpcode() == ISD::BUILD_VECTOR) {
16770       assert(V->getNumOperands() == NumElts &&
16771              "BUILD_VECTOR has wrong number of operands");
16772       SDValue Base;
16773       bool AllSame = true;
16774       for (unsigned i = 0; i != NumElts; ++i) {
16775         if (!V->getOperand(i).isUndef()) {
16776           Base = V->getOperand(i);
16777           break;
16778         }
16779       }
16780       // Splat of <u, u, u, u>, return <u, u, u, u>
16781       if (!Base.getNode())
16782         return N0;
16783       for (unsigned i = 0; i != NumElts; ++i) {
16784         if (V->getOperand(i) != Base) {
16785           AllSame = false;
16786           break;
16787         }
16788       }
16789       // Splat of <x, x, x, x>, return <x, x, x, x>
16790       if (AllSame)
16791         return N0;
16792 
16793       // Canonicalize any other splat as a build_vector.
16794       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
16795       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
16796       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
16797 
16798       // We may have jumped through bitcasts, so the type of the
16799       // BUILD_VECTOR may not match the type of the shuffle.
16800       if (V->getValueType(0) != VT)
16801         NewBV = DAG.getBitcast(VT, NewBV);
16802       return NewBV;
16803     }
16804   }
16805 
16806   // Simplify source operands based on shuffle mask.
16807   if (SimplifyDemandedVectorElts(SDValue(N, 0)))
16808     return SDValue(N, 0);
16809 
16810   // Match shuffles that can be converted to any_vector_extend_in_reg.
16811   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes))
16812     return V;
16813 
16814   // Combine "truncate_vector_in_reg" style shuffles.
16815   if (SDValue V = combineTruncationShuffle(SVN, DAG))
16816     return V;
16817 
16818   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
16819       Level < AfterLegalizeVectorOps &&
16820       (N1.isUndef() ||
16821       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
16822        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
16823     if (SDValue V = partitionShuffleOfConcats(N, DAG))
16824       return V;
16825   }
16826 
16827   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
16828   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
16829   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
16830     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
16831       return Res;
16832 
16833   // If this shuffle only has a single input that is a bitcasted shuffle,
16834   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
16835   // back to their original types.
16836   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
16837       N1.isUndef() && Level < AfterLegalizeVectorOps &&
16838       TLI.isTypeLegal(VT)) {
16839 
16840     // Peek through the bitcast only if there is one user.
16841     SDValue BC0 = N0;
16842     while (BC0.getOpcode() == ISD::BITCAST) {
16843       if (!BC0.hasOneUse())
16844         break;
16845       BC0 = BC0.getOperand(0);
16846     }
16847 
16848     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
16849       if (Scale == 1)
16850         return SmallVector<int, 8>(Mask.begin(), Mask.end());
16851 
16852       SmallVector<int, 8> NewMask;
16853       for (int M : Mask)
16854         for (int s = 0; s != Scale; ++s)
16855           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
16856       return NewMask;
16857     };
16858 
16859     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
16860       EVT SVT = VT.getScalarType();
16861       EVT InnerVT = BC0->getValueType(0);
16862       EVT InnerSVT = InnerVT.getScalarType();
16863 
16864       // Determine which shuffle works with the smaller scalar type.
16865       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
16866       EVT ScaleSVT = ScaleVT.getScalarType();
16867 
16868       if (TLI.isTypeLegal(ScaleVT) &&
16869           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
16870           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
16871         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16872         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16873 
16874         // Scale the shuffle masks to the smaller scalar type.
16875         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
16876         SmallVector<int, 8> InnerMask =
16877             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
16878         SmallVector<int, 8> OuterMask =
16879             ScaleShuffleMask(SVN->getMask(), OuterScale);
16880 
16881         // Merge the shuffle masks.
16882         SmallVector<int, 8> NewMask;
16883         for (int M : OuterMask)
16884           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
16885 
16886         // Test for shuffle mask legality over both commutations.
16887         SDValue SV0 = BC0->getOperand(0);
16888         SDValue SV1 = BC0->getOperand(1);
16889         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16890         if (!LegalMask) {
16891           std::swap(SV0, SV1);
16892           ShuffleVectorSDNode::commuteMask(NewMask);
16893           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16894         }
16895 
16896         if (LegalMask) {
16897           SV0 = DAG.getBitcast(ScaleVT, SV0);
16898           SV1 = DAG.getBitcast(ScaleVT, SV1);
16899           return DAG.getBitcast(
16900               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
16901         }
16902       }
16903     }
16904   }
16905 
16906   // Canonicalize shuffles according to rules:
16907   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
16908   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
16909   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
16910   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
16911       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
16912       TLI.isTypeLegal(VT)) {
16913     // The incoming shuffle must be of the same type as the result of the
16914     // current shuffle.
16915     assert(N1->getOperand(0).getValueType() == VT &&
16916            "Shuffle types don't match");
16917 
16918     SDValue SV0 = N1->getOperand(0);
16919     SDValue SV1 = N1->getOperand(1);
16920     bool HasSameOp0 = N0 == SV0;
16921     bool IsSV1Undef = SV1.isUndef();
16922     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
16923       // Commute the operands of this shuffle so that next rule
16924       // will trigger.
16925       return DAG.getCommutedVectorShuffle(*SVN);
16926   }
16927 
16928   // Try to fold according to rules:
16929   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16930   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16931   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16932   // Don't try to fold shuffles with illegal type.
16933   // Only fold if this shuffle is the only user of the other shuffle.
16934   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
16935       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
16936     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
16937 
16938     // Don't try to fold splats; they're likely to simplify somehow, or they
16939     // might be free.
16940     if (OtherSV->isSplat())
16941       return SDValue();
16942 
16943     // The incoming shuffle must be of the same type as the result of the
16944     // current shuffle.
16945     assert(OtherSV->getOperand(0).getValueType() == VT &&
16946            "Shuffle types don't match");
16947 
16948     SDValue SV0, SV1;
16949     SmallVector<int, 4> Mask;
16950     // Compute the combined shuffle mask for a shuffle with SV0 as the first
16951     // operand, and SV1 as the second operand.
16952     for (unsigned i = 0; i != NumElts; ++i) {
16953       int Idx = SVN->getMaskElt(i);
16954       if (Idx < 0) {
16955         // Propagate Undef.
16956         Mask.push_back(Idx);
16957         continue;
16958       }
16959 
16960       SDValue CurrentVec;
16961       if (Idx < (int)NumElts) {
16962         // This shuffle index refers to the inner shuffle N0. Lookup the inner
16963         // shuffle mask to identify which vector is actually referenced.
16964         Idx = OtherSV->getMaskElt(Idx);
16965         if (Idx < 0) {
16966           // Propagate Undef.
16967           Mask.push_back(Idx);
16968           continue;
16969         }
16970 
16971         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
16972                                            : OtherSV->getOperand(1);
16973       } else {
16974         // This shuffle index references an element within N1.
16975         CurrentVec = N1;
16976       }
16977 
16978       // Simple case where 'CurrentVec' is UNDEF.
16979       if (CurrentVec.isUndef()) {
16980         Mask.push_back(-1);
16981         continue;
16982       }
16983 
16984       // Canonicalize the shuffle index. We don't know yet if CurrentVec
16985       // will be the first or second operand of the combined shuffle.
16986       Idx = Idx % NumElts;
16987       if (!SV0.getNode() || SV0 == CurrentVec) {
16988         // Ok. CurrentVec is the left hand side.
16989         // Update the mask accordingly.
16990         SV0 = CurrentVec;
16991         Mask.push_back(Idx);
16992         continue;
16993       }
16994 
16995       // Bail out if we cannot convert the shuffle pair into a single shuffle.
16996       if (SV1.getNode() && SV1 != CurrentVec)
16997         return SDValue();
16998 
16999       // Ok. CurrentVec is the right hand side.
17000       // Update the mask accordingly.
17001       SV1 = CurrentVec;
17002       Mask.push_back(Idx + NumElts);
17003     }
17004 
17005     // Check if all indices in Mask are Undef. In case, propagate Undef.
17006     bool isUndefMask = true;
17007     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
17008       isUndefMask &= Mask[i] < 0;
17009 
17010     if (isUndefMask)
17011       return DAG.getUNDEF(VT);
17012 
17013     if (!SV0.getNode())
17014       SV0 = DAG.getUNDEF(VT);
17015     if (!SV1.getNode())
17016       SV1 = DAG.getUNDEF(VT);
17017 
17018     // Avoid introducing shuffles with illegal mask.
17019     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
17020       ShuffleVectorSDNode::commuteMask(Mask);
17021 
17022       if (!TLI.isShuffleMaskLegal(Mask, VT))
17023         return SDValue();
17024 
17025       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
17026       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
17027       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
17028       std::swap(SV0, SV1);
17029     }
17030 
17031     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
17032     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
17033     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
17034     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
17035   }
17036 
17037   return SDValue();
17038 }
17039 
17040 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
17041   SDValue InVal = N->getOperand(0);
17042   EVT VT = N->getValueType(0);
17043 
17044   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
17045   // with a VECTOR_SHUFFLE and possible truncate.
17046   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17047     SDValue InVec = InVal->getOperand(0);
17048     SDValue EltNo = InVal->getOperand(1);
17049     auto InVecT = InVec.getValueType();
17050     if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
17051       SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
17052       int Elt = C0->getZExtValue();
17053       NewMask[0] = Elt;
17054       SDValue Val;
17055       // If we have an implict truncate do truncate here as long as it's legal.
17056       // if it's not legal, this should
17057       if (VT.getScalarType() != InVal.getValueType() &&
17058           InVal.getValueType().isScalarInteger() &&
17059           isTypeLegal(VT.getScalarType())) {
17060         Val =
17061             DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
17062         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
17063       }
17064       if (VT.getScalarType() == InVecT.getScalarType() &&
17065           VT.getVectorNumElements() <= InVecT.getVectorNumElements() &&
17066           TLI.isShuffleMaskLegal(NewMask, VT)) {
17067         Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec,
17068                                    DAG.getUNDEF(InVecT), NewMask);
17069         // If the initial vector is the correct size this shuffle is a
17070         // valid result.
17071         if (VT == InVecT)
17072           return Val;
17073         // If not we must truncate the vector.
17074         if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
17075           MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
17076           SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy);
17077           EVT SubVT =
17078               EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(),
17079                                VT.getVectorNumElements());
17080           Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val,
17081                             ZeroIdx);
17082           return Val;
17083         }
17084       }
17085     }
17086   }
17087 
17088   return SDValue();
17089 }
17090 
17091 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
17092   EVT VT = N->getValueType(0);
17093   SDValue N0 = N->getOperand(0);
17094   SDValue N1 = N->getOperand(1);
17095   SDValue N2 = N->getOperand(2);
17096 
17097   // If inserting an UNDEF, just return the original vector.
17098   if (N1.isUndef())
17099     return N0;
17100 
17101   // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow
17102   // us to pull BITCASTs from input to output.
17103   if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR)
17104     if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode()))
17105       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2);
17106 
17107   // If this is an insert of an extracted vector into an undef vector, we can
17108   // just use the input to the extract.
17109   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
17110       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
17111     return N1.getOperand(0);
17112 
17113   // If we are inserting a bitcast value into an undef, with the same
17114   // number of elements, just use the bitcast input of the extract.
17115   // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
17116   //        BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
17117   if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
17118       N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
17119       N1.getOperand(0).getOperand(1) == N2 &&
17120       N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
17121           VT.getVectorNumElements() &&
17122       N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() ==
17123           VT.getSizeInBits()) {
17124     return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
17125   }
17126 
17127   // If both N1 and N2 are bitcast values on which insert_subvector
17128   // would makes sense, pull the bitcast through.
17129   // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
17130   //        BITCAST (INSERT_SUBVECTOR N0 N1 N2)
17131   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
17132     SDValue CN0 = N0.getOperand(0);
17133     SDValue CN1 = N1.getOperand(0);
17134     EVT CN0VT = CN0.getValueType();
17135     EVT CN1VT = CN1.getValueType();
17136     if (CN0VT.isVector() && CN1VT.isVector() &&
17137         CN0VT.getVectorElementType() == CN1VT.getVectorElementType() &&
17138         CN0VT.getVectorNumElements() == VT.getVectorNumElements()) {
17139       SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
17140                                       CN0.getValueType(), CN0, CN1, N2);
17141       return DAG.getBitcast(VT, NewINSERT);
17142     }
17143   }
17144 
17145   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
17146   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
17147   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
17148   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
17149       N0.getOperand(1).getValueType() == N1.getValueType() &&
17150       N0.getOperand(2) == N2)
17151     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
17152                        N1, N2);
17153 
17154   if (!isa<ConstantSDNode>(N2))
17155     return SDValue();
17156 
17157   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
17158 
17159   // Canonicalize insert_subvector dag nodes.
17160   // Example:
17161   // (insert_subvector (insert_subvector A, Idx0), Idx1)
17162   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
17163   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
17164       N1.getValueType() == N0.getOperand(1).getValueType() &&
17165       isa<ConstantSDNode>(N0.getOperand(2))) {
17166     unsigned OtherIdx = N0.getConstantOperandVal(2);
17167     if (InsIdx < OtherIdx) {
17168       // Swap nodes.
17169       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
17170                                   N0.getOperand(0), N1, N2);
17171       AddToWorklist(NewOp.getNode());
17172       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
17173                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
17174     }
17175   }
17176 
17177   // If the input vector is a concatenation, and the insert replaces
17178   // one of the pieces, we can optimize into a single concat_vectors.
17179   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
17180       N0.getOperand(0).getValueType() == N1.getValueType()) {
17181     unsigned Factor = N1.getValueType().getVectorNumElements();
17182 
17183     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
17184     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
17185 
17186     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
17187   }
17188 
17189   return SDValue();
17190 }
17191 
17192 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
17193   SDValue N0 = N->getOperand(0);
17194 
17195   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
17196   if (N0->getOpcode() == ISD::FP16_TO_FP)
17197     return N0->getOperand(0);
17198 
17199   return SDValue();
17200 }
17201 
17202 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
17203   SDValue N0 = N->getOperand(0);
17204 
17205   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
17206   if (N0->getOpcode() == ISD::AND) {
17207     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
17208     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
17209       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
17210                          N0.getOperand(0));
17211     }
17212   }
17213 
17214   return SDValue();
17215 }
17216 
17217 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
17218 /// with the destination vector and a zero vector.
17219 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
17220 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
17221 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
17222   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
17223 
17224   EVT VT = N->getValueType(0);
17225   SDValue LHS = N->getOperand(0);
17226   SDValue RHS = peekThroughBitcast(N->getOperand(1));
17227   SDLoc DL(N);
17228 
17229   // Make sure we're not running after operation legalization where it
17230   // may have custom lowered the vector shuffles.
17231   if (LegalOperations)
17232     return SDValue();
17233 
17234   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
17235     return SDValue();
17236 
17237   EVT RVT = RHS.getValueType();
17238   unsigned NumElts = RHS.getNumOperands();
17239 
17240   // Attempt to create a valid clear mask, splitting the mask into
17241   // sub elements and checking to see if each is
17242   // all zeros or all ones - suitable for shuffle masking.
17243   auto BuildClearMask = [&](int Split) {
17244     int NumSubElts = NumElts * Split;
17245     int NumSubBits = RVT.getScalarSizeInBits() / Split;
17246 
17247     SmallVector<int, 8> Indices;
17248     for (int i = 0; i != NumSubElts; ++i) {
17249       int EltIdx = i / Split;
17250       int SubIdx = i % Split;
17251       SDValue Elt = RHS.getOperand(EltIdx);
17252       if (Elt.isUndef()) {
17253         Indices.push_back(-1);
17254         continue;
17255       }
17256 
17257       APInt Bits;
17258       if (isa<ConstantSDNode>(Elt))
17259         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
17260       else if (isa<ConstantFPSDNode>(Elt))
17261         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
17262       else
17263         return SDValue();
17264 
17265       // Extract the sub element from the constant bit mask.
17266       if (DAG.getDataLayout().isBigEndian()) {
17267         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
17268       } else {
17269         Bits.lshrInPlace(SubIdx * NumSubBits);
17270       }
17271 
17272       if (Split > 1)
17273         Bits = Bits.trunc(NumSubBits);
17274 
17275       if (Bits.isAllOnesValue())
17276         Indices.push_back(i);
17277       else if (Bits == 0)
17278         Indices.push_back(i + NumSubElts);
17279       else
17280         return SDValue();
17281     }
17282 
17283     // Let's see if the target supports this vector_shuffle.
17284     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
17285     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
17286     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
17287       return SDValue();
17288 
17289     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
17290     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
17291                                                    DAG.getBitcast(ClearVT, LHS),
17292                                                    Zero, Indices));
17293   };
17294 
17295   // Determine maximum split level (byte level masking).
17296   int MaxSplit = 1;
17297   if (RVT.getScalarSizeInBits() % 8 == 0)
17298     MaxSplit = RVT.getScalarSizeInBits() / 8;
17299 
17300   for (int Split = 1; Split <= MaxSplit; ++Split)
17301     if (RVT.getScalarSizeInBits() % Split == 0)
17302       if (SDValue S = BuildClearMask(Split))
17303         return S;
17304 
17305   return SDValue();
17306 }
17307 
17308 /// Visit a binary vector operation, like ADD.
17309 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
17310   assert(N->getValueType(0).isVector() &&
17311          "SimplifyVBinOp only works on vectors!");
17312 
17313   SDValue LHS = N->getOperand(0);
17314   SDValue RHS = N->getOperand(1);
17315   SDValue Ops[] = {LHS, RHS};
17316 
17317   // See if we can constant fold the vector operation.
17318   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
17319           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
17320     return Fold;
17321 
17322   // Type legalization might introduce new shuffles in the DAG.
17323   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
17324   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
17325   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
17326       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
17327       LHS.getOperand(1).isUndef() &&
17328       RHS.getOperand(1).isUndef()) {
17329     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
17330     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
17331 
17332     if (SVN0->getMask().equals(SVN1->getMask())) {
17333       EVT VT = N->getValueType(0);
17334       SDValue UndefVector = LHS.getOperand(1);
17335       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
17336                                      LHS.getOperand(0), RHS.getOperand(0),
17337                                      N->getFlags());
17338       AddUsersToWorklist(N);
17339       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
17340                                   SVN0->getMask());
17341     }
17342   }
17343 
17344   return SDValue();
17345 }
17346 
17347 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
17348                                     SDValue N2) {
17349   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
17350 
17351   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
17352                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
17353 
17354   // If we got a simplified select_cc node back from SimplifySelectCC, then
17355   // break it down into a new SETCC node, and a new SELECT node, and then return
17356   // the SELECT node, since we were called with a SELECT node.
17357   if (SCC.getNode()) {
17358     // Check to see if we got a select_cc back (to turn into setcc/select).
17359     // Otherwise, just return whatever node we got back, like fabs.
17360     if (SCC.getOpcode() == ISD::SELECT_CC) {
17361       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
17362                                   N0.getValueType(),
17363                                   SCC.getOperand(0), SCC.getOperand(1),
17364                                   SCC.getOperand(4));
17365       AddToWorklist(SETCC.getNode());
17366       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
17367                            SCC.getOperand(2), SCC.getOperand(3));
17368     }
17369 
17370     return SCC;
17371   }
17372   return SDValue();
17373 }
17374 
17375 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
17376 /// being selected between, see if we can simplify the select.  Callers of this
17377 /// should assume that TheSelect is deleted if this returns true.  As such, they
17378 /// should return the appropriate thing (e.g. the node) back to the top-level of
17379 /// the DAG combiner loop to avoid it being looked at.
17380 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
17381                                     SDValue RHS) {
17382   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
17383   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
17384   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
17385     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
17386       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
17387       SDValue Sqrt = RHS;
17388       ISD::CondCode CC;
17389       SDValue CmpLHS;
17390       const ConstantFPSDNode *Zero = nullptr;
17391 
17392       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
17393         CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
17394         CmpLHS = TheSelect->getOperand(0);
17395         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
17396       } else {
17397         // SELECT or VSELECT
17398         SDValue Cmp = TheSelect->getOperand(0);
17399         if (Cmp.getOpcode() == ISD::SETCC) {
17400           CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
17401           CmpLHS = Cmp.getOperand(0);
17402           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
17403         }
17404       }
17405       if (Zero && Zero->isZero() &&
17406           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
17407           CC == ISD::SETULT || CC == ISD::SETLT)) {
17408         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
17409         CombineTo(TheSelect, Sqrt);
17410         return true;
17411       }
17412     }
17413   }
17414   // Cannot simplify select with vector condition
17415   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
17416 
17417   // If this is a select from two identical things, try to pull the operation
17418   // through the select.
17419   if (LHS.getOpcode() != RHS.getOpcode() ||
17420       !LHS.hasOneUse() || !RHS.hasOneUse())
17421     return false;
17422 
17423   // If this is a load and the token chain is identical, replace the select
17424   // of two loads with a load through a select of the address to load from.
17425   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
17426   // constants have been dropped into the constant pool.
17427   if (LHS.getOpcode() == ISD::LOAD) {
17428     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
17429     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
17430 
17431     // Token chains must be identical.
17432     if (LHS.getOperand(0) != RHS.getOperand(0) ||
17433         // Do not let this transformation reduce the number of volatile loads.
17434         LLD->isVolatile() || RLD->isVolatile() ||
17435         // FIXME: If either is a pre/post inc/dec load,
17436         // we'd need to split out the address adjustment.
17437         LLD->isIndexed() || RLD->isIndexed() ||
17438         // If this is an EXTLOAD, the VT's must match.
17439         LLD->getMemoryVT() != RLD->getMemoryVT() ||
17440         // If this is an EXTLOAD, the kind of extension must match.
17441         (LLD->getExtensionType() != RLD->getExtensionType() &&
17442          // The only exception is if one of the extensions is anyext.
17443          LLD->getExtensionType() != ISD::EXTLOAD &&
17444          RLD->getExtensionType() != ISD::EXTLOAD) ||
17445         // FIXME: this discards src value information.  This is
17446         // over-conservative. It would be beneficial to be able to remember
17447         // both potential memory locations.  Since we are discarding
17448         // src value info, don't do the transformation if the memory
17449         // locations are not in the default address space.
17450         LLD->getPointerInfo().getAddrSpace() != 0 ||
17451         RLD->getPointerInfo().getAddrSpace() != 0 ||
17452         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
17453                                       LLD->getBasePtr().getValueType()))
17454       return false;
17455 
17456     // Check that the select condition doesn't reach either load.  If so,
17457     // folding this will induce a cycle into the DAG.  If not, this is safe to
17458     // xform, so create a select of the addresses.
17459     SDValue Addr;
17460     if (TheSelect->getOpcode() == ISD::SELECT) {
17461       SDNode *CondNode = TheSelect->getOperand(0).getNode();
17462       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
17463           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
17464         return false;
17465       // The loads must not depend on one another.
17466       if (LLD->isPredecessorOf(RLD) ||
17467           RLD->isPredecessorOf(LLD))
17468         return false;
17469       Addr = DAG.getSelect(SDLoc(TheSelect),
17470                            LLD->getBasePtr().getValueType(),
17471                            TheSelect->getOperand(0), LLD->getBasePtr(),
17472                            RLD->getBasePtr());
17473     } else {  // Otherwise SELECT_CC
17474       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
17475       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
17476 
17477       if ((LLD->hasAnyUseOfValue(1) &&
17478            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
17479           (RLD->hasAnyUseOfValue(1) &&
17480            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
17481         return false;
17482 
17483       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
17484                          LLD->getBasePtr().getValueType(),
17485                          TheSelect->getOperand(0),
17486                          TheSelect->getOperand(1),
17487                          LLD->getBasePtr(), RLD->getBasePtr(),
17488                          TheSelect->getOperand(4));
17489     }
17490 
17491     SDValue Load;
17492     // It is safe to replace the two loads if they have different alignments,
17493     // but the new load must be the minimum (most restrictive) alignment of the
17494     // inputs.
17495     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
17496     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
17497     if (!RLD->isInvariant())
17498       MMOFlags &= ~MachineMemOperand::MOInvariant;
17499     if (!RLD->isDereferenceable())
17500       MMOFlags &= ~MachineMemOperand::MODereferenceable;
17501     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
17502       // FIXME: Discards pointer and AA info.
17503       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
17504                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
17505                          MMOFlags);
17506     } else {
17507       // FIXME: Discards pointer and AA info.
17508       Load = DAG.getExtLoad(
17509           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
17510                                                   : LLD->getExtensionType(),
17511           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
17512           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
17513     }
17514 
17515     // Users of the select now use the result of the load.
17516     CombineTo(TheSelect, Load);
17517 
17518     // Users of the old loads now use the new load's chain.  We know the
17519     // old-load value is dead now.
17520     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
17521     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
17522     return true;
17523   }
17524 
17525   return false;
17526 }
17527 
17528 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
17529 /// bitwise 'and'.
17530 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
17531                                             SDValue N1, SDValue N2, SDValue N3,
17532                                             ISD::CondCode CC) {
17533   // If this is a select where the false operand is zero and the compare is a
17534   // check of the sign bit, see if we can perform the "gzip trick":
17535   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
17536   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
17537   EVT XType = N0.getValueType();
17538   EVT AType = N2.getValueType();
17539   if (!isNullConstant(N3) || !XType.bitsGE(AType))
17540     return SDValue();
17541 
17542   // If the comparison is testing for a positive value, we have to invert
17543   // the sign bit mask, so only do that transform if the target has a bitwise
17544   // 'and not' instruction (the invert is free).
17545   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
17546     // (X > -1) ? A : 0
17547     // (X >  0) ? X : 0 <-- This is canonical signed max.
17548     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
17549       return SDValue();
17550   } else if (CC == ISD::SETLT) {
17551     // (X <  0) ? A : 0
17552     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
17553     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
17554       return SDValue();
17555   } else {
17556     return SDValue();
17557   }
17558 
17559   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
17560   // constant.
17561   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
17562   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
17563   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
17564     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
17565     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
17566     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
17567     AddToWorklist(Shift.getNode());
17568 
17569     if (XType.bitsGT(AType)) {
17570       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
17571       AddToWorklist(Shift.getNode());
17572     }
17573 
17574     if (CC == ISD::SETGT)
17575       Shift = DAG.getNOT(DL, Shift, AType);
17576 
17577     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
17578   }
17579 
17580   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
17581   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
17582   AddToWorklist(Shift.getNode());
17583 
17584   if (XType.bitsGT(AType)) {
17585     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
17586     AddToWorklist(Shift.getNode());
17587   }
17588 
17589   if (CC == ISD::SETGT)
17590     Shift = DAG.getNOT(DL, Shift, AType);
17591 
17592   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
17593 }
17594 
17595 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
17596 /// where 'cond' is the comparison specified by CC.
17597 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
17598                                       SDValue N2, SDValue N3, ISD::CondCode CC,
17599                                       bool NotExtCompare) {
17600   // (x ? y : y) -> y.
17601   if (N2 == N3) return N2;
17602 
17603   EVT VT = N2.getValueType();
17604   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
17605   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
17606 
17607   // Determine if the condition we're dealing with is constant
17608   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
17609                               N0, N1, CC, DL, false);
17610   if (SCC.getNode()) AddToWorklist(SCC.getNode());
17611 
17612   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
17613     // fold select_cc true, x, y -> x
17614     // fold select_cc false, x, y -> y
17615     return !SCCC->isNullValue() ? N2 : N3;
17616   }
17617 
17618   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
17619   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
17620   // in it.  This is a win when the constant is not otherwise available because
17621   // it replaces two constant pool loads with one.  We only do this if the FP
17622   // type is known to be legal, because if it isn't, then we are before legalize
17623   // types an we want the other legalization to happen first (e.g. to avoid
17624   // messing with soft float) and if the ConstantFP is not legal, because if
17625   // it is legal, we may not need to store the FP constant in a constant pool.
17626   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
17627     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
17628       if (TLI.isTypeLegal(N2.getValueType()) &&
17629           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
17630                TargetLowering::Legal &&
17631            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
17632            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
17633           // If both constants have multiple uses, then we won't need to do an
17634           // extra load, they are likely around in registers for other users.
17635           (TV->hasOneUse() || FV->hasOneUse())) {
17636         Constant *Elts[] = {
17637           const_cast<ConstantFP*>(FV->getConstantFPValue()),
17638           const_cast<ConstantFP*>(TV->getConstantFPValue())
17639         };
17640         Type *FPTy = Elts[0]->getType();
17641         const DataLayout &TD = DAG.getDataLayout();
17642 
17643         // Create a ConstantArray of the two constants.
17644         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
17645         SDValue CPIdx =
17646             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
17647                                 TD.getPrefTypeAlignment(FPTy));
17648         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
17649 
17650         // Get the offsets to the 0 and 1 element of the array so that we can
17651         // select between them.
17652         SDValue Zero = DAG.getIntPtrConstant(0, DL);
17653         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
17654         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
17655 
17656         SDValue Cond = DAG.getSetCC(DL,
17657                                     getSetCCResultType(N0.getValueType()),
17658                                     N0, N1, CC);
17659         AddToWorklist(Cond.getNode());
17660         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
17661                                           Cond, One, Zero);
17662         AddToWorklist(CstOffset.getNode());
17663         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
17664                             CstOffset);
17665         AddToWorklist(CPIdx.getNode());
17666         return DAG.getLoad(
17667             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
17668             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
17669             Alignment);
17670       }
17671     }
17672 
17673   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
17674     return V;
17675 
17676   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
17677   // where y is has a single bit set.
17678   // A plaintext description would be, we can turn the SELECT_CC into an AND
17679   // when the condition can be materialized as an all-ones register.  Any
17680   // single bit-test can be materialized as an all-ones register with
17681   // shift-left and shift-right-arith.
17682   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
17683       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
17684     SDValue AndLHS = N0->getOperand(0);
17685     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
17686     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
17687       // Shift the tested bit over the sign bit.
17688       const APInt &AndMask = ConstAndRHS->getAPIntValue();
17689       SDValue ShlAmt =
17690         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
17691                         getShiftAmountTy(AndLHS.getValueType()));
17692       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
17693 
17694       // Now arithmetic right shift it all the way over, so the result is either
17695       // all-ones, or zero.
17696       SDValue ShrAmt =
17697         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
17698                         getShiftAmountTy(Shl.getValueType()));
17699       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
17700 
17701       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
17702     }
17703   }
17704 
17705   // fold select C, 16, 0 -> shl C, 4
17706   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
17707       TLI.getBooleanContents(N0.getValueType()) ==
17708           TargetLowering::ZeroOrOneBooleanContent) {
17709 
17710     // If the caller doesn't want us to simplify this into a zext of a compare,
17711     // don't do it.
17712     if (NotExtCompare && N2C->isOne())
17713       return SDValue();
17714 
17715     // Get a SetCC of the condition
17716     // NOTE: Don't create a SETCC if it's not legal on this target.
17717     if (!LegalOperations ||
17718         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
17719       SDValue Temp, SCC;
17720       // cast from setcc result type to select result type
17721       if (LegalTypes) {
17722         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
17723                             N0, N1, CC);
17724         if (N2.getValueType().bitsLT(SCC.getValueType()))
17725           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
17726                                         N2.getValueType());
17727         else
17728           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17729                              N2.getValueType(), SCC);
17730       } else {
17731         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
17732         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17733                            N2.getValueType(), SCC);
17734       }
17735 
17736       AddToWorklist(SCC.getNode());
17737       AddToWorklist(Temp.getNode());
17738 
17739       if (N2C->isOne())
17740         return Temp;
17741 
17742       // shl setcc result by log2 n2c
17743       return DAG.getNode(
17744           ISD::SHL, DL, N2.getValueType(), Temp,
17745           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
17746                           getShiftAmountTy(Temp.getValueType())));
17747     }
17748   }
17749 
17750   // Check to see if this is an integer abs.
17751   // select_cc setg[te] X,  0,  X, -X ->
17752   // select_cc setgt    X, -1,  X, -X ->
17753   // select_cc setl[te] X,  0, -X,  X ->
17754   // select_cc setlt    X,  1, -X,  X ->
17755   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
17756   if (N1C) {
17757     ConstantSDNode *SubC = nullptr;
17758     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
17759          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
17760         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
17761       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
17762     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
17763               (N1C->isOne() && CC == ISD::SETLT)) &&
17764              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
17765       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
17766 
17767     EVT XType = N0.getValueType();
17768     if (SubC && SubC->isNullValue() && XType.isInteger()) {
17769       SDLoc DL(N0);
17770       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
17771                                   N0,
17772                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
17773                                          getShiftAmountTy(N0.getValueType())));
17774       SDValue Add = DAG.getNode(ISD::ADD, DL,
17775                                 XType, N0, Shift);
17776       AddToWorklist(Shift.getNode());
17777       AddToWorklist(Add.getNode());
17778       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
17779     }
17780   }
17781 
17782   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
17783   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
17784   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
17785   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
17786   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
17787   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
17788   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
17789   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
17790   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
17791     SDValue ValueOnZero = N2;
17792     SDValue Count = N3;
17793     // If the condition is NE instead of E, swap the operands.
17794     if (CC == ISD::SETNE)
17795       std::swap(ValueOnZero, Count);
17796     // Check if the value on zero is a constant equal to the bits in the type.
17797     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
17798       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
17799         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
17800         // legal, combine to just cttz.
17801         if ((Count.getOpcode() == ISD::CTTZ ||
17802              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
17803             N0 == Count.getOperand(0) &&
17804             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
17805           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
17806         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
17807         // legal, combine to just ctlz.
17808         if ((Count.getOpcode() == ISD::CTLZ ||
17809              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
17810             N0 == Count.getOperand(0) &&
17811             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
17812           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
17813       }
17814     }
17815   }
17816 
17817   return SDValue();
17818 }
17819 
17820 /// This is a stub for TargetLowering::SimplifySetCC.
17821 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
17822                                    ISD::CondCode Cond, const SDLoc &DL,
17823                                    bool foldBooleans) {
17824   TargetLowering::DAGCombinerInfo
17825     DagCombineInfo(DAG, Level, false, this);
17826   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
17827 }
17828 
17829 /// Given an ISD::SDIV node expressing a divide by constant, return
17830 /// a DAG expression to select that will generate the same value by multiplying
17831 /// by a magic number.
17832 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17833 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
17834   // when optimising for minimum size, we don't want to expand a div to a mul
17835   // and a shift.
17836   if (DAG.getMachineFunction().getFunction().optForMinSize())
17837     return SDValue();
17838 
17839   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17840   if (!C)
17841     return SDValue();
17842 
17843   // Avoid division by zero.
17844   if (C->isNullValue())
17845     return SDValue();
17846 
17847   std::vector<SDNode *> Built;
17848   SDValue S =
17849       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17850 
17851   for (SDNode *N : Built)
17852     AddToWorklist(N);
17853   return S;
17854 }
17855 
17856 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
17857 /// DAG expression that will generate the same value by right shifting.
17858 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
17859   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17860   if (!C)
17861     return SDValue();
17862 
17863   // Avoid division by zero.
17864   if (C->isNullValue())
17865     return SDValue();
17866 
17867   std::vector<SDNode *> Built;
17868   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
17869 
17870   for (SDNode *N : Built)
17871     AddToWorklist(N);
17872   return S;
17873 }
17874 
17875 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
17876 /// expression that will generate the same value by multiplying by a magic
17877 /// number.
17878 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17879 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
17880   // when optimising for minimum size, we don't want to expand a div to a mul
17881   // and a shift.
17882   if (DAG.getMachineFunction().getFunction().optForMinSize())
17883     return SDValue();
17884 
17885   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17886   if (!C)
17887     return SDValue();
17888 
17889   // Avoid division by zero.
17890   if (C->isNullValue())
17891     return SDValue();
17892 
17893   std::vector<SDNode *> Built;
17894   SDValue S =
17895       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17896 
17897   for (SDNode *N : Built)
17898     AddToWorklist(N);
17899   return S;
17900 }
17901 
17902 /// Determines the LogBase2 value for a non-null input value using the
17903 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
17904 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
17905   EVT VT = V.getValueType();
17906   unsigned EltBits = VT.getScalarSizeInBits();
17907   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
17908   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
17909   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
17910   return LogBase2;
17911 }
17912 
17913 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17914 /// For the reciprocal, we need to find the zero of the function:
17915 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
17916 ///     =>
17917 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
17918 ///     does not require additional intermediate precision]
17919 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
17920   if (Level >= AfterLegalizeDAG)
17921     return SDValue();
17922 
17923   // TODO: Handle half and/or extended types?
17924   EVT VT = Op.getValueType();
17925   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17926     return SDValue();
17927 
17928   // If estimates are explicitly disabled for this function, we're done.
17929   MachineFunction &MF = DAG.getMachineFunction();
17930   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
17931   if (Enabled == TLI.ReciprocalEstimate::Disabled)
17932     return SDValue();
17933 
17934   // Estimates may be explicitly enabled for this type with a custom number of
17935   // refinement steps.
17936   int Iterations = TLI.getDivRefinementSteps(VT, MF);
17937   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
17938     AddToWorklist(Est.getNode());
17939 
17940     if (Iterations) {
17941       EVT VT = Op.getValueType();
17942       SDLoc DL(Op);
17943       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
17944 
17945       // Newton iterations: Est = Est + Est (1 - Arg * Est)
17946       for (int i = 0; i < Iterations; ++i) {
17947         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
17948         AddToWorklist(NewEst.getNode());
17949 
17950         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
17951         AddToWorklist(NewEst.getNode());
17952 
17953         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17954         AddToWorklist(NewEst.getNode());
17955 
17956         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
17957         AddToWorklist(Est.getNode());
17958       }
17959     }
17960     return Est;
17961   }
17962 
17963   return SDValue();
17964 }
17965 
17966 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17967 /// For the reciprocal sqrt, we need to find the zero of the function:
17968 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17969 ///     =>
17970 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
17971 /// As a result, we precompute A/2 prior to the iteration loop.
17972 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
17973                                          unsigned Iterations,
17974                                          SDNodeFlags Flags, bool Reciprocal) {
17975   EVT VT = Arg.getValueType();
17976   SDLoc DL(Arg);
17977   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
17978 
17979   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
17980   // this entire sequence requires only one FP constant.
17981   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
17982   AddToWorklist(HalfArg.getNode());
17983 
17984   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
17985   AddToWorklist(HalfArg.getNode());
17986 
17987   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
17988   for (unsigned i = 0; i < Iterations; ++i) {
17989     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
17990     AddToWorklist(NewEst.getNode());
17991 
17992     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
17993     AddToWorklist(NewEst.getNode());
17994 
17995     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
17996     AddToWorklist(NewEst.getNode());
17997 
17998     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17999     AddToWorklist(Est.getNode());
18000   }
18001 
18002   // If non-reciprocal square root is requested, multiply the result by Arg.
18003   if (!Reciprocal) {
18004     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
18005     AddToWorklist(Est.getNode());
18006   }
18007 
18008   return Est;
18009 }
18010 
18011 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
18012 /// For the reciprocal sqrt, we need to find the zero of the function:
18013 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
18014 ///     =>
18015 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
18016 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
18017                                          unsigned Iterations,
18018                                          SDNodeFlags Flags, bool Reciprocal) {
18019   EVT VT = Arg.getValueType();
18020   SDLoc DL(Arg);
18021   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
18022   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
18023 
18024   // This routine must enter the loop below to work correctly
18025   // when (Reciprocal == false).
18026   assert(Iterations > 0);
18027 
18028   // Newton iterations for reciprocal square root:
18029   // E = (E * -0.5) * ((A * E) * E + -3.0)
18030   for (unsigned i = 0; i < Iterations; ++i) {
18031     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
18032     AddToWorklist(AE.getNode());
18033 
18034     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
18035     AddToWorklist(AEE.getNode());
18036 
18037     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
18038     AddToWorklist(RHS.getNode());
18039 
18040     // When calculating a square root at the last iteration build:
18041     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
18042     // (notice a common subexpression)
18043     SDValue LHS;
18044     if (Reciprocal || (i + 1) < Iterations) {
18045       // RSQRT: LHS = (E * -0.5)
18046       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
18047     } else {
18048       // SQRT: LHS = (A * E) * -0.5
18049       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
18050     }
18051     AddToWorklist(LHS.getNode());
18052 
18053     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
18054     AddToWorklist(Est.getNode());
18055   }
18056 
18057   return Est;
18058 }
18059 
18060 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
18061 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
18062 /// Op can be zero.
18063 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
18064                                            bool Reciprocal) {
18065   if (Level >= AfterLegalizeDAG)
18066     return SDValue();
18067 
18068   // TODO: Handle half and/or extended types?
18069   EVT VT = Op.getValueType();
18070   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
18071     return SDValue();
18072 
18073   // If estimates are explicitly disabled for this function, we're done.
18074   MachineFunction &MF = DAG.getMachineFunction();
18075   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
18076   if (Enabled == TLI.ReciprocalEstimate::Disabled)
18077     return SDValue();
18078 
18079   // Estimates may be explicitly enabled for this type with a custom number of
18080   // refinement steps.
18081   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
18082 
18083   bool UseOneConstNR = false;
18084   if (SDValue Est =
18085       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
18086                           Reciprocal)) {
18087     AddToWorklist(Est.getNode());
18088 
18089     if (Iterations) {
18090       Est = UseOneConstNR
18091             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
18092             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
18093 
18094       if (!Reciprocal) {
18095         // The estimate is now completely wrong if the input was exactly 0.0 or
18096         // possibly a denormal. Force the answer to 0.0 for those cases.
18097         EVT VT = Op.getValueType();
18098         SDLoc DL(Op);
18099         EVT CCVT = getSetCCResultType(VT);
18100         ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
18101         const Function &F = DAG.getMachineFunction().getFunction();
18102         Attribute Denorms = F.getFnAttribute("denormal-fp-math");
18103         if (Denorms.getValueAsString().equals("ieee")) {
18104           // fabs(X) < SmallestNormal ? 0.0 : Est
18105           const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
18106           APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
18107           SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
18108           SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
18109           SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
18110           SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
18111           Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est);
18112           AddToWorklist(Fabs.getNode());
18113           AddToWorklist(IsDenorm.getNode());
18114           AddToWorklist(Est.getNode());
18115         } else {
18116           // X == 0.0 ? 0.0 : Est
18117           SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
18118           SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
18119           Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est);
18120           AddToWorklist(IsZero.getNode());
18121           AddToWorklist(Est.getNode());
18122         }
18123       }
18124     }
18125     return Est;
18126   }
18127 
18128   return SDValue();
18129 }
18130 
18131 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
18132   return buildSqrtEstimateImpl(Op, Flags, true);
18133 }
18134 
18135 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
18136   return buildSqrtEstimateImpl(Op, Flags, false);
18137 }
18138 
18139 /// Return true if there is any possibility that the two addresses overlap.
18140 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
18141   // If they are the same then they must be aliases.
18142   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
18143 
18144   // If they are both volatile then they cannot be reordered.
18145   if (Op0->isVolatile() && Op1->isVolatile()) return true;
18146 
18147   // If one operation reads from invariant memory, and the other may store, they
18148   // cannot alias. These should really be checking the equivalent of mayWrite,
18149   // but it only matters for memory nodes other than load /store.
18150   if (Op0->isInvariant() && Op1->writeMem())
18151     return false;
18152 
18153   if (Op1->isInvariant() && Op0->writeMem())
18154     return false;
18155 
18156   unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize();
18157   unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize();
18158 
18159   // Check for BaseIndexOffset matching.
18160   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0, DAG);
18161   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1, DAG);
18162   int64_t PtrDiff;
18163   if (BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()) {
18164     if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
18165       return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
18166 
18167     // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
18168     // able to calculate their relative offset if at least one arises
18169     // from an alloca. However, these allocas cannot overlap and we
18170     // can infer there is no alias.
18171     if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
18172       if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
18173         MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
18174         // If the base are the same frame index but the we couldn't find a
18175         // constant offset, (indices are different) be conservative.
18176         if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
18177                        !MFI.isFixedObjectIndex(B->getIndex())))
18178           return false;
18179       }
18180 
18181     bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase());
18182     bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase());
18183     bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase());
18184     bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase());
18185     bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase());
18186     bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase());
18187 
18188     // If of mismatched base types or checkable indices we can check
18189     // they do not alias.
18190     if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) ||
18191          (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) &&
18192         (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1))
18193       return false;
18194   }
18195 
18196   // If we know required SrcValue1 and SrcValue2 have relatively large
18197   // alignment compared to the size and offset of the access, we may be able
18198   // to prove they do not alias. This check is conservative for now to catch
18199   // cases created by splitting vector types.
18200   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
18201   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
18202   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
18203   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
18204   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
18205       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
18206     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
18207     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
18208 
18209     // There is no overlap between these relatively aligned accesses of
18210     // similar size. Return no alias.
18211     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
18212         (OffAlign1 + NumBytes1) <= OffAlign0)
18213       return false;
18214   }
18215 
18216   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
18217                    ? CombinerGlobalAA
18218                    : DAG.getSubtarget().useAA();
18219 #ifndef NDEBUG
18220   if (CombinerAAOnlyFunc.getNumOccurrences() &&
18221       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
18222     UseAA = false;
18223 #endif
18224 
18225   if (UseAA && AA &&
18226       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
18227     // Use alias analysis information.
18228     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
18229     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
18230     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
18231     AliasResult AAResult =
18232         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
18233                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
18234                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
18235                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
18236     if (AAResult == NoAlias)
18237       return false;
18238   }
18239 
18240   // Otherwise we have to assume they alias.
18241   return true;
18242 }
18243 
18244 /// Walk up chain skipping non-aliasing memory nodes,
18245 /// looking for aliasing nodes and adding them to the Aliases vector.
18246 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
18247                                    SmallVectorImpl<SDValue> &Aliases) {
18248   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
18249   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
18250 
18251   // Get alias information for node.
18252   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
18253 
18254   // Starting off.
18255   Chains.push_back(OriginalChain);
18256   unsigned Depth = 0;
18257 
18258   // Look at each chain and determine if it is an alias.  If so, add it to the
18259   // aliases list.  If not, then continue up the chain looking for the next
18260   // candidate.
18261   while (!Chains.empty()) {
18262     SDValue Chain = Chains.pop_back_val();
18263 
18264     // For TokenFactor nodes, look at each operand and only continue up the
18265     // chain until we reach the depth limit.
18266     //
18267     // FIXME: The depth check could be made to return the last non-aliasing
18268     // chain we found before we hit a tokenfactor rather than the original
18269     // chain.
18270     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
18271       Aliases.clear();
18272       Aliases.push_back(OriginalChain);
18273       return;
18274     }
18275 
18276     // Don't bother if we've been before.
18277     if (!Visited.insert(Chain.getNode()).second)
18278       continue;
18279 
18280     switch (Chain.getOpcode()) {
18281     case ISD::EntryToken:
18282       // Entry token is ideal chain operand, but handled in FindBetterChain.
18283       break;
18284 
18285     case ISD::LOAD:
18286     case ISD::STORE: {
18287       // Get alias information for Chain.
18288       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
18289           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
18290 
18291       // If chain is alias then stop here.
18292       if (!(IsLoad && IsOpLoad) &&
18293           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
18294         Aliases.push_back(Chain);
18295       } else {
18296         // Look further up the chain.
18297         Chains.push_back(Chain.getOperand(0));
18298         ++Depth;
18299       }
18300       break;
18301     }
18302 
18303     case ISD::TokenFactor:
18304       // We have to check each of the operands of the token factor for "small"
18305       // token factors, so we queue them up.  Adding the operands to the queue
18306       // (stack) in reverse order maintains the original order and increases the
18307       // likelihood that getNode will find a matching token factor (CSE.)
18308       if (Chain.getNumOperands() > 16) {
18309         Aliases.push_back(Chain);
18310         break;
18311       }
18312       for (unsigned n = Chain.getNumOperands(); n;)
18313         Chains.push_back(Chain.getOperand(--n));
18314       ++Depth;
18315       break;
18316 
18317     case ISD::CopyFromReg:
18318       // Forward past CopyFromReg.
18319       Chains.push_back(Chain.getOperand(0));
18320       ++Depth;
18321       break;
18322 
18323     default:
18324       // For all other instructions we will just have to take what we can get.
18325       Aliases.push_back(Chain);
18326       break;
18327     }
18328   }
18329 }
18330 
18331 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
18332 /// (aliasing node.)
18333 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
18334   if (OptLevel == CodeGenOpt::None)
18335     return OldChain;
18336 
18337   // Ops for replacing token factor.
18338   SmallVector<SDValue, 8> Aliases;
18339 
18340   // Accumulate all the aliases to this node.
18341   GatherAllAliases(N, OldChain, Aliases);
18342 
18343   // If no operands then chain to entry token.
18344   if (Aliases.size() == 0)
18345     return DAG.getEntryNode();
18346 
18347   // If a single operand then chain to it.  We don't need to revisit it.
18348   if (Aliases.size() == 1)
18349     return Aliases[0];
18350 
18351   // Construct a custom tailored token factor.
18352   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
18353 }
18354 
18355 // This function tries to collect a bunch of potentially interesting
18356 // nodes to improve the chains of, all at once. This might seem
18357 // redundant, as this function gets called when visiting every store
18358 // node, so why not let the work be done on each store as it's visited?
18359 //
18360 // I believe this is mainly important because MergeConsecutiveStores
18361 // is unable to deal with merging stores of different sizes, so unless
18362 // we improve the chains of all the potential candidates up-front
18363 // before running MergeConsecutiveStores, it might only see some of
18364 // the nodes that will eventually be candidates, and then not be able
18365 // to go from a partially-merged state to the desired final
18366 // fully-merged state.
18367 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
18368   if (OptLevel == CodeGenOpt::None)
18369     return false;
18370 
18371   // This holds the base pointer, index, and the offset in bytes from the base
18372   // pointer.
18373   BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
18374 
18375   // We must have a base and an offset.
18376   if (!BasePtr.getBase().getNode())
18377     return false;
18378 
18379   // Do not handle stores to undef base pointers.
18380   if (BasePtr.getBase().isUndef())
18381     return false;
18382 
18383   SmallVector<StoreSDNode *, 8> ChainedStores;
18384   ChainedStores.push_back(St);
18385 
18386   // Walk up the chain and look for nodes with offsets from the same
18387   // base pointer. Stop when reaching an instruction with a different kind
18388   // or instruction which has a different base pointer.
18389   StoreSDNode *Index = St;
18390   while (Index) {
18391     // If the chain has more than one use, then we can't reorder the mem ops.
18392     if (Index != St && !SDValue(Index, 0)->hasOneUse())
18393       break;
18394 
18395     if (Index->isVolatile() || Index->isIndexed())
18396       break;
18397 
18398     // Find the base pointer and offset for this memory node.
18399     BaseIndexOffset Ptr = BaseIndexOffset::match(Index, DAG);
18400 
18401     // Check that the base pointer is the same as the original one.
18402     if (!BasePtr.equalBaseIndex(Ptr, DAG))
18403       break;
18404 
18405     // Walk up the chain to find the next store node, ignoring any
18406     // intermediate loads. Any other kind of node will halt the loop.
18407     SDNode *NextInChain = Index->getChain().getNode();
18408     while (true) {
18409       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
18410         // We found a store node. Use it for the next iteration.
18411         if (STn->isVolatile() || STn->isIndexed()) {
18412           Index = nullptr;
18413           break;
18414         }
18415         ChainedStores.push_back(STn);
18416         Index = STn;
18417         break;
18418       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
18419         NextInChain = Ldn->getChain().getNode();
18420         continue;
18421       } else {
18422         Index = nullptr;
18423         break;
18424       }
18425     }// end while
18426   }
18427 
18428   // At this point, ChainedStores lists all of the Store nodes
18429   // reachable by iterating up through chain nodes matching the above
18430   // conditions.  For each such store identified, try to find an
18431   // earlier chain to attach the store to which won't violate the
18432   // required ordering.
18433   bool MadeChangeToSt = false;
18434   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
18435 
18436   for (StoreSDNode *ChainedStore : ChainedStores) {
18437     SDValue Chain = ChainedStore->getChain();
18438     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
18439 
18440     if (Chain != BetterChain) {
18441       if (ChainedStore == St)
18442         MadeChangeToSt = true;
18443       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
18444     }
18445   }
18446 
18447   // Do all replacements after finding the replacements to make to avoid making
18448   // the chains more complicated by introducing new TokenFactors.
18449   for (auto Replacement : BetterChains)
18450     replaceStoreChain(Replacement.first, Replacement.second);
18451 
18452   return MadeChangeToSt;
18453 }
18454 
18455 /// This is the entry point for the file.
18456 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
18457                            CodeGenOpt::Level OptLevel) {
18458   /// This is the main entry point to this class.
18459   DAGCombiner(*this, AA, OptLevel).Run(Level);
18460 }
18461