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/MachineValueType.h"
40 #include "llvm/CodeGen/RuntimeLibcalls.h"
41 #include "llvm/CodeGen/SelectionDAG.h"
42 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/Constant.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DerivedTypes.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CodeGen.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/ErrorHandling.h"
59 #include "llvm/Support/KnownBits.h"
60 #include "llvm/Support/MathExtras.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/Target/TargetLowering.h"
63 #include "llvm/Target/TargetMachine.h"
64 #include "llvm/Target/TargetOptions.h"
65 #include "llvm/Target/TargetRegisterInfo.h"
66 #include "llvm/Target/TargetSubtargetInfo.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     /// \brief 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     /// \brief 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     /// \brief 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     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
236 
237     bool CombineToPreIndexedLoadStore(SDNode *N);
238     bool CombineToPostIndexedLoadStore(SDNode *N);
239     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
240     bool SliceUpLoad(SDNode *N);
241 
242     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
243     ///   load.
244     ///
245     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
246     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
247     /// \param EltNo index of the vector element to load.
248     /// \param OriginalLoad load that EVE came from to be replaced.
249     /// \returns EVE on success SDValue() on failure.
250     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
251         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
252     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
253     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
254     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
255     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
256     SDValue PromoteIntBinOp(SDValue Op);
257     SDValue PromoteIntShiftOp(SDValue Op);
258     SDValue PromoteExtend(SDValue Op);
259     bool PromoteLoad(SDValue Op);
260 
261     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
262                          SDValue ExtLoad, const SDLoc &DL,
263                          ISD::NodeType ExtType);
264 
265     /// Call the node-specific routine that knows how to fold each
266     /// particular type of node. If that doesn't do anything, try the
267     /// target-specific DAG combines.
268     SDValue combine(SDNode *N);
269 
270     // Visitation implementation - Implement dag node combining for different
271     // node types.  The semantics are as follows:
272     // Return Value:
273     //   SDValue.getNode() == 0 - No change was made
274     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
275     //   otherwise              - N should be replaced by the returned Operand.
276     //
277     SDValue visitTokenFactor(SDNode *N);
278     SDValue visitMERGE_VALUES(SDNode *N);
279     SDValue visitADD(SDNode *N);
280     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
281     SDValue visitSUB(SDNode *N);
282     SDValue visitADDC(SDNode *N);
283     SDValue visitUADDO(SDNode *N);
284     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
285     SDValue visitSUBC(SDNode *N);
286     SDValue visitUSUBO(SDNode *N);
287     SDValue visitADDE(SDNode *N);
288     SDValue visitADDCARRY(SDNode *N);
289     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
290     SDValue visitSUBE(SDNode *N);
291     SDValue visitSUBCARRY(SDNode *N);
292     SDValue visitMUL(SDNode *N);
293     SDValue useDivRem(SDNode *N);
294     SDValue visitSDIV(SDNode *N);
295     SDValue visitUDIV(SDNode *N);
296     SDValue visitREM(SDNode *N);
297     SDValue visitMULHU(SDNode *N);
298     SDValue visitMULHS(SDNode *N);
299     SDValue visitSMUL_LOHI(SDNode *N);
300     SDValue visitUMUL_LOHI(SDNode *N);
301     SDValue visitSMULO(SDNode *N);
302     SDValue visitUMULO(SDNode *N);
303     SDValue visitIMINMAX(SDNode *N);
304     SDValue visitAND(SDNode *N);
305     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
306     SDValue visitOR(SDNode *N);
307     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
308     SDValue visitXOR(SDNode *N);
309     SDValue SimplifyVBinOp(SDNode *N);
310     SDValue visitSHL(SDNode *N);
311     SDValue visitSRA(SDNode *N);
312     SDValue visitSRL(SDNode *N);
313     SDValue visitRotate(SDNode *N);
314     SDValue visitABS(SDNode *N);
315     SDValue visitBSWAP(SDNode *N);
316     SDValue visitBITREVERSE(SDNode *N);
317     SDValue visitCTLZ(SDNode *N);
318     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
319     SDValue visitCTTZ(SDNode *N);
320     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
321     SDValue visitCTPOP(SDNode *N);
322     SDValue visitSELECT(SDNode *N);
323     SDValue visitVSELECT(SDNode *N);
324     SDValue visitSELECT_CC(SDNode *N);
325     SDValue visitSETCC(SDNode *N);
326     SDValue visitSETCCE(SDNode *N);
327     SDValue visitSETCCCARRY(SDNode *N);
328     SDValue visitSIGN_EXTEND(SDNode *N);
329     SDValue visitZERO_EXTEND(SDNode *N);
330     SDValue visitANY_EXTEND(SDNode *N);
331     SDValue visitAssertExt(SDNode *N);
332     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
333     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
334     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
335     SDValue visitTRUNCATE(SDNode *N);
336     SDValue visitBITCAST(SDNode *N);
337     SDValue visitBUILD_PAIR(SDNode *N);
338     SDValue visitFADD(SDNode *N);
339     SDValue visitFSUB(SDNode *N);
340     SDValue visitFMUL(SDNode *N);
341     SDValue visitFMA(SDNode *N);
342     SDValue visitFDIV(SDNode *N);
343     SDValue visitFREM(SDNode *N);
344     SDValue visitFSQRT(SDNode *N);
345     SDValue visitFCOPYSIGN(SDNode *N);
346     SDValue visitSINT_TO_FP(SDNode *N);
347     SDValue visitUINT_TO_FP(SDNode *N);
348     SDValue visitFP_TO_SINT(SDNode *N);
349     SDValue visitFP_TO_UINT(SDNode *N);
350     SDValue visitFP_ROUND(SDNode *N);
351     SDValue visitFP_ROUND_INREG(SDNode *N);
352     SDValue visitFP_EXTEND(SDNode *N);
353     SDValue visitFNEG(SDNode *N);
354     SDValue visitFABS(SDNode *N);
355     SDValue visitFCEIL(SDNode *N);
356     SDValue visitFTRUNC(SDNode *N);
357     SDValue visitFFLOOR(SDNode *N);
358     SDValue visitFMINNUM(SDNode *N);
359     SDValue visitFMAXNUM(SDNode *N);
360     SDValue visitBRCOND(SDNode *N);
361     SDValue visitBR_CC(SDNode *N);
362     SDValue visitLOAD(SDNode *N);
363 
364     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
365     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
366 
367     SDValue visitSTORE(SDNode *N);
368     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
369     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
370     SDValue visitBUILD_VECTOR(SDNode *N);
371     SDValue visitCONCAT_VECTORS(SDNode *N);
372     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
373     SDValue visitVECTOR_SHUFFLE(SDNode *N);
374     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
375     SDValue visitINSERT_SUBVECTOR(SDNode *N);
376     SDValue visitMLOAD(SDNode *N);
377     SDValue visitMSTORE(SDNode *N);
378     SDValue visitMGATHER(SDNode *N);
379     SDValue visitMSCATTER(SDNode *N);
380     SDValue visitFP_TO_FP16(SDNode *N);
381     SDValue visitFP16_TO_FP(SDNode *N);
382 
383     SDValue visitFADDForFMACombine(SDNode *N);
384     SDValue visitFSUBForFMACombine(SDNode *N);
385     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
386 
387     SDValue XformToShuffleWithZero(SDNode *N);
388     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
389                            SDValue RHS);
390 
391     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
392 
393     SDValue foldSelectOfConstants(SDNode *N);
394     SDValue foldVSelectOfConstants(SDNode *N);
395     SDValue foldBinOpIntoSelect(SDNode *BO);
396     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
397     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
398     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
399     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
400                              SDValue N2, SDValue N3, ISD::CondCode CC,
401                              bool NotExtCompare = false);
402     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
403                                    SDValue N2, SDValue N3, ISD::CondCode CC);
404     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
405                               const SDLoc &DL);
406     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
407                           const SDLoc &DL, bool foldBooleans = true);
408 
409     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
410                            SDValue &CC) const;
411     bool isOneUseSetCC(SDValue N) const;
412 
413     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
414                                          unsigned HiOp);
415     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
416     SDValue CombineExtLoad(SDNode *N);
417     SDValue combineRepeatedFPDivisors(SDNode *N);
418     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
419     SDValue BuildSDIV(SDNode *N);
420     SDValue BuildSDIVPow2(SDNode *N);
421     SDValue BuildUDIV(SDNode *N);
422     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
423     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
424     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
425     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
426     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
427     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
428                                 SDNodeFlags Flags, bool Reciprocal);
429     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
430                                 SDNodeFlags Flags, bool Reciprocal);
431     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
432                                bool DemandHighBits = true);
433     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
434     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
435                               SDValue InnerPos, SDValue InnerNeg,
436                               unsigned PosOpcode, unsigned NegOpcode,
437                               const SDLoc &DL);
438     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
439     SDValue MatchLoadCombine(SDNode *N);
440     SDValue ReduceLoadWidth(SDNode *N);
441     SDValue ReduceLoadOpStoreWidth(SDNode *N);
442     SDValue splitMergedValStore(StoreSDNode *ST);
443     SDValue TransformFPLoadStorePair(SDNode *N);
444     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
445     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
446     SDValue reduceBuildVecToShuffle(SDNode *N);
447     SDValue reduceBuildVecToTrunc(SDNode *N);
448     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
449                                   ArrayRef<int> VectorMask, SDValue VecIn1,
450                                   SDValue VecIn2, unsigned LeftIdx);
451     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
452 
453     /// Walk up chain skipping non-aliasing memory nodes,
454     /// looking for aliasing nodes and adding them to the Aliases vector.
455     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
456                           SmallVectorImpl<SDValue> &Aliases);
457 
458     /// Return true if there is any possibility that the two addresses overlap.
459     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
460 
461     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
462     /// chain (aliasing node.)
463     SDValue FindBetterChain(SDNode *N, SDValue Chain);
464 
465     /// Try to replace a store and any possibly adjacent stores on
466     /// consecutive chains with better chains. Return true only if St is
467     /// replaced.
468     ///
469     /// Notice that other chains may still be replaced even if the function
470     /// returns false.
471     bool findBetterNeighborChains(StoreSDNode *St);
472 
473     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
474     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
475 
476     /// Holds a pointer to an LSBaseSDNode as well as information on where it
477     /// is located in a sequence of memory operations connected by a chain.
478     struct MemOpLink {
479       // Ptr to the mem node.
480       LSBaseSDNode *MemNode;
481 
482       // Offset from the base ptr.
483       int64_t OffsetFromBase;
484 
485       MemOpLink(LSBaseSDNode *N, int64_t Offset)
486           : MemNode(N), OffsetFromBase(Offset) {}
487     };
488 
489     /// This is a helper function for visitMUL to check the profitability
490     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
491     /// MulNode is the original multiply, AddNode is (add x, c1),
492     /// and ConstNode is c2.
493     bool isMulAddWithConstProfitable(SDNode *MulNode,
494                                      SDValue &AddNode,
495                                      SDValue &ConstNode);
496 
497     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
498     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
499     /// the type of the loaded value to be extended.  LoadedVT returns the type
500     /// of the original loaded value.  NarrowLoad returns whether the load would
501     /// need to be narrowed in order to match.
502     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
503                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
504                           bool &NarrowLoad);
505 
506     /// Helper function for MergeConsecutiveStores which merges the
507     /// component store chains.
508     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
509                                 unsigned NumStores);
510 
511     /// This is a helper function for MergeConsecutiveStores. When the
512     /// source elements of the consecutive stores are all constants or
513     /// all extracted vector elements, try to merge them into one
514     /// larger store introducing bitcasts if necessary.  \return True
515     /// if a merged store was created.
516     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
517                                          EVT MemVT, unsigned NumStores,
518                                          bool IsConstantSrc, bool UseVector,
519                                          bool UseTrunc);
520 
521     /// This is a helper function for MergeConsecutiveStores. Stores
522     /// that potentially may be merged with St are placed in
523     /// StoreNodes.
524     void getStoreMergeCandidates(StoreSDNode *St,
525                                  SmallVectorImpl<MemOpLink> &StoreNodes);
526 
527     /// Helper function for MergeConsecutiveStores. Checks if
528     /// candidate stores have indirect dependency through their
529     /// operands. \return True if safe to merge.
530     bool checkMergeStoreCandidatesForDependencies(
531         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
532 
533     /// Merge consecutive store operations into a wide store.
534     /// This optimization uses wide integers or vectors when possible.
535     /// \return number of stores that were merged into a merged store (the
536     /// affected nodes are stored as a prefix in \p StoreNodes).
537     bool MergeConsecutiveStores(StoreSDNode *N);
538 
539     /// \brief Try to transform a truncation where C is a constant:
540     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
541     ///
542     /// \p N needs to be a truncation and its first operand an AND. Other
543     /// requirements are checked by the function (e.g. that trunc is
544     /// single-use) and if missed an empty SDValue is returned.
545     SDValue distributeTruncateThroughAnd(SDNode *N);
546 
547   public:
548     /// Runs the dag combiner on all nodes in the work list
549     void Run(CombineLevel AtLevel);
550 
551     SelectionDAG &getDAG() const { return DAG; }
552 
553     /// Returns a type large enough to hold any valid shift amount - before type
554     /// legalization these can be huge.
555     EVT getShiftAmountTy(EVT LHSTy) {
556       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
557       if (LHSTy.isVector())
558         return LHSTy;
559       auto &DL = DAG.getDataLayout();
560       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
561                         : TLI.getPointerTy(DL);
562     }
563 
564     /// This method returns true if we are running before type legalization or
565     /// if the specified VT is legal.
566     bool isTypeLegal(const EVT &VT) {
567       if (!LegalTypes) return true;
568       return TLI.isTypeLegal(VT);
569     }
570 
571     /// Convenience wrapper around TargetLowering::getSetCCResultType
572     EVT getSetCCResultType(EVT VT) const {
573       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
574     }
575   };
576 
577 /// This class is a DAGUpdateListener that removes any deleted
578 /// nodes from the worklist.
579 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
580   DAGCombiner &DC;
581 
582 public:
583   explicit WorklistRemover(DAGCombiner &dc)
584     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
585 
586   void NodeDeleted(SDNode *N, SDNode *E) override {
587     DC.removeFromWorklist(N);
588   }
589 };
590 
591 } // end anonymous namespace
592 
593 //===----------------------------------------------------------------------===//
594 //  TargetLowering::DAGCombinerInfo implementation
595 //===----------------------------------------------------------------------===//
596 
597 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
598   ((DAGCombiner*)DC)->AddToWorklist(N);
599 }
600 
601 SDValue TargetLowering::DAGCombinerInfo::
602 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
603   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
604 }
605 
606 SDValue TargetLowering::DAGCombinerInfo::
607 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
608   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
609 }
610 
611 SDValue TargetLowering::DAGCombinerInfo::
612 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
613   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
614 }
615 
616 void TargetLowering::DAGCombinerInfo::
617 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
618   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
619 }
620 
621 //===----------------------------------------------------------------------===//
622 // Helper Functions
623 //===----------------------------------------------------------------------===//
624 
625 void DAGCombiner::deleteAndRecombine(SDNode *N) {
626   removeFromWorklist(N);
627 
628   // If the operands of this node are only used by the node, they will now be
629   // dead. Make sure to re-visit them and recursively delete dead nodes.
630   for (const SDValue &Op : N->ops())
631     // For an operand generating multiple values, one of the values may
632     // become dead allowing further simplification (e.g. split index
633     // arithmetic from an indexed load).
634     if (Op->hasOneUse() || Op->getNumValues() > 1)
635       AddToWorklist(Op.getNode());
636 
637   DAG.DeleteNode(N);
638 }
639 
640 /// Return 1 if we can compute the negated form of the specified expression for
641 /// the same cost as the expression itself, or 2 if we can compute the negated
642 /// form more cheaply than the expression itself.
643 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
644                                const TargetLowering &TLI,
645                                const TargetOptions *Options,
646                                unsigned Depth = 0) {
647   // fneg is removable even if it has multiple uses.
648   if (Op.getOpcode() == ISD::FNEG) return 2;
649 
650   // Don't allow anything with multiple uses.
651   if (!Op.hasOneUse()) return 0;
652 
653   // Don't recurse exponentially.
654   if (Depth > 6) return 0;
655 
656   switch (Op.getOpcode()) {
657   default: return false;
658   case ISD::ConstantFP: {
659     if (!LegalOperations)
660       return 1;
661 
662     // Don't invert constant FP values after legalization unless the target says
663     // the negated constant is legal.
664     EVT VT = Op.getValueType();
665     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
666       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
667   }
668   case ISD::FADD:
669     // FIXME: determine better conditions for this xform.
670     if (!Options->UnsafeFPMath) return 0;
671 
672     // After operation legalization, it might not be legal to create new FSUBs.
673     if (LegalOperations &&
674         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
675       return 0;
676 
677     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
678     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
679                                     Options, Depth + 1))
680       return V;
681     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
682     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
683                               Depth + 1);
684   case ISD::FSUB:
685     // We can't turn -(A-B) into B-A when we honor signed zeros.
686     if (!Options->NoSignedZerosFPMath &&
687         !Op.getNode()->getFlags().hasNoSignedZeros())
688       return 0;
689 
690     // fold (fneg (fsub A, B)) -> (fsub B, A)
691     return 1;
692 
693   case ISD::FMUL:
694   case ISD::FDIV:
695     if (Options->HonorSignDependentRoundingFPMath()) return 0;
696 
697     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
698     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
699                                     Options, Depth + 1))
700       return V;
701 
702     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
703                               Depth + 1);
704 
705   case ISD::FP_EXTEND:
706   case ISD::FP_ROUND:
707   case ISD::FSIN:
708     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
709                               Depth + 1);
710   }
711 }
712 
713 /// If isNegatibleForFree returns true, return the newly negated expression.
714 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
715                                     bool LegalOperations, unsigned Depth = 0) {
716   const TargetOptions &Options = DAG.getTarget().Options;
717   // fneg is removable even if it has multiple uses.
718   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
719 
720   // Don't allow anything with multiple uses.
721   assert(Op.hasOneUse() && "Unknown reuse!");
722 
723   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
724 
725   const SDNodeFlags Flags = Op.getNode()->getFlags();
726 
727   switch (Op.getOpcode()) {
728   default: llvm_unreachable("Unknown code");
729   case ISD::ConstantFP: {
730     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
731     V.changeSign();
732     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
733   }
734   case ISD::FADD:
735     // FIXME: determine better conditions for this xform.
736     assert(Options.UnsafeFPMath);
737 
738     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
739     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
740                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
741       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
742                          GetNegatedExpression(Op.getOperand(0), DAG,
743                                               LegalOperations, Depth+1),
744                          Op.getOperand(1), Flags);
745     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
746     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
747                        GetNegatedExpression(Op.getOperand(1), DAG,
748                                             LegalOperations, Depth+1),
749                        Op.getOperand(0), Flags);
750   case ISD::FSUB:
751     // fold (fneg (fsub 0, B)) -> B
752     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
753       if (N0CFP->isZero())
754         return Op.getOperand(1);
755 
756     // fold (fneg (fsub A, B)) -> (fsub B, A)
757     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
758                        Op.getOperand(1), Op.getOperand(0), Flags);
759 
760   case ISD::FMUL:
761   case ISD::FDIV:
762     assert(!Options.HonorSignDependentRoundingFPMath());
763 
764     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
765     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
766                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
767       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
768                          GetNegatedExpression(Op.getOperand(0), DAG,
769                                               LegalOperations, Depth+1),
770                          Op.getOperand(1), Flags);
771 
772     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
773     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
774                        Op.getOperand(0),
775                        GetNegatedExpression(Op.getOperand(1), DAG,
776                                             LegalOperations, Depth+1), Flags);
777 
778   case ISD::FP_EXTEND:
779   case ISD::FSIN:
780     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
781                        GetNegatedExpression(Op.getOperand(0), DAG,
782                                             LegalOperations, Depth+1));
783   case ISD::FP_ROUND:
784       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
785                          GetNegatedExpression(Op.getOperand(0), DAG,
786                                               LegalOperations, Depth+1),
787                          Op.getOperand(1));
788   }
789 }
790 
791 // APInts must be the same size for most operations, this helper
792 // function zero extends the shorter of the pair so that they match.
793 // We provide an Offset so that we can create bitwidths that won't overflow.
794 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
795   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
796   LHS = LHS.zextOrSelf(Bits);
797   RHS = RHS.zextOrSelf(Bits);
798 }
799 
800 // Return true if this node is a setcc, or is a select_cc
801 // that selects between the target values used for true and false, making it
802 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
803 // the appropriate nodes based on the type of node we are checking. This
804 // simplifies life a bit for the callers.
805 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
806                                     SDValue &CC) const {
807   if (N.getOpcode() == ISD::SETCC) {
808     LHS = N.getOperand(0);
809     RHS = N.getOperand(1);
810     CC  = N.getOperand(2);
811     return true;
812   }
813 
814   if (N.getOpcode() != ISD::SELECT_CC ||
815       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
816       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
817     return false;
818 
819   if (TLI.getBooleanContents(N.getValueType()) ==
820       TargetLowering::UndefinedBooleanContent)
821     return false;
822 
823   LHS = N.getOperand(0);
824   RHS = N.getOperand(1);
825   CC  = N.getOperand(4);
826   return true;
827 }
828 
829 /// Return true if this is a SetCC-equivalent operation with only one use.
830 /// If this is true, it allows the users to invert the operation for free when
831 /// it is profitable to do so.
832 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
833   SDValue N0, N1, N2;
834   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
835     return true;
836   return false;
837 }
838 
839 // \brief Returns the SDNode if it is a constant float BuildVector
840 // or constant float.
841 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
842   if (isa<ConstantFPSDNode>(N))
843     return N.getNode();
844   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
845     return N.getNode();
846   return nullptr;
847 }
848 
849 // Determines if it is a constant integer or a build vector of constant
850 // integers (and undefs).
851 // Do not permit build vector implicit truncation.
852 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
853   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
854     return !(Const->isOpaque() && NoOpaques);
855   if (N.getOpcode() != ISD::BUILD_VECTOR)
856     return false;
857   unsigned BitWidth = N.getScalarValueSizeInBits();
858   for (const SDValue &Op : N->op_values()) {
859     if (Op.isUndef())
860       continue;
861     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
862     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
863         (Const->isOpaque() && NoOpaques))
864       return false;
865   }
866   return true;
867 }
868 
869 // Determines if it is a constant null integer or a splatted vector of a
870 // constant null integer (with no undefs).
871 // Build vector implicit truncation is not an issue for null values.
872 static bool isNullConstantOrNullSplatConstant(SDValue N) {
873   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
874     return Splat->isNullValue();
875   return false;
876 }
877 
878 // Determines if it is a constant integer of one or a splatted vector of a
879 // constant integer of one (with no undefs).
880 // Do not permit build vector implicit truncation.
881 static bool isOneConstantOrOneSplatConstant(SDValue N) {
882   unsigned BitWidth = N.getScalarValueSizeInBits();
883   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
884     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
885   return false;
886 }
887 
888 // Determines if it is a constant integer of all ones or a splatted vector of a
889 // constant integer of all ones (with no undefs).
890 // Do not permit build vector implicit truncation.
891 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
892   unsigned BitWidth = N.getScalarValueSizeInBits();
893   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
894     return Splat->isAllOnesValue() &&
895            Splat->getAPIntValue().getBitWidth() == BitWidth;
896   return false;
897 }
898 
899 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
900 // undef's.
901 static bool isAnyConstantBuildVector(const SDNode *N) {
902   return ISD::isBuildVectorOfConstantSDNodes(N) ||
903          ISD::isBuildVectorOfConstantFPSDNodes(N);
904 }
905 
906 // Attempt to match a unary predicate against a scalar/splat constant or
907 // every element of a constant BUILD_VECTOR.
908 static bool matchUnaryPredicate(SDValue Op,
909                                 std::function<bool(ConstantSDNode *)> Match) {
910   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
911     return Match(Cst);
912 
913   if (ISD::BUILD_VECTOR != Op.getOpcode())
914     return false;
915 
916   EVT SVT = Op.getValueType().getScalarType();
917   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
918     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
919     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
920       return false;
921   }
922   return true;
923 }
924 
925 // Attempt to match a binary predicate against a pair of scalar/splat constants
926 // or every element of a pair of constant BUILD_VECTORs.
927 static bool matchBinaryPredicate(
928     SDValue LHS, SDValue RHS,
929     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match) {
930   if (LHS.getValueType() != RHS.getValueType())
931     return false;
932 
933   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
934     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
935       return Match(LHSCst, RHSCst);
936 
937   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
938       ISD::BUILD_VECTOR != RHS.getOpcode())
939     return false;
940 
941   EVT SVT = LHS.getValueType().getScalarType();
942   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
943     auto *LHSCst = dyn_cast<ConstantSDNode>(LHS.getOperand(i));
944     auto *RHSCst = dyn_cast<ConstantSDNode>(RHS.getOperand(i));
945     if (!LHSCst || !RHSCst)
946       return false;
947     if (LHSCst->getValueType(0) != SVT ||
948         LHSCst->getValueType(0) != RHSCst->getValueType(0))
949       return false;
950     if (!Match(LHSCst, RHSCst))
951       return false;
952   }
953   return true;
954 }
955 
956 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
957                                     SDValue N1) {
958   EVT VT = N0.getValueType();
959   if (N0.getOpcode() == Opc) {
960     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
961       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
962         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
963         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
964           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
965         return SDValue();
966       }
967       if (N0.hasOneUse()) {
968         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
969         // use
970         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
971         if (!OpNode.getNode())
972           return SDValue();
973         AddToWorklist(OpNode.getNode());
974         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
975       }
976     }
977   }
978 
979   if (N1.getOpcode() == Opc) {
980     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
981       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
982         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
983         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
984           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
985         return SDValue();
986       }
987       if (N1.hasOneUse()) {
988         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
989         // use
990         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
991         if (!OpNode.getNode())
992           return SDValue();
993         AddToWorklist(OpNode.getNode());
994         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
995       }
996     }
997   }
998 
999   return SDValue();
1000 }
1001 
1002 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1003                                bool AddTo) {
1004   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
1005   ++NodesCombined;
1006   DEBUG(dbgs() << "\nReplacing.1 ";
1007         N->dump(&DAG);
1008         dbgs() << "\nWith: ";
1009         To[0].getNode()->dump(&DAG);
1010         dbgs() << " and " << NumTo-1 << " other values\n");
1011   for (unsigned i = 0, e = NumTo; i != e; ++i)
1012     assert((!To[i].getNode() ||
1013             N->getValueType(i) == To[i].getValueType()) &&
1014            "Cannot combine value to value of different type!");
1015 
1016   WorklistRemover DeadNodes(*this);
1017   DAG.ReplaceAllUsesWith(N, To);
1018   if (AddTo) {
1019     // Push the new nodes and any users onto the worklist
1020     for (unsigned i = 0, e = NumTo; i != e; ++i) {
1021       if (To[i].getNode()) {
1022         AddToWorklist(To[i].getNode());
1023         AddUsersToWorklist(To[i].getNode());
1024       }
1025     }
1026   }
1027 
1028   // Finally, if the node is now dead, remove it from the graph.  The node
1029   // may not be dead if the replacement process recursively simplified to
1030   // something else needing this node.
1031   if (N->use_empty())
1032     deleteAndRecombine(N);
1033   return SDValue(N, 0);
1034 }
1035 
1036 void DAGCombiner::
1037 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1038   // Replace all uses.  If any nodes become isomorphic to other nodes and
1039   // are deleted, make sure to remove them from our worklist.
1040   WorklistRemover DeadNodes(*this);
1041   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1042 
1043   // Push the new node and any (possibly new) users onto the worklist.
1044   AddToWorklist(TLO.New.getNode());
1045   AddUsersToWorklist(TLO.New.getNode());
1046 
1047   // Finally, if the node is now dead, remove it from the graph.  The node
1048   // may not be dead if the replacement process recursively simplified to
1049   // something else needing this node.
1050   if (TLO.Old.getNode()->use_empty())
1051     deleteAndRecombine(TLO.Old.getNode());
1052 }
1053 
1054 /// Check the specified integer node value to see if it can be simplified or if
1055 /// things it uses can be simplified by bit propagation. If so, return true.
1056 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
1057   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1058   KnownBits Known;
1059   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
1060     return false;
1061 
1062   // Revisit the node.
1063   AddToWorklist(Op.getNode());
1064 
1065   // Replace the old value with the new one.
1066   ++NodesCombined;
1067   DEBUG(dbgs() << "\nReplacing.2 ";
1068         TLO.Old.getNode()->dump(&DAG);
1069         dbgs() << "\nWith: ";
1070         TLO.New.getNode()->dump(&DAG);
1071         dbgs() << '\n');
1072 
1073   CommitTargetLoweringOpt(TLO);
1074   return true;
1075 }
1076 
1077 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1078   SDLoc DL(Load);
1079   EVT VT = Load->getValueType(0);
1080   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1081 
1082   DEBUG(dbgs() << "\nReplacing.9 ";
1083         Load->dump(&DAG);
1084         dbgs() << "\nWith: ";
1085         Trunc.getNode()->dump(&DAG);
1086         dbgs() << '\n');
1087   WorklistRemover DeadNodes(*this);
1088   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1089   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1090   deleteAndRecombine(Load);
1091   AddToWorklist(Trunc.getNode());
1092 }
1093 
1094 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1095   Replace = false;
1096   SDLoc DL(Op);
1097   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1098     LoadSDNode *LD = cast<LoadSDNode>(Op);
1099     EVT MemVT = LD->getMemoryVT();
1100     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1101       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1102                                                        : ISD::EXTLOAD)
1103       : LD->getExtensionType();
1104     Replace = true;
1105     return DAG.getExtLoad(ExtType, DL, PVT,
1106                           LD->getChain(), LD->getBasePtr(),
1107                           MemVT, LD->getMemOperand());
1108   }
1109 
1110   unsigned Opc = Op.getOpcode();
1111   switch (Opc) {
1112   default: break;
1113   case ISD::AssertSext:
1114     if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1115       return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1116     break;
1117   case ISD::AssertZext:
1118     if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1119       return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1120     break;
1121   case ISD::Constant: {
1122     unsigned ExtOpc =
1123       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1124     return DAG.getNode(ExtOpc, DL, PVT, Op);
1125   }
1126   }
1127 
1128   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1129     return SDValue();
1130   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1131 }
1132 
1133 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1134   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1135     return SDValue();
1136   EVT OldVT = Op.getValueType();
1137   SDLoc DL(Op);
1138   bool Replace = false;
1139   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1140   if (!NewOp.getNode())
1141     return SDValue();
1142   AddToWorklist(NewOp.getNode());
1143 
1144   if (Replace)
1145     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1146   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1147                      DAG.getValueType(OldVT));
1148 }
1149 
1150 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1151   EVT OldVT = Op.getValueType();
1152   SDLoc DL(Op);
1153   bool Replace = false;
1154   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1155   if (!NewOp.getNode())
1156     return SDValue();
1157   AddToWorklist(NewOp.getNode());
1158 
1159   if (Replace)
1160     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1161   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1162 }
1163 
1164 /// Promote the specified integer binary operation if the target indicates it is
1165 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1166 /// i32 since i16 instructions are longer.
1167 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1168   if (!LegalOperations)
1169     return SDValue();
1170 
1171   EVT VT = Op.getValueType();
1172   if (VT.isVector() || !VT.isInteger())
1173     return SDValue();
1174 
1175   // If operation type is 'undesirable', e.g. i16 on x86, consider
1176   // promoting it.
1177   unsigned Opc = Op.getOpcode();
1178   if (TLI.isTypeDesirableForOp(Opc, VT))
1179     return SDValue();
1180 
1181   EVT PVT = VT;
1182   // Consult target whether it is a good idea to promote this operation and
1183   // what's the right type to promote it to.
1184   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1185     assert(PVT != VT && "Don't know what type to promote to!");
1186 
1187     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1188 
1189     bool Replace0 = false;
1190     SDValue N0 = Op.getOperand(0);
1191     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1192 
1193     bool Replace1 = false;
1194     SDValue N1 = Op.getOperand(1);
1195     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1196     SDLoc DL(Op);
1197 
1198     SDValue RV =
1199         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1200 
1201     // We are always replacing N0/N1's use in N and only need
1202     // additional replacements if there are additional uses.
1203     Replace0 &= !N0->hasOneUse();
1204     Replace1 &= (N0 != N1) && !N1->hasOneUse();
1205 
1206     // Combine Op here so it is presreved past replacements.
1207     CombineTo(Op.getNode(), RV);
1208 
1209     // If operands have a use ordering, make sur we deal with
1210     // predecessor first.
1211     if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1212       std::swap(N0, N1);
1213       std::swap(NN0, NN1);
1214     }
1215 
1216     if (Replace0) {
1217       AddToWorklist(NN0.getNode());
1218       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1219     }
1220     if (Replace1) {
1221       AddToWorklist(NN1.getNode());
1222       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1223     }
1224     return Op;
1225   }
1226   return SDValue();
1227 }
1228 
1229 /// Promote the specified integer shift operation if the target indicates it is
1230 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1231 /// i32 since i16 instructions are longer.
1232 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1233   if (!LegalOperations)
1234     return SDValue();
1235 
1236   EVT VT = Op.getValueType();
1237   if (VT.isVector() || !VT.isInteger())
1238     return SDValue();
1239 
1240   // If operation type is 'undesirable', e.g. i16 on x86, consider
1241   // promoting it.
1242   unsigned Opc = Op.getOpcode();
1243   if (TLI.isTypeDesirableForOp(Opc, VT))
1244     return SDValue();
1245 
1246   EVT PVT = VT;
1247   // Consult target whether it is a good idea to promote this operation and
1248   // what's the right type to promote it to.
1249   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1250     assert(PVT != VT && "Don't know what type to promote to!");
1251 
1252     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1253 
1254     bool Replace = false;
1255     SDValue N0 = Op.getOperand(0);
1256     SDValue N1 = Op.getOperand(1);
1257     if (Opc == ISD::SRA)
1258       N0 = SExtPromoteOperand(N0, PVT);
1259     else if (Opc == ISD::SRL)
1260       N0 = ZExtPromoteOperand(N0, PVT);
1261     else
1262       N0 = PromoteOperand(N0, PVT, Replace);
1263 
1264     if (!N0.getNode())
1265       return SDValue();
1266 
1267     SDLoc DL(Op);
1268     SDValue RV =
1269         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1270 
1271     AddToWorklist(N0.getNode());
1272     if (Replace)
1273       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1274 
1275     // Deal with Op being deleted.
1276     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1277       return RV;
1278   }
1279   return SDValue();
1280 }
1281 
1282 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1283   if (!LegalOperations)
1284     return SDValue();
1285 
1286   EVT VT = Op.getValueType();
1287   if (VT.isVector() || !VT.isInteger())
1288     return SDValue();
1289 
1290   // If operation type is 'undesirable', e.g. i16 on x86, consider
1291   // promoting it.
1292   unsigned Opc = Op.getOpcode();
1293   if (TLI.isTypeDesirableForOp(Opc, VT))
1294     return SDValue();
1295 
1296   EVT PVT = VT;
1297   // Consult target whether it is a good idea to promote this operation and
1298   // what's the right type to promote it to.
1299   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1300     assert(PVT != VT && "Don't know what type to promote to!");
1301     // fold (aext (aext x)) -> (aext x)
1302     // fold (aext (zext x)) -> (zext x)
1303     // fold (aext (sext x)) -> (sext x)
1304     DEBUG(dbgs() << "\nPromoting ";
1305           Op.getNode()->dump(&DAG));
1306     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1307   }
1308   return SDValue();
1309 }
1310 
1311 bool DAGCombiner::PromoteLoad(SDValue Op) {
1312   if (!LegalOperations)
1313     return false;
1314 
1315   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1316     return false;
1317 
1318   EVT VT = Op.getValueType();
1319   if (VT.isVector() || !VT.isInteger())
1320     return false;
1321 
1322   // If operation type is 'undesirable', e.g. i16 on x86, consider
1323   // promoting it.
1324   unsigned Opc = Op.getOpcode();
1325   if (TLI.isTypeDesirableForOp(Opc, VT))
1326     return false;
1327 
1328   EVT PVT = VT;
1329   // Consult target whether it is a good idea to promote this operation and
1330   // what's the right type to promote it to.
1331   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1332     assert(PVT != VT && "Don't know what type to promote to!");
1333 
1334     SDLoc DL(Op);
1335     SDNode *N = Op.getNode();
1336     LoadSDNode *LD = cast<LoadSDNode>(N);
1337     EVT MemVT = LD->getMemoryVT();
1338     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1339       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1340                                                        : ISD::EXTLOAD)
1341       : LD->getExtensionType();
1342     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1343                                    LD->getChain(), LD->getBasePtr(),
1344                                    MemVT, LD->getMemOperand());
1345     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1346 
1347     DEBUG(dbgs() << "\nPromoting ";
1348           N->dump(&DAG);
1349           dbgs() << "\nTo: ";
1350           Result.getNode()->dump(&DAG);
1351           dbgs() << '\n');
1352     WorklistRemover DeadNodes(*this);
1353     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1354     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1355     deleteAndRecombine(N);
1356     AddToWorklist(Result.getNode());
1357     return true;
1358   }
1359   return false;
1360 }
1361 
1362 /// \brief Recursively delete a node which has no uses and any operands for
1363 /// which it is the only use.
1364 ///
1365 /// Note that this both deletes the nodes and removes them from the worklist.
1366 /// It also adds any nodes who have had a user deleted to the worklist as they
1367 /// may now have only one use and subject to other combines.
1368 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1369   if (!N->use_empty())
1370     return false;
1371 
1372   SmallSetVector<SDNode *, 16> Nodes;
1373   Nodes.insert(N);
1374   do {
1375     N = Nodes.pop_back_val();
1376     if (!N)
1377       continue;
1378 
1379     if (N->use_empty()) {
1380       for (const SDValue &ChildN : N->op_values())
1381         Nodes.insert(ChildN.getNode());
1382 
1383       removeFromWorklist(N);
1384       DAG.DeleteNode(N);
1385     } else {
1386       AddToWorklist(N);
1387     }
1388   } while (!Nodes.empty());
1389   return true;
1390 }
1391 
1392 //===----------------------------------------------------------------------===//
1393 //  Main DAG Combiner implementation
1394 //===----------------------------------------------------------------------===//
1395 
1396 void DAGCombiner::Run(CombineLevel AtLevel) {
1397   // set the instance variables, so that the various visit routines may use it.
1398   Level = AtLevel;
1399   LegalOperations = Level >= AfterLegalizeVectorOps;
1400   LegalTypes = Level >= AfterLegalizeTypes;
1401 
1402   // Add all the dag nodes to the worklist.
1403   for (SDNode &Node : DAG.allnodes())
1404     AddToWorklist(&Node);
1405 
1406   // Create a dummy node (which is not added to allnodes), that adds a reference
1407   // to the root node, preventing it from being deleted, and tracking any
1408   // changes of the root.
1409   HandleSDNode Dummy(DAG.getRoot());
1410 
1411   // While the worklist isn't empty, find a node and try to combine it.
1412   while (!WorklistMap.empty()) {
1413     SDNode *N;
1414     // The Worklist holds the SDNodes in order, but it may contain null entries.
1415     do {
1416       N = Worklist.pop_back_val();
1417     } while (!N);
1418 
1419     bool GoodWorklistEntry = WorklistMap.erase(N);
1420     (void)GoodWorklistEntry;
1421     assert(GoodWorklistEntry &&
1422            "Found a worklist entry without a corresponding map entry!");
1423 
1424     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1425     // N is deleted from the DAG, since they too may now be dead or may have a
1426     // reduced number of uses, allowing other xforms.
1427     if (recursivelyDeleteUnusedNodes(N))
1428       continue;
1429 
1430     WorklistRemover DeadNodes(*this);
1431 
1432     // If this combine is running after legalizing the DAG, re-legalize any
1433     // nodes pulled off the worklist.
1434     if (Level == AfterLegalizeDAG) {
1435       SmallSetVector<SDNode *, 16> UpdatedNodes;
1436       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1437 
1438       for (SDNode *LN : UpdatedNodes) {
1439         AddToWorklist(LN);
1440         AddUsersToWorklist(LN);
1441       }
1442       if (!NIsValid)
1443         continue;
1444     }
1445 
1446     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1447 
1448     // Add any operands of the new node which have not yet been combined to the
1449     // worklist as well. Because the worklist uniques things already, this
1450     // won't repeatedly process the same operand.
1451     CombinedNodes.insert(N);
1452     for (const SDValue &ChildN : N->op_values())
1453       if (!CombinedNodes.count(ChildN.getNode()))
1454         AddToWorklist(ChildN.getNode());
1455 
1456     SDValue RV = combine(N);
1457 
1458     if (!RV.getNode())
1459       continue;
1460 
1461     ++NodesCombined;
1462 
1463     // If we get back the same node we passed in, rather than a new node or
1464     // zero, we know that the node must have defined multiple values and
1465     // CombineTo was used.  Since CombineTo takes care of the worklist
1466     // mechanics for us, we have no work to do in this case.
1467     if (RV.getNode() == N)
1468       continue;
1469 
1470     assert(N->getOpcode() != ISD::DELETED_NODE &&
1471            RV.getOpcode() != ISD::DELETED_NODE &&
1472            "Node was deleted but visit returned new node!");
1473 
1474     DEBUG(dbgs() << " ... into: ";
1475           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::SETCCE:             return visitSETCCE(N);
1552   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1553   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1554   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1555   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1556   case ISD::AssertSext:
1557   case ISD::AssertZext:         return visitAssertExt(N);
1558   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1559   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1560   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1561   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1562   case ISD::BITCAST:            return visitBITCAST(N);
1563   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1564   case ISD::FADD:               return visitFADD(N);
1565   case ISD::FSUB:               return visitFSUB(N);
1566   case ISD::FMUL:               return visitFMUL(N);
1567   case ISD::FMA:                return visitFMA(N);
1568   case ISD::FDIV:               return visitFDIV(N);
1569   case ISD::FREM:               return visitFREM(N);
1570   case ISD::FSQRT:              return visitFSQRT(N);
1571   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1572   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1573   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1574   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1575   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1576   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1577   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1578   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1579   case ISD::FNEG:               return visitFNEG(N);
1580   case ISD::FABS:               return visitFABS(N);
1581   case ISD::FFLOOR:             return visitFFLOOR(N);
1582   case ISD::FMINNUM:            return visitFMINNUM(N);
1583   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1584   case ISD::FCEIL:              return visitFCEIL(N);
1585   case ISD::FTRUNC:             return visitFTRUNC(N);
1586   case ISD::BRCOND:             return visitBRCOND(N);
1587   case ISD::BR_CC:              return visitBR_CC(N);
1588   case ISD::LOAD:               return visitLOAD(N);
1589   case ISD::STORE:              return visitSTORE(N);
1590   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1591   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1592   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1593   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1594   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1595   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1596   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1597   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1598   case ISD::MGATHER:            return visitMGATHER(N);
1599   case ISD::MLOAD:              return visitMLOAD(N);
1600   case ISD::MSCATTER:           return visitMSCATTER(N);
1601   case ISD::MSTORE:             return visitMSTORE(N);
1602   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1603   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1604   }
1605   return SDValue();
1606 }
1607 
1608 SDValue DAGCombiner::combine(SDNode *N) {
1609   SDValue RV = visit(N);
1610 
1611   // If nothing happened, try a target-specific DAG combine.
1612   if (!RV.getNode()) {
1613     assert(N->getOpcode() != ISD::DELETED_NODE &&
1614            "Node was deleted but visit returned NULL!");
1615 
1616     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1617         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1618 
1619       // Expose the DAG combiner to the target combiner impls.
1620       TargetLowering::DAGCombinerInfo
1621         DagCombineInfo(DAG, Level, false, this);
1622 
1623       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1624     }
1625   }
1626 
1627   // If nothing happened still, try promoting the operation.
1628   if (!RV.getNode()) {
1629     switch (N->getOpcode()) {
1630     default: break;
1631     case ISD::ADD:
1632     case ISD::SUB:
1633     case ISD::MUL:
1634     case ISD::AND:
1635     case ISD::OR:
1636     case ISD::XOR:
1637       RV = PromoteIntBinOp(SDValue(N, 0));
1638       break;
1639     case ISD::SHL:
1640     case ISD::SRA:
1641     case ISD::SRL:
1642       RV = PromoteIntShiftOp(SDValue(N, 0));
1643       break;
1644     case ISD::SIGN_EXTEND:
1645     case ISD::ZERO_EXTEND:
1646     case ISD::ANY_EXTEND:
1647       RV = PromoteExtend(SDValue(N, 0));
1648       break;
1649     case ISD::LOAD:
1650       if (PromoteLoad(SDValue(N, 0)))
1651         RV = SDValue(N, 0);
1652       break;
1653     }
1654   }
1655 
1656   // If N is a commutative binary node, try eliminate it if the commuted
1657   // version is already present in the DAG.
1658   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1659       N->getNumValues() == 1) {
1660     SDValue N0 = N->getOperand(0);
1661     SDValue N1 = N->getOperand(1);
1662 
1663     // Constant operands are canonicalized to RHS.
1664     if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1665       SDValue Ops[] = {N1, N0};
1666       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1667                                             N->getFlags());
1668       if (CSENode)
1669         return SDValue(CSENode, 0);
1670     }
1671   }
1672 
1673   return RV;
1674 }
1675 
1676 /// Given a node, return its input chain if it has one, otherwise return a null
1677 /// sd operand.
1678 static SDValue getInputChainForNode(SDNode *N) {
1679   if (unsigned NumOps = N->getNumOperands()) {
1680     if (N->getOperand(0).getValueType() == MVT::Other)
1681       return N->getOperand(0);
1682     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1683       return N->getOperand(NumOps-1);
1684     for (unsigned i = 1; i < NumOps-1; ++i)
1685       if (N->getOperand(i).getValueType() == MVT::Other)
1686         return N->getOperand(i);
1687   }
1688   return SDValue();
1689 }
1690 
1691 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1692   // If N has two operands, where one has an input chain equal to the other,
1693   // the 'other' chain is redundant.
1694   if (N->getNumOperands() == 2) {
1695     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1696       return N->getOperand(0);
1697     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1698       return N->getOperand(1);
1699   }
1700 
1701   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1702   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1703   SmallPtrSet<SDNode*, 16> SeenOps;
1704   bool Changed = false;             // If we should replace this token factor.
1705 
1706   // Start out with this token factor.
1707   TFs.push_back(N);
1708 
1709   // Iterate through token factors.  The TFs grows when new token factors are
1710   // encountered.
1711   for (unsigned i = 0; i < TFs.size(); ++i) {
1712     SDNode *TF = TFs[i];
1713 
1714     // Check each of the operands.
1715     for (const SDValue &Op : TF->op_values()) {
1716       switch (Op.getOpcode()) {
1717       case ISD::EntryToken:
1718         // Entry tokens don't need to be added to the list. They are
1719         // redundant.
1720         Changed = true;
1721         break;
1722 
1723       case ISD::TokenFactor:
1724         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1725           // Queue up for processing.
1726           TFs.push_back(Op.getNode());
1727           // Clean up in case the token factor is removed.
1728           AddToWorklist(Op.getNode());
1729           Changed = true;
1730           break;
1731         }
1732         LLVM_FALLTHROUGH;
1733 
1734       default:
1735         // Only add if it isn't already in the list.
1736         if (SeenOps.insert(Op.getNode()).second)
1737           Ops.push_back(Op);
1738         else
1739           Changed = true;
1740         break;
1741       }
1742     }
1743   }
1744 
1745   // Remove Nodes that are chained to another node in the list. Do so
1746   // by walking up chains breath-first stopping when we've seen
1747   // another operand. In general we must climb to the EntryNode, but we can exit
1748   // early if we find all remaining work is associated with just one operand as
1749   // no further pruning is possible.
1750 
1751   // List of nodes to search through and original Ops from which they originate.
1752   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1753   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1754   SmallPtrSet<SDNode *, 16> SeenChains;
1755   bool DidPruneOps = false;
1756 
1757   unsigned NumLeftToConsider = 0;
1758   for (const SDValue &Op : Ops) {
1759     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1760     OpWorkCount.push_back(1);
1761   }
1762 
1763   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1764     // If this is an Op, we can remove the op from the list. Remark any
1765     // search associated with it as from the current OpNumber.
1766     if (SeenOps.count(Op) != 0) {
1767       Changed = true;
1768       DidPruneOps = true;
1769       unsigned OrigOpNumber = 0;
1770       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1771         OrigOpNumber++;
1772       assert((OrigOpNumber != Ops.size()) &&
1773              "expected to find TokenFactor Operand");
1774       // Re-mark worklist from OrigOpNumber to OpNumber
1775       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1776         if (Worklist[i].second == OrigOpNumber) {
1777           Worklist[i].second = OpNumber;
1778         }
1779       }
1780       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1781       OpWorkCount[OrigOpNumber] = 0;
1782       NumLeftToConsider--;
1783     }
1784     // Add if it's a new chain
1785     if (SeenChains.insert(Op).second) {
1786       OpWorkCount[OpNumber]++;
1787       Worklist.push_back(std::make_pair(Op, OpNumber));
1788     }
1789   };
1790 
1791   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1792     // We need at least be consider at least 2 Ops to prune.
1793     if (NumLeftToConsider <= 1)
1794       break;
1795     auto CurNode = Worklist[i].first;
1796     auto CurOpNumber = Worklist[i].second;
1797     assert((OpWorkCount[CurOpNumber] > 0) &&
1798            "Node should not appear in worklist");
1799     switch (CurNode->getOpcode()) {
1800     case ISD::EntryToken:
1801       // Hitting EntryToken is the only way for the search to terminate without
1802       // hitting
1803       // another operand's search. Prevent us from marking this operand
1804       // considered.
1805       NumLeftToConsider++;
1806       break;
1807     case ISD::TokenFactor:
1808       for (const SDValue &Op : CurNode->op_values())
1809         AddToWorklist(i, Op.getNode(), CurOpNumber);
1810       break;
1811     case ISD::CopyFromReg:
1812     case ISD::CopyToReg:
1813       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1814       break;
1815     default:
1816       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1817         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1818       break;
1819     }
1820     OpWorkCount[CurOpNumber]--;
1821     if (OpWorkCount[CurOpNumber] == 0)
1822       NumLeftToConsider--;
1823   }
1824 
1825   // If we've changed things around then replace token factor.
1826   if (Changed) {
1827     SDValue Result;
1828     if (Ops.empty()) {
1829       // The entry token is the only possible outcome.
1830       Result = DAG.getEntryNode();
1831     } else {
1832       if (DidPruneOps) {
1833         SmallVector<SDValue, 8> PrunedOps;
1834         //
1835         for (const SDValue &Op : Ops) {
1836           if (SeenChains.count(Op.getNode()) == 0)
1837             PrunedOps.push_back(Op);
1838         }
1839         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1840       } else {
1841         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1842       }
1843     }
1844     return Result;
1845   }
1846   return SDValue();
1847 }
1848 
1849 /// MERGE_VALUES can always be eliminated.
1850 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1851   WorklistRemover DeadNodes(*this);
1852   // Replacing results may cause a different MERGE_VALUES to suddenly
1853   // be CSE'd with N, and carry its uses with it. Iterate until no
1854   // uses remain, to ensure that the node can be safely deleted.
1855   // First add the users of this node to the work list so that they
1856   // can be tried again once they have new operands.
1857   AddUsersToWorklist(N);
1858   do {
1859     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1860       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1861   } while (!N->use_empty());
1862   deleteAndRecombine(N);
1863   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1864 }
1865 
1866 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1867 /// ConstantSDNode pointer else nullptr.
1868 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1869   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1870   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1871 }
1872 
1873 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1874   auto BinOpcode = BO->getOpcode();
1875   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1876           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1877           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1878           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1879           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1880           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1881           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1882           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1883           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1884          "Unexpected binary operator");
1885 
1886   // Bail out if any constants are opaque because we can't constant fold those.
1887   SDValue C1 = BO->getOperand(1);
1888   if (!isConstantOrConstantVector(C1, true) &&
1889       !isConstantFPBuildVectorOrConstantFP(C1))
1890     return SDValue();
1891 
1892   // Don't do this unless the old select is going away. We want to eliminate the
1893   // binary operator, not replace a binop with a select.
1894   // TODO: Handle ISD::SELECT_CC.
1895   SDValue Sel = BO->getOperand(0);
1896   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1897     return SDValue();
1898 
1899   SDValue CT = Sel.getOperand(1);
1900   if (!isConstantOrConstantVector(CT, true) &&
1901       !isConstantFPBuildVectorOrConstantFP(CT))
1902     return SDValue();
1903 
1904   SDValue CF = Sel.getOperand(2);
1905   if (!isConstantOrConstantVector(CF, true) &&
1906       !isConstantFPBuildVectorOrConstantFP(CF))
1907     return SDValue();
1908 
1909   // We have a select-of-constants followed by a binary operator with a
1910   // constant. Eliminate the binop by pulling the constant math into the select.
1911   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1912   EVT VT = Sel.getValueType();
1913   SDLoc DL(Sel);
1914   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1915   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1916           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1917          "Failed to constant fold a binop with constant operands");
1918 
1919   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1920   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1921           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1922          "Failed to constant fold a binop with constant operands");
1923 
1924   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1925 }
1926 
1927 SDValue DAGCombiner::visitADD(SDNode *N) {
1928   SDValue N0 = N->getOperand(0);
1929   SDValue N1 = N->getOperand(1);
1930   EVT VT = N0.getValueType();
1931   SDLoc DL(N);
1932 
1933   // fold vector ops
1934   if (VT.isVector()) {
1935     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1936       return FoldedVOp;
1937 
1938     // fold (add x, 0) -> x, vector edition
1939     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1940       return N0;
1941     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1942       return N1;
1943   }
1944 
1945   // fold (add x, undef) -> undef
1946   if (N0.isUndef())
1947     return N0;
1948 
1949   if (N1.isUndef())
1950     return N1;
1951 
1952   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1953     // canonicalize constant to RHS
1954     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1955       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1956     // fold (add c1, c2) -> c1+c2
1957     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1958                                       N1.getNode());
1959   }
1960 
1961   // fold (add x, 0) -> x
1962   if (isNullConstant(N1))
1963     return N0;
1964 
1965   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1966     // fold ((c1-A)+c2) -> (c1+c2)-A
1967     if (N0.getOpcode() == ISD::SUB &&
1968         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1969       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1970       return DAG.getNode(ISD::SUB, DL, VT,
1971                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1972                          N0.getOperand(1));
1973     }
1974 
1975     // add (sext i1 X), 1 -> zext (not i1 X)
1976     // We don't transform this pattern:
1977     //   add (zext i1 X), -1 -> sext (not i1 X)
1978     // because most (?) targets generate better code for the zext form.
1979     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1980         isOneConstantOrOneSplatConstant(N1)) {
1981       SDValue X = N0.getOperand(0);
1982       if ((!LegalOperations ||
1983            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1984             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1985           X.getScalarValueSizeInBits() == 1) {
1986         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1987         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1988       }
1989     }
1990 
1991     // Undo the add -> or combine to merge constant offsets from a frame index.
1992     if (N0.getOpcode() == ISD::OR &&
1993         isa<FrameIndexSDNode>(N0.getOperand(0)) &&
1994         isa<ConstantSDNode>(N0.getOperand(1)) &&
1995         DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
1996       SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
1997       return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
1998     }
1999   }
2000 
2001   if (SDValue NewSel = foldBinOpIntoSelect(N))
2002     return NewSel;
2003 
2004   // reassociate add
2005   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
2006     return RADD;
2007 
2008   // fold ((0-A) + B) -> B-A
2009   if (N0.getOpcode() == ISD::SUB &&
2010       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
2011     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2012 
2013   // fold (A + (0-B)) -> A-B
2014   if (N1.getOpcode() == ISD::SUB &&
2015       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
2016     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2017 
2018   // fold (A+(B-A)) -> B
2019   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2020     return N1.getOperand(0);
2021 
2022   // fold ((B-A)+A) -> B
2023   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2024     return N0.getOperand(0);
2025 
2026   // fold (A+(B-(A+C))) to (B-C)
2027   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2028       N0 == N1.getOperand(1).getOperand(0))
2029     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2030                        N1.getOperand(1).getOperand(1));
2031 
2032   // fold (A+(B-(C+A))) to (B-C)
2033   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2034       N0 == N1.getOperand(1).getOperand(1))
2035     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2036                        N1.getOperand(1).getOperand(0));
2037 
2038   // fold (A+((B-A)+or-C)) to (B+or-C)
2039   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2040       N1.getOperand(0).getOpcode() == ISD::SUB &&
2041       N0 == N1.getOperand(0).getOperand(1))
2042     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2043                        N1.getOperand(1));
2044 
2045   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2046   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2047     SDValue N00 = N0.getOperand(0);
2048     SDValue N01 = N0.getOperand(1);
2049     SDValue N10 = N1.getOperand(0);
2050     SDValue N11 = N1.getOperand(1);
2051 
2052     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2053       return DAG.getNode(ISD::SUB, DL, VT,
2054                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2055                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2056   }
2057 
2058   if (SimplifyDemandedBits(SDValue(N, 0)))
2059     return SDValue(N, 0);
2060 
2061   // fold (a+b) -> (a|b) iff a and b share no bits.
2062   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2063       DAG.haveNoCommonBitsSet(N0, N1))
2064     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2065 
2066   if (SDValue Combined = visitADDLike(N0, N1, N))
2067     return Combined;
2068 
2069   if (SDValue Combined = visitADDLike(N1, N0, N))
2070     return Combined;
2071 
2072   return SDValue();
2073 }
2074 
2075 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2076   bool Masked = false;
2077 
2078   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2079   while (true) {
2080     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2081       V = V.getOperand(0);
2082       continue;
2083     }
2084 
2085     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2086       Masked = true;
2087       V = V.getOperand(0);
2088       continue;
2089     }
2090 
2091     break;
2092   }
2093 
2094   // If this is not a carry, return.
2095   if (V.getResNo() != 1)
2096     return SDValue();
2097 
2098   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2099       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2100     return SDValue();
2101 
2102   // If the result is masked, then no matter what kind of bool it is we can
2103   // return. If it isn't, then we need to make sure the bool type is either 0 or
2104   // 1 and not other values.
2105   if (Masked ||
2106       TLI.getBooleanContents(V.getValueType()) ==
2107           TargetLoweringBase::ZeroOrOneBooleanContent)
2108     return V;
2109 
2110   return SDValue();
2111 }
2112 
2113 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2114   EVT VT = N0.getValueType();
2115   SDLoc DL(LocReference);
2116 
2117   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2118   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2119       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2120     return DAG.getNode(ISD::SUB, DL, VT, N0,
2121                        DAG.getNode(ISD::SHL, DL, VT,
2122                                    N1.getOperand(0).getOperand(1),
2123                                    N1.getOperand(1)));
2124 
2125   if (N1.getOpcode() == ISD::AND) {
2126     SDValue AndOp0 = N1.getOperand(0);
2127     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2128     unsigned DestBits = VT.getScalarSizeInBits();
2129 
2130     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2131     // and similar xforms where the inner op is either ~0 or 0.
2132     if (NumSignBits == DestBits &&
2133         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2134       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2135   }
2136 
2137   // add (sext i1), X -> sub X, (zext i1)
2138   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2139       N0.getOperand(0).getValueType() == MVT::i1 &&
2140       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2141     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2142     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2143   }
2144 
2145   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2146   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2147     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2148     if (TN->getVT() == MVT::i1) {
2149       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2150                                  DAG.getConstant(1, DL, VT));
2151       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2152     }
2153   }
2154 
2155   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2156   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2157     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2158                        N0, N1.getOperand(0), N1.getOperand(2));
2159 
2160   // (add X, Carry) -> (addcarry X, 0, Carry)
2161   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2162     if (SDValue Carry = getAsCarry(TLI, N1))
2163       return DAG.getNode(ISD::ADDCARRY, DL,
2164                          DAG.getVTList(VT, Carry.getValueType()), N0,
2165                          DAG.getConstant(0, DL, VT), Carry);
2166 
2167   return SDValue();
2168 }
2169 
2170 SDValue DAGCombiner::visitADDC(SDNode *N) {
2171   SDValue N0 = N->getOperand(0);
2172   SDValue N1 = N->getOperand(1);
2173   EVT VT = N0.getValueType();
2174   SDLoc DL(N);
2175 
2176   // If the flag result is dead, turn this into an ADD.
2177   if (!N->hasAnyUseOfValue(1))
2178     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2179                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2180 
2181   // canonicalize constant to RHS.
2182   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2183   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2184   if (N0C && !N1C)
2185     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2186 
2187   // fold (addc x, 0) -> x + no carry out
2188   if (isNullConstant(N1))
2189     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2190                                         DL, MVT::Glue));
2191 
2192   // If it cannot overflow, transform into an add.
2193   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2194     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2195                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2196 
2197   return SDValue();
2198 }
2199 
2200 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2201   SDValue N0 = N->getOperand(0);
2202   SDValue N1 = N->getOperand(1);
2203   EVT VT = N0.getValueType();
2204   if (VT.isVector())
2205     return SDValue();
2206 
2207   EVT CarryVT = N->getValueType(1);
2208   SDLoc DL(N);
2209 
2210   // If the flag result is dead, turn this into an ADD.
2211   if (!N->hasAnyUseOfValue(1))
2212     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2213                      DAG.getUNDEF(CarryVT));
2214 
2215   // canonicalize constant to RHS.
2216   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2217   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2218   if (N0C && !N1C)
2219     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2220 
2221   // fold (uaddo x, 0) -> x + no carry out
2222   if (isNullConstant(N1))
2223     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2224 
2225   // If it cannot overflow, transform into an add.
2226   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2227     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2228                      DAG.getConstant(0, DL, CarryVT));
2229 
2230   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2231     return Combined;
2232 
2233   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2234     return Combined;
2235 
2236   return SDValue();
2237 }
2238 
2239 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2240   auto VT = N0.getValueType();
2241 
2242   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2243   // If Y + 1 cannot overflow.
2244   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2245     SDValue Y = N1.getOperand(0);
2246     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2247     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2248       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2249                          N1.getOperand(2));
2250   }
2251 
2252   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2253   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2254     if (SDValue Carry = getAsCarry(TLI, N1))
2255       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2256                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2257 
2258   return SDValue();
2259 }
2260 
2261 SDValue DAGCombiner::visitADDE(SDNode *N) {
2262   SDValue N0 = N->getOperand(0);
2263   SDValue N1 = N->getOperand(1);
2264   SDValue CarryIn = N->getOperand(2);
2265 
2266   // canonicalize constant to RHS
2267   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2268   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2269   if (N0C && !N1C)
2270     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2271                        N1, N0, CarryIn);
2272 
2273   // fold (adde x, y, false) -> (addc x, y)
2274   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2275     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2276 
2277   return SDValue();
2278 }
2279 
2280 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2281   SDValue N0 = N->getOperand(0);
2282   SDValue N1 = N->getOperand(1);
2283   SDValue CarryIn = N->getOperand(2);
2284   SDLoc DL(N);
2285 
2286   // canonicalize constant to RHS
2287   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2288   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2289   if (N0C && !N1C)
2290     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2291 
2292   // fold (addcarry x, y, false) -> (uaddo x, y)
2293   if (isNullConstant(CarryIn))
2294     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2295 
2296   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2297   if (isNullConstant(N0) && isNullConstant(N1)) {
2298     EVT VT = N0.getValueType();
2299     EVT CarryVT = CarryIn.getValueType();
2300     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2301     AddToWorklist(CarryExt.getNode());
2302     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2303                                     DAG.getConstant(1, DL, VT)),
2304                      DAG.getConstant(0, DL, CarryVT));
2305   }
2306 
2307   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2308     return Combined;
2309 
2310   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2311     return Combined;
2312 
2313   return SDValue();
2314 }
2315 
2316 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2317                                        SDNode *N) {
2318   // Iff the flag result is dead:
2319   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2320   if ((N0.getOpcode() == ISD::ADD ||
2321        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2322       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2323     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2324                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2325 
2326   /**
2327    * When one of the addcarry argument is itself a carry, we may be facing
2328    * a diamond carry propagation. In which case we try to transform the DAG
2329    * to ensure linear carry propagation if that is possible.
2330    *
2331    * We are trying to get:
2332    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2333    */
2334   if (auto Y = getAsCarry(TLI, N1)) {
2335     /**
2336      *            (uaddo A, B)
2337      *             /       \
2338      *          Carry      Sum
2339      *            |          \
2340      *            | (addcarry *, 0, Z)
2341      *            |       /
2342      *             \   Carry
2343      *              |   /
2344      * (addcarry X, *, *)
2345      */
2346     if (Y.getOpcode() == ISD::UADDO &&
2347         CarryIn.getResNo() == 1 &&
2348         CarryIn.getOpcode() == ISD::ADDCARRY &&
2349         isNullConstant(CarryIn.getOperand(1)) &&
2350         CarryIn.getOperand(0) == Y.getValue(0)) {
2351       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2352                               Y.getOperand(0), Y.getOperand(1),
2353                               CarryIn.getOperand(2));
2354       AddToWorklist(NewY.getNode());
2355       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2356                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2357                          NewY.getValue(1));
2358     }
2359   }
2360 
2361   return SDValue();
2362 }
2363 
2364 // Since it may not be valid to emit a fold to zero for vector initializers
2365 // check if we can before folding.
2366 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2367                              SelectionDAG &DAG, bool LegalOperations,
2368                              bool LegalTypes) {
2369   if (!VT.isVector())
2370     return DAG.getConstant(0, DL, VT);
2371   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2372     return DAG.getConstant(0, DL, VT);
2373   return SDValue();
2374 }
2375 
2376 SDValue DAGCombiner::visitSUB(SDNode *N) {
2377   SDValue N0 = N->getOperand(0);
2378   SDValue N1 = N->getOperand(1);
2379   EVT VT = N0.getValueType();
2380   SDLoc DL(N);
2381 
2382   // fold vector ops
2383   if (VT.isVector()) {
2384     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2385       return FoldedVOp;
2386 
2387     // fold (sub x, 0) -> x, vector edition
2388     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2389       return N0;
2390   }
2391 
2392   // fold (sub x, x) -> 0
2393   // FIXME: Refactor this and xor and other similar operations together.
2394   if (N0 == N1)
2395     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2396   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2397       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2398     // fold (sub c1, c2) -> c1-c2
2399     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2400                                       N1.getNode());
2401   }
2402 
2403   if (SDValue NewSel = foldBinOpIntoSelect(N))
2404     return NewSel;
2405 
2406   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2407 
2408   // fold (sub x, c) -> (add x, -c)
2409   if (N1C) {
2410     return DAG.getNode(ISD::ADD, DL, VT, N0,
2411                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2412   }
2413 
2414   if (isNullConstantOrNullSplatConstant(N0)) {
2415     unsigned BitWidth = VT.getScalarSizeInBits();
2416     // Right-shifting everything out but the sign bit followed by negation is
2417     // the same as flipping arithmetic/logical shift type without the negation:
2418     // -(X >>u 31) -> (X >>s 31)
2419     // -(X >>s 31) -> (X >>u 31)
2420     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2421       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2422       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2423         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2424         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2425           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2426       }
2427     }
2428 
2429     // 0 - X --> 0 if the sub is NUW.
2430     if (N->getFlags().hasNoUnsignedWrap())
2431       return N0;
2432 
2433     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2434       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2435       // N1 must be 0 because negating the minimum signed value is undefined.
2436       if (N->getFlags().hasNoSignedWrap())
2437         return N0;
2438 
2439       // 0 - X --> X if X is 0 or the minimum signed value.
2440       return N1;
2441     }
2442   }
2443 
2444   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2445   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2446     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2447 
2448   // fold A-(A-B) -> B
2449   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2450     return N1.getOperand(1);
2451 
2452   // fold (A+B)-A -> B
2453   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2454     return N0.getOperand(1);
2455 
2456   // fold (A+B)-B -> A
2457   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2458     return N0.getOperand(0);
2459 
2460   // fold C2-(A+C1) -> (C2-C1)-A
2461   if (N1.getOpcode() == ISD::ADD) {
2462     SDValue N11 = N1.getOperand(1);
2463     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2464         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2465       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2466       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2467     }
2468   }
2469 
2470   // fold ((A+(B+or-C))-B) -> A+or-C
2471   if (N0.getOpcode() == ISD::ADD &&
2472       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2473        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2474       N0.getOperand(1).getOperand(0) == N1)
2475     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2476                        N0.getOperand(1).getOperand(1));
2477 
2478   // fold ((A+(C+B))-B) -> A+C
2479   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2480       N0.getOperand(1).getOperand(1) == N1)
2481     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2482                        N0.getOperand(1).getOperand(0));
2483 
2484   // fold ((A-(B-C))-C) -> A-B
2485   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2486       N0.getOperand(1).getOperand(1) == N1)
2487     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2488                        N0.getOperand(1).getOperand(0));
2489 
2490   // If either operand of a sub is undef, the result is undef
2491   if (N0.isUndef())
2492     return N0;
2493   if (N1.isUndef())
2494     return N1;
2495 
2496   // If the relocation model supports it, consider symbol offsets.
2497   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2498     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2499       // fold (sub Sym, c) -> Sym-c
2500       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2501         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2502                                     GA->getOffset() -
2503                                         (uint64_t)N1C->getSExtValue());
2504       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2505       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2506         if (GA->getGlobal() == GB->getGlobal())
2507           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2508                                  DL, VT);
2509     }
2510 
2511   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2512   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2513     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2514     if (TN->getVT() == MVT::i1) {
2515       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2516                                  DAG.getConstant(1, DL, VT));
2517       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2518     }
2519   }
2520 
2521   return SDValue();
2522 }
2523 
2524 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2525   SDValue N0 = N->getOperand(0);
2526   SDValue N1 = N->getOperand(1);
2527   EVT VT = N0.getValueType();
2528   SDLoc DL(N);
2529 
2530   // If the flag result is dead, turn this into an SUB.
2531   if (!N->hasAnyUseOfValue(1))
2532     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2533                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2534 
2535   // fold (subc x, x) -> 0 + no borrow
2536   if (N0 == N1)
2537     return CombineTo(N, DAG.getConstant(0, DL, VT),
2538                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2539 
2540   // fold (subc x, 0) -> x + no borrow
2541   if (isNullConstant(N1))
2542     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2543 
2544   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2545   if (isAllOnesConstant(N0))
2546     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2547                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2548 
2549   return SDValue();
2550 }
2551 
2552 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2553   SDValue N0 = N->getOperand(0);
2554   SDValue N1 = N->getOperand(1);
2555   EVT VT = N0.getValueType();
2556   if (VT.isVector())
2557     return SDValue();
2558 
2559   EVT CarryVT = N->getValueType(1);
2560   SDLoc DL(N);
2561 
2562   // If the flag result is dead, turn this into an SUB.
2563   if (!N->hasAnyUseOfValue(1))
2564     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2565                      DAG.getUNDEF(CarryVT));
2566 
2567   // fold (usubo x, x) -> 0 + no borrow
2568   if (N0 == N1)
2569     return CombineTo(N, DAG.getConstant(0, DL, VT),
2570                      DAG.getConstant(0, DL, CarryVT));
2571 
2572   // fold (usubo x, 0) -> x + no borrow
2573   if (isNullConstant(N1))
2574     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2575 
2576   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2577   if (isAllOnesConstant(N0))
2578     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2579                      DAG.getConstant(0, DL, CarryVT));
2580 
2581   return SDValue();
2582 }
2583 
2584 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2585   SDValue N0 = N->getOperand(0);
2586   SDValue N1 = N->getOperand(1);
2587   SDValue CarryIn = N->getOperand(2);
2588 
2589   // fold (sube x, y, false) -> (subc x, y)
2590   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2591     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2592 
2593   return SDValue();
2594 }
2595 
2596 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2597   SDValue N0 = N->getOperand(0);
2598   SDValue N1 = N->getOperand(1);
2599   SDValue CarryIn = N->getOperand(2);
2600 
2601   // fold (subcarry x, y, false) -> (usubo x, y)
2602   if (isNullConstant(CarryIn))
2603     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2604 
2605   return SDValue();
2606 }
2607 
2608 SDValue DAGCombiner::visitMUL(SDNode *N) {
2609   SDValue N0 = N->getOperand(0);
2610   SDValue N1 = N->getOperand(1);
2611   EVT VT = N0.getValueType();
2612 
2613   // fold (mul x, undef) -> 0
2614   if (N0.isUndef() || N1.isUndef())
2615     return DAG.getConstant(0, SDLoc(N), VT);
2616 
2617   bool N0IsConst = false;
2618   bool N1IsConst = false;
2619   bool N1IsOpaqueConst = false;
2620   bool N0IsOpaqueConst = false;
2621   APInt ConstValue0, ConstValue1;
2622   // fold vector ops
2623   if (VT.isVector()) {
2624     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2625       return FoldedVOp;
2626 
2627     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2628     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2629     assert((!N0IsConst ||
2630             ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) &&
2631            "Splat APInt should be element width");
2632     assert((!N1IsConst ||
2633             ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
2634            "Splat APInt should be element width");
2635   } else {
2636     N0IsConst = isa<ConstantSDNode>(N0);
2637     if (N0IsConst) {
2638       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2639       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2640     }
2641     N1IsConst = isa<ConstantSDNode>(N1);
2642     if (N1IsConst) {
2643       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2644       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2645     }
2646   }
2647 
2648   // fold (mul c1, c2) -> c1*c2
2649   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2650     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2651                                       N0.getNode(), N1.getNode());
2652 
2653   // canonicalize constant to RHS (vector doesn't have to splat)
2654   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2655      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2656     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2657   // fold (mul x, 0) -> 0
2658   if (N1IsConst && ConstValue1.isNullValue())
2659     return N1;
2660   // fold (mul x, 1) -> x
2661   if (N1IsConst && ConstValue1.isOneValue())
2662     return N0;
2663 
2664   if (SDValue NewSel = foldBinOpIntoSelect(N))
2665     return NewSel;
2666 
2667   // fold (mul x, -1) -> 0-x
2668   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2669     SDLoc DL(N);
2670     return DAG.getNode(ISD::SUB, DL, VT,
2671                        DAG.getConstant(0, DL, VT), N0);
2672   }
2673   // fold (mul x, (1 << c)) -> x << c
2674   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2675       DAG.isKnownToBeAPowerOfTwo(N1)) {
2676     SDLoc DL(N);
2677     SDValue LogBase2 = BuildLogBase2(N1, DL);
2678     AddToWorklist(LogBase2.getNode());
2679 
2680     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2681     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2682     AddToWorklist(Trunc.getNode());
2683     return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
2684   }
2685   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2686   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
2687     unsigned Log2Val = (-ConstValue1).logBase2();
2688     SDLoc DL(N);
2689     // FIXME: If the input is something that is easily negated (e.g. a
2690     // single-use add), we should put the negate there.
2691     return DAG.getNode(ISD::SUB, DL, VT,
2692                        DAG.getConstant(0, DL, VT),
2693                        DAG.getNode(ISD::SHL, DL, VT, N0,
2694                             DAG.getConstant(Log2Val, DL,
2695                                       getShiftAmountTy(N0.getValueType()))));
2696   }
2697 
2698   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2699   if (N0.getOpcode() == ISD::SHL &&
2700       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2701       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2702     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2703     if (isConstantOrConstantVector(C3))
2704       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2705   }
2706 
2707   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2708   // use.
2709   {
2710     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2711 
2712     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2713     if (N0.getOpcode() == ISD::SHL &&
2714         isConstantOrConstantVector(N0.getOperand(1)) &&
2715         N0.getNode()->hasOneUse()) {
2716       Sh = N0; Y = N1;
2717     } else if (N1.getOpcode() == ISD::SHL &&
2718                isConstantOrConstantVector(N1.getOperand(1)) &&
2719                N1.getNode()->hasOneUse()) {
2720       Sh = N1; Y = N0;
2721     }
2722 
2723     if (Sh.getNode()) {
2724       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2725       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2726     }
2727   }
2728 
2729   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2730   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2731       N0.getOpcode() == ISD::ADD &&
2732       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2733       isMulAddWithConstProfitable(N, N0, N1))
2734       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2735                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2736                                      N0.getOperand(0), N1),
2737                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2738                                      N0.getOperand(1), N1));
2739 
2740   // reassociate mul
2741   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2742     return RMUL;
2743 
2744   return SDValue();
2745 }
2746 
2747 /// Return true if divmod libcall is available.
2748 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2749                                      const TargetLowering &TLI) {
2750   RTLIB::Libcall LC;
2751   EVT NodeType = Node->getValueType(0);
2752   if (!NodeType.isSimple())
2753     return false;
2754   switch (NodeType.getSimpleVT().SimpleTy) {
2755   default: return false; // No libcall for vector types.
2756   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2757   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2758   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2759   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2760   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2761   }
2762 
2763   return TLI.getLibcallName(LC) != nullptr;
2764 }
2765 
2766 /// Issue divrem if both quotient and remainder are needed.
2767 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2768   if (Node->use_empty())
2769     return SDValue(); // This is a dead node, leave it alone.
2770 
2771   unsigned Opcode = Node->getOpcode();
2772   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2773   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2774 
2775   // DivMod lib calls can still work on non-legal types if using lib-calls.
2776   EVT VT = Node->getValueType(0);
2777   if (VT.isVector() || !VT.isInteger())
2778     return SDValue();
2779 
2780   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2781     return SDValue();
2782 
2783   // If DIVREM is going to get expanded into a libcall,
2784   // but there is no libcall available, then don't combine.
2785   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2786       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2787     return SDValue();
2788 
2789   // If div is legal, it's better to do the normal expansion
2790   unsigned OtherOpcode = 0;
2791   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2792     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2793     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2794       return SDValue();
2795   } else {
2796     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2797     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2798       return SDValue();
2799   }
2800 
2801   SDValue Op0 = Node->getOperand(0);
2802   SDValue Op1 = Node->getOperand(1);
2803   SDValue combined;
2804   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2805          UE = Op0.getNode()->use_end(); UI != UE;) {
2806     SDNode *User = *UI++;
2807     if (User == Node || User->use_empty())
2808       continue;
2809     // Convert the other matching node(s), too;
2810     // otherwise, the DIVREM may get target-legalized into something
2811     // target-specific that we won't be able to recognize.
2812     unsigned UserOpc = User->getOpcode();
2813     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2814         User->getOperand(0) == Op0 &&
2815         User->getOperand(1) == Op1) {
2816       if (!combined) {
2817         if (UserOpc == OtherOpcode) {
2818           SDVTList VTs = DAG.getVTList(VT, VT);
2819           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2820         } else if (UserOpc == DivRemOpc) {
2821           combined = SDValue(User, 0);
2822         } else {
2823           assert(UserOpc == Opcode);
2824           continue;
2825         }
2826       }
2827       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2828         CombineTo(User, combined);
2829       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2830         CombineTo(User, combined.getValue(1));
2831     }
2832   }
2833   return combined;
2834 }
2835 
2836 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2837   SDValue N0 = N->getOperand(0);
2838   SDValue N1 = N->getOperand(1);
2839   EVT VT = N->getValueType(0);
2840   SDLoc DL(N);
2841 
2842   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2843     return DAG.getUNDEF(VT);
2844 
2845   // undef / X -> 0
2846   // undef % X -> 0
2847   if (N0.isUndef())
2848     return DAG.getConstant(0, DL, VT);
2849 
2850   return SDValue();
2851 }
2852 
2853 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2854   SDValue N0 = N->getOperand(0);
2855   SDValue N1 = N->getOperand(1);
2856   EVT VT = N->getValueType(0);
2857 
2858   // fold vector ops
2859   if (VT.isVector())
2860     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2861       return FoldedVOp;
2862 
2863   SDLoc DL(N);
2864 
2865   // fold (sdiv c1, c2) -> c1/c2
2866   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2867   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2868   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2869     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2870   // fold (sdiv X, 1) -> X
2871   if (N1C && N1C->isOne())
2872     return N0;
2873   // fold (sdiv X, -1) -> 0-X
2874   if (N1C && N1C->isAllOnesValue())
2875     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2876 
2877   if (SDValue V = simplifyDivRem(N, DAG))
2878     return V;
2879 
2880   if (SDValue NewSel = foldBinOpIntoSelect(N))
2881     return NewSel;
2882 
2883   // If we know the sign bits of both operands are zero, strength reduce to a
2884   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2885   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2886     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2887 
2888   // fold (sdiv X, pow2) -> simple ops after legalize
2889   // FIXME: We check for the exact bit here because the generic lowering gives
2890   // better results in that case. The target-specific lowering should learn how
2891   // to handle exact sdivs efficiently.
2892   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2893       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2894                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2895     // Target-specific implementation of sdiv x, pow2.
2896     if (SDValue Res = BuildSDIVPow2(N))
2897       return Res;
2898 
2899     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2900 
2901     // Splat the sign bit into the register
2902     SDValue SGN =
2903         DAG.getNode(ISD::SRA, DL, VT, N0,
2904                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2905                                     getShiftAmountTy(N0.getValueType())));
2906     AddToWorklist(SGN.getNode());
2907 
2908     // Add (N0 < 0) ? abs2 - 1 : 0;
2909     SDValue SRL =
2910         DAG.getNode(ISD::SRL, DL, VT, SGN,
2911                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2912                                     getShiftAmountTy(SGN.getValueType())));
2913     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2914     AddToWorklist(SRL.getNode());
2915     AddToWorklist(ADD.getNode());    // Divide by pow2
2916     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2917                   DAG.getConstant(lg2, DL,
2918                                   getShiftAmountTy(ADD.getValueType())));
2919 
2920     // If we're dividing by a positive value, we're done.  Otherwise, we must
2921     // negate the result.
2922     if (N1C->getAPIntValue().isNonNegative())
2923       return SRA;
2924 
2925     AddToWorklist(SRA.getNode());
2926     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2927   }
2928 
2929   // If integer divide is expensive and we satisfy the requirements, emit an
2930   // alternate sequence.  Targets may check function attributes for size/speed
2931   // trade-offs.
2932   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2933   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2934     if (SDValue Op = BuildSDIV(N))
2935       return Op;
2936 
2937   // sdiv, srem -> sdivrem
2938   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2939   // true.  Otherwise, we break the simplification logic in visitREM().
2940   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2941     if (SDValue DivRem = useDivRem(N))
2942         return DivRem;
2943 
2944   return SDValue();
2945 }
2946 
2947 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2948   SDValue N0 = N->getOperand(0);
2949   SDValue N1 = N->getOperand(1);
2950   EVT VT = N->getValueType(0);
2951 
2952   // fold vector ops
2953   if (VT.isVector())
2954     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2955       return FoldedVOp;
2956 
2957   SDLoc DL(N);
2958 
2959   // fold (udiv c1, c2) -> c1/c2
2960   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2961   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2962   if (N0C && N1C)
2963     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2964                                                     N0C, N1C))
2965       return Folded;
2966 
2967   if (SDValue V = simplifyDivRem(N, DAG))
2968     return V;
2969 
2970   if (SDValue NewSel = foldBinOpIntoSelect(N))
2971     return NewSel;
2972 
2973   // fold (udiv x, (1 << c)) -> x >>u c
2974   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2975       DAG.isKnownToBeAPowerOfTwo(N1)) {
2976     SDValue LogBase2 = BuildLogBase2(N1, DL);
2977     AddToWorklist(LogBase2.getNode());
2978 
2979     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2980     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2981     AddToWorklist(Trunc.getNode());
2982     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2983   }
2984 
2985   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2986   if (N1.getOpcode() == ISD::SHL) {
2987     SDValue N10 = N1.getOperand(0);
2988     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2989         DAG.isKnownToBeAPowerOfTwo(N10)) {
2990       SDValue LogBase2 = BuildLogBase2(N10, DL);
2991       AddToWorklist(LogBase2.getNode());
2992 
2993       EVT ADDVT = N1.getOperand(1).getValueType();
2994       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2995       AddToWorklist(Trunc.getNode());
2996       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2997       AddToWorklist(Add.getNode());
2998       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2999     }
3000   }
3001 
3002   // fold (udiv x, c) -> alternate
3003   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
3004   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
3005     if (SDValue Op = BuildUDIV(N))
3006       return Op;
3007 
3008   // sdiv, srem -> sdivrem
3009   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3010   // true.  Otherwise, we break the simplification logic in visitREM().
3011   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3012     if (SDValue DivRem = useDivRem(N))
3013         return DivRem;
3014 
3015   return SDValue();
3016 }
3017 
3018 // handles ISD::SREM and ISD::UREM
3019 SDValue DAGCombiner::visitREM(SDNode *N) {
3020   unsigned Opcode = N->getOpcode();
3021   SDValue N0 = N->getOperand(0);
3022   SDValue N1 = N->getOperand(1);
3023   EVT VT = N->getValueType(0);
3024   bool isSigned = (Opcode == ISD::SREM);
3025   SDLoc DL(N);
3026 
3027   // fold (rem c1, c2) -> c1%c2
3028   ConstantSDNode *N0C = isConstOrConstSplat(N0);
3029   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3030   if (N0C && N1C)
3031     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
3032       return Folded;
3033 
3034   if (SDValue V = simplifyDivRem(N, DAG))
3035     return V;
3036 
3037   if (SDValue NewSel = foldBinOpIntoSelect(N))
3038     return NewSel;
3039 
3040   if (isSigned) {
3041     // If we know the sign bits of both operands are zero, strength reduce to a
3042     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
3043     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3044       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
3045   } else {
3046     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
3047     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
3048       // fold (urem x, pow2) -> (and x, pow2-1)
3049       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3050       AddToWorklist(Add.getNode());
3051       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3052     }
3053     if (N1.getOpcode() == ISD::SHL &&
3054         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
3055       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
3056       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3057       AddToWorklist(Add.getNode());
3058       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3059     }
3060   }
3061 
3062   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
3063 
3064   // If X/C can be simplified by the division-by-constant logic, lower
3065   // X%C to the equivalent of X-X/C*C.
3066   // To avoid mangling nodes, this simplification requires that the combine()
3067   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
3068   // against this by skipping the simplification if isIntDivCheap().  When
3069   // div is not cheap, combine will not return a DIVREM.  Regardless,
3070   // checking cheapness here makes sense since the simplification results in
3071   // fatter code.
3072   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
3073     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3074     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
3075     AddToWorklist(Div.getNode());
3076     SDValue OptimizedDiv = combine(Div.getNode());
3077     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
3078       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
3079              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
3080       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
3081       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3082       AddToWorklist(Mul.getNode());
3083       return Sub;
3084     }
3085   }
3086 
3087   // sdiv, srem -> sdivrem
3088   if (SDValue DivRem = useDivRem(N))
3089     return DivRem.getValue(1);
3090 
3091   return SDValue();
3092 }
3093 
3094 SDValue DAGCombiner::visitMULHS(SDNode *N) {
3095   SDValue N0 = N->getOperand(0);
3096   SDValue N1 = N->getOperand(1);
3097   EVT VT = N->getValueType(0);
3098   SDLoc DL(N);
3099 
3100   // fold (mulhs x, 0) -> 0
3101   if (isNullConstant(N1))
3102     return N1;
3103   // fold (mulhs x, 1) -> (sra x, size(x)-1)
3104   if (isOneConstant(N1)) {
3105     SDLoc DL(N);
3106     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3107                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3108                                        getShiftAmountTy(N0.getValueType())));
3109   }
3110   // fold (mulhs x, undef) -> 0
3111   if (N0.isUndef() || N1.isUndef())
3112     return DAG.getConstant(0, SDLoc(N), VT);
3113 
3114   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3115   // plus a shift.
3116   if (VT.isSimple() && !VT.isVector()) {
3117     MVT Simple = VT.getSimpleVT();
3118     unsigned SimpleSize = Simple.getSizeInBits();
3119     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3120     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3121       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3122       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3123       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3124       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3125             DAG.getConstant(SimpleSize, DL,
3126                             getShiftAmountTy(N1.getValueType())));
3127       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3128     }
3129   }
3130 
3131   return SDValue();
3132 }
3133 
3134 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3135   SDValue N0 = N->getOperand(0);
3136   SDValue N1 = N->getOperand(1);
3137   EVT VT = N->getValueType(0);
3138   SDLoc DL(N);
3139 
3140   // fold (mulhu x, 0) -> 0
3141   if (isNullConstant(N1))
3142     return N1;
3143   // fold (mulhu x, 1) -> 0
3144   if (isOneConstant(N1))
3145     return DAG.getConstant(0, DL, N0.getValueType());
3146   // fold (mulhu x, undef) -> 0
3147   if (N0.isUndef() || N1.isUndef())
3148     return DAG.getConstant(0, DL, VT);
3149 
3150   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3151   // plus a shift.
3152   if (VT.isSimple() && !VT.isVector()) {
3153     MVT Simple = VT.getSimpleVT();
3154     unsigned SimpleSize = Simple.getSizeInBits();
3155     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3156     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3157       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3158       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3159       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3160       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3161             DAG.getConstant(SimpleSize, DL,
3162                             getShiftAmountTy(N1.getValueType())));
3163       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3164     }
3165   }
3166 
3167   return SDValue();
3168 }
3169 
3170 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3171 /// give the opcodes for the two computations that are being performed. Return
3172 /// true if a simplification was made.
3173 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3174                                                 unsigned HiOp) {
3175   // If the high half is not needed, just compute the low half.
3176   bool HiExists = N->hasAnyUseOfValue(1);
3177   if (!HiExists &&
3178       (!LegalOperations ||
3179        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3180     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3181     return CombineTo(N, Res, Res);
3182   }
3183 
3184   // If the low half is not needed, just compute the high half.
3185   bool LoExists = N->hasAnyUseOfValue(0);
3186   if (!LoExists &&
3187       (!LegalOperations ||
3188        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3189     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3190     return CombineTo(N, Res, Res);
3191   }
3192 
3193   // If both halves are used, return as it is.
3194   if (LoExists && HiExists)
3195     return SDValue();
3196 
3197   // If the two computed results can be simplified separately, separate them.
3198   if (LoExists) {
3199     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3200     AddToWorklist(Lo.getNode());
3201     SDValue LoOpt = combine(Lo.getNode());
3202     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3203         (!LegalOperations ||
3204          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3205       return CombineTo(N, LoOpt, LoOpt);
3206   }
3207 
3208   if (HiExists) {
3209     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3210     AddToWorklist(Hi.getNode());
3211     SDValue HiOpt = combine(Hi.getNode());
3212     if (HiOpt.getNode() && HiOpt != Hi &&
3213         (!LegalOperations ||
3214          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3215       return CombineTo(N, HiOpt, HiOpt);
3216   }
3217 
3218   return SDValue();
3219 }
3220 
3221 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3222   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3223     return Res;
3224 
3225   EVT VT = N->getValueType(0);
3226   SDLoc DL(N);
3227 
3228   // If the type is twice as wide is legal, transform the mulhu to a wider
3229   // multiply plus a shift.
3230   if (VT.isSimple() && !VT.isVector()) {
3231     MVT Simple = VT.getSimpleVT();
3232     unsigned SimpleSize = Simple.getSizeInBits();
3233     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3234     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3235       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3236       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3237       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3238       // Compute the high part as N1.
3239       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3240             DAG.getConstant(SimpleSize, DL,
3241                             getShiftAmountTy(Lo.getValueType())));
3242       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3243       // Compute the low part as N0.
3244       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3245       return CombineTo(N, Lo, Hi);
3246     }
3247   }
3248 
3249   return SDValue();
3250 }
3251 
3252 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3253   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3254     return Res;
3255 
3256   EVT VT = N->getValueType(0);
3257   SDLoc DL(N);
3258 
3259   // If the type is twice as wide is legal, transform the mulhu to a wider
3260   // multiply plus a shift.
3261   if (VT.isSimple() && !VT.isVector()) {
3262     MVT Simple = VT.getSimpleVT();
3263     unsigned SimpleSize = Simple.getSizeInBits();
3264     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3265     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3266       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3267       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3268       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3269       // Compute the high part as N1.
3270       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3271             DAG.getConstant(SimpleSize, DL,
3272                             getShiftAmountTy(Lo.getValueType())));
3273       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3274       // Compute the low part as N0.
3275       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3276       return CombineTo(N, Lo, Hi);
3277     }
3278   }
3279 
3280   return SDValue();
3281 }
3282 
3283 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3284   // (smulo x, 2) -> (saddo x, x)
3285   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3286     if (C2->getAPIntValue() == 2)
3287       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3288                          N->getOperand(0), N->getOperand(0));
3289 
3290   return SDValue();
3291 }
3292 
3293 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3294   // (umulo x, 2) -> (uaddo x, x)
3295   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3296     if (C2->getAPIntValue() == 2)
3297       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3298                          N->getOperand(0), N->getOperand(0));
3299 
3300   return SDValue();
3301 }
3302 
3303 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3304   SDValue N0 = N->getOperand(0);
3305   SDValue N1 = N->getOperand(1);
3306   EVT VT = N0.getValueType();
3307 
3308   // fold vector ops
3309   if (VT.isVector())
3310     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3311       return FoldedVOp;
3312 
3313   // fold operation with constant operands.
3314   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3315   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3316   if (N0C && N1C)
3317     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3318 
3319   // canonicalize constant to RHS
3320   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3321      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3322     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3323 
3324   return SDValue();
3325 }
3326 
3327 /// If this is a binary operator with two operands of the same opcode, try to
3328 /// simplify it.
3329 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3330   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3331   EVT VT = N0.getValueType();
3332   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3333 
3334   // Bail early if none of these transforms apply.
3335   if (N0.getNumOperands() == 0) return SDValue();
3336 
3337   // For each of OP in AND/OR/XOR:
3338   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3339   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3340   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3341   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3342   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3343   //
3344   // do not sink logical op inside of a vector extend, since it may combine
3345   // into a vsetcc.
3346   EVT Op0VT = N0.getOperand(0).getValueType();
3347   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3348        N0.getOpcode() == ISD::SIGN_EXTEND ||
3349        N0.getOpcode() == ISD::BSWAP ||
3350        // Avoid infinite looping with PromoteIntBinOp.
3351        (N0.getOpcode() == ISD::ANY_EXTEND &&
3352         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3353        (N0.getOpcode() == ISD::TRUNCATE &&
3354         (!TLI.isZExtFree(VT, Op0VT) ||
3355          !TLI.isTruncateFree(Op0VT, VT)) &&
3356         TLI.isTypeLegal(Op0VT))) &&
3357       !VT.isVector() &&
3358       Op0VT == N1.getOperand(0).getValueType() &&
3359       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3360     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3361                                  N0.getOperand(0).getValueType(),
3362                                  N0.getOperand(0), N1.getOperand(0));
3363     AddToWorklist(ORNode.getNode());
3364     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3365   }
3366 
3367   // For each of OP in SHL/SRL/SRA/AND...
3368   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3369   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3370   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3371   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3372        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3373       N0.getOperand(1) == N1.getOperand(1)) {
3374     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3375                                  N0.getOperand(0).getValueType(),
3376                                  N0.getOperand(0), N1.getOperand(0));
3377     AddToWorklist(ORNode.getNode());
3378     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3379                        ORNode, N0.getOperand(1));
3380   }
3381 
3382   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3383   // Only perform this optimization up until type legalization, before
3384   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3385   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3386   // we don't want to undo this promotion.
3387   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3388   // on scalars.
3389   if ((N0.getOpcode() == ISD::BITCAST ||
3390        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3391        Level <= AfterLegalizeTypes) {
3392     SDValue In0 = N0.getOperand(0);
3393     SDValue In1 = N1.getOperand(0);
3394     EVT In0Ty = In0.getValueType();
3395     EVT In1Ty = In1.getValueType();
3396     SDLoc DL(N);
3397     // If both incoming values are integers, and the original types are the
3398     // same.
3399     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3400       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3401       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3402       AddToWorklist(Op.getNode());
3403       return BC;
3404     }
3405   }
3406 
3407   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3408   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3409   // If both shuffles use the same mask, and both shuffle within a single
3410   // vector, then it is worthwhile to move the swizzle after the operation.
3411   // The type-legalizer generates this pattern when loading illegal
3412   // vector types from memory. In many cases this allows additional shuffle
3413   // optimizations.
3414   // There are other cases where moving the shuffle after the xor/and/or
3415   // is profitable even if shuffles don't perform a swizzle.
3416   // If both shuffles use the same mask, and both shuffles have the same first
3417   // or second operand, then it might still be profitable to move the shuffle
3418   // after the xor/and/or operation.
3419   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3420     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3421     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3422 
3423     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3424            "Inputs to shuffles are not the same type");
3425 
3426     // Check that both shuffles use the same mask. The masks are known to be of
3427     // the same length because the result vector type is the same.
3428     // Check also that shuffles have only one use to avoid introducing extra
3429     // instructions.
3430     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3431         SVN0->getMask().equals(SVN1->getMask())) {
3432       SDValue ShOp = N0->getOperand(1);
3433 
3434       // Don't try to fold this node if it requires introducing a
3435       // build vector of all zeros that might be illegal at this stage.
3436       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3437         if (!LegalTypes)
3438           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3439         else
3440           ShOp = SDValue();
3441       }
3442 
3443       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3444       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3445       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3446       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3447         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3448                                       N0->getOperand(0), N1->getOperand(0));
3449         AddToWorklist(NewNode.getNode());
3450         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3451                                     SVN0->getMask());
3452       }
3453 
3454       // Don't try to fold this node if it requires introducing a
3455       // build vector of all zeros that might be illegal at this stage.
3456       ShOp = N0->getOperand(0);
3457       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3458         if (!LegalTypes)
3459           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3460         else
3461           ShOp = SDValue();
3462       }
3463 
3464       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3465       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3466       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3467       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3468         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3469                                       N0->getOperand(1), N1->getOperand(1));
3470         AddToWorklist(NewNode.getNode());
3471         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3472                                     SVN0->getMask());
3473       }
3474     }
3475   }
3476 
3477   return SDValue();
3478 }
3479 
3480 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3481 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3482                                        const SDLoc &DL) {
3483   SDValue LL, LR, RL, RR, N0CC, N1CC;
3484   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3485       !isSetCCEquivalent(N1, RL, RR, N1CC))
3486     return SDValue();
3487 
3488   assert(N0.getValueType() == N1.getValueType() &&
3489          "Unexpected operand types for bitwise logic op");
3490   assert(LL.getValueType() == LR.getValueType() &&
3491          RL.getValueType() == RR.getValueType() &&
3492          "Unexpected operand types for setcc");
3493 
3494   // If we're here post-legalization or the logic op type is not i1, the logic
3495   // op type must match a setcc result type. Also, all folds require new
3496   // operations on the left and right operands, so those types must match.
3497   EVT VT = N0.getValueType();
3498   EVT OpVT = LL.getValueType();
3499   if (LegalOperations || VT != MVT::i1)
3500     if (VT != getSetCCResultType(OpVT))
3501       return SDValue();
3502   if (OpVT != RL.getValueType())
3503     return SDValue();
3504 
3505   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3506   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3507   bool IsInteger = OpVT.isInteger();
3508   if (LR == RR && CC0 == CC1 && IsInteger) {
3509     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3510     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3511 
3512     // All bits clear?
3513     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3514     // All sign bits clear?
3515     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3516     // Any bits set?
3517     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3518     // Any sign bits set?
3519     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3520 
3521     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3522     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3523     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3524     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3525     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3526       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3527       AddToWorklist(Or.getNode());
3528       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3529     }
3530 
3531     // All bits set?
3532     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3533     // All sign bits set?
3534     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3535     // Any bits clear?
3536     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3537     // Any sign bits clear?
3538     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3539 
3540     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3541     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3542     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3543     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3544     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3545       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3546       AddToWorklist(And.getNode());
3547       return DAG.getSetCC(DL, VT, And, LR, CC1);
3548     }
3549   }
3550 
3551   // TODO: What is the 'or' equivalent of this fold?
3552   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3553   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3554       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3555        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3556     SDValue One = DAG.getConstant(1, DL, OpVT);
3557     SDValue Two = DAG.getConstant(2, DL, OpVT);
3558     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3559     AddToWorklist(Add.getNode());
3560     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3561   }
3562 
3563   // Try more general transforms if the predicates match and the only user of
3564   // the compares is the 'and' or 'or'.
3565   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3566       N0.hasOneUse() && N1.hasOneUse()) {
3567     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3568     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3569     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3570       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3571       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3572       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3573       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3574       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3575     }
3576   }
3577 
3578   // Canonicalize equivalent operands to LL == RL.
3579   if (LL == RR && LR == RL) {
3580     CC1 = ISD::getSetCCSwappedOperands(CC1);
3581     std::swap(RL, RR);
3582   }
3583 
3584   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3585   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3586   if (LL == RL && LR == RR) {
3587     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3588                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3589     if (NewCC != ISD::SETCC_INVALID &&
3590         (!LegalOperations ||
3591          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3592           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3593       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3594   }
3595 
3596   return SDValue();
3597 }
3598 
3599 /// This contains all DAGCombine rules which reduce two values combined by
3600 /// an And operation to a single value. This makes them reusable in the context
3601 /// of visitSELECT(). Rules involving constants are not included as
3602 /// visitSELECT() already handles those cases.
3603 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3604   EVT VT = N1.getValueType();
3605   SDLoc DL(N);
3606 
3607   // fold (and x, undef) -> 0
3608   if (N0.isUndef() || N1.isUndef())
3609     return DAG.getConstant(0, DL, VT);
3610 
3611   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3612     return V;
3613 
3614   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3615       VT.getSizeInBits() <= 64) {
3616     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3617       APInt ADDC = ADDI->getAPIntValue();
3618       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3619         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3620         // immediate for an add, but it is legal if its top c2 bits are set,
3621         // transform the ADD so the immediate doesn't need to be materialized
3622         // in a register.
3623         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3624           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3625                                              SRLI->getZExtValue());
3626           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3627             ADDC |= Mask;
3628             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3629               SDLoc DL0(N0);
3630               SDValue NewAdd =
3631                 DAG.getNode(ISD::ADD, DL0, VT,
3632                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3633               CombineTo(N0.getNode(), NewAdd);
3634               // Return N so it doesn't get rechecked!
3635               return SDValue(N, 0);
3636             }
3637           }
3638         }
3639       }
3640     }
3641   }
3642 
3643   // Reduce bit extract of low half of an integer to the narrower type.
3644   // (and (srl i64:x, K), KMask) ->
3645   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3646   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3647     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3648       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3649         unsigned Size = VT.getSizeInBits();
3650         const APInt &AndMask = CAnd->getAPIntValue();
3651         unsigned ShiftBits = CShift->getZExtValue();
3652 
3653         // Bail out, this node will probably disappear anyway.
3654         if (ShiftBits == 0)
3655           return SDValue();
3656 
3657         unsigned MaskBits = AndMask.countTrailingOnes();
3658         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3659 
3660         if (AndMask.isMask() &&
3661             // Required bits must not span the two halves of the integer and
3662             // must fit in the half size type.
3663             (ShiftBits + MaskBits <= Size / 2) &&
3664             TLI.isNarrowingProfitable(VT, HalfVT) &&
3665             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3666             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3667             TLI.isTruncateFree(VT, HalfVT) &&
3668             TLI.isZExtFree(HalfVT, VT)) {
3669           // The isNarrowingProfitable is to avoid regressions on PPC and
3670           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3671           // on downstream users of this. Those patterns could probably be
3672           // extended to handle extensions mixed in.
3673 
3674           SDValue SL(N0);
3675           assert(MaskBits <= Size);
3676 
3677           // Extracting the highest bit of the low half.
3678           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3679           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3680                                       N0.getOperand(0));
3681 
3682           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3683           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3684           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3685           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3686           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3687         }
3688       }
3689     }
3690   }
3691 
3692   return SDValue();
3693 }
3694 
3695 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3696                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3697                                    bool &NarrowLoad) {
3698   if (!AndC->getAPIntValue().isMask())
3699     return false;
3700 
3701   unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
3702 
3703   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3704   LoadedVT = LoadN->getMemoryVT();
3705 
3706   if (ExtVT == LoadedVT &&
3707       (!LegalOperations ||
3708        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3709     // ZEXTLOAD will match without needing to change the size of the value being
3710     // loaded.
3711     NarrowLoad = false;
3712     return true;
3713   }
3714 
3715   // Do not change the width of a volatile load.
3716   if (LoadN->isVolatile())
3717     return false;
3718 
3719   // Do not generate loads of non-round integer types since these can
3720   // be expensive (and would be wrong if the type is not byte sized).
3721   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3722     return false;
3723 
3724   if (LegalOperations &&
3725       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3726     return false;
3727 
3728   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3729     return false;
3730 
3731   NarrowLoad = true;
3732   return true;
3733 }
3734 
3735 SDValue DAGCombiner::visitAND(SDNode *N) {
3736   SDValue N0 = N->getOperand(0);
3737   SDValue N1 = N->getOperand(1);
3738   EVT VT = N1.getValueType();
3739 
3740   // x & x --> x
3741   if (N0 == N1)
3742     return N0;
3743 
3744   // fold vector ops
3745   if (VT.isVector()) {
3746     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3747       return FoldedVOp;
3748 
3749     // fold (and x, 0) -> 0, vector edition
3750     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3751       // do not return N0, because undef node may exist in N0
3752       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3753                              SDLoc(N), N0.getValueType());
3754     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3755       // do not return N1, because undef node may exist in N1
3756       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3757                              SDLoc(N), N1.getValueType());
3758 
3759     // fold (and x, -1) -> x, vector edition
3760     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3761       return N1;
3762     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3763       return N0;
3764   }
3765 
3766   // fold (and c1, c2) -> c1&c2
3767   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3768   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3769   if (N0C && N1C && !N1C->isOpaque())
3770     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3771   // canonicalize constant to RHS
3772   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3773      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3774     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3775   // fold (and x, -1) -> x
3776   if (isAllOnesConstant(N1))
3777     return N0;
3778   // if (and x, c) is known to be zero, return 0
3779   unsigned BitWidth = VT.getScalarSizeInBits();
3780   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3781                                    APInt::getAllOnesValue(BitWidth)))
3782     return DAG.getConstant(0, SDLoc(N), VT);
3783 
3784   if (SDValue NewSel = foldBinOpIntoSelect(N))
3785     return NewSel;
3786 
3787   // reassociate and
3788   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3789     return RAND;
3790   // fold (and (or x, C), D) -> D if (C & D) == D
3791   if (N1C && N0.getOpcode() == ISD::OR)
3792     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3793       if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue()))
3794         return N1;
3795   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3796   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3797     SDValue N0Op0 = N0.getOperand(0);
3798     APInt Mask = ~N1C->getAPIntValue();
3799     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3800     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3801       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3802                                  N0.getValueType(), N0Op0);
3803 
3804       // Replace uses of the AND with uses of the Zero extend node.
3805       CombineTo(N, Zext);
3806 
3807       // We actually want to replace all uses of the any_extend with the
3808       // zero_extend, to avoid duplicating things.  This will later cause this
3809       // AND to be folded.
3810       CombineTo(N0.getNode(), Zext);
3811       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3812     }
3813   }
3814   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3815   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3816   // already be zero by virtue of the width of the base type of the load.
3817   //
3818   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3819   // more cases.
3820   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3821        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3822        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3823        N0.getOperand(0).getResNo() == 0) ||
3824       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3825     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3826                                          N0 : N0.getOperand(0) );
3827 
3828     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3829     // This can be a pure constant or a vector splat, in which case we treat the
3830     // vector as a scalar and use the splat value.
3831     APInt Constant = APInt::getNullValue(1);
3832     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3833       Constant = C->getAPIntValue();
3834     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3835       APInt SplatValue, SplatUndef;
3836       unsigned SplatBitSize;
3837       bool HasAnyUndefs;
3838       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3839                                              SplatBitSize, HasAnyUndefs);
3840       if (IsSplat) {
3841         // Undef bits can contribute to a possible optimisation if set, so
3842         // set them.
3843         SplatValue |= SplatUndef;
3844 
3845         // The splat value may be something like "0x00FFFFFF", which means 0 for
3846         // the first vector value and FF for the rest, repeating. We need a mask
3847         // that will apply equally to all members of the vector, so AND all the
3848         // lanes of the constant together.
3849         EVT VT = Vector->getValueType(0);
3850         unsigned BitWidth = VT.getScalarSizeInBits();
3851 
3852         // If the splat value has been compressed to a bitlength lower
3853         // than the size of the vector lane, we need to re-expand it to
3854         // the lane size.
3855         if (BitWidth > SplatBitSize)
3856           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3857                SplatBitSize < BitWidth;
3858                SplatBitSize = SplatBitSize * 2)
3859             SplatValue |= SplatValue.shl(SplatBitSize);
3860 
3861         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3862         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3863         if (SplatBitSize % BitWidth == 0) {
3864           Constant = APInt::getAllOnesValue(BitWidth);
3865           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3866             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3867         }
3868       }
3869     }
3870 
3871     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3872     // actually legal and isn't going to get expanded, else this is a false
3873     // optimisation.
3874     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3875                                                     Load->getValueType(0),
3876                                                     Load->getMemoryVT());
3877 
3878     // Resize the constant to the same size as the original memory access before
3879     // extension. If it is still the AllOnesValue then this AND is completely
3880     // unneeded.
3881     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3882 
3883     bool B;
3884     switch (Load->getExtensionType()) {
3885     default: B = false; break;
3886     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3887     case ISD::ZEXTLOAD:
3888     case ISD::NON_EXTLOAD: B = true; break;
3889     }
3890 
3891     if (B && Constant.isAllOnesValue()) {
3892       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3893       // preserve semantics once we get rid of the AND.
3894       SDValue NewLoad(Load, 0);
3895 
3896       // Fold the AND away. NewLoad may get replaced immediately.
3897       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3898 
3899       if (Load->getExtensionType() == ISD::EXTLOAD) {
3900         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3901                               Load->getValueType(0), SDLoc(Load),
3902                               Load->getChain(), Load->getBasePtr(),
3903                               Load->getOffset(), Load->getMemoryVT(),
3904                               Load->getMemOperand());
3905         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3906         if (Load->getNumValues() == 3) {
3907           // PRE/POST_INC loads have 3 values.
3908           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3909                            NewLoad.getValue(2) };
3910           CombineTo(Load, To, 3, true);
3911         } else {
3912           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3913         }
3914       }
3915 
3916       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3917     }
3918   }
3919 
3920   // fold (and (load x), 255) -> (zextload x, i8)
3921   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3922   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3923   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3924                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3925                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3926     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3927     LoadSDNode *LN0 = HasAnyExt
3928       ? cast<LoadSDNode>(N0.getOperand(0))
3929       : cast<LoadSDNode>(N0);
3930     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3931         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3932       auto NarrowLoad = false;
3933       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3934       EVT ExtVT, LoadedVT;
3935       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3936                            NarrowLoad)) {
3937         if (!NarrowLoad) {
3938           SDValue NewLoad =
3939             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3940                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3941                            LN0->getMemOperand());
3942           AddToWorklist(N);
3943           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3944           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3945         } else {
3946           EVT PtrType = LN0->getOperand(1).getValueType();
3947 
3948           unsigned Alignment = LN0->getAlignment();
3949           SDValue NewPtr = LN0->getBasePtr();
3950 
3951           // For big endian targets, we need to add an offset to the pointer
3952           // to load the correct bytes.  For little endian systems, we merely
3953           // need to read fewer bytes from the same pointer.
3954           if (DAG.getDataLayout().isBigEndian()) {
3955             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3956             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3957             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3958             SDLoc DL(LN0);
3959             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3960                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3961             Alignment = MinAlign(Alignment, PtrOff);
3962           }
3963 
3964           AddToWorklist(NewPtr.getNode());
3965 
3966           SDValue Load = DAG.getExtLoad(
3967               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3968               LN0->getPointerInfo(), ExtVT, Alignment,
3969               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3970           AddToWorklist(N);
3971           CombineTo(LN0, Load, Load.getValue(1));
3972           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3973         }
3974       }
3975     }
3976   }
3977 
3978   if (SDValue Combined = visitANDLike(N0, N1, N))
3979     return Combined;
3980 
3981   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3982   if (N0.getOpcode() == N1.getOpcode())
3983     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3984       return Tmp;
3985 
3986   // Masking the negated extension of a boolean is just the zero-extended
3987   // boolean:
3988   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3989   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3990   //
3991   // Note: the SimplifyDemandedBits fold below can make an information-losing
3992   // transform, and then we have no way to find this better fold.
3993   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3994     if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
3995       SDValue SubRHS = N0.getOperand(1);
3996       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3997           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3998         return SubRHS;
3999       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
4000           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4001         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
4002     }
4003   }
4004 
4005   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
4006   // fold (and (sra)) -> (and (srl)) when possible.
4007   if (SimplifyDemandedBits(SDValue(N, 0)))
4008     return SDValue(N, 0);
4009 
4010   // fold (zext_inreg (extload x)) -> (zextload x)
4011   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
4012     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4013     EVT MemVT = LN0->getMemoryVT();
4014     // If we zero all the possible extended bits, then we can turn this into
4015     // a zextload if we are running before legalize or the operation is legal.
4016     unsigned BitWidth = N1.getScalarValueSizeInBits();
4017     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4018                            BitWidth - MemVT.getScalarSizeInBits())) &&
4019         ((!LegalOperations && !LN0->isVolatile()) ||
4020          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4021       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4022                                        LN0->getChain(), LN0->getBasePtr(),
4023                                        MemVT, LN0->getMemOperand());
4024       AddToWorklist(N);
4025       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4026       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4027     }
4028   }
4029   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
4030   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4031       N0.hasOneUse()) {
4032     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4033     EVT MemVT = LN0->getMemoryVT();
4034     // If we zero all the possible extended bits, then we can turn this into
4035     // a zextload if we are running before legalize or the operation is legal.
4036     unsigned BitWidth = N1.getScalarValueSizeInBits();
4037     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4038                            BitWidth - MemVT.getScalarSizeInBits())) &&
4039         ((!LegalOperations && !LN0->isVolatile()) ||
4040          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4041       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4042                                        LN0->getChain(), LN0->getBasePtr(),
4043                                        MemVT, LN0->getMemOperand());
4044       AddToWorklist(N);
4045       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4046       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4047     }
4048   }
4049   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
4050   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
4051     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4052                                            N0.getOperand(1), false))
4053       return BSwap;
4054   }
4055 
4056   return SDValue();
4057 }
4058 
4059 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
4060 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
4061                                         bool DemandHighBits) {
4062   if (!LegalOperations)
4063     return SDValue();
4064 
4065   EVT VT = N->getValueType(0);
4066   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
4067     return SDValue();
4068   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4069     return SDValue();
4070 
4071   // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
4072   bool LookPassAnd0 = false;
4073   bool LookPassAnd1 = false;
4074   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
4075       std::swap(N0, N1);
4076   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
4077       std::swap(N0, N1);
4078   if (N0.getOpcode() == ISD::AND) {
4079     if (!N0.getNode()->hasOneUse())
4080       return SDValue();
4081     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4082     if (!N01C || N01C->getZExtValue() != 0xFF00)
4083       return SDValue();
4084     N0 = N0.getOperand(0);
4085     LookPassAnd0 = true;
4086   }
4087 
4088   if (N1.getOpcode() == ISD::AND) {
4089     if (!N1.getNode()->hasOneUse())
4090       return SDValue();
4091     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4092     if (!N11C || N11C->getZExtValue() != 0xFF)
4093       return SDValue();
4094     N1 = N1.getOperand(0);
4095     LookPassAnd1 = true;
4096   }
4097 
4098   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
4099     std::swap(N0, N1);
4100   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4101     return SDValue();
4102   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4103     return SDValue();
4104 
4105   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4106   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4107   if (!N01C || !N11C)
4108     return SDValue();
4109   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4110     return SDValue();
4111 
4112   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4113   SDValue N00 = N0->getOperand(0);
4114   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4115     if (!N00.getNode()->hasOneUse())
4116       return SDValue();
4117     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4118     if (!N001C || N001C->getZExtValue() != 0xFF)
4119       return SDValue();
4120     N00 = N00.getOperand(0);
4121     LookPassAnd0 = true;
4122   }
4123 
4124   SDValue N10 = N1->getOperand(0);
4125   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4126     if (!N10.getNode()->hasOneUse())
4127       return SDValue();
4128     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4129     if (!N101C || N101C->getZExtValue() != 0xFF00)
4130       return SDValue();
4131     N10 = N10.getOperand(0);
4132     LookPassAnd1 = true;
4133   }
4134 
4135   if (N00 != N10)
4136     return SDValue();
4137 
4138   // Make sure everything beyond the low halfword gets set to zero since the SRL
4139   // 16 will clear the top bits.
4140   unsigned OpSizeInBits = VT.getSizeInBits();
4141   if (DemandHighBits && OpSizeInBits > 16) {
4142     // If the left-shift isn't masked out then the only way this is a bswap is
4143     // if all bits beyond the low 8 are 0. In that case the entire pattern
4144     // reduces to a left shift anyway: leave it for other parts of the combiner.
4145     if (!LookPassAnd0)
4146       return SDValue();
4147 
4148     // However, if the right shift isn't masked out then it might be because
4149     // it's not needed. See if we can spot that too.
4150     if (!LookPassAnd1 &&
4151         !DAG.MaskedValueIsZero(
4152             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4153       return SDValue();
4154   }
4155 
4156   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4157   if (OpSizeInBits > 16) {
4158     SDLoc DL(N);
4159     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4160                       DAG.getConstant(OpSizeInBits - 16, DL,
4161                                       getShiftAmountTy(VT)));
4162   }
4163   return Res;
4164 }
4165 
4166 /// Return true if the specified node is an element that makes up a 32-bit
4167 /// packed halfword byteswap.
4168 /// ((x & 0x000000ff) << 8) |
4169 /// ((x & 0x0000ff00) >> 8) |
4170 /// ((x & 0x00ff0000) << 8) |
4171 /// ((x & 0xff000000) >> 8)
4172 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4173   if (!N.getNode()->hasOneUse())
4174     return false;
4175 
4176   unsigned Opc = N.getOpcode();
4177   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4178     return false;
4179 
4180   SDValue N0 = N.getOperand(0);
4181   unsigned Opc0 = N0.getOpcode();
4182   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4183     return false;
4184 
4185   ConstantSDNode *N1C = nullptr;
4186   // SHL or SRL: look upstream for AND mask operand
4187   if (Opc == ISD::AND)
4188     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4189   else if (Opc0 == ISD::AND)
4190     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4191   if (!N1C)
4192     return false;
4193 
4194   unsigned MaskByteOffset;
4195   switch (N1C->getZExtValue()) {
4196   default:
4197     return false;
4198   case 0xFF:       MaskByteOffset = 0; break;
4199   case 0xFF00:     MaskByteOffset = 1; break;
4200   case 0xFF0000:   MaskByteOffset = 2; break;
4201   case 0xFF000000: MaskByteOffset = 3; break;
4202   }
4203 
4204   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4205   if (Opc == ISD::AND) {
4206     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4207       // (x >> 8) & 0xff
4208       // (x >> 8) & 0xff0000
4209       if (Opc0 != ISD::SRL)
4210         return false;
4211       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4212       if (!C || C->getZExtValue() != 8)
4213         return false;
4214     } else {
4215       // (x << 8) & 0xff00
4216       // (x << 8) & 0xff000000
4217       if (Opc0 != ISD::SHL)
4218         return false;
4219       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4220       if (!C || C->getZExtValue() != 8)
4221         return false;
4222     }
4223   } else if (Opc == ISD::SHL) {
4224     // (x & 0xff) << 8
4225     // (x & 0xff0000) << 8
4226     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4227       return false;
4228     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4229     if (!C || C->getZExtValue() != 8)
4230       return false;
4231   } else { // Opc == ISD::SRL
4232     // (x & 0xff00) >> 8
4233     // (x & 0xff000000) >> 8
4234     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4235       return false;
4236     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4237     if (!C || C->getZExtValue() != 8)
4238       return false;
4239   }
4240 
4241   if (Parts[MaskByteOffset])
4242     return false;
4243 
4244   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4245   return true;
4246 }
4247 
4248 /// Match a 32-bit packed halfword bswap. That is
4249 /// ((x & 0x000000ff) << 8) |
4250 /// ((x & 0x0000ff00) >> 8) |
4251 /// ((x & 0x00ff0000) << 8) |
4252 /// ((x & 0xff000000) >> 8)
4253 /// => (rotl (bswap x), 16)
4254 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4255   if (!LegalOperations)
4256     return SDValue();
4257 
4258   EVT VT = N->getValueType(0);
4259   if (VT != MVT::i32)
4260     return SDValue();
4261   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4262     return SDValue();
4263 
4264   // Look for either
4265   // (or (or (and), (and)), (or (and), (and)))
4266   // (or (or (or (and), (and)), (and)), (and))
4267   if (N0.getOpcode() != ISD::OR)
4268     return SDValue();
4269   SDValue N00 = N0.getOperand(0);
4270   SDValue N01 = N0.getOperand(1);
4271   SDNode *Parts[4] = {};
4272 
4273   if (N1.getOpcode() == ISD::OR &&
4274       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4275     // (or (or (and), (and)), (or (and), (and)))
4276     if (!isBSwapHWordElement(N00, Parts))
4277       return SDValue();
4278 
4279     if (!isBSwapHWordElement(N01, Parts))
4280       return SDValue();
4281     SDValue N10 = N1.getOperand(0);
4282     if (!isBSwapHWordElement(N10, Parts))
4283       return SDValue();
4284     SDValue N11 = N1.getOperand(1);
4285     if (!isBSwapHWordElement(N11, Parts))
4286       return SDValue();
4287   } else {
4288     // (or (or (or (and), (and)), (and)), (and))
4289     if (!isBSwapHWordElement(N1, Parts))
4290       return SDValue();
4291     if (!isBSwapHWordElement(N01, Parts))
4292       return SDValue();
4293     if (N00.getOpcode() != ISD::OR)
4294       return SDValue();
4295     SDValue N000 = N00.getOperand(0);
4296     if (!isBSwapHWordElement(N000, Parts))
4297       return SDValue();
4298     SDValue N001 = N00.getOperand(1);
4299     if (!isBSwapHWordElement(N001, Parts))
4300       return SDValue();
4301   }
4302 
4303   // Make sure the parts are all coming from the same node.
4304   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4305     return SDValue();
4306 
4307   SDLoc DL(N);
4308   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4309                               SDValue(Parts[0], 0));
4310 
4311   // Result of the bswap should be rotated by 16. If it's not legal, then
4312   // do  (x << 16) | (x >> 16).
4313   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4314   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4315     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4316   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4317     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4318   return DAG.getNode(ISD::OR, DL, VT,
4319                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4320                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4321 }
4322 
4323 /// This contains all DAGCombine rules which reduce two values combined by
4324 /// an Or operation to a single value \see visitANDLike().
4325 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4326   EVT VT = N1.getValueType();
4327   SDLoc DL(N);
4328 
4329   // fold (or x, undef) -> -1
4330   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4331     return DAG.getAllOnesConstant(DL, VT);
4332 
4333   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4334     return V;
4335 
4336   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4337   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4338       // Don't increase # computations.
4339       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4340     // We can only do this xform if we know that bits from X that are set in C2
4341     // but not in C1 are already zero.  Likewise for Y.
4342     if (const ConstantSDNode *N0O1C =
4343         getAsNonOpaqueConstant(N0.getOperand(1))) {
4344       if (const ConstantSDNode *N1O1C =
4345           getAsNonOpaqueConstant(N1.getOperand(1))) {
4346         // We can only do this xform if we know that bits from X that are set in
4347         // C2 but not in C1 are already zero.  Likewise for Y.
4348         const APInt &LHSMask = N0O1C->getAPIntValue();
4349         const APInt &RHSMask = N1O1C->getAPIntValue();
4350 
4351         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4352             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4353           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4354                                   N0.getOperand(0), N1.getOperand(0));
4355           return DAG.getNode(ISD::AND, DL, VT, X,
4356                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4357         }
4358       }
4359     }
4360   }
4361 
4362   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4363   if (N0.getOpcode() == ISD::AND &&
4364       N1.getOpcode() == ISD::AND &&
4365       N0.getOperand(0) == N1.getOperand(0) &&
4366       // Don't increase # computations.
4367       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4368     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4369                             N0.getOperand(1), N1.getOperand(1));
4370     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4371   }
4372 
4373   return SDValue();
4374 }
4375 
4376 SDValue DAGCombiner::visitOR(SDNode *N) {
4377   SDValue N0 = N->getOperand(0);
4378   SDValue N1 = N->getOperand(1);
4379   EVT VT = N1.getValueType();
4380 
4381   // x | x --> x
4382   if (N0 == N1)
4383     return N0;
4384 
4385   // fold vector ops
4386   if (VT.isVector()) {
4387     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4388       return FoldedVOp;
4389 
4390     // fold (or x, 0) -> x, vector edition
4391     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4392       return N1;
4393     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4394       return N0;
4395 
4396     // fold (or x, -1) -> -1, vector edition
4397     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4398       // do not return N0, because undef node may exist in N0
4399       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4400     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4401       // do not return N1, because undef node may exist in N1
4402       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4403 
4404     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4405     // Do this only if the resulting shuffle is legal.
4406     if (isa<ShuffleVectorSDNode>(N0) &&
4407         isa<ShuffleVectorSDNode>(N1) &&
4408         // Avoid folding a node with illegal type.
4409         TLI.isTypeLegal(VT)) {
4410       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4411       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4412       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4413       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4414       // Ensure both shuffles have a zero input.
4415       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4416         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4417         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4418         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4419         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4420         bool CanFold = true;
4421         int NumElts = VT.getVectorNumElements();
4422         SmallVector<int, 4> Mask(NumElts);
4423 
4424         for (int i = 0; i != NumElts; ++i) {
4425           int M0 = SV0->getMaskElt(i);
4426           int M1 = SV1->getMaskElt(i);
4427 
4428           // Determine if either index is pointing to a zero vector.
4429           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4430           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4431 
4432           // If one element is zero and the otherside is undef, keep undef.
4433           // This also handles the case that both are undef.
4434           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4435             Mask[i] = -1;
4436             continue;
4437           }
4438 
4439           // Make sure only one of the elements is zero.
4440           if (M0Zero == M1Zero) {
4441             CanFold = false;
4442             break;
4443           }
4444 
4445           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4446 
4447           // We have a zero and non-zero element. If the non-zero came from
4448           // SV0 make the index a LHS index. If it came from SV1, make it
4449           // a RHS index. We need to mod by NumElts because we don't care
4450           // which operand it came from in the original shuffles.
4451           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4452         }
4453 
4454         if (CanFold) {
4455           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4456           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4457 
4458           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4459           if (!LegalMask) {
4460             std::swap(NewLHS, NewRHS);
4461             ShuffleVectorSDNode::commuteMask(Mask);
4462             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4463           }
4464 
4465           if (LegalMask)
4466             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4467         }
4468       }
4469     }
4470   }
4471 
4472   // fold (or c1, c2) -> c1|c2
4473   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4474   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4475   if (N0C && N1C && !N1C->isOpaque())
4476     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4477   // canonicalize constant to RHS
4478   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4479      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4480     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4481   // fold (or x, 0) -> x
4482   if (isNullConstant(N1))
4483     return N0;
4484   // fold (or x, -1) -> -1
4485   if (isAllOnesConstant(N1))
4486     return N1;
4487 
4488   if (SDValue NewSel = foldBinOpIntoSelect(N))
4489     return NewSel;
4490 
4491   // fold (or x, c) -> c iff (x & ~c) == 0
4492   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4493     return N1;
4494 
4495   if (SDValue Combined = visitORLike(N0, N1, N))
4496     return Combined;
4497 
4498   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4499   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4500     return BSwap;
4501   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4502     return BSwap;
4503 
4504   // reassociate or
4505   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4506     return ROR;
4507 
4508   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4509   // iff (c1 & c2) != 0.
4510   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4511     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4512       if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4513         if (SDValue COR =
4514                 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4515           return DAG.getNode(
4516               ISD::AND, SDLoc(N), VT,
4517               DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4518         return SDValue();
4519       }
4520     }
4521   }
4522 
4523   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4524   if (N0.getOpcode() == N1.getOpcode())
4525     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4526       return Tmp;
4527 
4528   // See if this is some rotate idiom.
4529   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4530     return SDValue(Rot, 0);
4531 
4532   if (SDValue Load = MatchLoadCombine(N))
4533     return Load;
4534 
4535   // Simplify the operands using demanded-bits information.
4536   if (SimplifyDemandedBits(SDValue(N, 0)))
4537     return SDValue(N, 0);
4538 
4539   return SDValue();
4540 }
4541 
4542 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4543 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4544   if (Op.getOpcode() == ISD::AND) {
4545     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4546       Mask = Op.getOperand(1);
4547       Op = Op.getOperand(0);
4548     } else {
4549       return false;
4550     }
4551   }
4552 
4553   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4554     Shift = Op;
4555     return true;
4556   }
4557 
4558   return false;
4559 }
4560 
4561 // Return true if we can prove that, whenever Neg and Pos are both in the
4562 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4563 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4564 //
4565 //     (or (shift1 X, Neg), (shift2 X, Pos))
4566 //
4567 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4568 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4569 // to consider shift amounts with defined behavior.
4570 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4571   // If EltSize is a power of 2 then:
4572   //
4573   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4574   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4575   //
4576   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4577   // for the stronger condition:
4578   //
4579   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4580   //
4581   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4582   // we can just replace Neg with Neg' for the rest of the function.
4583   //
4584   // In other cases we check for the even stronger condition:
4585   //
4586   //     Neg == EltSize - Pos                                    [B]
4587   //
4588   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4589   // behavior if Pos == 0 (and consequently Neg == EltSize).
4590   //
4591   // We could actually use [A] whenever EltSize is a power of 2, but the
4592   // only extra cases that it would match are those uninteresting ones
4593   // where Neg and Pos are never in range at the same time.  E.g. for
4594   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4595   // as well as (sub 32, Pos), but:
4596   //
4597   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4598   //
4599   // always invokes undefined behavior for 32-bit X.
4600   //
4601   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4602   unsigned MaskLoBits = 0;
4603   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4604     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4605       if (NegC->getAPIntValue() == EltSize - 1) {
4606         Neg = Neg.getOperand(0);
4607         MaskLoBits = Log2_64(EltSize);
4608       }
4609     }
4610   }
4611 
4612   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4613   if (Neg.getOpcode() != ISD::SUB)
4614     return false;
4615   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4616   if (!NegC)
4617     return false;
4618   SDValue NegOp1 = Neg.getOperand(1);
4619 
4620   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4621   // Pos'.  The truncation is redundant for the purpose of the equality.
4622   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4623     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4624       if (PosC->getAPIntValue() == EltSize - 1)
4625         Pos = Pos.getOperand(0);
4626 
4627   // The condition we need is now:
4628   //
4629   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4630   //
4631   // If NegOp1 == Pos then we need:
4632   //
4633   //              EltSize & Mask == NegC & Mask
4634   //
4635   // (because "x & Mask" is a truncation and distributes through subtraction).
4636   APInt Width;
4637   if (Pos == NegOp1)
4638     Width = NegC->getAPIntValue();
4639 
4640   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4641   // Then the condition we want to prove becomes:
4642   //
4643   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4644   //
4645   // which, again because "x & Mask" is a truncation, becomes:
4646   //
4647   //                NegC & Mask == (EltSize - PosC) & Mask
4648   //             EltSize & Mask == (NegC + PosC) & Mask
4649   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4650     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4651       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4652     else
4653       return false;
4654   } else
4655     return false;
4656 
4657   // Now we just need to check that EltSize & Mask == Width & Mask.
4658   if (MaskLoBits)
4659     // EltSize & Mask is 0 since Mask is EltSize - 1.
4660     return Width.getLoBits(MaskLoBits) == 0;
4661   return Width == EltSize;
4662 }
4663 
4664 // A subroutine of MatchRotate used once we have found an OR of two opposite
4665 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4666 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4667 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4668 // Neg with outer conversions stripped away.
4669 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4670                                        SDValue Neg, SDValue InnerPos,
4671                                        SDValue InnerNeg, unsigned PosOpcode,
4672                                        unsigned NegOpcode, const SDLoc &DL) {
4673   // fold (or (shl x, (*ext y)),
4674   //          (srl x, (*ext (sub 32, y)))) ->
4675   //   (rotl x, y) or (rotr x, (sub 32, y))
4676   //
4677   // fold (or (shl x, (*ext (sub 32, y))),
4678   //          (srl x, (*ext y))) ->
4679   //   (rotr x, y) or (rotl x, (sub 32, y))
4680   EVT VT = Shifted.getValueType();
4681   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4682     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4683     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4684                        HasPos ? Pos : Neg).getNode();
4685   }
4686 
4687   return nullptr;
4688 }
4689 
4690 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4691 // idioms for rotate, and if the target supports rotation instructions, generate
4692 // a rot[lr].
4693 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4694   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4695   EVT VT = LHS.getValueType();
4696   if (!TLI.isTypeLegal(VT)) return nullptr;
4697 
4698   // The target must have at least one rotate flavor.
4699   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4700   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4701   if (!HasROTL && !HasROTR) return nullptr;
4702 
4703   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4704   SDValue LHSShift;   // The shift.
4705   SDValue LHSMask;    // AND value if any.
4706   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4707     return nullptr; // Not part of a rotate.
4708 
4709   SDValue RHSShift;   // The shift.
4710   SDValue RHSMask;    // AND value if any.
4711   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4712     return nullptr; // Not part of a rotate.
4713 
4714   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4715     return nullptr;   // Not shifting the same value.
4716 
4717   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4718     return nullptr;   // Shifts must disagree.
4719 
4720   // Canonicalize shl to left side in a shl/srl pair.
4721   if (RHSShift.getOpcode() == ISD::SHL) {
4722     std::swap(LHS, RHS);
4723     std::swap(LHSShift, RHSShift);
4724     std::swap(LHSMask, RHSMask);
4725   }
4726 
4727   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4728   SDValue LHSShiftArg = LHSShift.getOperand(0);
4729   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4730   SDValue RHSShiftArg = RHSShift.getOperand(0);
4731   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4732 
4733   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4734   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4735   auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
4736                                         ConstantSDNode *RHS) {
4737     return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
4738   };
4739   if (matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
4740     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4741                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4742 
4743     // If there is an AND of either shifted operand, apply it to the result.
4744     if (LHSMask.getNode() || RHSMask.getNode()) {
4745       SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4746       SDValue Mask = AllOnes;
4747 
4748       if (LHSMask.getNode()) {
4749         SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
4750         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4751                            DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
4752       }
4753       if (RHSMask.getNode()) {
4754         SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
4755         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4756                            DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
4757       }
4758 
4759       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4760     }
4761 
4762     return Rot.getNode();
4763   }
4764 
4765   // If there is a mask here, and we have a variable shift, we can't be sure
4766   // that we're masking out the right stuff.
4767   if (LHSMask.getNode() || RHSMask.getNode())
4768     return nullptr;
4769 
4770   // If the shift amount is sign/zext/any-extended just peel it off.
4771   SDValue LExtOp0 = LHSShiftAmt;
4772   SDValue RExtOp0 = RHSShiftAmt;
4773   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4774        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4775        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4776        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4777       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4778        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4779        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4780        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4781     LExtOp0 = LHSShiftAmt.getOperand(0);
4782     RExtOp0 = RHSShiftAmt.getOperand(0);
4783   }
4784 
4785   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4786                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4787   if (TryL)
4788     return TryL;
4789 
4790   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4791                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4792   if (TryR)
4793     return TryR;
4794 
4795   return nullptr;
4796 }
4797 
4798 namespace {
4799 
4800 /// Represents known origin of an individual byte in load combine pattern. The
4801 /// value of the byte is either constant zero or comes from memory.
4802 struct ByteProvider {
4803   // For constant zero providers Load is set to nullptr. For memory providers
4804   // Load represents the node which loads the byte from memory.
4805   // ByteOffset is the offset of the byte in the value produced by the load.
4806   LoadSDNode *Load = nullptr;
4807   unsigned ByteOffset = 0;
4808 
4809   ByteProvider() = default;
4810 
4811   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4812     return ByteProvider(Load, ByteOffset);
4813   }
4814 
4815   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4816 
4817   bool isConstantZero() const { return !Load; }
4818   bool isMemory() const { return Load; }
4819 
4820   bool operator==(const ByteProvider &Other) const {
4821     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4822   }
4823 
4824 private:
4825   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4826       : Load(Load), ByteOffset(ByteOffset) {}
4827 };
4828 
4829 } // end anonymous namespace
4830 
4831 /// Recursively traverses the expression calculating the origin of the requested
4832 /// byte of the given value. Returns None if the provider can't be calculated.
4833 ///
4834 /// For all the values except the root of the expression verifies that the value
4835 /// has exactly one use and if it's not true return None. This way if the origin
4836 /// of the byte is returned it's guaranteed that the values which contribute to
4837 /// the byte are not used outside of this expression.
4838 ///
4839 /// Because the parts of the expression are not allowed to have more than one
4840 /// use this function iterates over trees, not DAGs. So it never visits the same
4841 /// node more than once.
4842 static const Optional<ByteProvider>
4843 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
4844                       bool Root = false) {
4845   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4846   if (Depth == 10)
4847     return None;
4848 
4849   if (!Root && !Op.hasOneUse())
4850     return None;
4851 
4852   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4853   unsigned BitWidth = Op.getValueSizeInBits();
4854   if (BitWidth % 8 != 0)
4855     return None;
4856   unsigned ByteWidth = BitWidth / 8;
4857   assert(Index < ByteWidth && "invalid index requested");
4858   (void) ByteWidth;
4859 
4860   switch (Op.getOpcode()) {
4861   case ISD::OR: {
4862     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4863     if (!LHS)
4864       return None;
4865     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4866     if (!RHS)
4867       return None;
4868 
4869     if (LHS->isConstantZero())
4870       return RHS;
4871     if (RHS->isConstantZero())
4872       return LHS;
4873     return None;
4874   }
4875   case ISD::SHL: {
4876     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4877     if (!ShiftOp)
4878       return None;
4879 
4880     uint64_t BitShift = ShiftOp->getZExtValue();
4881     if (BitShift % 8 != 0)
4882       return None;
4883     uint64_t ByteShift = BitShift / 8;
4884 
4885     return Index < ByteShift
4886                ? ByteProvider::getConstantZero()
4887                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4888                                        Depth + 1);
4889   }
4890   case ISD::ANY_EXTEND:
4891   case ISD::SIGN_EXTEND:
4892   case ISD::ZERO_EXTEND: {
4893     SDValue NarrowOp = Op->getOperand(0);
4894     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4895     if (NarrowBitWidth % 8 != 0)
4896       return None;
4897     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4898 
4899     if (Index >= NarrowByteWidth)
4900       return Op.getOpcode() == ISD::ZERO_EXTEND
4901                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4902                  : None;
4903     return calculateByteProvider(NarrowOp, Index, Depth + 1);
4904   }
4905   case ISD::BSWAP:
4906     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4907                                  Depth + 1);
4908   case ISD::LOAD: {
4909     auto L = cast<LoadSDNode>(Op.getNode());
4910     if (L->isVolatile() || L->isIndexed())
4911       return None;
4912 
4913     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4914     if (NarrowBitWidth % 8 != 0)
4915       return None;
4916     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4917 
4918     if (Index >= NarrowByteWidth)
4919       return L->getExtensionType() == ISD::ZEXTLOAD
4920                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4921                  : None;
4922     return ByteProvider::getMemory(L, Index);
4923   }
4924   }
4925 
4926   return None;
4927 }
4928 
4929 /// Match a pattern where a wide type scalar value is loaded by several narrow
4930 /// loads and combined by shifts and ors. Fold it into a single load or a load
4931 /// and a BSWAP if the targets supports it.
4932 ///
4933 /// Assuming little endian target:
4934 ///  i8 *a = ...
4935 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4936 /// =>
4937 ///  i32 val = *((i32)a)
4938 ///
4939 ///  i8 *a = ...
4940 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4941 /// =>
4942 ///  i32 val = BSWAP(*((i32)a))
4943 ///
4944 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4945 /// interact well with the worklist mechanism. When a part of the pattern is
4946 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4947 /// but the root node of the pattern which triggers the load combine is not
4948 /// necessarily a direct user of the changed node. For example, once the address
4949 /// of t28 load is reassociated load combine won't be triggered:
4950 ///             t25: i32 = add t4, Constant:i32<2>
4951 ///           t26: i64 = sign_extend t25
4952 ///        t27: i64 = add t2, t26
4953 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4954 ///     t29: i32 = zero_extend t28
4955 ///   t32: i32 = shl t29, Constant:i8<8>
4956 /// t33: i32 = or t23, t32
4957 /// As a possible fix visitLoad can check if the load can be a part of a load
4958 /// combine pattern and add corresponding OR roots to the worklist.
4959 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4960   assert(N->getOpcode() == ISD::OR &&
4961          "Can only match load combining against OR nodes");
4962 
4963   // Handles simple types only
4964   EVT VT = N->getValueType(0);
4965   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4966     return SDValue();
4967   unsigned ByteWidth = VT.getSizeInBits() / 8;
4968 
4969   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4970   // Before legalize we can introduce too wide illegal loads which will be later
4971   // split into legal sized loads. This enables us to combine i64 load by i8
4972   // patterns to a couple of i32 loads on 32 bit targets.
4973   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4974     return SDValue();
4975 
4976   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4977     unsigned BW, unsigned i) { return i; };
4978   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4979     unsigned BW, unsigned i) { return BW - i - 1; };
4980 
4981   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4982   auto MemoryByteOffset = [&] (ByteProvider P) {
4983     assert(P.isMemory() && "Must be a memory byte provider");
4984     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4985     assert(LoadBitWidth % 8 == 0 &&
4986            "can only analyze providers for individual bytes not bit");
4987     unsigned LoadByteWidth = LoadBitWidth / 8;
4988     return IsBigEndianTarget
4989             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4990             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4991   };
4992 
4993   Optional<BaseIndexOffset> Base;
4994   SDValue Chain;
4995 
4996   SmallSet<LoadSDNode *, 8> Loads;
4997   Optional<ByteProvider> FirstByteProvider;
4998   int64_t FirstOffset = INT64_MAX;
4999 
5000   // Check if all the bytes of the OR we are looking at are loaded from the same
5001   // base address. Collect bytes offsets from Base address in ByteOffsets.
5002   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
5003   for (unsigned i = 0; i < ByteWidth; i++) {
5004     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
5005     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
5006       return SDValue();
5007 
5008     LoadSDNode *L = P->Load;
5009     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
5010            "Must be enforced by calculateByteProvider");
5011     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
5012 
5013     // All loads must share the same chain
5014     SDValue LChain = L->getChain();
5015     if (!Chain)
5016       Chain = LChain;
5017     else if (Chain != LChain)
5018       return SDValue();
5019 
5020     // Loads must share the same base address
5021     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
5022     int64_t ByteOffsetFromBase = 0;
5023     if (!Base)
5024       Base = Ptr;
5025     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
5026       return SDValue();
5027 
5028     // Calculate the offset of the current byte from the base address
5029     ByteOffsetFromBase += MemoryByteOffset(*P);
5030     ByteOffsets[i] = ByteOffsetFromBase;
5031 
5032     // Remember the first byte load
5033     if (ByteOffsetFromBase < FirstOffset) {
5034       FirstByteProvider = P;
5035       FirstOffset = ByteOffsetFromBase;
5036     }
5037 
5038     Loads.insert(L);
5039   }
5040   assert(!Loads.empty() && "All the bytes of the value must be loaded from "
5041          "memory, so there must be at least one load which produces the value");
5042   assert(Base && "Base address of the accessed memory location must be set");
5043   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
5044 
5045   // Check if the bytes of the OR we are looking at match with either big or
5046   // little endian value load
5047   bool BigEndian = true, LittleEndian = true;
5048   for (unsigned i = 0; i < ByteWidth; i++) {
5049     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
5050     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
5051     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
5052     if (!BigEndian && !LittleEndian)
5053       return SDValue();
5054   }
5055   assert((BigEndian != LittleEndian) && "should be either or");
5056   assert(FirstByteProvider && "must be set");
5057 
5058   // Ensure that the first byte is loaded from zero offset of the first load.
5059   // So the combined value can be loaded from the first load address.
5060   if (MemoryByteOffset(*FirstByteProvider) != 0)
5061     return SDValue();
5062   LoadSDNode *FirstLoad = FirstByteProvider->Load;
5063 
5064   // The node we are looking at matches with the pattern, check if we can
5065   // replace it with a single load and bswap if needed.
5066 
5067   // If the load needs byte swap check if the target supports it
5068   bool NeedsBswap = IsBigEndianTarget != BigEndian;
5069 
5070   // Before legalize we can introduce illegal bswaps which will be later
5071   // converted to an explicit bswap sequence. This way we end up with a single
5072   // load and byte shuffling instead of several loads and byte shuffling.
5073   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
5074     return SDValue();
5075 
5076   // Check that a load of the wide type is both allowed and fast on the target
5077   bool Fast = false;
5078   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
5079                                         VT, FirstLoad->getAddressSpace(),
5080                                         FirstLoad->getAlignment(), &Fast);
5081   if (!Allowed || !Fast)
5082     return SDValue();
5083 
5084   SDValue NewLoad =
5085       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
5086                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5087 
5088   // Transfer chain users from old loads to the new load.
5089   for (LoadSDNode *L : Loads)
5090     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5091 
5092   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5093 }
5094 
5095 SDValue DAGCombiner::visitXOR(SDNode *N) {
5096   SDValue N0 = N->getOperand(0);
5097   SDValue N1 = N->getOperand(1);
5098   EVT VT = N0.getValueType();
5099 
5100   // fold vector ops
5101   if (VT.isVector()) {
5102     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5103       return FoldedVOp;
5104 
5105     // fold (xor x, 0) -> x, vector edition
5106     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5107       return N1;
5108     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5109       return N0;
5110   }
5111 
5112   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5113   if (N0.isUndef() && N1.isUndef())
5114     return DAG.getConstant(0, SDLoc(N), VT);
5115   // fold (xor x, undef) -> undef
5116   if (N0.isUndef())
5117     return N0;
5118   if (N1.isUndef())
5119     return N1;
5120   // fold (xor c1, c2) -> c1^c2
5121   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5122   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5123   if (N0C && N1C)
5124     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5125   // canonicalize constant to RHS
5126   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5127      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5128     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5129   // fold (xor x, 0) -> x
5130   if (isNullConstant(N1))
5131     return N0;
5132 
5133   if (SDValue NewSel = foldBinOpIntoSelect(N))
5134     return NewSel;
5135 
5136   // reassociate xor
5137   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5138     return RXOR;
5139 
5140   // fold !(x cc y) -> (x !cc y)
5141   SDValue LHS, RHS, CC;
5142   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5143     bool isInt = LHS.getValueType().isInteger();
5144     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5145                                                isInt);
5146 
5147     if (!LegalOperations ||
5148         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5149       switch (N0.getOpcode()) {
5150       default:
5151         llvm_unreachable("Unhandled SetCC Equivalent!");
5152       case ISD::SETCC:
5153         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5154       case ISD::SELECT_CC:
5155         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5156                                N0.getOperand(3), NotCC);
5157       }
5158     }
5159   }
5160 
5161   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5162   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5163       N0.getNode()->hasOneUse() &&
5164       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5165     SDValue V = N0.getOperand(0);
5166     SDLoc DL(N0);
5167     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5168                     DAG.getConstant(1, DL, V.getValueType()));
5169     AddToWorklist(V.getNode());
5170     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5171   }
5172 
5173   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5174   if (isOneConstant(N1) && VT == MVT::i1 &&
5175       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5176     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5177     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5178       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5179       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5180       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5181       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5182       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5183     }
5184   }
5185   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5186   if (isAllOnesConstant(N1) &&
5187       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5188     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5189     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5190       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5191       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5192       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5193       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5194       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5195     }
5196   }
5197   // fold (xor (and x, y), y) -> (and (not x), y)
5198   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5199       N0->getOperand(1) == N1) {
5200     SDValue X = N0->getOperand(0);
5201     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5202     AddToWorklist(NotX.getNode());
5203     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5204   }
5205   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5206   if (N1C && N0.getOpcode() == ISD::XOR) {
5207     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5208       SDLoc DL(N);
5209       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5210                          DAG.getConstant(N1C->getAPIntValue() ^
5211                                          N00C->getAPIntValue(), DL, VT));
5212     }
5213     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5214       SDLoc DL(N);
5215       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5216                          DAG.getConstant(N1C->getAPIntValue() ^
5217                                          N01C->getAPIntValue(), DL, VT));
5218     }
5219   }
5220 
5221   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5222   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5223   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5224       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5225       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5226     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5227       if (C->getAPIntValue() == (OpSizeInBits - 1))
5228         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5229   }
5230 
5231   // fold (xor x, x) -> 0
5232   if (N0 == N1)
5233     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5234 
5235   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5236   // Here is a concrete example of this equivalence:
5237   // i16   x ==  14
5238   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5239   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5240   //
5241   // =>
5242   //
5243   // i16     ~1      == 0b1111111111111110
5244   // i16 rol(~1, 14) == 0b1011111111111111
5245   //
5246   // Some additional tips to help conceptualize this transform:
5247   // - Try to see the operation as placing a single zero in a value of all ones.
5248   // - There exists no value for x which would allow the result to contain zero.
5249   // - Values of x larger than the bitwidth are undefined and do not require a
5250   //   consistent result.
5251   // - Pushing the zero left requires shifting one bits in from the right.
5252   // A rotate left of ~1 is a nice way of achieving the desired result.
5253   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5254       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5255     SDLoc DL(N);
5256     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5257                        N0.getOperand(1));
5258   }
5259 
5260   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5261   if (N0.getOpcode() == N1.getOpcode())
5262     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5263       return Tmp;
5264 
5265   // Simplify the expression using non-local knowledge.
5266   if (SimplifyDemandedBits(SDValue(N, 0)))
5267     return SDValue(N, 0);
5268 
5269   return SDValue();
5270 }
5271 
5272 /// Handle transforms common to the three shifts, when the shift amount is a
5273 /// constant.
5274 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5275   SDNode *LHS = N->getOperand(0).getNode();
5276   if (!LHS->hasOneUse()) return SDValue();
5277 
5278   // We want to pull some binops through shifts, so that we have (and (shift))
5279   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5280   // thing happens with address calculations, so it's important to canonicalize
5281   // it.
5282   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5283 
5284   switch (LHS->getOpcode()) {
5285   default: return SDValue();
5286   case ISD::OR:
5287   case ISD::XOR:
5288     HighBitSet = false; // We can only transform sra if the high bit is clear.
5289     break;
5290   case ISD::AND:
5291     HighBitSet = true;  // We can only transform sra if the high bit is set.
5292     break;
5293   case ISD::ADD:
5294     if (N->getOpcode() != ISD::SHL)
5295       return SDValue(); // only shl(add) not sr[al](add).
5296     HighBitSet = false; // We can only transform sra if the high bit is clear.
5297     break;
5298   }
5299 
5300   // We require the RHS of the binop to be a constant and not opaque as well.
5301   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5302   if (!BinOpCst) return SDValue();
5303 
5304   // FIXME: disable this unless the input to the binop is a shift by a constant
5305   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5306   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5307   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5308                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5309                  BinOpLHSVal->getOpcode() == ISD::SRL;
5310   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5311                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5312 
5313   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5314       !isCopyOrSelect)
5315     return SDValue();
5316 
5317   if (isCopyOrSelect && N->hasOneUse())
5318     return SDValue();
5319 
5320   EVT VT = N->getValueType(0);
5321 
5322   // If this is a signed shift right, and the high bit is modified by the
5323   // logical operation, do not perform the transformation. The highBitSet
5324   // boolean indicates the value of the high bit of the constant which would
5325   // cause it to be modified for this operation.
5326   if (N->getOpcode() == ISD::SRA) {
5327     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5328     if (BinOpRHSSignSet != HighBitSet)
5329       return SDValue();
5330   }
5331 
5332   if (!TLI.isDesirableToCommuteWithShift(LHS))
5333     return SDValue();
5334 
5335   // Fold the constants, shifting the binop RHS by the shift amount.
5336   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5337                                N->getValueType(0),
5338                                LHS->getOperand(1), N->getOperand(1));
5339   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5340 
5341   // Create the new shift.
5342   SDValue NewShift = DAG.getNode(N->getOpcode(),
5343                                  SDLoc(LHS->getOperand(0)),
5344                                  VT, LHS->getOperand(0), N->getOperand(1));
5345 
5346   // Create the new binop.
5347   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5348 }
5349 
5350 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5351   assert(N->getOpcode() == ISD::TRUNCATE);
5352   assert(N->getOperand(0).getOpcode() == ISD::AND);
5353 
5354   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5355   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5356     SDValue N01 = N->getOperand(0).getOperand(1);
5357     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5358       SDLoc DL(N);
5359       EVT TruncVT = N->getValueType(0);
5360       SDValue N00 = N->getOperand(0).getOperand(0);
5361       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5362       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5363       AddToWorklist(Trunc00.getNode());
5364       AddToWorklist(Trunc01.getNode());
5365       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5366     }
5367   }
5368 
5369   return SDValue();
5370 }
5371 
5372 SDValue DAGCombiner::visitRotate(SDNode *N) {
5373   SDLoc dl(N);
5374   SDValue N0 = N->getOperand(0);
5375   SDValue N1 = N->getOperand(1);
5376   EVT VT = N->getValueType(0);
5377   unsigned Bitsize = VT.getScalarSizeInBits();
5378 
5379   // fold (rot x, 0) -> x
5380   if (isNullConstantOrNullSplatConstant(N1))
5381     return N0;
5382 
5383   // fold (rot x, c) -> (rot x, c % BitSize)
5384   if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5385     if (Cst->getAPIntValue().uge(Bitsize)) {
5386       uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5387       return DAG.getNode(N->getOpcode(), dl, VT, N0,
5388                          DAG.getConstant(RotAmt, dl, N1.getValueType()));
5389     }
5390   }
5391 
5392   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5393   if (N1.getOpcode() == ISD::TRUNCATE &&
5394       N1.getOperand(0).getOpcode() == ISD::AND) {
5395     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5396       return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5397   }
5398 
5399   unsigned NextOp = N0.getOpcode();
5400   // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5401   if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5402     SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5403     SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5404     if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5405       EVT ShiftVT = C1->getValueType(0);
5406       bool SameSide = (N->getOpcode() == NextOp);
5407       unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5408       if (SDValue CombinedShift =
5409               DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5410         SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5411         SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5412             ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5413             BitsizeC.getNode());
5414         return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5415                            CombinedShiftNorm);
5416       }
5417     }
5418   }
5419   return SDValue();
5420 }
5421 
5422 SDValue DAGCombiner::visitSHL(SDNode *N) {
5423   SDValue N0 = N->getOperand(0);
5424   SDValue N1 = N->getOperand(1);
5425   EVT VT = N0.getValueType();
5426   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5427 
5428   // fold vector ops
5429   if (VT.isVector()) {
5430     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5431       return FoldedVOp;
5432 
5433     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5434     // If setcc produces all-one true value then:
5435     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5436     if (N1CV && N1CV->isConstant()) {
5437       if (N0.getOpcode() == ISD::AND) {
5438         SDValue N00 = N0->getOperand(0);
5439         SDValue N01 = N0->getOperand(1);
5440         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5441 
5442         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5443             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5444                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5445           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5446                                                      N01CV, N1CV))
5447             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5448         }
5449       }
5450     }
5451   }
5452 
5453   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5454 
5455   // fold (shl c1, c2) -> c1<<c2
5456   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5457   if (N0C && N1C && !N1C->isOpaque())
5458     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5459   // fold (shl 0, x) -> 0
5460   if (isNullConstantOrNullSplatConstant(N0))
5461     return N0;
5462   // fold (shl x, c >= size(x)) -> undef
5463   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5464   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5465     return Val->getAPIntValue().uge(OpSizeInBits);
5466   };
5467   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5468     return DAG.getUNDEF(VT);
5469   // fold (shl x, 0) -> x
5470   if (N1C && N1C->isNullValue())
5471     return N0;
5472   // fold (shl undef, x) -> 0
5473   if (N0.isUndef())
5474     return DAG.getConstant(0, SDLoc(N), VT);
5475 
5476   if (SDValue NewSel = foldBinOpIntoSelect(N))
5477     return NewSel;
5478 
5479   // if (shl x, c) is known to be zero, return 0
5480   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5481                             APInt::getAllOnesValue(OpSizeInBits)))
5482     return DAG.getConstant(0, SDLoc(N), VT);
5483   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5484   if (N1.getOpcode() == ISD::TRUNCATE &&
5485       N1.getOperand(0).getOpcode() == ISD::AND) {
5486     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5487       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5488   }
5489 
5490   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5491     return SDValue(N, 0);
5492 
5493   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5494   if (N0.getOpcode() == ISD::SHL) {
5495     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5496                                           ConstantSDNode *RHS) {
5497       APInt c1 = LHS->getAPIntValue();
5498       APInt c2 = RHS->getAPIntValue();
5499       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5500       return (c1 + c2).uge(OpSizeInBits);
5501     };
5502     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5503       return DAG.getConstant(0, SDLoc(N), VT);
5504 
5505     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5506                                        ConstantSDNode *RHS) {
5507       APInt c1 = LHS->getAPIntValue();
5508       APInt c2 = RHS->getAPIntValue();
5509       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5510       return (c1 + c2).ult(OpSizeInBits);
5511     };
5512     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5513       SDLoc DL(N);
5514       EVT ShiftVT = N1.getValueType();
5515       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5516       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
5517     }
5518   }
5519 
5520   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5521   // For this to be valid, the second form must not preserve any of the bits
5522   // that are shifted out by the inner shift in the first form.  This means
5523   // the outer shift size must be >= the number of bits added by the ext.
5524   // As a corollary, we don't care what kind of ext it is.
5525   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5526               N0.getOpcode() == ISD::ANY_EXTEND ||
5527               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5528       N0.getOperand(0).getOpcode() == ISD::SHL) {
5529     SDValue N0Op0 = N0.getOperand(0);
5530     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5531       APInt c1 = N0Op0C1->getAPIntValue();
5532       APInt c2 = N1C->getAPIntValue();
5533       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5534 
5535       EVT InnerShiftVT = N0Op0.getValueType();
5536       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5537       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5538         SDLoc DL(N0);
5539         APInt Sum = c1 + c2;
5540         if (Sum.uge(OpSizeInBits))
5541           return DAG.getConstant(0, DL, VT);
5542 
5543         return DAG.getNode(
5544             ISD::SHL, DL, VT,
5545             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5546             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5547       }
5548     }
5549   }
5550 
5551   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5552   // Only fold this if the inner zext has no other uses to avoid increasing
5553   // the total number of instructions.
5554   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5555       N0.getOperand(0).getOpcode() == ISD::SRL) {
5556     SDValue N0Op0 = N0.getOperand(0);
5557     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5558       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5559         uint64_t c1 = N0Op0C1->getZExtValue();
5560         uint64_t c2 = N1C->getZExtValue();
5561         if (c1 == c2) {
5562           SDValue NewOp0 = N0.getOperand(0);
5563           EVT CountVT = NewOp0.getOperand(1).getValueType();
5564           SDLoc DL(N);
5565           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5566                                        NewOp0,
5567                                        DAG.getConstant(c2, DL, CountVT));
5568           AddToWorklist(NewSHL.getNode());
5569           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5570         }
5571       }
5572     }
5573   }
5574 
5575   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5576   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5577   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5578       N0->getFlags().hasExact()) {
5579     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5580       uint64_t C1 = N0C1->getZExtValue();
5581       uint64_t C2 = N1C->getZExtValue();
5582       SDLoc DL(N);
5583       if (C1 <= C2)
5584         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5585                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5586       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5587                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5588     }
5589   }
5590 
5591   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5592   //                               (and (srl x, (sub c1, c2), MASK)
5593   // Only fold this if the inner shift has no other uses -- if it does, folding
5594   // this will increase the total number of instructions.
5595   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5596     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5597       uint64_t c1 = N0C1->getZExtValue();
5598       if (c1 < OpSizeInBits) {
5599         uint64_t c2 = N1C->getZExtValue();
5600         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5601         SDValue Shift;
5602         if (c2 > c1) {
5603           Mask <<= c2 - c1;
5604           SDLoc DL(N);
5605           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5606                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5607         } else {
5608           Mask.lshrInPlace(c1 - c2);
5609           SDLoc DL(N);
5610           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5611                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5612         }
5613         SDLoc DL(N0);
5614         return DAG.getNode(ISD::AND, DL, VT, Shift,
5615                            DAG.getConstant(Mask, DL, VT));
5616       }
5617     }
5618   }
5619 
5620   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5621   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5622       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5623     SDLoc DL(N);
5624     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5625     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5626     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5627   }
5628 
5629   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5630   // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
5631   // Variant of version done on multiply, except mul by a power of 2 is turned
5632   // into a shift.
5633   if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
5634       N0.getNode()->hasOneUse() &&
5635       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5636       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5637     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5638     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5639     AddToWorklist(Shl0.getNode());
5640     AddToWorklist(Shl1.getNode());
5641     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
5642   }
5643 
5644   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5645   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5646       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5647       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5648     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5649     if (isConstantOrConstantVector(Shl))
5650       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5651   }
5652 
5653   if (N1C && !N1C->isOpaque())
5654     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5655       return NewSHL;
5656 
5657   return SDValue();
5658 }
5659 
5660 SDValue DAGCombiner::visitSRA(SDNode *N) {
5661   SDValue N0 = N->getOperand(0);
5662   SDValue N1 = N->getOperand(1);
5663   EVT VT = N0.getValueType();
5664   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5665 
5666   // Arithmetic shifting an all-sign-bit value is a no-op.
5667   // fold (sra 0, x) -> 0
5668   // fold (sra -1, x) -> -1
5669   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5670     return N0;
5671 
5672   // fold vector ops
5673   if (VT.isVector())
5674     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5675       return FoldedVOp;
5676 
5677   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5678 
5679   // fold (sra c1, c2) -> (sra c1, c2)
5680   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5681   if (N0C && N1C && !N1C->isOpaque())
5682     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5683   // fold (sra x, c >= size(x)) -> undef
5684   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5685   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5686     return Val->getAPIntValue().uge(OpSizeInBits);
5687   };
5688   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5689     return DAG.getUNDEF(VT);
5690   // fold (sra x, 0) -> x
5691   if (N1C && N1C->isNullValue())
5692     return N0;
5693 
5694   if (SDValue NewSel = foldBinOpIntoSelect(N))
5695     return NewSel;
5696 
5697   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5698   // sext_inreg.
5699   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5700     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5701     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5702     if (VT.isVector())
5703       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5704                                ExtVT, VT.getVectorNumElements());
5705     if ((!LegalOperations ||
5706          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5707       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5708                          N0.getOperand(0), DAG.getValueType(ExtVT));
5709   }
5710 
5711   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5712   if (N0.getOpcode() == ISD::SRA) {
5713     SDLoc DL(N);
5714     EVT ShiftVT = N1.getValueType();
5715 
5716     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5717                                           ConstantSDNode *RHS) {
5718       APInt c1 = LHS->getAPIntValue();
5719       APInt c2 = RHS->getAPIntValue();
5720       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5721       return (c1 + c2).uge(OpSizeInBits);
5722     };
5723     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5724       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
5725                          DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT));
5726 
5727     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5728                                        ConstantSDNode *RHS) {
5729       APInt c1 = LHS->getAPIntValue();
5730       APInt c2 = RHS->getAPIntValue();
5731       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5732       return (c1 + c2).ult(OpSizeInBits);
5733     };
5734     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5735       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5736       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum);
5737     }
5738   }
5739 
5740   // fold (sra (shl X, m), (sub result_size, n))
5741   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5742   // result_size - n != m.
5743   // If truncate is free for the target sext(shl) is likely to result in better
5744   // code.
5745   if (N0.getOpcode() == ISD::SHL && N1C) {
5746     // Get the two constanst of the shifts, CN0 = m, CN = n.
5747     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5748     if (N01C) {
5749       LLVMContext &Ctx = *DAG.getContext();
5750       // Determine what the truncate's result bitsize and type would be.
5751       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5752 
5753       if (VT.isVector())
5754         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5755 
5756       // Determine the residual right-shift amount.
5757       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5758 
5759       // If the shift is not a no-op (in which case this should be just a sign
5760       // extend already), the truncated to type is legal, sign_extend is legal
5761       // on that type, and the truncate to that type is both legal and free,
5762       // perform the transform.
5763       if ((ShiftAmt > 0) &&
5764           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5765           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5766           TLI.isTruncateFree(VT, TruncVT)) {
5767         SDLoc DL(N);
5768         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5769             getShiftAmountTy(N0.getOperand(0).getValueType()));
5770         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5771                                     N0.getOperand(0), Amt);
5772         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5773                                     Shift);
5774         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5775                            N->getValueType(0), Trunc);
5776       }
5777     }
5778   }
5779 
5780   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5781   if (N1.getOpcode() == ISD::TRUNCATE &&
5782       N1.getOperand(0).getOpcode() == ISD::AND) {
5783     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5784       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5785   }
5786 
5787   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5788   //      if c1 is equal to the number of bits the trunc removes
5789   if (N0.getOpcode() == ISD::TRUNCATE &&
5790       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5791        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5792       N0.getOperand(0).hasOneUse() &&
5793       N0.getOperand(0).getOperand(1).hasOneUse() &&
5794       N1C) {
5795     SDValue N0Op0 = N0.getOperand(0);
5796     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5797       unsigned LargeShiftVal = LargeShift->getZExtValue();
5798       EVT LargeVT = N0Op0.getValueType();
5799 
5800       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5801         SDLoc DL(N);
5802         SDValue Amt =
5803           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5804                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5805         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5806                                   N0Op0.getOperand(0), Amt);
5807         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5808       }
5809     }
5810   }
5811 
5812   // Simplify, based on bits shifted out of the LHS.
5813   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5814     return SDValue(N, 0);
5815 
5816   // If the sign bit is known to be zero, switch this to a SRL.
5817   if (DAG.SignBitIsZero(N0))
5818     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5819 
5820   if (N1C && !N1C->isOpaque())
5821     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5822       return NewSRA;
5823 
5824   return SDValue();
5825 }
5826 
5827 SDValue DAGCombiner::visitSRL(SDNode *N) {
5828   SDValue N0 = N->getOperand(0);
5829   SDValue N1 = N->getOperand(1);
5830   EVT VT = N0.getValueType();
5831   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5832 
5833   // fold vector ops
5834   if (VT.isVector())
5835     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5836       return FoldedVOp;
5837 
5838   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5839 
5840   // fold (srl c1, c2) -> c1 >>u c2
5841   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5842   if (N0C && N1C && !N1C->isOpaque())
5843     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5844   // fold (srl 0, x) -> 0
5845   if (isNullConstantOrNullSplatConstant(N0))
5846     return N0;
5847   // fold (srl x, c >= size(x)) -> undef
5848   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5849   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5850     return Val->getAPIntValue().uge(OpSizeInBits);
5851   };
5852   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5853     return DAG.getUNDEF(VT);
5854   // fold (srl x, 0) -> x
5855   if (N1C && N1C->isNullValue())
5856     return N0;
5857 
5858   if (SDValue NewSel = foldBinOpIntoSelect(N))
5859     return NewSel;
5860 
5861   // if (srl x, c) is known to be zero, return 0
5862   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5863                                    APInt::getAllOnesValue(OpSizeInBits)))
5864     return DAG.getConstant(0, SDLoc(N), VT);
5865 
5866   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5867   if (N0.getOpcode() == ISD::SRL) {
5868     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5869                                           ConstantSDNode *RHS) {
5870       APInt c1 = LHS->getAPIntValue();
5871       APInt c2 = RHS->getAPIntValue();
5872       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5873       return (c1 + c2).uge(OpSizeInBits);
5874     };
5875     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5876       return DAG.getConstant(0, SDLoc(N), VT);
5877 
5878     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5879                                        ConstantSDNode *RHS) {
5880       APInt c1 = LHS->getAPIntValue();
5881       APInt c2 = RHS->getAPIntValue();
5882       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5883       return (c1 + c2).ult(OpSizeInBits);
5884     };
5885     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5886       SDLoc DL(N);
5887       EVT ShiftVT = N1.getValueType();
5888       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5889       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
5890     }
5891   }
5892 
5893   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5894   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5895       N0.getOperand(0).getOpcode() == ISD::SRL) {
5896     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5897       uint64_t c1 = N001C->getZExtValue();
5898       uint64_t c2 = N1C->getZExtValue();
5899       EVT InnerShiftVT = N0.getOperand(0).getValueType();
5900       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5901       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5902       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5903       if (c1 + OpSizeInBits == InnerShiftSize) {
5904         SDLoc DL(N0);
5905         if (c1 + c2 >= InnerShiftSize)
5906           return DAG.getConstant(0, DL, VT);
5907         return DAG.getNode(ISD::TRUNCATE, DL, VT,
5908                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5909                                        N0.getOperand(0).getOperand(0),
5910                                        DAG.getConstant(c1 + c2, DL,
5911                                                        ShiftCountVT)));
5912       }
5913     }
5914   }
5915 
5916   // fold (srl (shl x, c), c) -> (and x, cst2)
5917   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5918       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5919     SDLoc DL(N);
5920     SDValue Mask =
5921         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5922     AddToWorklist(Mask.getNode());
5923     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5924   }
5925 
5926   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5927   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5928     // Shifting in all undef bits?
5929     EVT SmallVT = N0.getOperand(0).getValueType();
5930     unsigned BitSize = SmallVT.getScalarSizeInBits();
5931     if (N1C->getZExtValue() >= BitSize)
5932       return DAG.getUNDEF(VT);
5933 
5934     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5935       uint64_t ShiftAmt = N1C->getZExtValue();
5936       SDLoc DL0(N0);
5937       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5938                                        N0.getOperand(0),
5939                           DAG.getConstant(ShiftAmt, DL0,
5940                                           getShiftAmountTy(SmallVT)));
5941       AddToWorklist(SmallShift.getNode());
5942       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5943       SDLoc DL(N);
5944       return DAG.getNode(ISD::AND, DL, VT,
5945                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5946                          DAG.getConstant(Mask, DL, VT));
5947     }
5948   }
5949 
5950   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5951   // bit, which is unmodified by sra.
5952   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5953     if (N0.getOpcode() == ISD::SRA)
5954       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5955   }
5956 
5957   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5958   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5959       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5960     KnownBits Known;
5961     DAG.computeKnownBits(N0.getOperand(0), Known);
5962 
5963     // If any of the input bits are KnownOne, then the input couldn't be all
5964     // zeros, thus the result of the srl will always be zero.
5965     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5966 
5967     // If all of the bits input the to ctlz node are known to be zero, then
5968     // the result of the ctlz is "32" and the result of the shift is one.
5969     APInt UnknownBits = ~Known.Zero;
5970     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5971 
5972     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5973     if (UnknownBits.isPowerOf2()) {
5974       // Okay, we know that only that the single bit specified by UnknownBits
5975       // could be set on input to the CTLZ node. If this bit is set, the SRL
5976       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5977       // to an SRL/XOR pair, which is likely to simplify more.
5978       unsigned ShAmt = UnknownBits.countTrailingZeros();
5979       SDValue Op = N0.getOperand(0);
5980 
5981       if (ShAmt) {
5982         SDLoc DL(N0);
5983         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5984                   DAG.getConstant(ShAmt, DL,
5985                                   getShiftAmountTy(Op.getValueType())));
5986         AddToWorklist(Op.getNode());
5987       }
5988 
5989       SDLoc DL(N);
5990       return DAG.getNode(ISD::XOR, DL, VT,
5991                          Op, DAG.getConstant(1, DL, VT));
5992     }
5993   }
5994 
5995   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5996   if (N1.getOpcode() == ISD::TRUNCATE &&
5997       N1.getOperand(0).getOpcode() == ISD::AND) {
5998     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5999       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
6000   }
6001 
6002   // fold operands of srl based on knowledge that the low bits are not
6003   // demanded.
6004   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6005     return SDValue(N, 0);
6006 
6007   if (N1C && !N1C->isOpaque())
6008     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
6009       return NewSRL;
6010 
6011   // Attempt to convert a srl of a load into a narrower zero-extending load.
6012   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6013     return NarrowLoad;
6014 
6015   // Here is a common situation. We want to optimize:
6016   //
6017   //   %a = ...
6018   //   %b = and i32 %a, 2
6019   //   %c = srl i32 %b, 1
6020   //   brcond i32 %c ...
6021   //
6022   // into
6023   //
6024   //   %a = ...
6025   //   %b = and %a, 2
6026   //   %c = setcc eq %b, 0
6027   //   brcond %c ...
6028   //
6029   // However when after the source operand of SRL is optimized into AND, the SRL
6030   // itself may not be optimized further. Look for it and add the BRCOND into
6031   // the worklist.
6032   if (N->hasOneUse()) {
6033     SDNode *Use = *N->use_begin();
6034     if (Use->getOpcode() == ISD::BRCOND)
6035       AddToWorklist(Use);
6036     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
6037       // Also look pass the truncate.
6038       Use = *Use->use_begin();
6039       if (Use->getOpcode() == ISD::BRCOND)
6040         AddToWorklist(Use);
6041     }
6042   }
6043 
6044   return SDValue();
6045 }
6046 
6047 SDValue DAGCombiner::visitABS(SDNode *N) {
6048   SDValue N0 = N->getOperand(0);
6049   EVT VT = N->getValueType(0);
6050 
6051   // fold (abs c1) -> c2
6052   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6053     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
6054   // fold (abs (abs x)) -> (abs x)
6055   if (N0.getOpcode() == ISD::ABS)
6056     return N0;
6057   // fold (abs x) -> x iff not-negative
6058   if (DAG.SignBitIsZero(N0))
6059     return N0;
6060   return SDValue();
6061 }
6062 
6063 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
6064   SDValue N0 = N->getOperand(0);
6065   EVT VT = N->getValueType(0);
6066 
6067   // fold (bswap c1) -> c2
6068   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6069     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
6070   // fold (bswap (bswap x)) -> x
6071   if (N0.getOpcode() == ISD::BSWAP)
6072     return N0->getOperand(0);
6073   return SDValue();
6074 }
6075 
6076 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
6077   SDValue N0 = N->getOperand(0);
6078   EVT VT = N->getValueType(0);
6079 
6080   // fold (bitreverse c1) -> c2
6081   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6082     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
6083   // fold (bitreverse (bitreverse x)) -> x
6084   if (N0.getOpcode() == ISD::BITREVERSE)
6085     return N0.getOperand(0);
6086   return SDValue();
6087 }
6088 
6089 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
6090   SDValue N0 = N->getOperand(0);
6091   EVT VT = N->getValueType(0);
6092 
6093   // fold (ctlz c1) -> c2
6094   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6095     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
6096   return SDValue();
6097 }
6098 
6099 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
6100   SDValue N0 = N->getOperand(0);
6101   EVT VT = N->getValueType(0);
6102 
6103   // fold (ctlz_zero_undef c1) -> c2
6104   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6105     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6106   return SDValue();
6107 }
6108 
6109 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
6110   SDValue N0 = N->getOperand(0);
6111   EVT VT = N->getValueType(0);
6112 
6113   // fold (cttz c1) -> c2
6114   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6115     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
6116   return SDValue();
6117 }
6118 
6119 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
6120   SDValue N0 = N->getOperand(0);
6121   EVT VT = N->getValueType(0);
6122 
6123   // fold (cttz_zero_undef c1) -> c2
6124   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6125     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6126   return SDValue();
6127 }
6128 
6129 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6130   SDValue N0 = N->getOperand(0);
6131   EVT VT = N->getValueType(0);
6132 
6133   // fold (ctpop c1) -> c2
6134   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6135     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6136   return SDValue();
6137 }
6138 
6139 /// \brief Generate Min/Max node
6140 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6141                                    SDValue RHS, SDValue True, SDValue False,
6142                                    ISD::CondCode CC, const TargetLowering &TLI,
6143                                    SelectionDAG &DAG) {
6144   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6145     return SDValue();
6146 
6147   switch (CC) {
6148   case ISD::SETOLT:
6149   case ISD::SETOLE:
6150   case ISD::SETLT:
6151   case ISD::SETLE:
6152   case ISD::SETULT:
6153   case ISD::SETULE: {
6154     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6155     if (TLI.isOperationLegal(Opcode, VT))
6156       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6157     return SDValue();
6158   }
6159   case ISD::SETOGT:
6160   case ISD::SETOGE:
6161   case ISD::SETGT:
6162   case ISD::SETGE:
6163   case ISD::SETUGT:
6164   case ISD::SETUGE: {
6165     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6166     if (TLI.isOperationLegal(Opcode, VT))
6167       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6168     return SDValue();
6169   }
6170   default:
6171     return SDValue();
6172   }
6173 }
6174 
6175 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6176   SDValue Cond = N->getOperand(0);
6177   SDValue N1 = N->getOperand(1);
6178   SDValue N2 = N->getOperand(2);
6179   EVT VT = N->getValueType(0);
6180   EVT CondVT = Cond.getValueType();
6181   SDLoc DL(N);
6182 
6183   if (!VT.isInteger())
6184     return SDValue();
6185 
6186   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6187   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6188   if (!C1 || !C2)
6189     return SDValue();
6190 
6191   // Only do this before legalization to avoid conflicting with target-specific
6192   // transforms in the other direction (create a select from a zext/sext). There
6193   // is also a target-independent combine here in DAGCombiner in the other
6194   // direction for (select Cond, -1, 0) when the condition is not i1.
6195   if (CondVT == MVT::i1 && !LegalOperations) {
6196     if (C1->isNullValue() && C2->isOne()) {
6197       // select Cond, 0, 1 --> zext (!Cond)
6198       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6199       if (VT != MVT::i1)
6200         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6201       return NotCond;
6202     }
6203     if (C1->isNullValue() && C2->isAllOnesValue()) {
6204       // select Cond, 0, -1 --> sext (!Cond)
6205       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6206       if (VT != MVT::i1)
6207         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6208       return NotCond;
6209     }
6210     if (C1->isOne() && C2->isNullValue()) {
6211       // select Cond, 1, 0 --> zext (Cond)
6212       if (VT != MVT::i1)
6213         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6214       return Cond;
6215     }
6216     if (C1->isAllOnesValue() && C2->isNullValue()) {
6217       // select Cond, -1, 0 --> sext (Cond)
6218       if (VT != MVT::i1)
6219         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6220       return Cond;
6221     }
6222 
6223     // For any constants that differ by 1, we can transform the select into an
6224     // extend and add. Use a target hook because some targets may prefer to
6225     // transform in the other direction.
6226     if (TLI.convertSelectOfConstantsToMath(VT)) {
6227       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6228         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6229         if (VT != MVT::i1)
6230           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6231         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6232       }
6233       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6234         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6235         if (VT != MVT::i1)
6236           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6237         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6238       }
6239     }
6240 
6241     return SDValue();
6242   }
6243 
6244   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6245   // We can't do this reliably if integer based booleans have different contents
6246   // to floating point based booleans. This is because we can't tell whether we
6247   // have an integer-based boolean or a floating-point-based boolean unless we
6248   // can find the SETCC that produced it and inspect its operands. This is
6249   // fairly easy if C is the SETCC node, but it can potentially be
6250   // undiscoverable (or not reasonably discoverable). For example, it could be
6251   // in another basic block or it could require searching a complicated
6252   // expression.
6253   if (CondVT.isInteger() &&
6254       TLI.getBooleanContents(false, true) ==
6255           TargetLowering::ZeroOrOneBooleanContent &&
6256       TLI.getBooleanContents(false, false) ==
6257           TargetLowering::ZeroOrOneBooleanContent &&
6258       C1->isNullValue() && C2->isOne()) {
6259     SDValue NotCond =
6260         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6261     if (VT.bitsEq(CondVT))
6262       return NotCond;
6263     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6264   }
6265 
6266   return SDValue();
6267 }
6268 
6269 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6270   SDValue N0 = N->getOperand(0);
6271   SDValue N1 = N->getOperand(1);
6272   SDValue N2 = N->getOperand(2);
6273   EVT VT = N->getValueType(0);
6274   EVT VT0 = N0.getValueType();
6275   SDLoc DL(N);
6276 
6277   // fold (select C, X, X) -> X
6278   if (N1 == N2)
6279     return N1;
6280 
6281   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6282     // fold (select true, X, Y) -> X
6283     // fold (select false, X, Y) -> Y
6284     return !N0C->isNullValue() ? N1 : N2;
6285   }
6286 
6287   // fold (select X, X, Y) -> (or X, Y)
6288   // fold (select X, 1, Y) -> (or C, Y)
6289   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6290     return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6291 
6292   if (SDValue V = foldSelectOfConstants(N))
6293     return V;
6294 
6295   // fold (select C, 0, X) -> (and (not C), X)
6296   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6297     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6298     AddToWorklist(NOTNode.getNode());
6299     return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6300   }
6301   // fold (select C, X, 1) -> (or (not C), X)
6302   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6303     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6304     AddToWorklist(NOTNode.getNode());
6305     return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6306   }
6307   // fold (select X, Y, X) -> (and X, Y)
6308   // fold (select X, Y, 0) -> (and X, Y)
6309   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6310     return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6311 
6312   // If we can fold this based on the true/false value, do so.
6313   if (SimplifySelectOps(N, N1, N2))
6314     return SDValue(N, 0); // Don't revisit N.
6315 
6316   if (VT0 == MVT::i1) {
6317     // The code in this block deals with the following 2 equivalences:
6318     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6319     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6320     // The target can specify its preferred form with the
6321     // shouldNormalizeToSelectSequence() callback. However we always transform
6322     // to the right anyway if we find the inner select exists in the DAG anyway
6323     // and we always transform to the left side if we know that we can further
6324     // optimize the combination of the conditions.
6325     bool normalizeToSequence =
6326         TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6327     // select (and Cond0, Cond1), X, Y
6328     //   -> select Cond0, (select Cond1, X, Y), Y
6329     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6330       SDValue Cond0 = N0->getOperand(0);
6331       SDValue Cond1 = N0->getOperand(1);
6332       SDValue InnerSelect =
6333           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6334       if (normalizeToSequence || !InnerSelect.use_empty())
6335         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6336                            InnerSelect, N2);
6337     }
6338     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6339     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6340       SDValue Cond0 = N0->getOperand(0);
6341       SDValue Cond1 = N0->getOperand(1);
6342       SDValue InnerSelect =
6343           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6344       if (normalizeToSequence || !InnerSelect.use_empty())
6345         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6346                            InnerSelect);
6347     }
6348 
6349     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6350     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6351       SDValue N1_0 = N1->getOperand(0);
6352       SDValue N1_1 = N1->getOperand(1);
6353       SDValue N1_2 = N1->getOperand(2);
6354       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6355         // Create the actual and node if we can generate good code for it.
6356         if (!normalizeToSequence) {
6357           SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6358           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6359         }
6360         // Otherwise see if we can optimize the "and" to a better pattern.
6361         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6362           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6363                              N2);
6364       }
6365     }
6366     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6367     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6368       SDValue N2_0 = N2->getOperand(0);
6369       SDValue N2_1 = N2->getOperand(1);
6370       SDValue N2_2 = N2->getOperand(2);
6371       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6372         // Create the actual or node if we can generate good code for it.
6373         if (!normalizeToSequence) {
6374           SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6375           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6376         }
6377         // Otherwise see if we can optimize to a better pattern.
6378         if (SDValue Combined = visitORLike(N0, N2_0, N))
6379           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6380                              N2_2);
6381       }
6382     }
6383   }
6384 
6385   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6386   if (VT0 == MVT::i1) {
6387     if (N0->getOpcode() == ISD::XOR) {
6388       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6389         SDValue Cond0 = N0->getOperand(0);
6390         if (C->isOne())
6391           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6392       }
6393     }
6394   }
6395 
6396   // fold selects based on a setcc into other things, such as min/max/abs
6397   if (N0.getOpcode() == ISD::SETCC) {
6398     // select x, y (fcmp lt x, y) -> fminnum x, y
6399     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6400     //
6401     // This is OK if we don't care about what happens if either operand is a
6402     // NaN.
6403     //
6404 
6405     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6406     // no signed zeros as well as no nans.
6407     const TargetOptions &Options = DAG.getTarget().Options;
6408     if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6409         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6410       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6411 
6412       if (SDValue FMinMax = combineMinNumMaxNum(
6413               DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6414         return FMinMax;
6415     }
6416 
6417     if ((!LegalOperations &&
6418          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6419         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6420       return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6421                          N0.getOperand(1), N1, N2, N0.getOperand(2));
6422     return SimplifySelect(DL, N0, N1, N2);
6423   }
6424 
6425   return SDValue();
6426 }
6427 
6428 static
6429 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6430   SDLoc DL(N);
6431   EVT LoVT, HiVT;
6432   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6433 
6434   // Split the inputs.
6435   SDValue Lo, Hi, LL, LH, RL, RH;
6436   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6437   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6438 
6439   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6440   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6441 
6442   return std::make_pair(Lo, Hi);
6443 }
6444 
6445 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6446 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6447 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6448   SDLoc DL(N);
6449   SDValue Cond = N->getOperand(0);
6450   SDValue LHS = N->getOperand(1);
6451   SDValue RHS = N->getOperand(2);
6452   EVT VT = N->getValueType(0);
6453   int NumElems = VT.getVectorNumElements();
6454   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6455          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6456          Cond.getOpcode() == ISD::BUILD_VECTOR);
6457 
6458   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6459   // binary ones here.
6460   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6461     return SDValue();
6462 
6463   // We're sure we have an even number of elements due to the
6464   // concat_vectors we have as arguments to vselect.
6465   // Skip BV elements until we find one that's not an UNDEF
6466   // After we find an UNDEF element, keep looping until we get to half the
6467   // length of the BV and see if all the non-undef nodes are the same.
6468   ConstantSDNode *BottomHalf = nullptr;
6469   for (int i = 0; i < NumElems / 2; ++i) {
6470     if (Cond->getOperand(i)->isUndef())
6471       continue;
6472 
6473     if (BottomHalf == nullptr)
6474       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6475     else if (Cond->getOperand(i).getNode() != BottomHalf)
6476       return SDValue();
6477   }
6478 
6479   // Do the same for the second half of the BuildVector
6480   ConstantSDNode *TopHalf = nullptr;
6481   for (int i = NumElems / 2; i < NumElems; ++i) {
6482     if (Cond->getOperand(i)->isUndef())
6483       continue;
6484 
6485     if (TopHalf == nullptr)
6486       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6487     else if (Cond->getOperand(i).getNode() != TopHalf)
6488       return SDValue();
6489   }
6490 
6491   assert(TopHalf && BottomHalf &&
6492          "One half of the selector was all UNDEFs and the other was all the "
6493          "same value. This should have been addressed before this function.");
6494   return DAG.getNode(
6495       ISD::CONCAT_VECTORS, DL, VT,
6496       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6497       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6498 }
6499 
6500 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6501   if (Level >= AfterLegalizeTypes)
6502     return SDValue();
6503 
6504   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6505   SDValue Mask = MSC->getMask();
6506   SDValue Data  = MSC->getValue();
6507   SDLoc DL(N);
6508 
6509   // If the MSCATTER data type requires splitting and the mask is provided by a
6510   // SETCC, then split both nodes and its operands before legalization. This
6511   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6512   // and enables future optimizations (e.g. min/max pattern matching on X86).
6513   if (Mask.getOpcode() != ISD::SETCC)
6514     return SDValue();
6515 
6516   // Check if any splitting is required.
6517   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6518       TargetLowering::TypeSplitVector)
6519     return SDValue();
6520   SDValue MaskLo, MaskHi, Lo, Hi;
6521   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6522 
6523   EVT LoVT, HiVT;
6524   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6525 
6526   SDValue Chain = MSC->getChain();
6527 
6528   EVT MemoryVT = MSC->getMemoryVT();
6529   unsigned Alignment = MSC->getOriginalAlignment();
6530 
6531   EVT LoMemVT, HiMemVT;
6532   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6533 
6534   SDValue DataLo, DataHi;
6535   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6536 
6537   SDValue BasePtr = MSC->getBasePtr();
6538   SDValue IndexLo, IndexHi;
6539   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6540 
6541   MachineMemOperand *MMO = DAG.getMachineFunction().
6542     getMachineMemOperand(MSC->getPointerInfo(),
6543                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6544                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6545 
6546   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6547   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6548                             DL, OpsLo, MMO);
6549 
6550   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6551   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6552                             DL, OpsHi, MMO);
6553 
6554   AddToWorklist(Lo.getNode());
6555   AddToWorklist(Hi.getNode());
6556 
6557   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6558 }
6559 
6560 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6561   if (Level >= AfterLegalizeTypes)
6562     return SDValue();
6563 
6564   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6565   SDValue Mask = MST->getMask();
6566   SDValue Data  = MST->getValue();
6567   EVT VT = Data.getValueType();
6568   SDLoc DL(N);
6569 
6570   // If the MSTORE data type requires splitting and the mask is provided by a
6571   // SETCC, then split both nodes and its operands before legalization. This
6572   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6573   // and enables future optimizations (e.g. min/max pattern matching on X86).
6574   if (Mask.getOpcode() == ISD::SETCC) {
6575     // Check if any splitting is required.
6576     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6577         TargetLowering::TypeSplitVector)
6578       return SDValue();
6579 
6580     SDValue MaskLo, MaskHi, Lo, Hi;
6581     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6582 
6583     SDValue Chain = MST->getChain();
6584     SDValue Ptr   = MST->getBasePtr();
6585 
6586     EVT MemoryVT = MST->getMemoryVT();
6587     unsigned Alignment = MST->getOriginalAlignment();
6588 
6589     // if Alignment is equal to the vector size,
6590     // take the half of it for the second part
6591     unsigned SecondHalfAlignment =
6592       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6593 
6594     EVT LoMemVT, HiMemVT;
6595     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6596 
6597     SDValue DataLo, DataHi;
6598     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6599 
6600     MachineMemOperand *MMO = DAG.getMachineFunction().
6601       getMachineMemOperand(MST->getPointerInfo(),
6602                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6603                            Alignment, MST->getAAInfo(), MST->getRanges());
6604 
6605     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6606                             MST->isTruncatingStore(),
6607                             MST->isCompressingStore());
6608 
6609     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6610                                      MST->isCompressingStore());
6611 
6612     MMO = DAG.getMachineFunction().
6613       getMachineMemOperand(MST->getPointerInfo(),
6614                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6615                            SecondHalfAlignment, MST->getAAInfo(),
6616                            MST->getRanges());
6617 
6618     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6619                             MST->isTruncatingStore(),
6620                             MST->isCompressingStore());
6621 
6622     AddToWorklist(Lo.getNode());
6623     AddToWorklist(Hi.getNode());
6624 
6625     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6626   }
6627   return SDValue();
6628 }
6629 
6630 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6631   if (Level >= AfterLegalizeTypes)
6632     return SDValue();
6633 
6634   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6635   SDValue Mask = MGT->getMask();
6636   SDLoc DL(N);
6637 
6638   // If the MGATHER result requires splitting and the mask is provided by a
6639   // SETCC, then split both nodes and its operands before legalization. This
6640   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6641   // and enables future optimizations (e.g. min/max pattern matching on X86).
6642 
6643   if (Mask.getOpcode() != ISD::SETCC)
6644     return SDValue();
6645 
6646   EVT VT = N->getValueType(0);
6647 
6648   // Check if any splitting is required.
6649   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6650       TargetLowering::TypeSplitVector)
6651     return SDValue();
6652 
6653   SDValue MaskLo, MaskHi, Lo, Hi;
6654   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6655 
6656   SDValue Src0 = MGT->getValue();
6657   SDValue Src0Lo, Src0Hi;
6658   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6659 
6660   EVT LoVT, HiVT;
6661   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6662 
6663   SDValue Chain = MGT->getChain();
6664   EVT MemoryVT = MGT->getMemoryVT();
6665   unsigned Alignment = MGT->getOriginalAlignment();
6666 
6667   EVT LoMemVT, HiMemVT;
6668   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6669 
6670   SDValue BasePtr = MGT->getBasePtr();
6671   SDValue Index = MGT->getIndex();
6672   SDValue IndexLo, IndexHi;
6673   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6674 
6675   MachineMemOperand *MMO = DAG.getMachineFunction().
6676     getMachineMemOperand(MGT->getPointerInfo(),
6677                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6678                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6679 
6680   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6681   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6682                             MMO);
6683 
6684   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6685   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6686                             MMO);
6687 
6688   AddToWorklist(Lo.getNode());
6689   AddToWorklist(Hi.getNode());
6690 
6691   // Build a factor node to remember that this load is independent of the
6692   // other one.
6693   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6694                       Hi.getValue(1));
6695 
6696   // Legalized the chain result - switch anything that used the old chain to
6697   // use the new one.
6698   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6699 
6700   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6701 
6702   SDValue RetOps[] = { GatherRes, Chain };
6703   return DAG.getMergeValues(RetOps, DL);
6704 }
6705 
6706 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6707   if (Level >= AfterLegalizeTypes)
6708     return SDValue();
6709 
6710   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6711   SDValue Mask = MLD->getMask();
6712   SDLoc DL(N);
6713 
6714   // If the MLOAD result requires splitting and the mask is provided by a
6715   // SETCC, then split both nodes and its operands before legalization. This
6716   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6717   // and enables future optimizations (e.g. min/max pattern matching on X86).
6718   if (Mask.getOpcode() == ISD::SETCC) {
6719     EVT VT = N->getValueType(0);
6720 
6721     // Check if any splitting is required.
6722     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6723         TargetLowering::TypeSplitVector)
6724       return SDValue();
6725 
6726     SDValue MaskLo, MaskHi, Lo, Hi;
6727     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6728 
6729     SDValue Src0 = MLD->getSrc0();
6730     SDValue Src0Lo, Src0Hi;
6731     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6732 
6733     EVT LoVT, HiVT;
6734     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6735 
6736     SDValue Chain = MLD->getChain();
6737     SDValue Ptr   = MLD->getBasePtr();
6738     EVT MemoryVT = MLD->getMemoryVT();
6739     unsigned Alignment = MLD->getOriginalAlignment();
6740 
6741     // if Alignment is equal to the vector size,
6742     // take the half of it for the second part
6743     unsigned SecondHalfAlignment =
6744       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6745          Alignment/2 : Alignment;
6746 
6747     EVT LoMemVT, HiMemVT;
6748     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6749 
6750     MachineMemOperand *MMO = DAG.getMachineFunction().
6751     getMachineMemOperand(MLD->getPointerInfo(),
6752                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6753                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6754 
6755     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6756                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6757 
6758     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6759                                      MLD->isExpandingLoad());
6760 
6761     MMO = DAG.getMachineFunction().
6762     getMachineMemOperand(MLD->getPointerInfo(),
6763                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6764                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6765 
6766     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6767                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6768 
6769     AddToWorklist(Lo.getNode());
6770     AddToWorklist(Hi.getNode());
6771 
6772     // Build a factor node to remember that this load is independent of the
6773     // other one.
6774     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6775                         Hi.getValue(1));
6776 
6777     // Legalized the chain result - switch anything that used the old chain to
6778     // use the new one.
6779     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6780 
6781     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6782 
6783     SDValue RetOps[] = { LoadRes, Chain };
6784     return DAG.getMergeValues(RetOps, DL);
6785   }
6786   return SDValue();
6787 }
6788 
6789 /// A vector select of 2 constant vectors can be simplified to math/logic to
6790 /// avoid a variable select instruction and possibly avoid constant loads.
6791 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
6792   SDValue Cond = N->getOperand(0);
6793   SDValue N1 = N->getOperand(1);
6794   SDValue N2 = N->getOperand(2);
6795   EVT VT = N->getValueType(0);
6796   if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
6797       !TLI.convertSelectOfConstantsToMath(VT) ||
6798       !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
6799       !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
6800     return SDValue();
6801 
6802   // Check if we can use the condition value to increment/decrement a single
6803   // constant value. This simplifies a select to an add and removes a constant
6804   // load/materialization from the general case.
6805   bool AllAddOne = true;
6806   bool AllSubOne = true;
6807   unsigned Elts = VT.getVectorNumElements();
6808   for (unsigned i = 0; i != Elts; ++i) {
6809     SDValue N1Elt = N1.getOperand(i);
6810     SDValue N2Elt = N2.getOperand(i);
6811     if (N1Elt.isUndef() || N2Elt.isUndef())
6812       continue;
6813 
6814     const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
6815     const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
6816     if (C1 != C2 + 1)
6817       AllAddOne = false;
6818     if (C1 != C2 - 1)
6819       AllSubOne = false;
6820   }
6821 
6822   // Further simplifications for the extra-special cases where the constants are
6823   // all 0 or all -1 should be implemented as folds of these patterns.
6824   SDLoc DL(N);
6825   if (AllAddOne || AllSubOne) {
6826     // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
6827     // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
6828     auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
6829     SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
6830     return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
6831   }
6832 
6833   // The general case for select-of-constants:
6834   // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
6835   // ...but that only makes sense if a vselect is slower than 2 logic ops, so
6836   // leave that to a machine-specific pass.
6837   return SDValue();
6838 }
6839 
6840 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6841   SDValue N0 = N->getOperand(0);
6842   SDValue N1 = N->getOperand(1);
6843   SDValue N2 = N->getOperand(2);
6844   SDLoc DL(N);
6845 
6846   // fold (vselect C, X, X) -> X
6847   if (N1 == N2)
6848     return N1;
6849 
6850   // Canonicalize integer abs.
6851   // vselect (setg[te] X,  0),  X, -X ->
6852   // vselect (setgt    X, -1),  X, -X ->
6853   // vselect (setl[te] X,  0), -X,  X ->
6854   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6855   if (N0.getOpcode() == ISD::SETCC) {
6856     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6857     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6858     bool isAbs = false;
6859     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6860 
6861     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6862          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6863         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6864       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6865     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6866              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6867       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6868 
6869     if (isAbs) {
6870       EVT VT = LHS.getValueType();
6871       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
6872         return DAG.getNode(ISD::ABS, DL, VT, LHS);
6873 
6874       SDValue Shift = DAG.getNode(
6875           ISD::SRA, DL, VT, LHS,
6876           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6877       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6878       AddToWorklist(Shift.getNode());
6879       AddToWorklist(Add.getNode());
6880       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6881     }
6882   }
6883 
6884   if (SimplifySelectOps(N, N1, N2))
6885     return SDValue(N, 0);  // Don't revisit N.
6886 
6887   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6888   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6889     return N1;
6890   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6891   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6892     return N2;
6893 
6894   // The ConvertSelectToConcatVector function is assuming both the above
6895   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6896   // and addressed.
6897   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6898       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6899       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6900     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6901       return CV;
6902   }
6903 
6904   if (SDValue V = foldVSelectOfConstants(N))
6905     return V;
6906 
6907   return SDValue();
6908 }
6909 
6910 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6911   SDValue N0 = N->getOperand(0);
6912   SDValue N1 = N->getOperand(1);
6913   SDValue N2 = N->getOperand(2);
6914   SDValue N3 = N->getOperand(3);
6915   SDValue N4 = N->getOperand(4);
6916   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6917 
6918   // fold select_cc lhs, rhs, x, x, cc -> x
6919   if (N2 == N3)
6920     return N2;
6921 
6922   // Determine if the condition we're dealing with is constant
6923   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6924                                   CC, SDLoc(N), false)) {
6925     AddToWorklist(SCC.getNode());
6926 
6927     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6928       if (!SCCC->isNullValue())
6929         return N2;    // cond always true -> true val
6930       else
6931         return N3;    // cond always false -> false val
6932     } else if (SCC->isUndef()) {
6933       // When the condition is UNDEF, just return the first operand. This is
6934       // coherent the DAG creation, no setcc node is created in this case
6935       return N2;
6936     } else if (SCC.getOpcode() == ISD::SETCC) {
6937       // Fold to a simpler select_cc
6938       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6939                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6940                          SCC.getOperand(2));
6941     }
6942   }
6943 
6944   // If we can fold this based on the true/false value, do so.
6945   if (SimplifySelectOps(N, N2, N3))
6946     return SDValue(N, 0);  // Don't revisit N.
6947 
6948   // fold select_cc into other things, such as min/max/abs
6949   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6950 }
6951 
6952 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6953   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6954                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6955                        SDLoc(N));
6956 }
6957 
6958 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6959   SDValue LHS = N->getOperand(0);
6960   SDValue RHS = N->getOperand(1);
6961   SDValue Carry = N->getOperand(2);
6962   SDValue Cond = N->getOperand(3);
6963 
6964   // If Carry is false, fold to a regular SETCC.
6965   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6966     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6967 
6968   return SDValue();
6969 }
6970 
6971 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
6972   SDValue LHS = N->getOperand(0);
6973   SDValue RHS = N->getOperand(1);
6974   SDValue Carry = N->getOperand(2);
6975   SDValue Cond = N->getOperand(3);
6976 
6977   // If Carry is false, fold to a regular SETCC.
6978   if (isNullConstant(Carry))
6979     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6980 
6981   return SDValue();
6982 }
6983 
6984 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6985 /// a build_vector of constants.
6986 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6987 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6988 /// Vector extends are not folded if operations are legal; this is to
6989 /// avoid introducing illegal build_vector dag nodes.
6990 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6991                                          SelectionDAG &DAG, bool LegalTypes,
6992                                          bool LegalOperations) {
6993   unsigned Opcode = N->getOpcode();
6994   SDValue N0 = N->getOperand(0);
6995   EVT VT = N->getValueType(0);
6996 
6997   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6998          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6999          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
7000          && "Expected EXTEND dag node in input!");
7001 
7002   // fold (sext c1) -> c1
7003   // fold (zext c1) -> c1
7004   // fold (aext c1) -> c1
7005   if (isa<ConstantSDNode>(N0))
7006     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
7007 
7008   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
7009   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
7010   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
7011   EVT SVT = VT.getScalarType();
7012   if (!(VT.isVector() &&
7013       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
7014       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
7015     return nullptr;
7016 
7017   // We can fold this node into a build_vector.
7018   unsigned VTBits = SVT.getSizeInBits();
7019   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
7020   SmallVector<SDValue, 8> Elts;
7021   unsigned NumElts = VT.getVectorNumElements();
7022   SDLoc DL(N);
7023 
7024   for (unsigned i=0; i != NumElts; ++i) {
7025     SDValue Op = N0->getOperand(i);
7026     if (Op->isUndef()) {
7027       Elts.push_back(DAG.getUNDEF(SVT));
7028       continue;
7029     }
7030 
7031     SDLoc DL(Op);
7032     // Get the constant value and if needed trunc it to the size of the type.
7033     // Nodes like build_vector might have constants wider than the scalar type.
7034     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
7035     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
7036       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
7037     else
7038       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
7039   }
7040 
7041   return DAG.getBuildVector(VT, DL, Elts).getNode();
7042 }
7043 
7044 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
7045 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
7046 // transformation. Returns true if extension are possible and the above
7047 // mentioned transformation is profitable.
7048 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
7049                                     unsigned ExtOpc,
7050                                     SmallVectorImpl<SDNode *> &ExtendNodes,
7051                                     const TargetLowering &TLI) {
7052   bool HasCopyToRegUses = false;
7053   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
7054   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
7055                             UE = N0.getNode()->use_end();
7056        UI != UE; ++UI) {
7057     SDNode *User = *UI;
7058     if (User == N)
7059       continue;
7060     if (UI.getUse().getResNo() != N0.getResNo())
7061       continue;
7062     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
7063     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
7064       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
7065       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
7066         // Sign bits will be lost after a zext.
7067         return false;
7068       bool Add = false;
7069       for (unsigned i = 0; i != 2; ++i) {
7070         SDValue UseOp = User->getOperand(i);
7071         if (UseOp == N0)
7072           continue;
7073         if (!isa<ConstantSDNode>(UseOp))
7074           return false;
7075         Add = true;
7076       }
7077       if (Add)
7078         ExtendNodes.push_back(User);
7079       continue;
7080     }
7081     // If truncates aren't free and there are users we can't
7082     // extend, it isn't worthwhile.
7083     if (!isTruncFree)
7084       return false;
7085     // Remember if this value is live-out.
7086     if (User->getOpcode() == ISD::CopyToReg)
7087       HasCopyToRegUses = true;
7088   }
7089 
7090   if (HasCopyToRegUses) {
7091     bool BothLiveOut = false;
7092     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7093          UI != UE; ++UI) {
7094       SDUse &Use = UI.getUse();
7095       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
7096         BothLiveOut = true;
7097         break;
7098       }
7099     }
7100     if (BothLiveOut)
7101       // Both unextended and extended values are live out. There had better be
7102       // a good reason for the transformation.
7103       return ExtendNodes.size();
7104   }
7105   return true;
7106 }
7107 
7108 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
7109                                   SDValue Trunc, SDValue ExtLoad,
7110                                   const SDLoc &DL, ISD::NodeType ExtType) {
7111   // Extend SetCC uses if necessary.
7112   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
7113     SDNode *SetCC = SetCCs[i];
7114     SmallVector<SDValue, 4> Ops;
7115 
7116     for (unsigned j = 0; j != 2; ++j) {
7117       SDValue SOp = SetCC->getOperand(j);
7118       if (SOp == Trunc)
7119         Ops.push_back(ExtLoad);
7120       else
7121         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
7122     }
7123 
7124     Ops.push_back(SetCC->getOperand(2));
7125     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7126   }
7127 }
7128 
7129 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
7130 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
7131   SDValue N0 = N->getOperand(0);
7132   EVT DstVT = N->getValueType(0);
7133   EVT SrcVT = N0.getValueType();
7134 
7135   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
7136           N->getOpcode() == ISD::ZERO_EXTEND) &&
7137          "Unexpected node type (not an extend)!");
7138 
7139   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
7140   // For example, on a target with legal v4i32, but illegal v8i32, turn:
7141   //   (v8i32 (sext (v8i16 (load x))))
7142   // into:
7143   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
7144   //                          (v4i32 (sextload (x + 16)))))
7145   // Where uses of the original load, i.e.:
7146   //   (v8i16 (load x))
7147   // are replaced with:
7148   //   (v8i16 (truncate
7149   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
7150   //                            (v4i32 (sextload (x + 16)))))))
7151   //
7152   // This combine is only applicable to illegal, but splittable, vectors.
7153   // All legal types, and illegal non-vector types, are handled elsewhere.
7154   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
7155   //
7156   if (N0->getOpcode() != ISD::LOAD)
7157     return SDValue();
7158 
7159   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7160 
7161   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
7162       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
7163       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
7164     return SDValue();
7165 
7166   SmallVector<SDNode *, 4> SetCCs;
7167   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
7168     return SDValue();
7169 
7170   ISD::LoadExtType ExtType =
7171       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7172 
7173   // Try to split the vector types to get down to legal types.
7174   EVT SplitSrcVT = SrcVT;
7175   EVT SplitDstVT = DstVT;
7176   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7177          SplitSrcVT.getVectorNumElements() > 1) {
7178     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7179     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7180   }
7181 
7182   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7183     return SDValue();
7184 
7185   SDLoc DL(N);
7186   const unsigned NumSplits =
7187       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7188   const unsigned Stride = SplitSrcVT.getStoreSize();
7189   SmallVector<SDValue, 4> Loads;
7190   SmallVector<SDValue, 4> Chains;
7191 
7192   SDValue BasePtr = LN0->getBasePtr();
7193   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7194     const unsigned Offset = Idx * Stride;
7195     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7196 
7197     SDValue SplitLoad = DAG.getExtLoad(
7198         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7199         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7200         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7201 
7202     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7203                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7204 
7205     Loads.push_back(SplitLoad.getValue(0));
7206     Chains.push_back(SplitLoad.getValue(1));
7207   }
7208 
7209   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7210   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7211 
7212   // Simplify TF.
7213   AddToWorklist(NewChain.getNode());
7214 
7215   CombineTo(N, NewValue);
7216 
7217   // Replace uses of the original load (before extension)
7218   // with a truncate of the concatenated sextloaded vectors.
7219   SDValue Trunc =
7220       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7221   CombineTo(N0.getNode(), Trunc, NewChain);
7222   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7223                   (ISD::NodeType)N->getOpcode());
7224   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7225 }
7226 
7227 /// If we're narrowing or widening the result of a vector select and the final
7228 /// size is the same size as a setcc (compare) feeding the select, then try to
7229 /// apply the cast operation to the select's operands because matching vector
7230 /// sizes for a select condition and other operands should be more efficient.
7231 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7232   unsigned CastOpcode = Cast->getOpcode();
7233   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7234           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7235           CastOpcode == ISD::FP_ROUND) &&
7236          "Unexpected opcode for vector select narrowing/widening");
7237 
7238   // We only do this transform before legal ops because the pattern may be
7239   // obfuscated by target-specific operations after legalization. Do not create
7240   // an illegal select op, however, because that may be difficult to lower.
7241   EVT VT = Cast->getValueType(0);
7242   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7243     return SDValue();
7244 
7245   SDValue VSel = Cast->getOperand(0);
7246   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7247       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7248     return SDValue();
7249 
7250   // Does the setcc have the same vector size as the casted select?
7251   SDValue SetCC = VSel.getOperand(0);
7252   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7253   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7254     return SDValue();
7255 
7256   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7257   SDValue A = VSel.getOperand(1);
7258   SDValue B = VSel.getOperand(2);
7259   SDValue CastA, CastB;
7260   SDLoc DL(Cast);
7261   if (CastOpcode == ISD::FP_ROUND) {
7262     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7263     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7264     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7265   } else {
7266     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7267     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7268   }
7269   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7270 }
7271 
7272 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7273   SDValue N0 = N->getOperand(0);
7274   EVT VT = N->getValueType(0);
7275   SDLoc DL(N);
7276 
7277   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7278                                               LegalOperations))
7279     return SDValue(Res, 0);
7280 
7281   // fold (sext (sext x)) -> (sext x)
7282   // fold (sext (aext x)) -> (sext x)
7283   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7284     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7285 
7286   if (N0.getOpcode() == ISD::TRUNCATE) {
7287     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7288     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7289     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7290       SDNode *oye = N0.getOperand(0).getNode();
7291       if (NarrowLoad.getNode() != N0.getNode()) {
7292         CombineTo(N0.getNode(), NarrowLoad);
7293         // CombineTo deleted the truncate, if needed, but not what's under it.
7294         AddToWorklist(oye);
7295       }
7296       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7297     }
7298 
7299     // See if the value being truncated is already sign extended.  If so, just
7300     // eliminate the trunc/sext pair.
7301     SDValue Op = N0.getOperand(0);
7302     unsigned OpBits   = Op.getScalarValueSizeInBits();
7303     unsigned MidBits  = N0.getScalarValueSizeInBits();
7304     unsigned DestBits = VT.getScalarSizeInBits();
7305     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7306 
7307     if (OpBits == DestBits) {
7308       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7309       // bits, it is already ready.
7310       if (NumSignBits > DestBits-MidBits)
7311         return Op;
7312     } else if (OpBits < DestBits) {
7313       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7314       // bits, just sext from i32.
7315       if (NumSignBits > OpBits-MidBits)
7316         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7317     } else {
7318       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7319       // bits, just truncate to i32.
7320       if (NumSignBits > OpBits-MidBits)
7321         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7322     }
7323 
7324     // fold (sext (truncate x)) -> (sextinreg x).
7325     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7326                                                  N0.getValueType())) {
7327       if (OpBits < DestBits)
7328         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7329       else if (OpBits > DestBits)
7330         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7331       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7332                          DAG.getValueType(N0.getValueType()));
7333     }
7334   }
7335 
7336   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7337   // Only generate vector extloads when 1) they're legal, and 2) they are
7338   // deemed desirable by the target.
7339   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7340       ((!LegalOperations && !VT.isVector() &&
7341         !cast<LoadSDNode>(N0)->isVolatile()) ||
7342        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7343     bool DoXform = true;
7344     SmallVector<SDNode*, 4> SetCCs;
7345     if (!N0.hasOneUse())
7346       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7347     if (VT.isVector())
7348       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7349     if (DoXform) {
7350       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7351       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7352                                        LN0->getBasePtr(), N0.getValueType(),
7353                                        LN0->getMemOperand());
7354       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7355                                   N0.getValueType(), ExtLoad);
7356       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7357       // If the load value is used only by N, replace it via CombineTo N.
7358       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7359       CombineTo(N, ExtLoad);
7360       if (NoReplaceTrunc)
7361         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7362       else
7363         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7364       return SDValue(N, 0);
7365     }
7366   }
7367 
7368   // fold (sext (load x)) to multiple smaller sextloads.
7369   // Only on illegal but splittable vectors.
7370   if (SDValue ExtLoad = CombineExtLoad(N))
7371     return ExtLoad;
7372 
7373   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7374   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7375   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7376       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7377     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7378     EVT MemVT = LN0->getMemoryVT();
7379     if ((!LegalOperations && !LN0->isVolatile()) ||
7380         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7381       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7382                                        LN0->getBasePtr(), MemVT,
7383                                        LN0->getMemOperand());
7384       CombineTo(N, ExtLoad);
7385       CombineTo(N0.getNode(),
7386                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7387                             N0.getValueType(), ExtLoad),
7388                 ExtLoad.getValue(1));
7389       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7390     }
7391   }
7392 
7393   // fold (sext (and/or/xor (load x), cst)) ->
7394   //      (and/or/xor (sextload x), (sext cst))
7395   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7396        N0.getOpcode() == ISD::XOR) &&
7397       isa<LoadSDNode>(N0.getOperand(0)) &&
7398       N0.getOperand(1).getOpcode() == ISD::Constant &&
7399       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7400       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7401     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7402     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7403       bool DoXform = true;
7404       SmallVector<SDNode*, 4> SetCCs;
7405       if (!N0.hasOneUse())
7406         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7407                                           SetCCs, TLI);
7408       if (DoXform) {
7409         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7410                                          LN0->getChain(), LN0->getBasePtr(),
7411                                          LN0->getMemoryVT(),
7412                                          LN0->getMemOperand());
7413         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7414         Mask = Mask.sext(VT.getSizeInBits());
7415         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7416                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7417         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7418                                     SDLoc(N0.getOperand(0)),
7419                                     N0.getOperand(0).getValueType(), ExtLoad);
7420         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7421         bool NoReplaceTruncAnd = !N0.hasOneUse();
7422         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7423         CombineTo(N, And);
7424         // If N0 has multiple uses, change other uses as well.
7425         if (NoReplaceTruncAnd) {
7426           SDValue TruncAnd =
7427               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7428           CombineTo(N0.getNode(), TruncAnd);
7429         }
7430         if (NoReplaceTrunc)
7431           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7432         else
7433           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7434         return SDValue(N,0); // Return N so it doesn't get rechecked!
7435       }
7436     }
7437   }
7438 
7439   if (N0.getOpcode() == ISD::SETCC) {
7440     SDValue N00 = N0.getOperand(0);
7441     SDValue N01 = N0.getOperand(1);
7442     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7443     EVT N00VT = N0.getOperand(0).getValueType();
7444 
7445     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7446     // Only do this before legalize for now.
7447     if (VT.isVector() && !LegalOperations &&
7448         TLI.getBooleanContents(N00VT) ==
7449             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7450       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7451       // of the same size as the compared operands. Only optimize sext(setcc())
7452       // if this is the case.
7453       EVT SVT = getSetCCResultType(N00VT);
7454 
7455       // We know that the # elements of the results is the same as the
7456       // # elements of the compare (and the # elements of the compare result
7457       // for that matter).  Check to see that they are the same size.  If so,
7458       // we know that the element size of the sext'd result matches the
7459       // element size of the compare operands.
7460       if (VT.getSizeInBits() == SVT.getSizeInBits())
7461         return DAG.getSetCC(DL, VT, N00, N01, CC);
7462 
7463       // If the desired elements are smaller or larger than the source
7464       // elements, we can use a matching integer vector type and then
7465       // truncate/sign extend.
7466       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7467       if (SVT == MatchingVecType) {
7468         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7469         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7470       }
7471     }
7472 
7473     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7474     // Here, T can be 1 or -1, depending on the type of the setcc and
7475     // getBooleanContents().
7476     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7477 
7478     // To determine the "true" side of the select, we need to know the high bit
7479     // of the value returned by the setcc if it evaluates to true.
7480     // If the type of the setcc is i1, then the true case of the select is just
7481     // sext(i1 1), that is, -1.
7482     // If the type of the setcc is larger (say, i8) then the value of the high
7483     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7484     // of the appropriate width.
7485     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7486                                            : TLI.getConstTrueVal(DAG, VT, DL);
7487     SDValue Zero = DAG.getConstant(0, DL, VT);
7488     if (SDValue SCC =
7489             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7490       return SCC;
7491 
7492     if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
7493       EVT SetCCVT = getSetCCResultType(N00VT);
7494       // Don't do this transform for i1 because there's a select transform
7495       // that would reverse it.
7496       // TODO: We should not do this transform at all without a target hook
7497       // because a sext is likely cheaper than a select?
7498       if (SetCCVT.getScalarSizeInBits() != 1 &&
7499           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7500         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7501         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7502       }
7503     }
7504   }
7505 
7506   // fold (sext x) -> (zext x) if the sign bit is known zero.
7507   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7508       DAG.SignBitIsZero(N0))
7509     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7510 
7511   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7512     return NewVSel;
7513 
7514   return SDValue();
7515 }
7516 
7517 // isTruncateOf - If N is a truncate of some other value, return true, record
7518 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7519 // This function computes KnownBits to avoid a duplicated call to
7520 // computeKnownBits in the caller.
7521 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7522                          KnownBits &Known) {
7523   if (N->getOpcode() == ISD::TRUNCATE) {
7524     Op = N->getOperand(0);
7525     DAG.computeKnownBits(Op, Known);
7526     return true;
7527   }
7528 
7529   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7530       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7531     return false;
7532 
7533   SDValue Op0 = N->getOperand(0);
7534   SDValue Op1 = N->getOperand(1);
7535   assert(Op0.getValueType() == Op1.getValueType());
7536 
7537   if (isNullConstant(Op0))
7538     Op = Op1;
7539   else if (isNullConstant(Op1))
7540     Op = Op0;
7541   else
7542     return false;
7543 
7544   DAG.computeKnownBits(Op, Known);
7545 
7546   if (!(Known.Zero | 1).isAllOnesValue())
7547     return false;
7548 
7549   return true;
7550 }
7551 
7552 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7553   SDValue N0 = N->getOperand(0);
7554   EVT VT = N->getValueType(0);
7555 
7556   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7557                                               LegalOperations))
7558     return SDValue(Res, 0);
7559 
7560   // fold (zext (zext x)) -> (zext x)
7561   // fold (zext (aext x)) -> (zext x)
7562   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7563     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7564                        N0.getOperand(0));
7565 
7566   // fold (zext (truncate x)) -> (zext x) or
7567   //      (zext (truncate x)) -> (truncate x)
7568   // This is valid when the truncated bits of x are already zero.
7569   // FIXME: We should extend this to work for vectors too.
7570   SDValue Op;
7571   KnownBits Known;
7572   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7573     APInt TruncatedBits =
7574       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7575       APInt(Op.getValueSizeInBits(), 0) :
7576       APInt::getBitsSet(Op.getValueSizeInBits(),
7577                         N0.getValueSizeInBits(),
7578                         std::min(Op.getValueSizeInBits(),
7579                                  VT.getSizeInBits()));
7580     if (TruncatedBits.isSubsetOf(Known.Zero))
7581       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7582   }
7583 
7584   // fold (zext (truncate x)) -> (and x, mask)
7585   if (N0.getOpcode() == ISD::TRUNCATE) {
7586     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7587     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7588     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7589       SDNode *oye = N0.getOperand(0).getNode();
7590       if (NarrowLoad.getNode() != N0.getNode()) {
7591         CombineTo(N0.getNode(), NarrowLoad);
7592         // CombineTo deleted the truncate, if needed, but not what's under it.
7593         AddToWorklist(oye);
7594       }
7595       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7596     }
7597 
7598     EVT SrcVT = N0.getOperand(0).getValueType();
7599     EVT MinVT = N0.getValueType();
7600 
7601     // Try to mask before the extension to avoid having to generate a larger mask,
7602     // possibly over several sub-vectors.
7603     if (SrcVT.bitsLT(VT)) {
7604       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7605                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7606         SDValue Op = N0.getOperand(0);
7607         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7608         AddToWorklist(Op.getNode());
7609         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7610       }
7611     }
7612 
7613     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7614       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7615       AddToWorklist(Op.getNode());
7616       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7617     }
7618   }
7619 
7620   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7621   // if either of the casts is not free.
7622   if (N0.getOpcode() == ISD::AND &&
7623       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7624       N0.getOperand(1).getOpcode() == ISD::Constant &&
7625       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7626                            N0.getValueType()) ||
7627        !TLI.isZExtFree(N0.getValueType(), VT))) {
7628     SDValue X = N0.getOperand(0).getOperand(0);
7629     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7630     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7631     Mask = Mask.zext(VT.getSizeInBits());
7632     SDLoc DL(N);
7633     return DAG.getNode(ISD::AND, DL, VT,
7634                        X, DAG.getConstant(Mask, DL, VT));
7635   }
7636 
7637   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7638   // Only generate vector extloads when 1) they're legal, and 2) they are
7639   // deemed desirable by the target.
7640   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7641       ((!LegalOperations && !VT.isVector() &&
7642         !cast<LoadSDNode>(N0)->isVolatile()) ||
7643        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7644     bool DoXform = true;
7645     SmallVector<SDNode*, 4> SetCCs;
7646     if (!N0.hasOneUse())
7647       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7648     if (VT.isVector())
7649       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7650     if (DoXform) {
7651       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7652       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7653                                        LN0->getChain(),
7654                                        LN0->getBasePtr(), N0.getValueType(),
7655                                        LN0->getMemOperand());
7656 
7657       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7658                                   N0.getValueType(), ExtLoad);
7659       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7660       // If the load value is used only by N, replace it via CombineTo N.
7661       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7662       CombineTo(N, ExtLoad);
7663       if (NoReplaceTrunc)
7664         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7665       else
7666         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7667       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7668     }
7669   }
7670 
7671   // fold (zext (load x)) to multiple smaller zextloads.
7672   // Only on illegal but splittable vectors.
7673   if (SDValue ExtLoad = CombineExtLoad(N))
7674     return ExtLoad;
7675 
7676   // fold (zext (and/or/xor (load x), cst)) ->
7677   //      (and/or/xor (zextload x), (zext cst))
7678   // Unless (and (load x) cst) will match as a zextload already and has
7679   // additional users.
7680   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7681        N0.getOpcode() == ISD::XOR) &&
7682       isa<LoadSDNode>(N0.getOperand(0)) &&
7683       N0.getOperand(1).getOpcode() == ISD::Constant &&
7684       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7685       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7686     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7687     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7688       bool DoXform = true;
7689       SmallVector<SDNode*, 4> SetCCs;
7690       if (!N0.hasOneUse()) {
7691         if (N0.getOpcode() == ISD::AND) {
7692           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7693           auto NarrowLoad = false;
7694           EVT LoadResultTy = AndC->getValueType(0);
7695           EVT ExtVT, LoadedVT;
7696           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7697                                NarrowLoad))
7698             DoXform = false;
7699         }
7700         if (DoXform)
7701           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7702                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7703       }
7704       if (DoXform) {
7705         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7706                                          LN0->getChain(), LN0->getBasePtr(),
7707                                          LN0->getMemoryVT(),
7708                                          LN0->getMemOperand());
7709         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7710         Mask = Mask.zext(VT.getSizeInBits());
7711         SDLoc DL(N);
7712         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7713                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7714         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7715                                     SDLoc(N0.getOperand(0)),
7716                                     N0.getOperand(0).getValueType(), ExtLoad);
7717         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND);
7718         bool NoReplaceTruncAnd = !N0.hasOneUse();
7719         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7720         CombineTo(N, And);
7721         // If N0 has multiple uses, change other uses as well.
7722         if (NoReplaceTruncAnd) {
7723           SDValue TruncAnd =
7724               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7725           CombineTo(N0.getNode(), TruncAnd);
7726         }
7727         if (NoReplaceTrunc)
7728           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7729         else
7730           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7731         return SDValue(N,0); // Return N so it doesn't get rechecked!
7732       }
7733     }
7734   }
7735 
7736   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7737   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7738   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7739       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7740     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7741     EVT MemVT = LN0->getMemoryVT();
7742     if ((!LegalOperations && !LN0->isVolatile()) ||
7743         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7744       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7745                                        LN0->getChain(),
7746                                        LN0->getBasePtr(), MemVT,
7747                                        LN0->getMemOperand());
7748       CombineTo(N, ExtLoad);
7749       CombineTo(N0.getNode(),
7750                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7751                             ExtLoad),
7752                 ExtLoad.getValue(1));
7753       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7754     }
7755   }
7756 
7757   if (N0.getOpcode() == ISD::SETCC) {
7758     // Only do this before legalize for now.
7759     if (!LegalOperations && VT.isVector() &&
7760         N0.getValueType().getVectorElementType() == MVT::i1) {
7761       EVT N00VT = N0.getOperand(0).getValueType();
7762       if (getSetCCResultType(N00VT) == N0.getValueType())
7763         return SDValue();
7764 
7765       // We know that the # elements of the results is the same as the #
7766       // elements of the compare (and the # elements of the compare result for
7767       // that matter). Check to see that they are the same size. If so, we know
7768       // that the element size of the sext'd result matches the element size of
7769       // the compare operands.
7770       SDLoc DL(N);
7771       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7772       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7773         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7774         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7775                                      N0.getOperand(1), N0.getOperand(2));
7776         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7777       }
7778 
7779       // If the desired elements are smaller or larger than the source
7780       // elements we can use a matching integer vector type and then
7781       // truncate/sign extend.
7782       EVT MatchingElementType = EVT::getIntegerVT(
7783           *DAG.getContext(), N00VT.getScalarSizeInBits());
7784       EVT MatchingVectorType = EVT::getVectorVT(
7785           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7786       SDValue VsetCC =
7787           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7788                       N0.getOperand(1), N0.getOperand(2));
7789       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7790                          VecOnes);
7791     }
7792 
7793     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7794     SDLoc DL(N);
7795     if (SDValue SCC = SimplifySelectCC(
7796             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7797             DAG.getConstant(0, DL, VT),
7798             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7799       return SCC;
7800   }
7801 
7802   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7803   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7804       isa<ConstantSDNode>(N0.getOperand(1)) &&
7805       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7806       N0.hasOneUse()) {
7807     SDValue ShAmt = N0.getOperand(1);
7808     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7809     if (N0.getOpcode() == ISD::SHL) {
7810       SDValue InnerZExt = N0.getOperand(0);
7811       // If the original shl may be shifting out bits, do not perform this
7812       // transformation.
7813       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7814         InnerZExt.getOperand(0).getValueSizeInBits();
7815       if (ShAmtVal > KnownZeroBits)
7816         return SDValue();
7817     }
7818 
7819     SDLoc DL(N);
7820 
7821     // Ensure that the shift amount is wide enough for the shifted value.
7822     if (VT.getSizeInBits() >= 256)
7823       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7824 
7825     return DAG.getNode(N0.getOpcode(), DL, VT,
7826                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7827                        ShAmt);
7828   }
7829 
7830   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7831     return NewVSel;
7832 
7833   return SDValue();
7834 }
7835 
7836 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7837   SDValue N0 = N->getOperand(0);
7838   EVT VT = N->getValueType(0);
7839 
7840   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7841                                               LegalOperations))
7842     return SDValue(Res, 0);
7843 
7844   // fold (aext (aext x)) -> (aext x)
7845   // fold (aext (zext x)) -> (zext x)
7846   // fold (aext (sext x)) -> (sext x)
7847   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7848       N0.getOpcode() == ISD::ZERO_EXTEND ||
7849       N0.getOpcode() == ISD::SIGN_EXTEND)
7850     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7851 
7852   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7853   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7854   if (N0.getOpcode() == ISD::TRUNCATE) {
7855     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7856       SDNode *oye = N0.getOperand(0).getNode();
7857       if (NarrowLoad.getNode() != N0.getNode()) {
7858         CombineTo(N0.getNode(), NarrowLoad);
7859         // CombineTo deleted the truncate, if needed, but not what's under it.
7860         AddToWorklist(oye);
7861       }
7862       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7863     }
7864   }
7865 
7866   // fold (aext (truncate x))
7867   if (N0.getOpcode() == ISD::TRUNCATE)
7868     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7869 
7870   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7871   // if the trunc is not free.
7872   if (N0.getOpcode() == ISD::AND &&
7873       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7874       N0.getOperand(1).getOpcode() == ISD::Constant &&
7875       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7876                           N0.getValueType())) {
7877     SDLoc DL(N);
7878     SDValue X = N0.getOperand(0).getOperand(0);
7879     X = DAG.getAnyExtOrTrunc(X, DL, VT);
7880     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7881     Mask = Mask.zext(VT.getSizeInBits());
7882     return DAG.getNode(ISD::AND, DL, VT,
7883                        X, DAG.getConstant(Mask, DL, VT));
7884   }
7885 
7886   // fold (aext (load x)) -> (aext (truncate (extload x)))
7887   // None of the supported targets knows how to perform load and any_ext
7888   // on vectors in one instruction.  We only perform this transformation on
7889   // scalars.
7890   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7891       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7892       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7893     bool DoXform = true;
7894     SmallVector<SDNode*, 4> SetCCs;
7895     if (!N0.hasOneUse())
7896       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7897     if (DoXform) {
7898       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7899       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7900                                        LN0->getChain(),
7901                                        LN0->getBasePtr(), N0.getValueType(),
7902                                        LN0->getMemOperand());
7903       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7904                                   N0.getValueType(), ExtLoad);
7905       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7906                       ISD::ANY_EXTEND);
7907       // If the load value is used only by N, replace it via CombineTo N.
7908       bool NoReplaceTrunc = N0.hasOneUse();
7909       CombineTo(N, ExtLoad);
7910       if (NoReplaceTrunc)
7911         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7912       else
7913         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7914       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7915     }
7916   }
7917 
7918   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7919   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7920   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7921   if (N0.getOpcode() == ISD::LOAD &&
7922       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7923       N0.hasOneUse()) {
7924     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7925     ISD::LoadExtType ExtType = LN0->getExtensionType();
7926     EVT MemVT = LN0->getMemoryVT();
7927     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7928       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7929                                        VT, LN0->getChain(), LN0->getBasePtr(),
7930                                        MemVT, LN0->getMemOperand());
7931       CombineTo(N, ExtLoad);
7932       CombineTo(N0.getNode(),
7933                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7934                             N0.getValueType(), ExtLoad),
7935                 ExtLoad.getValue(1));
7936       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7937     }
7938   }
7939 
7940   if (N0.getOpcode() == ISD::SETCC) {
7941     // For vectors:
7942     // aext(setcc) -> vsetcc
7943     // aext(setcc) -> truncate(vsetcc)
7944     // aext(setcc) -> aext(vsetcc)
7945     // Only do this before legalize for now.
7946     if (VT.isVector() && !LegalOperations) {
7947       EVT N0VT = N0.getOperand(0).getValueType();
7948         // We know that the # elements of the results is the same as the
7949         // # elements of the compare (and the # elements of the compare result
7950         // for that matter).  Check to see that they are the same size.  If so,
7951         // we know that the element size of the sext'd result matches the
7952         // element size of the compare operands.
7953       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7954         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7955                              N0.getOperand(1),
7956                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7957       // If the desired elements are smaller or larger than the source
7958       // elements we can use a matching integer vector type and then
7959       // truncate/any extend
7960       else {
7961         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7962         SDValue VsetCC =
7963           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7964                         N0.getOperand(1),
7965                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7966         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7967       }
7968     }
7969 
7970     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7971     SDLoc DL(N);
7972     if (SDValue SCC = SimplifySelectCC(
7973             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7974             DAG.getConstant(0, DL, VT),
7975             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7976       return SCC;
7977   }
7978 
7979   return SDValue();
7980 }
7981 
7982 SDValue DAGCombiner::visitAssertExt(SDNode *N) {
7983   unsigned Opcode = N->getOpcode();
7984   SDValue N0 = N->getOperand(0);
7985   SDValue N1 = N->getOperand(1);
7986   EVT AssertVT = cast<VTSDNode>(N1)->getVT();
7987 
7988   // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
7989   if (N0.getOpcode() == Opcode &&
7990       AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7991     return N0;
7992 
7993   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
7994       N0.getOperand(0).getOpcode() == Opcode) {
7995     // We have an assert, truncate, assert sandwich. Make one stronger assert
7996     // by asserting on the smallest asserted type to the larger source type.
7997     // This eliminates the later assert:
7998     // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
7999     // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
8000     SDValue BigA = N0.getOperand(0);
8001     EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
8002     assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
8003            "Asserting zero/sign-extended bits to a type larger than the "
8004            "truncated destination does not provide information");
8005 
8006     SDLoc DL(N);
8007     EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
8008     SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
8009     SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
8010                                     BigA.getOperand(0), MinAssertVTVal);
8011     return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
8012   }
8013 
8014   return SDValue();
8015 }
8016 
8017 /// If the result of a wider load is shifted to right of N  bits and then
8018 /// truncated to a narrower type and where N is a multiple of number of bits of
8019 /// the narrower type, transform it to a narrower load from address + N / num of
8020 /// bits of new type. If the result is to be extended, also fold the extension
8021 /// to form a extending load.
8022 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
8023   unsigned Opc = N->getOpcode();
8024 
8025   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
8026   SDValue N0 = N->getOperand(0);
8027   EVT VT = N->getValueType(0);
8028   EVT ExtVT = VT;
8029 
8030   // This transformation isn't valid for vector loads.
8031   if (VT.isVector())
8032     return SDValue();
8033 
8034   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
8035   // extended to VT.
8036   if (Opc == ISD::SIGN_EXTEND_INREG) {
8037     ExtType = ISD::SEXTLOAD;
8038     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8039   } else if (Opc == ISD::SRL) {
8040     // Another special-case: SRL is basically zero-extending a narrower value.
8041     ExtType = ISD::ZEXTLOAD;
8042     N0 = SDValue(N, 0);
8043     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8044     if (!N01) return SDValue();
8045     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
8046                               VT.getSizeInBits() - N01->getZExtValue());
8047   }
8048   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
8049     return SDValue();
8050 
8051   unsigned EVTBits = ExtVT.getSizeInBits();
8052 
8053   // Do not generate loads of non-round integer types since these can
8054   // be expensive (and would be wrong if the type is not byte sized).
8055   if (!ExtVT.isRound())
8056     return SDValue();
8057 
8058   unsigned ShAmt = 0;
8059   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
8060     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8061       ShAmt = N01->getZExtValue();
8062       // Is the shift amount a multiple of size of VT?
8063       if ((ShAmt & (EVTBits-1)) == 0) {
8064         N0 = N0.getOperand(0);
8065         // Is the load width a multiple of size of VT?
8066         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
8067           return SDValue();
8068       }
8069 
8070       // At this point, we must have a load or else we can't do the transform.
8071       if (!isa<LoadSDNode>(N0)) return SDValue();
8072 
8073       // Because a SRL must be assumed to *need* to zero-extend the high bits
8074       // (as opposed to anyext the high bits), we can't combine the zextload
8075       // lowering of SRL and an sextload.
8076       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
8077         return SDValue();
8078 
8079       // If the shift amount is larger than the input type then we're not
8080       // accessing any of the loaded bytes.  If the load was a zextload/extload
8081       // then the result of the shift+trunc is zero/undef (handled elsewhere).
8082       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
8083         return SDValue();
8084     }
8085   }
8086 
8087   // If the load is shifted left (and the result isn't shifted back right),
8088   // we can fold the truncate through the shift.
8089   unsigned ShLeftAmt = 0;
8090   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8091       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
8092     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8093       ShLeftAmt = N01->getZExtValue();
8094       N0 = N0.getOperand(0);
8095     }
8096   }
8097 
8098   // If we haven't found a load, we can't narrow it.  Don't transform one with
8099   // multiple uses, this would require adding a new load.
8100   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
8101     return SDValue();
8102 
8103   // Don't change the width of a volatile load.
8104   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8105   if (LN0->isVolatile())
8106     return SDValue();
8107 
8108   // Verify that we are actually reducing a load width here.
8109   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
8110     return SDValue();
8111 
8112   // For the transform to be legal, the load must produce only two values
8113   // (the value loaded and the chain).  Don't transform a pre-increment
8114   // load, for example, which produces an extra value.  Otherwise the
8115   // transformation is not equivalent, and the downstream logic to replace
8116   // uses gets things wrong.
8117   if (LN0->getNumValues() > 2)
8118     return SDValue();
8119 
8120   // If the load that we're shrinking is an extload and we're not just
8121   // discarding the extension we can't simply shrink the load. Bail.
8122   // TODO: It would be possible to merge the extensions in some cases.
8123   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
8124       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
8125     return SDValue();
8126 
8127   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
8128     return SDValue();
8129 
8130   EVT PtrType = N0.getOperand(1).getValueType();
8131 
8132   if (PtrType == MVT::Untyped || PtrType.isExtended())
8133     // It's not possible to generate a constant of extended or untyped type.
8134     return SDValue();
8135 
8136   // For big endian targets, we need to adjust the offset to the pointer to
8137   // load the correct bytes.
8138   if (DAG.getDataLayout().isBigEndian()) {
8139     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
8140     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
8141     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
8142   }
8143 
8144   uint64_t PtrOff = ShAmt / 8;
8145   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8146   SDLoc DL(LN0);
8147   // The original load itself didn't wrap, so an offset within it doesn't.
8148   SDNodeFlags Flags;
8149   Flags.setNoUnsignedWrap(true);
8150   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8151                                PtrType, LN0->getBasePtr(),
8152                                DAG.getConstant(PtrOff, DL, PtrType),
8153                                Flags);
8154   AddToWorklist(NewPtr.getNode());
8155 
8156   SDValue Load;
8157   if (ExtType == ISD::NON_EXTLOAD)
8158     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8159                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8160                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8161   else
8162     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8163                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8164                           NewAlign, LN0->getMemOperand()->getFlags(),
8165                           LN0->getAAInfo());
8166 
8167   // Replace the old load's chain with the new load's chain.
8168   WorklistRemover DeadNodes(*this);
8169   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8170 
8171   // Shift the result left, if we've swallowed a left shift.
8172   SDValue Result = Load;
8173   if (ShLeftAmt != 0) {
8174     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8175     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8176       ShImmTy = VT;
8177     // If the shift amount is as large as the result size (but, presumably,
8178     // no larger than the source) then the useful bits of the result are
8179     // zero; we can't simply return the shortened shift, because the result
8180     // of that operation is undefined.
8181     SDLoc DL(N0);
8182     if (ShLeftAmt >= VT.getSizeInBits())
8183       Result = DAG.getConstant(0, DL, VT);
8184     else
8185       Result = DAG.getNode(ISD::SHL, DL, VT,
8186                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8187   }
8188 
8189   // Return the new loaded value.
8190   return Result;
8191 }
8192 
8193 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8194   SDValue N0 = N->getOperand(0);
8195   SDValue N1 = N->getOperand(1);
8196   EVT VT = N->getValueType(0);
8197   EVT EVT = cast<VTSDNode>(N1)->getVT();
8198   unsigned VTBits = VT.getScalarSizeInBits();
8199   unsigned EVTBits = EVT.getScalarSizeInBits();
8200 
8201   if (N0.isUndef())
8202     return DAG.getUNDEF(VT);
8203 
8204   // fold (sext_in_reg c1) -> c1
8205   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8206     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8207 
8208   // If the input is already sign extended, just drop the extension.
8209   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8210     return N0;
8211 
8212   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8213   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8214       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8215     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8216                        N0.getOperand(0), N1);
8217 
8218   // fold (sext_in_reg (sext x)) -> (sext x)
8219   // fold (sext_in_reg (aext x)) -> (sext x)
8220   // if x is small enough.
8221   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8222     SDValue N00 = N0.getOperand(0);
8223     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8224         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8225       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8226   }
8227 
8228   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8229   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8230        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8231        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8232       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8233     if (!LegalOperations ||
8234         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8235       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8236   }
8237 
8238   // fold (sext_in_reg (zext x)) -> (sext x)
8239   // iff we are extending the source sign bit.
8240   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8241     SDValue N00 = N0.getOperand(0);
8242     if (N00.getScalarValueSizeInBits() == EVTBits &&
8243         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8244       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8245   }
8246 
8247   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8248   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8249     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8250 
8251   // fold operands of sext_in_reg based on knowledge that the top bits are not
8252   // demanded.
8253   if (SimplifyDemandedBits(SDValue(N, 0)))
8254     return SDValue(N, 0);
8255 
8256   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8257   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8258   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8259     return NarrowLoad;
8260 
8261   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8262   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8263   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8264   if (N0.getOpcode() == ISD::SRL) {
8265     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8266       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8267         // We can turn this into an SRA iff the input to the SRL is already sign
8268         // extended enough.
8269         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8270         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8271           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8272                              N0.getOperand(0), N0.getOperand(1));
8273       }
8274   }
8275 
8276   // fold (sext_inreg (extload x)) -> (sextload x)
8277   if (ISD::isEXTLoad(N0.getNode()) &&
8278       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8279       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8280       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8281        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8282     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8283     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8284                                      LN0->getChain(),
8285                                      LN0->getBasePtr(), EVT,
8286                                      LN0->getMemOperand());
8287     CombineTo(N, ExtLoad);
8288     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8289     AddToWorklist(ExtLoad.getNode());
8290     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8291   }
8292   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8293   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8294       N0.hasOneUse() &&
8295       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8296       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8297        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8298     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8299     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8300                                      LN0->getChain(),
8301                                      LN0->getBasePtr(), EVT,
8302                                      LN0->getMemOperand());
8303     CombineTo(N, ExtLoad);
8304     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8305     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8306   }
8307 
8308   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8309   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8310     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8311                                            N0.getOperand(1), false))
8312       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8313                          BSwap, N1);
8314   }
8315 
8316   return SDValue();
8317 }
8318 
8319 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8320   SDValue N0 = N->getOperand(0);
8321   EVT VT = N->getValueType(0);
8322 
8323   if (N0.isUndef())
8324     return DAG.getUNDEF(VT);
8325 
8326   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8327                                               LegalOperations))
8328     return SDValue(Res, 0);
8329 
8330   return SDValue();
8331 }
8332 
8333 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8334   SDValue N0 = N->getOperand(0);
8335   EVT VT = N->getValueType(0);
8336 
8337   if (N0.isUndef())
8338     return DAG.getUNDEF(VT);
8339 
8340   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8341                                               LegalOperations))
8342     return SDValue(Res, 0);
8343 
8344   return SDValue();
8345 }
8346 
8347 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8348   SDValue N0 = N->getOperand(0);
8349   EVT VT = N->getValueType(0);
8350   bool isLE = DAG.getDataLayout().isLittleEndian();
8351 
8352   // noop truncate
8353   if (N0.getValueType() == N->getValueType(0))
8354     return N0;
8355   // fold (truncate c1) -> c1
8356   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8357     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8358   // fold (truncate (truncate x)) -> (truncate x)
8359   if (N0.getOpcode() == ISD::TRUNCATE)
8360     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8361   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8362   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8363       N0.getOpcode() == ISD::SIGN_EXTEND ||
8364       N0.getOpcode() == ISD::ANY_EXTEND) {
8365     // if the source is smaller than the dest, we still need an extend.
8366     if (N0.getOperand(0).getValueType().bitsLT(VT))
8367       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8368     // if the source is larger than the dest, than we just need the truncate.
8369     if (N0.getOperand(0).getValueType().bitsGT(VT))
8370       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8371     // if the source and dest are the same type, we can drop both the extend
8372     // and the truncate.
8373     return N0.getOperand(0);
8374   }
8375 
8376   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8377   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8378     return SDValue();
8379 
8380   // Fold extract-and-trunc into a narrow extract. For example:
8381   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8382   //   i32 y = TRUNCATE(i64 x)
8383   //        -- becomes --
8384   //   v16i8 b = BITCAST (v2i64 val)
8385   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8386   //
8387   // Note: We only run this optimization after type legalization (which often
8388   // creates this pattern) and before operation legalization after which
8389   // we need to be more careful about the vector instructions that we generate.
8390   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8391       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8392     EVT VecTy = N0.getOperand(0).getValueType();
8393     EVT ExTy = N0.getValueType();
8394     EVT TrTy = N->getValueType(0);
8395 
8396     unsigned NumElem = VecTy.getVectorNumElements();
8397     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8398 
8399     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8400     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8401 
8402     SDValue EltNo = N0->getOperand(1);
8403     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8404       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8405       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8406       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8407 
8408       SDLoc DL(N);
8409       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8410                          DAG.getBitcast(NVT, N0.getOperand(0)),
8411                          DAG.getConstant(Index, DL, IndexTy));
8412     }
8413   }
8414 
8415   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8416   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8417     EVT SrcVT = N0.getValueType();
8418     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8419         TLI.isTruncateFree(SrcVT, VT)) {
8420       SDLoc SL(N0);
8421       SDValue Cond = N0.getOperand(0);
8422       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8423       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8424       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8425     }
8426   }
8427 
8428   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8429   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8430       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8431       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8432     SDValue Amt = N0.getOperand(1);
8433     KnownBits Known;
8434     DAG.computeKnownBits(Amt, Known);
8435     unsigned Size = VT.getScalarSizeInBits();
8436     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8437       SDLoc SL(N);
8438       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8439 
8440       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8441       if (AmtVT != Amt.getValueType()) {
8442         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8443         AddToWorklist(Amt.getNode());
8444       }
8445       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8446     }
8447   }
8448 
8449   // Fold a series of buildvector, bitcast, and truncate if possible.
8450   // For example fold
8451   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8452   //   (2xi32 (buildvector x, y)).
8453   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8454       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8455       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8456       N0.getOperand(0).hasOneUse()) {
8457     SDValue BuildVect = N0.getOperand(0);
8458     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8459     EVT TruncVecEltTy = VT.getVectorElementType();
8460 
8461     // Check that the element types match.
8462     if (BuildVectEltTy == TruncVecEltTy) {
8463       // Now we only need to compute the offset of the truncated elements.
8464       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8465       unsigned TruncVecNumElts = VT.getVectorNumElements();
8466       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8467 
8468       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8469              "Invalid number of elements");
8470 
8471       SmallVector<SDValue, 8> Opnds;
8472       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8473         Opnds.push_back(BuildVect.getOperand(i));
8474 
8475       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8476     }
8477   }
8478 
8479   // See if we can simplify the input to this truncate through knowledge that
8480   // only the low bits are being used.
8481   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8482   // Currently we only perform this optimization on scalars because vectors
8483   // may have different active low bits.
8484   if (!VT.isVector()) {
8485     APInt Mask =
8486         APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
8487     if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
8488       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8489   }
8490 
8491   // fold (truncate (load x)) -> (smaller load x)
8492   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8493   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8494     if (SDValue Reduced = ReduceLoadWidth(N))
8495       return Reduced;
8496 
8497     // Handle the case where the load remains an extending load even
8498     // after truncation.
8499     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8500       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8501       if (!LN0->isVolatile() &&
8502           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8503         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8504                                          VT, LN0->getChain(), LN0->getBasePtr(),
8505                                          LN0->getMemoryVT(),
8506                                          LN0->getMemOperand());
8507         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8508         return NewLoad;
8509       }
8510     }
8511   }
8512 
8513   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8514   // where ... are all 'undef'.
8515   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8516     SmallVector<EVT, 8> VTs;
8517     SDValue V;
8518     unsigned Idx = 0;
8519     unsigned NumDefs = 0;
8520 
8521     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8522       SDValue X = N0.getOperand(i);
8523       if (!X.isUndef()) {
8524         V = X;
8525         Idx = i;
8526         NumDefs++;
8527       }
8528       // Stop if more than one members are non-undef.
8529       if (NumDefs > 1)
8530         break;
8531       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8532                                      VT.getVectorElementType(),
8533                                      X.getValueType().getVectorNumElements()));
8534     }
8535 
8536     if (NumDefs == 0)
8537       return DAG.getUNDEF(VT);
8538 
8539     if (NumDefs == 1) {
8540       assert(V.getNode() && "The single defined operand is empty!");
8541       SmallVector<SDValue, 8> Opnds;
8542       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8543         if (i != Idx) {
8544           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8545           continue;
8546         }
8547         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8548         AddToWorklist(NV.getNode());
8549         Opnds.push_back(NV);
8550       }
8551       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8552     }
8553   }
8554 
8555   // Fold truncate of a bitcast of a vector to an extract of the low vector
8556   // element.
8557   //
8558   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
8559   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8560     SDValue VecSrc = N0.getOperand(0);
8561     EVT SrcVT = VecSrc.getValueType();
8562     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8563         (!LegalOperations ||
8564          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8565       SDLoc SL(N);
8566 
8567       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8568       unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1;
8569       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8570                          VecSrc, DAG.getConstant(Idx, SL, IdxVT));
8571     }
8572   }
8573 
8574   // Simplify the operands using demanded-bits information.
8575   if (!VT.isVector() &&
8576       SimplifyDemandedBits(SDValue(N, 0)))
8577     return SDValue(N, 0);
8578 
8579   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8580   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8581   // When the adde's carry is not used.
8582   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8583       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8584       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8585     SDLoc SL(N);
8586     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8587     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8588     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8589     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8590   }
8591 
8592   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8593     return NewVSel;
8594 
8595   return SDValue();
8596 }
8597 
8598 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8599   SDValue Elt = N->getOperand(i);
8600   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8601     return Elt.getNode();
8602   return Elt.getOperand(Elt.getResNo()).getNode();
8603 }
8604 
8605 /// build_pair (load, load) -> load
8606 /// if load locations are consecutive.
8607 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8608   assert(N->getOpcode() == ISD::BUILD_PAIR);
8609 
8610   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8611   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8612   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8613       LD1->getAddressSpace() != LD2->getAddressSpace())
8614     return SDValue();
8615   EVT LD1VT = LD1->getValueType(0);
8616   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8617   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8618       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8619     unsigned Align = LD1->getAlignment();
8620     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8621         VT.getTypeForEVT(*DAG.getContext()));
8622 
8623     if (NewAlign <= Align &&
8624         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8625       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8626                          LD1->getPointerInfo(), Align);
8627   }
8628 
8629   return SDValue();
8630 }
8631 
8632 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8633   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8634   // and Lo parts; on big-endian machines it doesn't.
8635   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8636 }
8637 
8638 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8639                                     const TargetLowering &TLI) {
8640   // If this is not a bitcast to an FP type or if the target doesn't have
8641   // IEEE754-compliant FP logic, we're done.
8642   EVT VT = N->getValueType(0);
8643   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8644     return SDValue();
8645 
8646   // TODO: Use splat values for the constant-checking below and remove this
8647   // restriction.
8648   SDValue N0 = N->getOperand(0);
8649   EVT SourceVT = N0.getValueType();
8650   if (SourceVT.isVector())
8651     return SDValue();
8652 
8653   unsigned FPOpcode;
8654   APInt SignMask;
8655   switch (N0.getOpcode()) {
8656   case ISD::AND:
8657     FPOpcode = ISD::FABS;
8658     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8659     break;
8660   case ISD::XOR:
8661     FPOpcode = ISD::FNEG;
8662     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8663     break;
8664   // TODO: ISD::OR --> ISD::FNABS?
8665   default:
8666     return SDValue();
8667   }
8668 
8669   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8670   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8671   SDValue LogicOp0 = N0.getOperand(0);
8672   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8673   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8674       LogicOp0.getOpcode() == ISD::BITCAST &&
8675       LogicOp0->getOperand(0).getValueType() == VT)
8676     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8677 
8678   return SDValue();
8679 }
8680 
8681 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8682   SDValue N0 = N->getOperand(0);
8683   EVT VT = N->getValueType(0);
8684 
8685   if (N0.isUndef())
8686     return DAG.getUNDEF(VT);
8687 
8688   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8689   // Only do this before legalize, since afterward the target may be depending
8690   // on the bitconvert.
8691   // First check to see if this is all constant.
8692   if (!LegalTypes &&
8693       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8694       VT.isVector()) {
8695     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8696 
8697     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8698     assert(!DestEltVT.isVector() &&
8699            "Element type of vector ValueType must not be vector!");
8700     if (isSimple)
8701       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8702   }
8703 
8704   // If the input is a constant, let getNode fold it.
8705   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8706     // If we can't allow illegal operations, we need to check that this is just
8707     // a fp -> int or int -> conversion and that the resulting operation will
8708     // be legal.
8709     if (!LegalOperations ||
8710         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8711          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8712         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8713          TLI.isOperationLegal(ISD::Constant, VT)))
8714       return DAG.getBitcast(VT, N0);
8715   }
8716 
8717   // (conv (conv x, t1), t2) -> (conv x, t2)
8718   if (N0.getOpcode() == ISD::BITCAST)
8719     return DAG.getBitcast(VT, N0.getOperand(0));
8720 
8721   // fold (conv (load x)) -> (load (conv*)x)
8722   // If the resultant load doesn't need a higher alignment than the original!
8723   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8724       // Do not change the width of a volatile load.
8725       !cast<LoadSDNode>(N0)->isVolatile() &&
8726       // Do not remove the cast if the types differ in endian layout.
8727       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8728           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8729       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8730       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8731     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8732     unsigned OrigAlign = LN0->getAlignment();
8733 
8734     bool Fast = false;
8735     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8736                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8737         Fast) {
8738       SDValue Load =
8739           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8740                       LN0->getPointerInfo(), OrigAlign,
8741                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8742       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8743       return Load;
8744     }
8745   }
8746 
8747   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8748     return V;
8749 
8750   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8751   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8752   //
8753   // For ppc_fp128:
8754   // fold (bitcast (fneg x)) ->
8755   //     flipbit = signbit
8756   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8757   //
8758   // fold (bitcast (fabs x)) ->
8759   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8760   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8761   // This often reduces constant pool loads.
8762   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8763        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8764       N0.getNode()->hasOneUse() && VT.isInteger() &&
8765       !VT.isVector() && !N0.getValueType().isVector()) {
8766     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8767     AddToWorklist(NewConv.getNode());
8768 
8769     SDLoc DL(N);
8770     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8771       assert(VT.getSizeInBits() == 128);
8772       SDValue SignBit = DAG.getConstant(
8773           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8774       SDValue FlipBit;
8775       if (N0.getOpcode() == ISD::FNEG) {
8776         FlipBit = SignBit;
8777         AddToWorklist(FlipBit.getNode());
8778       } else {
8779         assert(N0.getOpcode() == ISD::FABS);
8780         SDValue Hi =
8781             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8782                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8783                                               SDLoc(NewConv)));
8784         AddToWorklist(Hi.getNode());
8785         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8786         AddToWorklist(FlipBit.getNode());
8787       }
8788       SDValue FlipBits =
8789           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8790       AddToWorklist(FlipBits.getNode());
8791       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8792     }
8793     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8794     if (N0.getOpcode() == ISD::FNEG)
8795       return DAG.getNode(ISD::XOR, DL, VT,
8796                          NewConv, DAG.getConstant(SignBit, DL, VT));
8797     assert(N0.getOpcode() == ISD::FABS);
8798     return DAG.getNode(ISD::AND, DL, VT,
8799                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8800   }
8801 
8802   // fold (bitconvert (fcopysign cst, x)) ->
8803   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8804   // Note that we don't handle (copysign x, cst) because this can always be
8805   // folded to an fneg or fabs.
8806   //
8807   // For ppc_fp128:
8808   // fold (bitcast (fcopysign cst, x)) ->
8809   //     flipbit = (and (extract_element
8810   //                     (xor (bitcast cst), (bitcast x)), 0),
8811   //                    signbit)
8812   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8813   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8814       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8815       VT.isInteger() && !VT.isVector()) {
8816     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8817     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8818     if (isTypeLegal(IntXVT)) {
8819       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8820       AddToWorklist(X.getNode());
8821 
8822       // If X has a different width than the result/lhs, sext it or truncate it.
8823       unsigned VTWidth = VT.getSizeInBits();
8824       if (OrigXWidth < VTWidth) {
8825         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8826         AddToWorklist(X.getNode());
8827       } else if (OrigXWidth > VTWidth) {
8828         // To get the sign bit in the right place, we have to shift it right
8829         // before truncating.
8830         SDLoc DL(X);
8831         X = DAG.getNode(ISD::SRL, DL,
8832                         X.getValueType(), X,
8833                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8834                                         X.getValueType()));
8835         AddToWorklist(X.getNode());
8836         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8837         AddToWorklist(X.getNode());
8838       }
8839 
8840       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8841         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8842         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8843         AddToWorklist(Cst.getNode());
8844         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8845         AddToWorklist(X.getNode());
8846         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8847         AddToWorklist(XorResult.getNode());
8848         SDValue XorResult64 = DAG.getNode(
8849             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8850             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8851                                   SDLoc(XorResult)));
8852         AddToWorklist(XorResult64.getNode());
8853         SDValue FlipBit =
8854             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8855                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8856         AddToWorklist(FlipBit.getNode());
8857         SDValue FlipBits =
8858             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8859         AddToWorklist(FlipBits.getNode());
8860         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8861       }
8862       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8863       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8864                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8865       AddToWorklist(X.getNode());
8866 
8867       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8868       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8869                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8870       AddToWorklist(Cst.getNode());
8871 
8872       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8873     }
8874   }
8875 
8876   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8877   if (N0.getOpcode() == ISD::BUILD_PAIR)
8878     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8879       return CombineLD;
8880 
8881   // Remove double bitcasts from shuffles - this is often a legacy of
8882   // XformToShuffleWithZero being used to combine bitmaskings (of
8883   // float vectors bitcast to integer vectors) into shuffles.
8884   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8885   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8886       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8887       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8888       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8889     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8890 
8891     // If operands are a bitcast, peek through if it casts the original VT.
8892     // If operands are a constant, just bitcast back to original VT.
8893     auto PeekThroughBitcast = [&](SDValue Op) {
8894       if (Op.getOpcode() == ISD::BITCAST &&
8895           Op.getOperand(0).getValueType() == VT)
8896         return SDValue(Op.getOperand(0));
8897       if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8898           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8899         return DAG.getBitcast(VT, Op);
8900       return SDValue();
8901     };
8902 
8903     // FIXME: If either input vector is bitcast, try to convert the shuffle to
8904     // the result type of this bitcast. This would eliminate at least one
8905     // bitcast. See the transform in InstCombine.
8906     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8907     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8908     if (!(SV0 && SV1))
8909       return SDValue();
8910 
8911     int MaskScale =
8912         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8913     SmallVector<int, 8> NewMask;
8914     for (int M : SVN->getMask())
8915       for (int i = 0; i != MaskScale; ++i)
8916         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8917 
8918     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8919     if (!LegalMask) {
8920       std::swap(SV0, SV1);
8921       ShuffleVectorSDNode::commuteMask(NewMask);
8922       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8923     }
8924 
8925     if (LegalMask)
8926       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8927   }
8928 
8929   return SDValue();
8930 }
8931 
8932 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8933   EVT VT = N->getValueType(0);
8934   return CombineConsecutiveLoads(N, VT);
8935 }
8936 
8937 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8938 /// operands. DstEltVT indicates the destination element value type.
8939 SDValue DAGCombiner::
8940 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8941   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8942 
8943   // If this is already the right type, we're done.
8944   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8945 
8946   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8947   unsigned DstBitSize = DstEltVT.getSizeInBits();
8948 
8949   // If this is a conversion of N elements of one type to N elements of another
8950   // type, convert each element.  This handles FP<->INT cases.
8951   if (SrcBitSize == DstBitSize) {
8952     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8953                               BV->getValueType(0).getVectorNumElements());
8954 
8955     // Due to the FP element handling below calling this routine recursively,
8956     // we can end up with a scalar-to-vector node here.
8957     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8958       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8959                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8960 
8961     SmallVector<SDValue, 8> Ops;
8962     for (SDValue Op : BV->op_values()) {
8963       // If the vector element type is not legal, the BUILD_VECTOR operands
8964       // are promoted and implicitly truncated.  Make that explicit here.
8965       if (Op.getValueType() != SrcEltVT)
8966         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8967       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8968       AddToWorklist(Ops.back().getNode());
8969     }
8970     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8971   }
8972 
8973   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8974   // handle annoying details of growing/shrinking FP values, we convert them to
8975   // int first.
8976   if (SrcEltVT.isFloatingPoint()) {
8977     // Convert the input float vector to a int vector where the elements are the
8978     // same sizes.
8979     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8980     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8981     SrcEltVT = IntVT;
8982   }
8983 
8984   // Now we know the input is an integer vector.  If the output is a FP type,
8985   // convert to integer first, then to FP of the right size.
8986   if (DstEltVT.isFloatingPoint()) {
8987     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8988     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8989 
8990     // Next, convert to FP elements of the same size.
8991     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8992   }
8993 
8994   SDLoc DL(BV);
8995 
8996   // Okay, we know the src/dst types are both integers of differing types.
8997   // Handling growing first.
8998   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8999   if (SrcBitSize < DstBitSize) {
9000     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
9001 
9002     SmallVector<SDValue, 8> Ops;
9003     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
9004          i += NumInputsPerOutput) {
9005       bool isLE = DAG.getDataLayout().isLittleEndian();
9006       APInt NewBits = APInt(DstBitSize, 0);
9007       bool EltIsUndef = true;
9008       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
9009         // Shift the previously computed bits over.
9010         NewBits <<= SrcBitSize;
9011         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
9012         if (Op.isUndef()) continue;
9013         EltIsUndef = false;
9014 
9015         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
9016                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
9017       }
9018 
9019       if (EltIsUndef)
9020         Ops.push_back(DAG.getUNDEF(DstEltVT));
9021       else
9022         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
9023     }
9024 
9025     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
9026     return DAG.getBuildVector(VT, DL, Ops);
9027   }
9028 
9029   // Finally, this must be the case where we are shrinking elements: each input
9030   // turns into multiple outputs.
9031   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
9032   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9033                             NumOutputsPerInput*BV->getNumOperands());
9034   SmallVector<SDValue, 8> Ops;
9035 
9036   for (const SDValue &Op : BV->op_values()) {
9037     if (Op.isUndef()) {
9038       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
9039       continue;
9040     }
9041 
9042     APInt OpVal = cast<ConstantSDNode>(Op)->
9043                   getAPIntValue().zextOrTrunc(SrcBitSize);
9044 
9045     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
9046       APInt ThisVal = OpVal.trunc(DstBitSize);
9047       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
9048       OpVal.lshrInPlace(DstBitSize);
9049     }
9050 
9051     // For big endian targets, swap the order of the pieces of each element.
9052     if (DAG.getDataLayout().isBigEndian())
9053       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
9054   }
9055 
9056   return DAG.getBuildVector(VT, DL, Ops);
9057 }
9058 
9059 static bool isContractable(SDNode *N) {
9060   SDNodeFlags F = N->getFlags();
9061   return F.hasAllowContract() || F.hasUnsafeAlgebra();
9062 }
9063 
9064 /// Try to perform FMA combining on a given FADD node.
9065 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
9066   SDValue N0 = N->getOperand(0);
9067   SDValue N1 = N->getOperand(1);
9068   EVT VT = N->getValueType(0);
9069   SDLoc SL(N);
9070 
9071   const TargetOptions &Options = DAG.getTarget().Options;
9072 
9073   // Floating-point multiply-add with intermediate rounding.
9074   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9075 
9076   // Floating-point multiply-add without intermediate rounding.
9077   bool HasFMA =
9078       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9079       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9080 
9081   // No valid opcode, do not combine.
9082   if (!HasFMAD && !HasFMA)
9083     return SDValue();
9084 
9085   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9086                               Options.UnsafeFPMath || HasFMAD);
9087   // If the addition is not contractable, do not combine.
9088   if (!AllowFusionGlobally && !isContractable(N))
9089     return SDValue();
9090 
9091   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9092   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9093     return SDValue();
9094 
9095   // Always prefer FMAD to FMA for precision.
9096   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9097   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9098   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9099 
9100   // Is the node an FMUL and contractable either due to global flags or
9101   // SDNodeFlags.
9102   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9103     if (N.getOpcode() != ISD::FMUL)
9104       return false;
9105     return AllowFusionGlobally || isContractable(N.getNode());
9106   };
9107   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
9108   // prefer to fold the multiply with fewer uses.
9109   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
9110     if (N0.getNode()->use_size() > N1.getNode()->use_size())
9111       std::swap(N0, N1);
9112   }
9113 
9114   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
9115   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9116     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9117                        N0.getOperand(0), N0.getOperand(1), N1);
9118   }
9119 
9120   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
9121   // Note: Commutes FADD operands.
9122   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
9123     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9124                        N1.getOperand(0), N1.getOperand(1), N0);
9125   }
9126 
9127   // Look through FP_EXTEND nodes to do more combining.
9128   if (LookThroughFPExt) {
9129     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
9130     if (N0.getOpcode() == ISD::FP_EXTEND) {
9131       SDValue N00 = N0.getOperand(0);
9132       if (isContractableFMUL(N00))
9133         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9134                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9135                                        N00.getOperand(0)),
9136                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9137                                        N00.getOperand(1)), N1);
9138     }
9139 
9140     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
9141     // Note: Commutes FADD operands.
9142     if (N1.getOpcode() == ISD::FP_EXTEND) {
9143       SDValue N10 = N1.getOperand(0);
9144       if (isContractableFMUL(N10))
9145         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9146                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9147                                        N10.getOperand(0)),
9148                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9149                                        N10.getOperand(1)), N0);
9150     }
9151   }
9152 
9153   // More folding opportunities when target permits.
9154   if (Aggressive) {
9155     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9156     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9157     // are currently only supported on binary nodes.
9158     if (Options.UnsafeFPMath &&
9159         N0.getOpcode() == PreferredFusedOpcode &&
9160         N0.getOperand(2).getOpcode() == ISD::FMUL &&
9161         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9162       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9163                          N0.getOperand(0), N0.getOperand(1),
9164                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9165                                      N0.getOperand(2).getOperand(0),
9166                                      N0.getOperand(2).getOperand(1),
9167                                      N1));
9168     }
9169 
9170     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9171     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9172     // are currently only supported on binary nodes.
9173     if (Options.UnsafeFPMath &&
9174         N1->getOpcode() == PreferredFusedOpcode &&
9175         N1.getOperand(2).getOpcode() == ISD::FMUL &&
9176         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9177       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9178                          N1.getOperand(0), N1.getOperand(1),
9179                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9180                                      N1.getOperand(2).getOperand(0),
9181                                      N1.getOperand(2).getOperand(1),
9182                                      N0));
9183     }
9184 
9185     if (LookThroughFPExt) {
9186       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9187       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
9188       auto FoldFAddFMAFPExtFMul = [&] (
9189           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9190         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9191                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9192                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9193                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9194                                        Z));
9195       };
9196       if (N0.getOpcode() == PreferredFusedOpcode) {
9197         SDValue N02 = N0.getOperand(2);
9198         if (N02.getOpcode() == ISD::FP_EXTEND) {
9199           SDValue N020 = N02.getOperand(0);
9200           if (isContractableFMUL(N020))
9201             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9202                                         N020.getOperand(0), N020.getOperand(1),
9203                                         N1);
9204         }
9205       }
9206 
9207       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9208       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9209       // FIXME: This turns two single-precision and one double-precision
9210       // operation into two double-precision operations, which might not be
9211       // interesting for all targets, especially GPUs.
9212       auto FoldFAddFPExtFMAFMul = [&] (
9213           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9214         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9215                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9216                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9217                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9218                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9219                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9220                                        Z));
9221       };
9222       if (N0.getOpcode() == ISD::FP_EXTEND) {
9223         SDValue N00 = N0.getOperand(0);
9224         if (N00.getOpcode() == PreferredFusedOpcode) {
9225           SDValue N002 = N00.getOperand(2);
9226           if (isContractableFMUL(N002))
9227             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9228                                         N002.getOperand(0), N002.getOperand(1),
9229                                         N1);
9230         }
9231       }
9232 
9233       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9234       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9235       if (N1.getOpcode() == PreferredFusedOpcode) {
9236         SDValue N12 = N1.getOperand(2);
9237         if (N12.getOpcode() == ISD::FP_EXTEND) {
9238           SDValue N120 = N12.getOperand(0);
9239           if (isContractableFMUL(N120))
9240             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9241                                         N120.getOperand(0), N120.getOperand(1),
9242                                         N0);
9243         }
9244       }
9245 
9246       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9247       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9248       // FIXME: This turns two single-precision and one double-precision
9249       // operation into two double-precision operations, which might not be
9250       // interesting for all targets, especially GPUs.
9251       if (N1.getOpcode() == ISD::FP_EXTEND) {
9252         SDValue N10 = N1.getOperand(0);
9253         if (N10.getOpcode() == PreferredFusedOpcode) {
9254           SDValue N102 = N10.getOperand(2);
9255           if (isContractableFMUL(N102))
9256             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9257                                         N102.getOperand(0), N102.getOperand(1),
9258                                         N0);
9259         }
9260       }
9261     }
9262   }
9263 
9264   return SDValue();
9265 }
9266 
9267 /// Try to perform FMA combining on a given FSUB node.
9268 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9269   SDValue N0 = N->getOperand(0);
9270   SDValue N1 = N->getOperand(1);
9271   EVT VT = N->getValueType(0);
9272   SDLoc SL(N);
9273 
9274   const TargetOptions &Options = DAG.getTarget().Options;
9275   // Floating-point multiply-add with intermediate rounding.
9276   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9277 
9278   // Floating-point multiply-add without intermediate rounding.
9279   bool HasFMA =
9280       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9281       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9282 
9283   // No valid opcode, do not combine.
9284   if (!HasFMAD && !HasFMA)
9285     return SDValue();
9286 
9287   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9288                               Options.UnsafeFPMath || HasFMAD);
9289   // If the subtraction is not contractable, do not combine.
9290   if (!AllowFusionGlobally && !isContractable(N))
9291     return SDValue();
9292 
9293   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9294   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9295     return SDValue();
9296 
9297   // Always prefer FMAD to FMA for precision.
9298   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9299   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9300   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9301 
9302   // Is the node an FMUL and contractable either due to global flags or
9303   // SDNodeFlags.
9304   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9305     if (N.getOpcode() != ISD::FMUL)
9306       return false;
9307     return AllowFusionGlobally || isContractable(N.getNode());
9308   };
9309 
9310   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9311   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9312     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9313                        N0.getOperand(0), N0.getOperand(1),
9314                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9315   }
9316 
9317   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9318   // Note: Commutes FSUB operands.
9319   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9320     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9321                        DAG.getNode(ISD::FNEG, SL, VT,
9322                                    N1.getOperand(0)),
9323                        N1.getOperand(1), N0);
9324 
9325   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9326   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9327       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9328     SDValue N00 = N0.getOperand(0).getOperand(0);
9329     SDValue N01 = N0.getOperand(0).getOperand(1);
9330     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9331                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9332                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9333   }
9334 
9335   // Look through FP_EXTEND nodes to do more combining.
9336   if (LookThroughFPExt) {
9337     // fold (fsub (fpext (fmul x, y)), z)
9338     //   -> (fma (fpext x), (fpext y), (fneg z))
9339     if (N0.getOpcode() == ISD::FP_EXTEND) {
9340       SDValue N00 = N0.getOperand(0);
9341       if (isContractableFMUL(N00))
9342         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9343                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9344                                        N00.getOperand(0)),
9345                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9346                                        N00.getOperand(1)),
9347                            DAG.getNode(ISD::FNEG, SL, VT, N1));
9348     }
9349 
9350     // fold (fsub x, (fpext (fmul y, z)))
9351     //   -> (fma (fneg (fpext y)), (fpext z), x)
9352     // Note: Commutes FSUB operands.
9353     if (N1.getOpcode() == ISD::FP_EXTEND) {
9354       SDValue N10 = N1.getOperand(0);
9355       if (isContractableFMUL(N10))
9356         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9357                            DAG.getNode(ISD::FNEG, SL, VT,
9358                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9359                                                    N10.getOperand(0))),
9360                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9361                                        N10.getOperand(1)),
9362                            N0);
9363     }
9364 
9365     // fold (fsub (fpext (fneg (fmul, x, y))), z)
9366     //   -> (fneg (fma (fpext x), (fpext y), z))
9367     // Note: This could be removed with appropriate canonicalization of the
9368     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9369     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9370     // from implementing the canonicalization in visitFSUB.
9371     if (N0.getOpcode() == ISD::FP_EXTEND) {
9372       SDValue N00 = N0.getOperand(0);
9373       if (N00.getOpcode() == ISD::FNEG) {
9374         SDValue N000 = N00.getOperand(0);
9375         if (isContractableFMUL(N000)) {
9376           return DAG.getNode(ISD::FNEG, SL, VT,
9377                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9378                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9379                                                      N000.getOperand(0)),
9380                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9381                                                      N000.getOperand(1)),
9382                                          N1));
9383         }
9384       }
9385     }
9386 
9387     // fold (fsub (fneg (fpext (fmul, x, y))), z)
9388     //   -> (fneg (fma (fpext x)), (fpext y), z)
9389     // Note: This could be removed with appropriate canonicalization of the
9390     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9391     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9392     // from implementing the canonicalization in visitFSUB.
9393     if (N0.getOpcode() == ISD::FNEG) {
9394       SDValue N00 = N0.getOperand(0);
9395       if (N00.getOpcode() == ISD::FP_EXTEND) {
9396         SDValue N000 = N00.getOperand(0);
9397         if (isContractableFMUL(N000)) {
9398           return DAG.getNode(ISD::FNEG, SL, VT,
9399                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9400                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9401                                                      N000.getOperand(0)),
9402                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9403                                                      N000.getOperand(1)),
9404                                          N1));
9405         }
9406       }
9407     }
9408 
9409   }
9410 
9411   // More folding opportunities when target permits.
9412   if (Aggressive) {
9413     // fold (fsub (fma x, y, (fmul u, v)), z)
9414     //   -> (fma x, y (fma u, v, (fneg z)))
9415     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9416     // are currently only supported on binary nodes.
9417     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9418         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9419         N0.getOperand(2)->hasOneUse()) {
9420       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9421                          N0.getOperand(0), N0.getOperand(1),
9422                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9423                                      N0.getOperand(2).getOperand(0),
9424                                      N0.getOperand(2).getOperand(1),
9425                                      DAG.getNode(ISD::FNEG, SL, VT,
9426                                                  N1)));
9427     }
9428 
9429     // fold (fsub x, (fma y, z, (fmul u, v)))
9430     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9431     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9432     // are currently only supported on binary nodes.
9433     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9434         isContractableFMUL(N1.getOperand(2))) {
9435       SDValue N20 = N1.getOperand(2).getOperand(0);
9436       SDValue N21 = N1.getOperand(2).getOperand(1);
9437       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9438                          DAG.getNode(ISD::FNEG, SL, VT,
9439                                      N1.getOperand(0)),
9440                          N1.getOperand(1),
9441                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9442                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9443 
9444                                      N21, N0));
9445     }
9446 
9447     if (LookThroughFPExt) {
9448       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9449       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9450       if (N0.getOpcode() == PreferredFusedOpcode) {
9451         SDValue N02 = N0.getOperand(2);
9452         if (N02.getOpcode() == ISD::FP_EXTEND) {
9453           SDValue N020 = N02.getOperand(0);
9454           if (isContractableFMUL(N020))
9455             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9456                                N0.getOperand(0), N0.getOperand(1),
9457                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9458                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9459                                                        N020.getOperand(0)),
9460                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9461                                                        N020.getOperand(1)),
9462                                            DAG.getNode(ISD::FNEG, SL, VT,
9463                                                        N1)));
9464         }
9465       }
9466 
9467       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9468       //   -> (fma (fpext x), (fpext y),
9469       //           (fma (fpext u), (fpext v), (fneg z)))
9470       // FIXME: This turns two single-precision and one double-precision
9471       // operation into two double-precision operations, which might not be
9472       // interesting for all targets, especially GPUs.
9473       if (N0.getOpcode() == ISD::FP_EXTEND) {
9474         SDValue N00 = N0.getOperand(0);
9475         if (N00.getOpcode() == PreferredFusedOpcode) {
9476           SDValue N002 = N00.getOperand(2);
9477           if (isContractableFMUL(N002))
9478             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9479                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9480                                            N00.getOperand(0)),
9481                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9482                                            N00.getOperand(1)),
9483                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9484                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9485                                                        N002.getOperand(0)),
9486                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9487                                                        N002.getOperand(1)),
9488                                            DAG.getNode(ISD::FNEG, SL, VT,
9489                                                        N1)));
9490         }
9491       }
9492 
9493       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9494       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9495       if (N1.getOpcode() == PreferredFusedOpcode &&
9496         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9497         SDValue N120 = N1.getOperand(2).getOperand(0);
9498         if (isContractableFMUL(N120)) {
9499           SDValue N1200 = N120.getOperand(0);
9500           SDValue N1201 = N120.getOperand(1);
9501           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9502                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9503                              N1.getOperand(1),
9504                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9505                                          DAG.getNode(ISD::FNEG, SL, VT,
9506                                              DAG.getNode(ISD::FP_EXTEND, SL,
9507                                                          VT, N1200)),
9508                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9509                                                      N1201),
9510                                          N0));
9511         }
9512       }
9513 
9514       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9515       //   -> (fma (fneg (fpext y)), (fpext z),
9516       //           (fma (fneg (fpext u)), (fpext v), x))
9517       // FIXME: This turns two single-precision and one double-precision
9518       // operation into two double-precision operations, which might not be
9519       // interesting for all targets, especially GPUs.
9520       if (N1.getOpcode() == ISD::FP_EXTEND &&
9521         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9522         SDValue N100 = N1.getOperand(0).getOperand(0);
9523         SDValue N101 = N1.getOperand(0).getOperand(1);
9524         SDValue N102 = N1.getOperand(0).getOperand(2);
9525         if (isContractableFMUL(N102)) {
9526           SDValue N1020 = N102.getOperand(0);
9527           SDValue N1021 = N102.getOperand(1);
9528           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9529                              DAG.getNode(ISD::FNEG, SL, VT,
9530                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9531                                                      N100)),
9532                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9533                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9534                                          DAG.getNode(ISD::FNEG, SL, VT,
9535                                              DAG.getNode(ISD::FP_EXTEND, SL,
9536                                                          VT, N1020)),
9537                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9538                                                      N1021),
9539                                          N0));
9540         }
9541       }
9542     }
9543   }
9544 
9545   return SDValue();
9546 }
9547 
9548 /// Try to perform FMA combining on a given FMUL node based on the distributive
9549 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9550 /// subtraction instead of addition).
9551 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9552   SDValue N0 = N->getOperand(0);
9553   SDValue N1 = N->getOperand(1);
9554   EVT VT = N->getValueType(0);
9555   SDLoc SL(N);
9556 
9557   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9558 
9559   const TargetOptions &Options = DAG.getTarget().Options;
9560 
9561   // The transforms below are incorrect when x == 0 and y == inf, because the
9562   // intermediate multiplication produces a nan.
9563   if (!Options.NoInfsFPMath)
9564     return SDValue();
9565 
9566   // Floating-point multiply-add without intermediate rounding.
9567   bool HasFMA =
9568       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9569       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9570       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9571 
9572   // Floating-point multiply-add with intermediate rounding. This can result
9573   // in a less precise result due to the changed rounding order.
9574   bool HasFMAD = Options.UnsafeFPMath &&
9575                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9576 
9577   // No valid opcode, do not combine.
9578   if (!HasFMAD && !HasFMA)
9579     return SDValue();
9580 
9581   // Always prefer FMAD to FMA for precision.
9582   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9583   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9584 
9585   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9586   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9587   auto FuseFADD = [&](SDValue X, SDValue Y) {
9588     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9589       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9590       if (XC1 && XC1->isExactlyValue(+1.0))
9591         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9592       if (XC1 && XC1->isExactlyValue(-1.0))
9593         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9594                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9595     }
9596     return SDValue();
9597   };
9598 
9599   if (SDValue FMA = FuseFADD(N0, N1))
9600     return FMA;
9601   if (SDValue FMA = FuseFADD(N1, N0))
9602     return FMA;
9603 
9604   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9605   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9606   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9607   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9608   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9609     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9610       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9611       if (XC0 && XC0->isExactlyValue(+1.0))
9612         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9613                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9614                            Y);
9615       if (XC0 && XC0->isExactlyValue(-1.0))
9616         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9617                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9618                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9619 
9620       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9621       if (XC1 && XC1->isExactlyValue(+1.0))
9622         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9623                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9624       if (XC1 && XC1->isExactlyValue(-1.0))
9625         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9626     }
9627     return SDValue();
9628   };
9629 
9630   if (SDValue FMA = FuseFSUB(N0, N1))
9631     return FMA;
9632   if (SDValue FMA = FuseFSUB(N1, N0))
9633     return FMA;
9634 
9635   return SDValue();
9636 }
9637 
9638 static bool isFMulNegTwo(SDValue &N) {
9639   if (N.getOpcode() != ISD::FMUL)
9640     return false;
9641   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9642     return CFP->isExactlyValue(-2.0);
9643   return false;
9644 }
9645 
9646 SDValue DAGCombiner::visitFADD(SDNode *N) {
9647   SDValue N0 = N->getOperand(0);
9648   SDValue N1 = N->getOperand(1);
9649   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9650   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9651   EVT VT = N->getValueType(0);
9652   SDLoc DL(N);
9653   const TargetOptions &Options = DAG.getTarget().Options;
9654   const SDNodeFlags Flags = N->getFlags();
9655 
9656   // fold vector ops
9657   if (VT.isVector())
9658     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9659       return FoldedVOp;
9660 
9661   // fold (fadd c1, c2) -> c1 + c2
9662   if (N0CFP && N1CFP)
9663     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9664 
9665   // canonicalize constant to RHS
9666   if (N0CFP && !N1CFP)
9667     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9668 
9669   if (SDValue NewSel = foldBinOpIntoSelect(N))
9670     return NewSel;
9671 
9672   // fold (fadd A, (fneg B)) -> (fsub A, B)
9673   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9674       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9675     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9676                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9677 
9678   // fold (fadd (fneg A), B) -> (fsub B, A)
9679   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9680       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9681     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9682                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9683 
9684   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9685   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9686   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9687       (isFMulNegTwo(N1) && N1.hasOneUse())) {
9688     bool N1IsFMul = isFMulNegTwo(N1);
9689     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9690     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9691     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9692   }
9693 
9694   // FIXME: Auto-upgrade the target/function-level option.
9695   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9696     // fold (fadd A, 0) -> A
9697     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9698       if (N1C->isZero())
9699         return N0;
9700   }
9701 
9702   // If 'unsafe math' is enabled, fold lots of things.
9703   if (Options.UnsafeFPMath) {
9704     // No FP constant should be created after legalization as Instruction
9705     // Selection pass has a hard time dealing with FP constants.
9706     bool AllowNewConst = (Level < AfterLegalizeDAG);
9707 
9708     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9709     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9710         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9711       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9712                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9713                                      Flags),
9714                          Flags);
9715 
9716     // If allowed, fold (fadd (fneg x), x) -> 0.0
9717     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9718       return DAG.getConstantFP(0.0, DL, VT);
9719 
9720     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9721     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9722       return DAG.getConstantFP(0.0, DL, VT);
9723 
9724     // We can fold chains of FADD's of the same value into multiplications.
9725     // This transform is not safe in general because we are reducing the number
9726     // of rounding steps.
9727     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9728       if (N0.getOpcode() == ISD::FMUL) {
9729         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9730         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9731 
9732         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9733         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9734           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9735                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9736           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9737         }
9738 
9739         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9740         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9741             N1.getOperand(0) == N1.getOperand(1) &&
9742             N0.getOperand(0) == N1.getOperand(0)) {
9743           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9744                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9745           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9746         }
9747       }
9748 
9749       if (N1.getOpcode() == ISD::FMUL) {
9750         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9751         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9752 
9753         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9754         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9755           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9756                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9757           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9758         }
9759 
9760         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9761         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9762             N0.getOperand(0) == N0.getOperand(1) &&
9763             N1.getOperand(0) == N0.getOperand(0)) {
9764           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9765                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9766           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9767         }
9768       }
9769 
9770       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9771         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9772         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9773         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9774             (N0.getOperand(0) == N1)) {
9775           return DAG.getNode(ISD::FMUL, DL, VT,
9776                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9777         }
9778       }
9779 
9780       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9781         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9782         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9783         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9784             N1.getOperand(0) == N0) {
9785           return DAG.getNode(ISD::FMUL, DL, VT,
9786                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9787         }
9788       }
9789 
9790       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9791       if (AllowNewConst &&
9792           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9793           N0.getOperand(0) == N0.getOperand(1) &&
9794           N1.getOperand(0) == N1.getOperand(1) &&
9795           N0.getOperand(0) == N1.getOperand(0)) {
9796         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9797                            DAG.getConstantFP(4.0, DL, VT), Flags);
9798       }
9799     }
9800   } // enable-unsafe-fp-math
9801 
9802   // FADD -> FMA combines:
9803   if (SDValue Fused = visitFADDForFMACombine(N)) {
9804     AddToWorklist(Fused.getNode());
9805     return Fused;
9806   }
9807   return SDValue();
9808 }
9809 
9810 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9811   SDValue N0 = N->getOperand(0);
9812   SDValue N1 = N->getOperand(1);
9813   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9814   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9815   EVT VT = N->getValueType(0);
9816   SDLoc DL(N);
9817   const TargetOptions &Options = DAG.getTarget().Options;
9818   const SDNodeFlags Flags = N->getFlags();
9819 
9820   // fold vector ops
9821   if (VT.isVector())
9822     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9823       return FoldedVOp;
9824 
9825   // fold (fsub c1, c2) -> c1-c2
9826   if (N0CFP && N1CFP)
9827     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9828 
9829   if (SDValue NewSel = foldBinOpIntoSelect(N))
9830     return NewSel;
9831 
9832   // fold (fsub A, (fneg B)) -> (fadd A, B)
9833   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9834     return DAG.getNode(ISD::FADD, DL, VT, N0,
9835                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9836 
9837   // FIXME: Auto-upgrade the target/function-level option.
9838   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
9839     // (fsub 0, B) -> -B
9840     if (N0CFP && N0CFP->isZero()) {
9841       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9842         return GetNegatedExpression(N1, DAG, LegalOperations);
9843       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9844         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9845     }
9846   }
9847 
9848   // If 'unsafe math' is enabled, fold lots of things.
9849   if (Options.UnsafeFPMath) {
9850     // (fsub A, 0) -> A
9851     if (N1CFP && N1CFP->isZero())
9852       return N0;
9853 
9854     // (fsub x, x) -> 0.0
9855     if (N0 == N1)
9856       return DAG.getConstantFP(0.0f, DL, VT);
9857 
9858     // (fsub x, (fadd x, y)) -> (fneg y)
9859     // (fsub x, (fadd y, x)) -> (fneg y)
9860     if (N1.getOpcode() == ISD::FADD) {
9861       SDValue N10 = N1->getOperand(0);
9862       SDValue N11 = N1->getOperand(1);
9863 
9864       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9865         return GetNegatedExpression(N11, DAG, LegalOperations);
9866 
9867       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9868         return GetNegatedExpression(N10, DAG, LegalOperations);
9869     }
9870   }
9871 
9872   // FSUB -> FMA combines:
9873   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9874     AddToWorklist(Fused.getNode());
9875     return Fused;
9876   }
9877 
9878   return SDValue();
9879 }
9880 
9881 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9882   SDValue N0 = N->getOperand(0);
9883   SDValue N1 = N->getOperand(1);
9884   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9885   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9886   EVT VT = N->getValueType(0);
9887   SDLoc DL(N);
9888   const TargetOptions &Options = DAG.getTarget().Options;
9889   const SDNodeFlags Flags = N->getFlags();
9890 
9891   // fold vector ops
9892   if (VT.isVector()) {
9893     // This just handles C1 * C2 for vectors. Other vector folds are below.
9894     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9895       return FoldedVOp;
9896   }
9897 
9898   // fold (fmul c1, c2) -> c1*c2
9899   if (N0CFP && N1CFP)
9900     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9901 
9902   // canonicalize constant to RHS
9903   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9904      !isConstantFPBuildVectorOrConstantFP(N1))
9905     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9906 
9907   // fold (fmul A, 1.0) -> A
9908   if (N1CFP && N1CFP->isExactlyValue(1.0))
9909     return N0;
9910 
9911   if (SDValue NewSel = foldBinOpIntoSelect(N))
9912     return NewSel;
9913 
9914   if (Options.UnsafeFPMath) {
9915     // fold (fmul A, 0) -> 0
9916     if (N1CFP && N1CFP->isZero())
9917       return N1;
9918 
9919     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9920     if (N0.getOpcode() == ISD::FMUL) {
9921       // Fold scalars or any vector constants (not just splats).
9922       // This fold is done in general by InstCombine, but extra fmul insts
9923       // may have been generated during lowering.
9924       SDValue N00 = N0.getOperand(0);
9925       SDValue N01 = N0.getOperand(1);
9926       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9927       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9928       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9929 
9930       // Check 1: Make sure that the first operand of the inner multiply is NOT
9931       // a constant. Otherwise, we may induce infinite looping.
9932       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9933         // Check 2: Make sure that the second operand of the inner multiply and
9934         // the second operand of the outer multiply are constants.
9935         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9936             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9937           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9938           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9939         }
9940       }
9941     }
9942 
9943     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9944     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9945     // during an early run of DAGCombiner can prevent folding with fmuls
9946     // inserted during lowering.
9947     if (N0.getOpcode() == ISD::FADD &&
9948         (N0.getOperand(0) == N0.getOperand(1)) &&
9949         N0.hasOneUse()) {
9950       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9951       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9952       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9953     }
9954   }
9955 
9956   // fold (fmul X, 2.0) -> (fadd X, X)
9957   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9958     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9959 
9960   // fold (fmul X, -1.0) -> (fneg X)
9961   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9962     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9963       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9964 
9965   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9966   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9967     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9968       // Both can be negated for free, check to see if at least one is cheaper
9969       // negated.
9970       if (LHSNeg == 2 || RHSNeg == 2)
9971         return DAG.getNode(ISD::FMUL, DL, VT,
9972                            GetNegatedExpression(N0, DAG, LegalOperations),
9973                            GetNegatedExpression(N1, DAG, LegalOperations),
9974                            Flags);
9975     }
9976   }
9977 
9978   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
9979   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
9980   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
9981       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
9982       TLI.isOperationLegal(ISD::FABS, VT)) {
9983     SDValue Select = N0, X = N1;
9984     if (Select.getOpcode() != ISD::SELECT)
9985       std::swap(Select, X);
9986 
9987     SDValue Cond = Select.getOperand(0);
9988     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
9989     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
9990 
9991     if (TrueOpnd && FalseOpnd &&
9992         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
9993         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
9994         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
9995       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9996       switch (CC) {
9997       default: break;
9998       case ISD::SETOLT:
9999       case ISD::SETULT:
10000       case ISD::SETOLE:
10001       case ISD::SETULE:
10002       case ISD::SETLT:
10003       case ISD::SETLE:
10004         std::swap(TrueOpnd, FalseOpnd);
10005         // Fall through
10006       case ISD::SETOGT:
10007       case ISD::SETUGT:
10008       case ISD::SETOGE:
10009       case ISD::SETUGE:
10010       case ISD::SETGT:
10011       case ISD::SETGE:
10012         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
10013             TLI.isOperationLegal(ISD::FNEG, VT))
10014           return DAG.getNode(ISD::FNEG, DL, VT,
10015                    DAG.getNode(ISD::FABS, DL, VT, X));
10016         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
10017           return DAG.getNode(ISD::FABS, DL, VT, X);
10018 
10019         break;
10020       }
10021     }
10022   }
10023 
10024   // FMUL -> FMA combines:
10025   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
10026     AddToWorklist(Fused.getNode());
10027     return Fused;
10028   }
10029 
10030   return SDValue();
10031 }
10032 
10033 SDValue DAGCombiner::visitFMA(SDNode *N) {
10034   SDValue N0 = N->getOperand(0);
10035   SDValue N1 = N->getOperand(1);
10036   SDValue N2 = N->getOperand(2);
10037   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10038   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10039   EVT VT = N->getValueType(0);
10040   SDLoc DL(N);
10041   const TargetOptions &Options = DAG.getTarget().Options;
10042 
10043   // Constant fold FMA.
10044   if (isa<ConstantFPSDNode>(N0) &&
10045       isa<ConstantFPSDNode>(N1) &&
10046       isa<ConstantFPSDNode>(N2)) {
10047     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
10048   }
10049 
10050   if (Options.UnsafeFPMath) {
10051     if (N0CFP && N0CFP->isZero())
10052       return N2;
10053     if (N1CFP && N1CFP->isZero())
10054       return N2;
10055   }
10056   // TODO: The FMA node should have flags that propagate to these nodes.
10057   if (N0CFP && N0CFP->isExactlyValue(1.0))
10058     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
10059   if (N1CFP && N1CFP->isExactlyValue(1.0))
10060     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
10061 
10062   // Canonicalize (fma c, x, y) -> (fma x, c, y)
10063   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10064      !isConstantFPBuildVectorOrConstantFP(N1))
10065     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
10066 
10067   // TODO: FMA nodes should have flags that propagate to the created nodes.
10068   // For now, create a Flags object for use with all unsafe math transforms.
10069   SDNodeFlags Flags;
10070   Flags.setUnsafeAlgebra(true);
10071 
10072   if (Options.UnsafeFPMath) {
10073     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
10074     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
10075         isConstantFPBuildVectorOrConstantFP(N1) &&
10076         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
10077       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10078                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
10079                                      Flags), Flags);
10080     }
10081 
10082     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
10083     if (N0.getOpcode() == ISD::FMUL &&
10084         isConstantFPBuildVectorOrConstantFP(N1) &&
10085         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
10086       return DAG.getNode(ISD::FMA, DL, VT,
10087                          N0.getOperand(0),
10088                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
10089                                      Flags),
10090                          N2);
10091     }
10092   }
10093 
10094   // (fma x, 1, y) -> (fadd x, y)
10095   // (fma x, -1, y) -> (fadd (fneg x), y)
10096   if (N1CFP) {
10097     if (N1CFP->isExactlyValue(1.0))
10098       // TODO: The FMA node should have flags that propagate to this node.
10099       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
10100 
10101     if (N1CFP->isExactlyValue(-1.0) &&
10102         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
10103       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
10104       AddToWorklist(RHSNeg.getNode());
10105       // TODO: The FMA node should have flags that propagate to this node.
10106       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
10107     }
10108   }
10109 
10110   if (Options.UnsafeFPMath) {
10111     // (fma x, c, x) -> (fmul x, (c+1))
10112     if (N1CFP && N0 == N2) {
10113       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10114                          DAG.getNode(ISD::FADD, DL, VT, N1,
10115                                      DAG.getConstantFP(1.0, DL, VT), Flags),
10116                          Flags);
10117     }
10118 
10119     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
10120     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
10121       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10122                          DAG.getNode(ISD::FADD, DL, VT, N1,
10123                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
10124                          Flags);
10125     }
10126   }
10127 
10128   return SDValue();
10129 }
10130 
10131 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10132 // reciprocal.
10133 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
10134 // Notice that this is not always beneficial. One reason is different targets
10135 // may have different costs for FDIV and FMUL, so sometimes the cost of two
10136 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
10137 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
10138 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
10139   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
10140   const SDNodeFlags Flags = N->getFlags();
10141   if (!UnsafeMath && !Flags.hasAllowReciprocal())
10142     return SDValue();
10143 
10144   // Skip if current node is a reciprocal.
10145   SDValue N0 = N->getOperand(0);
10146   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10147   if (N0CFP && N0CFP->isExactlyValue(1.0))
10148     return SDValue();
10149 
10150   // Exit early if the target does not want this transform or if there can't
10151   // possibly be enough uses of the divisor to make the transform worthwhile.
10152   SDValue N1 = N->getOperand(1);
10153   unsigned MinUses = TLI.combineRepeatedFPDivisors();
10154   if (!MinUses || N1->use_size() < MinUses)
10155     return SDValue();
10156 
10157   // Find all FDIV users of the same divisor.
10158   // Use a set because duplicates may be present in the user list.
10159   SetVector<SDNode *> Users;
10160   for (auto *U : N1->uses()) {
10161     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10162       // This division is eligible for optimization only if global unsafe math
10163       // is enabled or if this division allows reciprocal formation.
10164       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10165         Users.insert(U);
10166     }
10167   }
10168 
10169   // Now that we have the actual number of divisor uses, make sure it meets
10170   // the minimum threshold specified by the target.
10171   if (Users.size() < MinUses)
10172     return SDValue();
10173 
10174   EVT VT = N->getValueType(0);
10175   SDLoc DL(N);
10176   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10177   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10178 
10179   // Dividend / Divisor -> Dividend * Reciprocal
10180   for (auto *U : Users) {
10181     SDValue Dividend = U->getOperand(0);
10182     if (Dividend != FPOne) {
10183       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10184                                     Reciprocal, Flags);
10185       CombineTo(U, NewNode);
10186     } else if (U != Reciprocal.getNode()) {
10187       // In the absence of fast-math-flags, this user node is always the
10188       // same node as Reciprocal, but with FMF they may be different nodes.
10189       CombineTo(U, Reciprocal);
10190     }
10191   }
10192   return SDValue(N, 0);  // N was replaced.
10193 }
10194 
10195 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10196   SDValue N0 = N->getOperand(0);
10197   SDValue N1 = N->getOperand(1);
10198   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10199   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10200   EVT VT = N->getValueType(0);
10201   SDLoc DL(N);
10202   const TargetOptions &Options = DAG.getTarget().Options;
10203   SDNodeFlags Flags = N->getFlags();
10204 
10205   // fold vector ops
10206   if (VT.isVector())
10207     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10208       return FoldedVOp;
10209 
10210   // fold (fdiv c1, c2) -> c1/c2
10211   if (N0CFP && N1CFP)
10212     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10213 
10214   if (SDValue NewSel = foldBinOpIntoSelect(N))
10215     return NewSel;
10216 
10217   if (Options.UnsafeFPMath) {
10218     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10219     if (N1CFP) {
10220       // Compute the reciprocal 1.0 / c2.
10221       const APFloat &N1APF = N1CFP->getValueAPF();
10222       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10223       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10224       // Only do the transform if the reciprocal is a legal fp immediate that
10225       // isn't too nasty (eg NaN, denormal, ...).
10226       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10227           (!LegalOperations ||
10228            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10229            // backend)... we should handle this gracefully after Legalize.
10230            // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
10231            TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10232            TLI.isFPImmLegal(Recip, VT)))
10233         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10234                            DAG.getConstantFP(Recip, DL, VT), Flags);
10235     }
10236 
10237     // If this FDIV is part of a reciprocal square root, it may be folded
10238     // into a target-specific square root estimate instruction.
10239     if (N1.getOpcode() == ISD::FSQRT) {
10240       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10241         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10242       }
10243     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10244                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10245       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10246                                           Flags)) {
10247         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10248         AddToWorklist(RV.getNode());
10249         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10250       }
10251     } else if (N1.getOpcode() == ISD::FP_ROUND &&
10252                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10253       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10254                                           Flags)) {
10255         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10256         AddToWorklist(RV.getNode());
10257         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10258       }
10259     } else if (N1.getOpcode() == ISD::FMUL) {
10260       // Look through an FMUL. Even though this won't remove the FDIV directly,
10261       // it's still worthwhile to get rid of the FSQRT if possible.
10262       SDValue SqrtOp;
10263       SDValue OtherOp;
10264       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10265         SqrtOp = N1.getOperand(0);
10266         OtherOp = N1.getOperand(1);
10267       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10268         SqrtOp = N1.getOperand(1);
10269         OtherOp = N1.getOperand(0);
10270       }
10271       if (SqrtOp.getNode()) {
10272         // We found a FSQRT, so try to make this fold:
10273         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10274         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10275           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10276           AddToWorklist(RV.getNode());
10277           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10278         }
10279       }
10280     }
10281 
10282     // Fold into a reciprocal estimate and multiply instead of a real divide.
10283     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10284       AddToWorklist(RV.getNode());
10285       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10286     }
10287   }
10288 
10289   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10290   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10291     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10292       // Both can be negated for free, check to see if at least one is cheaper
10293       // negated.
10294       if (LHSNeg == 2 || RHSNeg == 2)
10295         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10296                            GetNegatedExpression(N0, DAG, LegalOperations),
10297                            GetNegatedExpression(N1, DAG, LegalOperations),
10298                            Flags);
10299     }
10300   }
10301 
10302   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10303     return CombineRepeatedDivisors;
10304 
10305   return SDValue();
10306 }
10307 
10308 SDValue DAGCombiner::visitFREM(SDNode *N) {
10309   SDValue N0 = N->getOperand(0);
10310   SDValue N1 = N->getOperand(1);
10311   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10312   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10313   EVT VT = N->getValueType(0);
10314 
10315   // fold (frem c1, c2) -> fmod(c1,c2)
10316   if (N0CFP && N1CFP)
10317     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10318 
10319   if (SDValue NewSel = foldBinOpIntoSelect(N))
10320     return NewSel;
10321 
10322   return SDValue();
10323 }
10324 
10325 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10326   if (!DAG.getTarget().Options.UnsafeFPMath)
10327     return SDValue();
10328 
10329   SDValue N0 = N->getOperand(0);
10330   if (TLI.isFsqrtCheap(N0, DAG))
10331     return SDValue();
10332 
10333   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10334   // For now, create a Flags object for use with all unsafe math transforms.
10335   SDNodeFlags Flags;
10336   Flags.setUnsafeAlgebra(true);
10337   return buildSqrtEstimate(N0, Flags);
10338 }
10339 
10340 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10341 /// copysign(x, fp_round(y)) -> copysign(x, y)
10342 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10343   SDValue N1 = N->getOperand(1);
10344   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10345        N1.getOpcode() == ISD::FP_ROUND)) {
10346     // Do not optimize out type conversion of f128 type yet.
10347     // For some targets like x86_64, configuration is changed to keep one f128
10348     // value in one SSE register, but instruction selection cannot handle
10349     // FCOPYSIGN on SSE registers yet.
10350     EVT N1VT = N1->getValueType(0);
10351     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10352     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10353   }
10354   return false;
10355 }
10356 
10357 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10358   SDValue N0 = N->getOperand(0);
10359   SDValue N1 = N->getOperand(1);
10360   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10361   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10362   EVT VT = N->getValueType(0);
10363 
10364   if (N0CFP && N1CFP) // Constant fold
10365     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10366 
10367   if (N1CFP) {
10368     const APFloat &V = N1CFP->getValueAPF();
10369     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10370     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10371     if (!V.isNegative()) {
10372       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10373         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10374     } else {
10375       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10376         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10377                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10378     }
10379   }
10380 
10381   // copysign(fabs(x), y) -> copysign(x, y)
10382   // copysign(fneg(x), y) -> copysign(x, y)
10383   // copysign(copysign(x,z), y) -> copysign(x, y)
10384   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10385       N0.getOpcode() == ISD::FCOPYSIGN)
10386     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10387 
10388   // copysign(x, abs(y)) -> abs(x)
10389   if (N1.getOpcode() == ISD::FABS)
10390     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10391 
10392   // copysign(x, copysign(y,z)) -> copysign(x, z)
10393   if (N1.getOpcode() == ISD::FCOPYSIGN)
10394     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10395 
10396   // copysign(x, fp_extend(y)) -> copysign(x, y)
10397   // copysign(x, fp_round(y)) -> copysign(x, y)
10398   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10399     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10400 
10401   return SDValue();
10402 }
10403 
10404 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10405   SDValue N0 = N->getOperand(0);
10406   EVT VT = N->getValueType(0);
10407   EVT OpVT = N0.getValueType();
10408 
10409   // fold (sint_to_fp c1) -> c1fp
10410   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10411       // ...but only if the target supports immediate floating-point values
10412       (!LegalOperations ||
10413        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10414     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10415 
10416   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10417   // but UINT_TO_FP is legal on this target, try to convert.
10418   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10419       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10420     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10421     if (DAG.SignBitIsZero(N0))
10422       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10423   }
10424 
10425   // The next optimizations are desirable only if SELECT_CC can be lowered.
10426   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10427     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10428     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10429         !VT.isVector() &&
10430         (!LegalOperations ||
10431          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10432       SDLoc DL(N);
10433       SDValue Ops[] =
10434         { N0.getOperand(0), N0.getOperand(1),
10435           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10436           N0.getOperand(2) };
10437       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10438     }
10439 
10440     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10441     //      (select_cc x, y, 1.0, 0.0,, cc)
10442     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10443         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10444         (!LegalOperations ||
10445          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10446       SDLoc DL(N);
10447       SDValue Ops[] =
10448         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10449           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10450           N0.getOperand(0).getOperand(2) };
10451       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10452     }
10453   }
10454 
10455   return SDValue();
10456 }
10457 
10458 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10459   SDValue N0 = N->getOperand(0);
10460   EVT VT = N->getValueType(0);
10461   EVT OpVT = N0.getValueType();
10462 
10463   // fold (uint_to_fp c1) -> c1fp
10464   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10465       // ...but only if the target supports immediate floating-point values
10466       (!LegalOperations ||
10467        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10468     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10469 
10470   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10471   // but SINT_TO_FP is legal on this target, try to convert.
10472   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10473       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10474     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10475     if (DAG.SignBitIsZero(N0))
10476       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10477   }
10478 
10479   // The next optimizations are desirable only if SELECT_CC can be lowered.
10480   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10481     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10482     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10483         (!LegalOperations ||
10484          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10485       SDLoc DL(N);
10486       SDValue Ops[] =
10487         { N0.getOperand(0), N0.getOperand(1),
10488           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10489           N0.getOperand(2) };
10490       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10491     }
10492   }
10493 
10494   return SDValue();
10495 }
10496 
10497 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10498 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10499   SDValue N0 = N->getOperand(0);
10500   EVT VT = N->getValueType(0);
10501 
10502   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10503     return SDValue();
10504 
10505   SDValue Src = N0.getOperand(0);
10506   EVT SrcVT = Src.getValueType();
10507   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10508   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10509 
10510   // We can safely assume the conversion won't overflow the output range,
10511   // because (for example) (uint8_t)18293.f is undefined behavior.
10512 
10513   // Since we can assume the conversion won't overflow, our decision as to
10514   // whether the input will fit in the float should depend on the minimum
10515   // of the input range and output range.
10516 
10517   // This means this is also safe for a signed input and unsigned output, since
10518   // a negative input would lead to undefined behavior.
10519   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10520   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10521   unsigned ActualSize = std::min(InputSize, OutputSize);
10522   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10523 
10524   // We can only fold away the float conversion if the input range can be
10525   // represented exactly in the float range.
10526   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10527     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10528       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10529                                                        : ISD::ZERO_EXTEND;
10530       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10531     }
10532     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10533       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10534     return DAG.getBitcast(VT, Src);
10535   }
10536   return SDValue();
10537 }
10538 
10539 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10540   SDValue N0 = N->getOperand(0);
10541   EVT VT = N->getValueType(0);
10542 
10543   // fold (fp_to_sint c1fp) -> c1
10544   if (isConstantFPBuildVectorOrConstantFP(N0))
10545     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10546 
10547   return FoldIntToFPToInt(N, DAG);
10548 }
10549 
10550 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10551   SDValue N0 = N->getOperand(0);
10552   EVT VT = N->getValueType(0);
10553 
10554   // fold (fp_to_uint c1fp) -> c1
10555   if (isConstantFPBuildVectorOrConstantFP(N0))
10556     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10557 
10558   return FoldIntToFPToInt(N, DAG);
10559 }
10560 
10561 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10562   SDValue N0 = N->getOperand(0);
10563   SDValue N1 = N->getOperand(1);
10564   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10565   EVT VT = N->getValueType(0);
10566 
10567   // fold (fp_round c1fp) -> c1fp
10568   if (N0CFP)
10569     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10570 
10571   // fold (fp_round (fp_extend x)) -> x
10572   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10573     return N0.getOperand(0);
10574 
10575   // fold (fp_round (fp_round x)) -> (fp_round x)
10576   if (N0.getOpcode() == ISD::FP_ROUND) {
10577     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10578     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10579 
10580     // Skip this folding if it results in an fp_round from f80 to f16.
10581     //
10582     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10583     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10584     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10585     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10586     // x86.
10587     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10588       return SDValue();
10589 
10590     // If the first fp_round isn't a value preserving truncation, it might
10591     // introduce a tie in the second fp_round, that wouldn't occur in the
10592     // single-step fp_round we want to fold to.
10593     // In other words, double rounding isn't the same as rounding.
10594     // Also, this is a value preserving truncation iff both fp_round's are.
10595     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10596       SDLoc DL(N);
10597       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10598                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10599     }
10600   }
10601 
10602   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10603   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10604     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10605                               N0.getOperand(0), N1);
10606     AddToWorklist(Tmp.getNode());
10607     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10608                        Tmp, N0.getOperand(1));
10609   }
10610 
10611   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10612     return NewVSel;
10613 
10614   return SDValue();
10615 }
10616 
10617 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10618   SDValue N0 = N->getOperand(0);
10619   EVT VT = N->getValueType(0);
10620   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10621   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10622 
10623   // fold (fp_round_inreg c1fp) -> c1fp
10624   if (N0CFP && isTypeLegal(EVT)) {
10625     SDLoc DL(N);
10626     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10627     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10628   }
10629 
10630   return SDValue();
10631 }
10632 
10633 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10634   SDValue N0 = N->getOperand(0);
10635   EVT VT = N->getValueType(0);
10636 
10637   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10638   if (N->hasOneUse() &&
10639       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10640     return SDValue();
10641 
10642   // fold (fp_extend c1fp) -> c1fp
10643   if (isConstantFPBuildVectorOrConstantFP(N0))
10644     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10645 
10646   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10647   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10648       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10649     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10650 
10651   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10652   // value of X.
10653   if (N0.getOpcode() == ISD::FP_ROUND
10654       && N0.getConstantOperandVal(1) == 1) {
10655     SDValue In = N0.getOperand(0);
10656     if (In.getValueType() == VT) return In;
10657     if (VT.bitsLT(In.getValueType()))
10658       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10659                          In, N0.getOperand(1));
10660     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10661   }
10662 
10663   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10664   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10665        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10666     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10667     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10668                                      LN0->getChain(),
10669                                      LN0->getBasePtr(), N0.getValueType(),
10670                                      LN0->getMemOperand());
10671     CombineTo(N, ExtLoad);
10672     CombineTo(N0.getNode(),
10673               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10674                           N0.getValueType(), ExtLoad,
10675                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10676               ExtLoad.getValue(1));
10677     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10678   }
10679 
10680   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10681     return NewVSel;
10682 
10683   return SDValue();
10684 }
10685 
10686 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10687   SDValue N0 = N->getOperand(0);
10688   EVT VT = N->getValueType(0);
10689 
10690   // fold (fceil c1) -> fceil(c1)
10691   if (isConstantFPBuildVectorOrConstantFP(N0))
10692     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10693 
10694   return SDValue();
10695 }
10696 
10697 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10698   SDValue N0 = N->getOperand(0);
10699   EVT VT = N->getValueType(0);
10700 
10701   // fold (ftrunc c1) -> ftrunc(c1)
10702   if (isConstantFPBuildVectorOrConstantFP(N0))
10703     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10704 
10705   // fold ftrunc (known rounded int x) -> x
10706   // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
10707   // likely to be generated to extract integer from a rounded floating value.
10708   switch (N0.getOpcode()) {
10709   default: break;
10710   case ISD::FRINT:
10711   case ISD::FTRUNC:
10712   case ISD::FNEARBYINT:
10713   case ISD::FFLOOR:
10714   case ISD::FCEIL:
10715     return N0;
10716   }
10717 
10718   return SDValue();
10719 }
10720 
10721 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10722   SDValue N0 = N->getOperand(0);
10723   EVT VT = N->getValueType(0);
10724 
10725   // fold (ffloor c1) -> ffloor(c1)
10726   if (isConstantFPBuildVectorOrConstantFP(N0))
10727     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10728 
10729   return SDValue();
10730 }
10731 
10732 // FIXME: FNEG and FABS have a lot in common; refactor.
10733 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10734   SDValue N0 = N->getOperand(0);
10735   EVT VT = N->getValueType(0);
10736 
10737   // Constant fold FNEG.
10738   if (isConstantFPBuildVectorOrConstantFP(N0))
10739     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10740 
10741   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10742                          &DAG.getTarget().Options))
10743     return GetNegatedExpression(N0, DAG, LegalOperations);
10744 
10745   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10746   // constant pool values.
10747   if (!TLI.isFNegFree(VT) &&
10748       N0.getOpcode() == ISD::BITCAST &&
10749       N0.getNode()->hasOneUse()) {
10750     SDValue Int = N0.getOperand(0);
10751     EVT IntVT = Int.getValueType();
10752     if (IntVT.isInteger() && !IntVT.isVector()) {
10753       APInt SignMask;
10754       if (N0.getValueType().isVector()) {
10755         // For a vector, get a mask such as 0x80... per scalar element
10756         // and splat it.
10757         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10758         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10759       } else {
10760         // For a scalar, just generate 0x80...
10761         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10762       }
10763       SDLoc DL0(N0);
10764       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10765                         DAG.getConstant(SignMask, DL0, IntVT));
10766       AddToWorklist(Int.getNode());
10767       return DAG.getBitcast(VT, Int);
10768     }
10769   }
10770 
10771   // (fneg (fmul c, x)) -> (fmul -c, x)
10772   if (N0.getOpcode() == ISD::FMUL &&
10773       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10774     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10775     if (CFP1) {
10776       APFloat CVal = CFP1->getValueAPF();
10777       CVal.changeSign();
10778       if (Level >= AfterLegalizeDAG &&
10779           (TLI.isFPImmLegal(CVal, VT) ||
10780            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10781         return DAG.getNode(
10782             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10783             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10784             N0->getFlags());
10785     }
10786   }
10787 
10788   return SDValue();
10789 }
10790 
10791 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10792   SDValue N0 = N->getOperand(0);
10793   SDValue N1 = N->getOperand(1);
10794   EVT VT = N->getValueType(0);
10795   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10796   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10797 
10798   if (N0CFP && N1CFP) {
10799     const APFloat &C0 = N0CFP->getValueAPF();
10800     const APFloat &C1 = N1CFP->getValueAPF();
10801     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10802   }
10803 
10804   // Canonicalize to constant on RHS.
10805   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10806      !isConstantFPBuildVectorOrConstantFP(N1))
10807     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10808 
10809   return SDValue();
10810 }
10811 
10812 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10813   SDValue N0 = N->getOperand(0);
10814   SDValue N1 = N->getOperand(1);
10815   EVT VT = N->getValueType(0);
10816   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10817   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10818 
10819   if (N0CFP && N1CFP) {
10820     const APFloat &C0 = N0CFP->getValueAPF();
10821     const APFloat &C1 = N1CFP->getValueAPF();
10822     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10823   }
10824 
10825   // Canonicalize to constant on RHS.
10826   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10827      !isConstantFPBuildVectorOrConstantFP(N1))
10828     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10829 
10830   return SDValue();
10831 }
10832 
10833 SDValue DAGCombiner::visitFABS(SDNode *N) {
10834   SDValue N0 = N->getOperand(0);
10835   EVT VT = N->getValueType(0);
10836 
10837   // fold (fabs c1) -> fabs(c1)
10838   if (isConstantFPBuildVectorOrConstantFP(N0))
10839     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10840 
10841   // fold (fabs (fabs x)) -> (fabs x)
10842   if (N0.getOpcode() == ISD::FABS)
10843     return N->getOperand(0);
10844 
10845   // fold (fabs (fneg x)) -> (fabs x)
10846   // fold (fabs (fcopysign x, y)) -> (fabs x)
10847   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10848     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10849 
10850   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10851   // constant pool values.
10852   if (!TLI.isFAbsFree(VT) &&
10853       N0.getOpcode() == ISD::BITCAST &&
10854       N0.getNode()->hasOneUse()) {
10855     SDValue Int = N0.getOperand(0);
10856     EVT IntVT = Int.getValueType();
10857     if (IntVT.isInteger() && !IntVT.isVector()) {
10858       APInt SignMask;
10859       if (N0.getValueType().isVector()) {
10860         // For a vector, get a mask such as 0x7f... per scalar element
10861         // and splat it.
10862         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10863         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10864       } else {
10865         // For a scalar, just generate 0x7f...
10866         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10867       }
10868       SDLoc DL(N0);
10869       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10870                         DAG.getConstant(SignMask, DL, IntVT));
10871       AddToWorklist(Int.getNode());
10872       return DAG.getBitcast(N->getValueType(0), Int);
10873     }
10874   }
10875 
10876   return SDValue();
10877 }
10878 
10879 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10880   SDValue Chain = N->getOperand(0);
10881   SDValue N1 = N->getOperand(1);
10882   SDValue N2 = N->getOperand(2);
10883 
10884   // If N is a constant we could fold this into a fallthrough or unconditional
10885   // branch. However that doesn't happen very often in normal code, because
10886   // Instcombine/SimplifyCFG should have handled the available opportunities.
10887   // If we did this folding here, it would be necessary to update the
10888   // MachineBasicBlock CFG, which is awkward.
10889 
10890   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10891   // on the target.
10892   if (N1.getOpcode() == ISD::SETCC &&
10893       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10894                                    N1.getOperand(0).getValueType())) {
10895     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10896                        Chain, N1.getOperand(2),
10897                        N1.getOperand(0), N1.getOperand(1), N2);
10898   }
10899 
10900   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10901       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10902        (N1.getOperand(0).hasOneUse() &&
10903         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10904     SDNode *Trunc = nullptr;
10905     if (N1.getOpcode() == ISD::TRUNCATE) {
10906       // Look pass the truncate.
10907       Trunc = N1.getNode();
10908       N1 = N1.getOperand(0);
10909     }
10910 
10911     // Match this pattern so that we can generate simpler code:
10912     //
10913     //   %a = ...
10914     //   %b = and i32 %a, 2
10915     //   %c = srl i32 %b, 1
10916     //   brcond i32 %c ...
10917     //
10918     // into
10919     //
10920     //   %a = ...
10921     //   %b = and i32 %a, 2
10922     //   %c = setcc eq %b, 0
10923     //   brcond %c ...
10924     //
10925     // This applies only when the AND constant value has one bit set and the
10926     // SRL constant is equal to the log2 of the AND constant. The back-end is
10927     // smart enough to convert the result into a TEST/JMP sequence.
10928     SDValue Op0 = N1.getOperand(0);
10929     SDValue Op1 = N1.getOperand(1);
10930 
10931     if (Op0.getOpcode() == ISD::AND &&
10932         Op1.getOpcode() == ISD::Constant) {
10933       SDValue AndOp1 = Op0.getOperand(1);
10934 
10935       if (AndOp1.getOpcode() == ISD::Constant) {
10936         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10937 
10938         if (AndConst.isPowerOf2() &&
10939             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10940           SDLoc DL(N);
10941           SDValue SetCC =
10942             DAG.getSetCC(DL,
10943                          getSetCCResultType(Op0.getValueType()),
10944                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10945                          ISD::SETNE);
10946 
10947           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10948                                           MVT::Other, Chain, SetCC, N2);
10949           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10950           // will convert it back to (X & C1) >> C2.
10951           CombineTo(N, NewBRCond, false);
10952           // Truncate is dead.
10953           if (Trunc)
10954             deleteAndRecombine(Trunc);
10955           // Replace the uses of SRL with SETCC
10956           WorklistRemover DeadNodes(*this);
10957           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10958           deleteAndRecombine(N1.getNode());
10959           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10960         }
10961       }
10962     }
10963 
10964     if (Trunc)
10965       // Restore N1 if the above transformation doesn't match.
10966       N1 = N->getOperand(1);
10967   }
10968 
10969   // Transform br(xor(x, y)) -> br(x != y)
10970   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10971   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10972     SDNode *TheXor = N1.getNode();
10973     SDValue Op0 = TheXor->getOperand(0);
10974     SDValue Op1 = TheXor->getOperand(1);
10975     if (Op0.getOpcode() == Op1.getOpcode()) {
10976       // Avoid missing important xor optimizations.
10977       if (SDValue Tmp = visitXOR(TheXor)) {
10978         if (Tmp.getNode() != TheXor) {
10979           DEBUG(dbgs() << "\nReplacing.8 ";
10980                 TheXor->dump(&DAG);
10981                 dbgs() << "\nWith: ";
10982                 Tmp.getNode()->dump(&DAG);
10983                 dbgs() << '\n');
10984           WorklistRemover DeadNodes(*this);
10985           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10986           deleteAndRecombine(TheXor);
10987           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10988                              MVT::Other, Chain, Tmp, N2);
10989         }
10990 
10991         // visitXOR has changed XOR's operands or replaced the XOR completely,
10992         // bail out.
10993         return SDValue(N, 0);
10994       }
10995     }
10996 
10997     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10998       bool Equal = false;
10999       if (isOneConstant(Op0) && Op0.hasOneUse() &&
11000           Op0.getOpcode() == ISD::XOR) {
11001         TheXor = Op0.getNode();
11002         Equal = true;
11003       }
11004 
11005       EVT SetCCVT = N1.getValueType();
11006       if (LegalTypes)
11007         SetCCVT = getSetCCResultType(SetCCVT);
11008       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
11009                                    SetCCVT,
11010                                    Op0, Op1,
11011                                    Equal ? ISD::SETEQ : ISD::SETNE);
11012       // Replace the uses of XOR with SETCC
11013       WorklistRemover DeadNodes(*this);
11014       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
11015       deleteAndRecombine(N1.getNode());
11016       return DAG.getNode(ISD::BRCOND, SDLoc(N),
11017                          MVT::Other, Chain, SetCC, N2);
11018     }
11019   }
11020 
11021   return SDValue();
11022 }
11023 
11024 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
11025 //
11026 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
11027   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
11028   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
11029 
11030   // If N is a constant we could fold this into a fallthrough or unconditional
11031   // branch. However that doesn't happen very often in normal code, because
11032   // Instcombine/SimplifyCFG should have handled the available opportunities.
11033   // If we did this folding here, it would be necessary to update the
11034   // MachineBasicBlock CFG, which is awkward.
11035 
11036   // Use SimplifySetCC to simplify SETCC's.
11037   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
11038                                CondLHS, CondRHS, CC->get(), SDLoc(N),
11039                                false);
11040   if (Simp.getNode()) AddToWorklist(Simp.getNode());
11041 
11042   // fold to a simpler setcc
11043   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
11044     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11045                        N->getOperand(0), Simp.getOperand(2),
11046                        Simp.getOperand(0), Simp.getOperand(1),
11047                        N->getOperand(4));
11048 
11049   return SDValue();
11050 }
11051 
11052 /// Return true if 'Use' is a load or a store that uses N as its base pointer
11053 /// and that N may be folded in the load / store addressing mode.
11054 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
11055                                     SelectionDAG &DAG,
11056                                     const TargetLowering &TLI) {
11057   EVT VT;
11058   unsigned AS;
11059 
11060   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
11061     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
11062       return false;
11063     VT = LD->getMemoryVT();
11064     AS = LD->getAddressSpace();
11065   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
11066     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
11067       return false;
11068     VT = ST->getMemoryVT();
11069     AS = ST->getAddressSpace();
11070   } else
11071     return false;
11072 
11073   TargetLowering::AddrMode AM;
11074   if (N->getOpcode() == ISD::ADD) {
11075     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11076     if (Offset)
11077       // [reg +/- imm]
11078       AM.BaseOffs = Offset->getSExtValue();
11079     else
11080       // [reg +/- reg]
11081       AM.Scale = 1;
11082   } else if (N->getOpcode() == ISD::SUB) {
11083     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11084     if (Offset)
11085       // [reg +/- imm]
11086       AM.BaseOffs = -Offset->getSExtValue();
11087     else
11088       // [reg +/- reg]
11089       AM.Scale = 1;
11090   } else
11091     return false;
11092 
11093   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
11094                                    VT.getTypeForEVT(*DAG.getContext()), AS);
11095 }
11096 
11097 /// Try turning a load/store into a pre-indexed load/store when the base
11098 /// pointer is an add or subtract and it has other uses besides the load/store.
11099 /// After the transformation, the new indexed load/store has effectively folded
11100 /// the add/subtract in and all of its other uses are redirected to the
11101 /// new load/store.
11102 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
11103   if (Level < AfterLegalizeDAG)
11104     return false;
11105 
11106   bool isLoad = true;
11107   SDValue Ptr;
11108   EVT VT;
11109   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11110     if (LD->isIndexed())
11111       return false;
11112     VT = LD->getMemoryVT();
11113     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
11114         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
11115       return false;
11116     Ptr = LD->getBasePtr();
11117   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11118     if (ST->isIndexed())
11119       return false;
11120     VT = ST->getMemoryVT();
11121     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
11122         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
11123       return false;
11124     Ptr = ST->getBasePtr();
11125     isLoad = false;
11126   } else {
11127     return false;
11128   }
11129 
11130   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
11131   // out.  There is no reason to make this a preinc/predec.
11132   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
11133       Ptr.getNode()->hasOneUse())
11134     return false;
11135 
11136   // Ask the target to do addressing mode selection.
11137   SDValue BasePtr;
11138   SDValue Offset;
11139   ISD::MemIndexedMode AM = ISD::UNINDEXED;
11140   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
11141     return false;
11142 
11143   // Backends without true r+i pre-indexed forms may need to pass a
11144   // constant base with a variable offset so that constant coercion
11145   // will work with the patterns in canonical form.
11146   bool Swapped = false;
11147   if (isa<ConstantSDNode>(BasePtr)) {
11148     std::swap(BasePtr, Offset);
11149     Swapped = true;
11150   }
11151 
11152   // Don't create a indexed load / store with zero offset.
11153   if (isNullConstant(Offset))
11154     return false;
11155 
11156   // Try turning it into a pre-indexed load / store except when:
11157   // 1) The new base ptr is a frame index.
11158   // 2) If N is a store and the new base ptr is either the same as or is a
11159   //    predecessor of the value being stored.
11160   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
11161   //    that would create a cycle.
11162   // 4) All uses are load / store ops that use it as old base ptr.
11163 
11164   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
11165   // (plus the implicit offset) to a register to preinc anyway.
11166   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11167     return false;
11168 
11169   // Check #2.
11170   if (!isLoad) {
11171     SDValue Val = cast<StoreSDNode>(N)->getValue();
11172     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11173       return false;
11174   }
11175 
11176   // Caches for hasPredecessorHelper.
11177   SmallPtrSet<const SDNode *, 32> Visited;
11178   SmallVector<const SDNode *, 16> Worklist;
11179   Worklist.push_back(N);
11180 
11181   // If the offset is a constant, there may be other adds of constants that
11182   // can be folded with this one. We should do this to avoid having to keep
11183   // a copy of the original base pointer.
11184   SmallVector<SDNode *, 16> OtherUses;
11185   if (isa<ConstantSDNode>(Offset))
11186     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11187                               UE = BasePtr.getNode()->use_end();
11188          UI != UE; ++UI) {
11189       SDUse &Use = UI.getUse();
11190       // Skip the use that is Ptr and uses of other results from BasePtr's
11191       // node (important for nodes that return multiple results).
11192       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11193         continue;
11194 
11195       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11196         continue;
11197 
11198       if (Use.getUser()->getOpcode() != ISD::ADD &&
11199           Use.getUser()->getOpcode() != ISD::SUB) {
11200         OtherUses.clear();
11201         break;
11202       }
11203 
11204       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11205       if (!isa<ConstantSDNode>(Op1)) {
11206         OtherUses.clear();
11207         break;
11208       }
11209 
11210       // FIXME: In some cases, we can be smarter about this.
11211       if (Op1.getValueType() != Offset.getValueType()) {
11212         OtherUses.clear();
11213         break;
11214       }
11215 
11216       OtherUses.push_back(Use.getUser());
11217     }
11218 
11219   if (Swapped)
11220     std::swap(BasePtr, Offset);
11221 
11222   // Now check for #3 and #4.
11223   bool RealUse = false;
11224 
11225   for (SDNode *Use : Ptr.getNode()->uses()) {
11226     if (Use == N)
11227       continue;
11228     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11229       return false;
11230 
11231     // If Ptr may be folded in addressing mode of other use, then it's
11232     // not profitable to do this transformation.
11233     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11234       RealUse = true;
11235   }
11236 
11237   if (!RealUse)
11238     return false;
11239 
11240   SDValue Result;
11241   if (isLoad)
11242     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11243                                 BasePtr, Offset, AM);
11244   else
11245     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11246                                  BasePtr, Offset, AM);
11247   ++PreIndexedNodes;
11248   ++NodesCombined;
11249   DEBUG(dbgs() << "\nReplacing.4 ";
11250         N->dump(&DAG);
11251         dbgs() << "\nWith: ";
11252         Result.getNode()->dump(&DAG);
11253         dbgs() << '\n');
11254   WorklistRemover DeadNodes(*this);
11255   if (isLoad) {
11256     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11257     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11258   } else {
11259     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11260   }
11261 
11262   // Finally, since the node is now dead, remove it from the graph.
11263   deleteAndRecombine(N);
11264 
11265   if (Swapped)
11266     std::swap(BasePtr, Offset);
11267 
11268   // Replace other uses of BasePtr that can be updated to use Ptr
11269   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11270     unsigned OffsetIdx = 1;
11271     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11272       OffsetIdx = 0;
11273     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11274            BasePtr.getNode() && "Expected BasePtr operand");
11275 
11276     // We need to replace ptr0 in the following expression:
11277     //   x0 * offset0 + y0 * ptr0 = t0
11278     // knowing that
11279     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11280     //
11281     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11282     // indexed load/store and the expression that needs to be re-written.
11283     //
11284     // Therefore, we have:
11285     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11286 
11287     ConstantSDNode *CN =
11288       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11289     int X0, X1, Y0, Y1;
11290     const APInt &Offset0 = CN->getAPIntValue();
11291     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11292 
11293     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11294     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11295     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11296     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11297 
11298     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11299 
11300     APInt CNV = Offset0;
11301     if (X0 < 0) CNV = -CNV;
11302     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11303     else CNV = CNV - Offset1;
11304 
11305     SDLoc DL(OtherUses[i]);
11306 
11307     // We can now generate the new expression.
11308     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11309     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11310 
11311     SDValue NewUse = DAG.getNode(Opcode,
11312                                  DL,
11313                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11314     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11315     deleteAndRecombine(OtherUses[i]);
11316   }
11317 
11318   // Replace the uses of Ptr with uses of the updated base value.
11319   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11320   deleteAndRecombine(Ptr.getNode());
11321 
11322   return true;
11323 }
11324 
11325 /// Try to combine a load/store with a add/sub of the base pointer node into a
11326 /// post-indexed load/store. The transformation folded the add/subtract into the
11327 /// new indexed load/store effectively and all of its uses are redirected to the
11328 /// new load/store.
11329 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11330   if (Level < AfterLegalizeDAG)
11331     return false;
11332 
11333   bool isLoad = true;
11334   SDValue Ptr;
11335   EVT VT;
11336   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11337     if (LD->isIndexed())
11338       return false;
11339     VT = LD->getMemoryVT();
11340     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11341         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11342       return false;
11343     Ptr = LD->getBasePtr();
11344   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11345     if (ST->isIndexed())
11346       return false;
11347     VT = ST->getMemoryVT();
11348     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11349         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11350       return false;
11351     Ptr = ST->getBasePtr();
11352     isLoad = false;
11353   } else {
11354     return false;
11355   }
11356 
11357   if (Ptr.getNode()->hasOneUse())
11358     return false;
11359 
11360   for (SDNode *Op : Ptr.getNode()->uses()) {
11361     if (Op == N ||
11362         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11363       continue;
11364 
11365     SDValue BasePtr;
11366     SDValue Offset;
11367     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11368     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11369       // Don't create a indexed load / store with zero offset.
11370       if (isNullConstant(Offset))
11371         continue;
11372 
11373       // Try turning it into a post-indexed load / store except when
11374       // 1) All uses are load / store ops that use it as base ptr (and
11375       //    it may be folded as addressing mmode).
11376       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11377       //    nor a successor of N. Otherwise, if Op is folded that would
11378       //    create a cycle.
11379 
11380       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11381         continue;
11382 
11383       // Check for #1.
11384       bool TryNext = false;
11385       for (SDNode *Use : BasePtr.getNode()->uses()) {
11386         if (Use == Ptr.getNode())
11387           continue;
11388 
11389         // If all the uses are load / store addresses, then don't do the
11390         // transformation.
11391         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11392           bool RealUse = false;
11393           for (SDNode *UseUse : Use->uses()) {
11394             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11395               RealUse = true;
11396           }
11397 
11398           if (!RealUse) {
11399             TryNext = true;
11400             break;
11401           }
11402         }
11403       }
11404 
11405       if (TryNext)
11406         continue;
11407 
11408       // Check for #2
11409       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11410         SDValue Result = isLoad
11411           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11412                                BasePtr, Offset, AM)
11413           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11414                                 BasePtr, Offset, AM);
11415         ++PostIndexedNodes;
11416         ++NodesCombined;
11417         DEBUG(dbgs() << "\nReplacing.5 ";
11418               N->dump(&DAG);
11419               dbgs() << "\nWith: ";
11420               Result.getNode()->dump(&DAG);
11421               dbgs() << '\n');
11422         WorklistRemover DeadNodes(*this);
11423         if (isLoad) {
11424           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11425           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11426         } else {
11427           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11428         }
11429 
11430         // Finally, since the node is now dead, remove it from the graph.
11431         deleteAndRecombine(N);
11432 
11433         // Replace the uses of Use with uses of the updated base value.
11434         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11435                                       Result.getValue(isLoad ? 1 : 0));
11436         deleteAndRecombine(Op);
11437         return true;
11438       }
11439     }
11440   }
11441 
11442   return false;
11443 }
11444 
11445 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11446 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11447   ISD::MemIndexedMode AM = LD->getAddressingMode();
11448   assert(AM != ISD::UNINDEXED);
11449   SDValue BP = LD->getOperand(1);
11450   SDValue Inc = LD->getOperand(2);
11451 
11452   // Some backends use TargetConstants for load offsets, but don't expect
11453   // TargetConstants in general ADD nodes. We can convert these constants into
11454   // regular Constants (if the constant is not opaque).
11455   assert((Inc.getOpcode() != ISD::TargetConstant ||
11456           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11457          "Cannot split out indexing using opaque target constants");
11458   if (Inc.getOpcode() == ISD::TargetConstant) {
11459     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11460     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11461                           ConstInc->getValueType(0));
11462   }
11463 
11464   unsigned Opc =
11465       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11466   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11467 }
11468 
11469 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11470   LoadSDNode *LD  = cast<LoadSDNode>(N);
11471   SDValue Chain = LD->getChain();
11472   SDValue Ptr   = LD->getBasePtr();
11473 
11474   // If load is not volatile and there are no uses of the loaded value (and
11475   // the updated indexed value in case of indexed loads), change uses of the
11476   // chain value into uses of the chain input (i.e. delete the dead load).
11477   if (!LD->isVolatile()) {
11478     if (N->getValueType(1) == MVT::Other) {
11479       // Unindexed loads.
11480       if (!N->hasAnyUseOfValue(0)) {
11481         // It's not safe to use the two value CombineTo variant here. e.g.
11482         // v1, chain2 = load chain1, loc
11483         // v2, chain3 = load chain2, loc
11484         // v3         = add v2, c
11485         // Now we replace use of chain2 with chain1.  This makes the second load
11486         // isomorphic to the one we are deleting, and thus makes this load live.
11487         DEBUG(dbgs() << "\nReplacing.6 ";
11488               N->dump(&DAG);
11489               dbgs() << "\nWith chain: ";
11490               Chain.getNode()->dump(&DAG);
11491               dbgs() << "\n");
11492         WorklistRemover DeadNodes(*this);
11493         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11494         AddUsersToWorklist(Chain.getNode());
11495         if (N->use_empty())
11496           deleteAndRecombine(N);
11497 
11498         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11499       }
11500     } else {
11501       // Indexed loads.
11502       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11503 
11504       // If this load has an opaque TargetConstant offset, then we cannot split
11505       // the indexing into an add/sub directly (that TargetConstant may not be
11506       // valid for a different type of node, and we cannot convert an opaque
11507       // target constant into a regular constant).
11508       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11509                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11510 
11511       if (!N->hasAnyUseOfValue(0) &&
11512           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11513         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11514         SDValue Index;
11515         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11516           Index = SplitIndexingFromLoad(LD);
11517           // Try to fold the base pointer arithmetic into subsequent loads and
11518           // stores.
11519           AddUsersToWorklist(N);
11520         } else
11521           Index = DAG.getUNDEF(N->getValueType(1));
11522         DEBUG(dbgs() << "\nReplacing.7 ";
11523               N->dump(&DAG);
11524               dbgs() << "\nWith: ";
11525               Undef.getNode()->dump(&DAG);
11526               dbgs() << " and 2 other values\n");
11527         WorklistRemover DeadNodes(*this);
11528         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11529         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11530         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11531         deleteAndRecombine(N);
11532         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11533       }
11534     }
11535   }
11536 
11537   // If this load is directly stored, replace the load value with the stored
11538   // value.
11539   // TODO: Handle store large -> read small portion.
11540   // TODO: Handle TRUNCSTORE/LOADEXT
11541   if (OptLevel != CodeGenOpt::None &&
11542       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11543     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11544       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11545       if (PrevST->getBasePtr() == Ptr &&
11546           PrevST->getValue().getValueType() == N->getValueType(0))
11547         return CombineTo(N, PrevST->getOperand(1), Chain);
11548     }
11549   }
11550 
11551   // Try to infer better alignment information than the load already has.
11552   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11553     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11554       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11555         SDValue NewLoad = DAG.getExtLoad(
11556             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11557             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11558             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11559         if (NewLoad.getNode() != N)
11560           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11561       }
11562     }
11563   }
11564 
11565   if (LD->isUnindexed()) {
11566     // Walk up chain skipping non-aliasing memory nodes.
11567     SDValue BetterChain = FindBetterChain(N, Chain);
11568 
11569     // If there is a better chain.
11570     if (Chain != BetterChain) {
11571       SDValue ReplLoad;
11572 
11573       // Replace the chain to void dependency.
11574       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11575         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11576                                BetterChain, Ptr, LD->getMemOperand());
11577       } else {
11578         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11579                                   LD->getValueType(0),
11580                                   BetterChain, Ptr, LD->getMemoryVT(),
11581                                   LD->getMemOperand());
11582       }
11583 
11584       // Create token factor to keep old chain connected.
11585       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11586                                   MVT::Other, Chain, ReplLoad.getValue(1));
11587 
11588       // Replace uses with load result and token factor
11589       return CombineTo(N, ReplLoad.getValue(0), Token);
11590     }
11591   }
11592 
11593   // Try transforming N to an indexed load.
11594   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11595     return SDValue(N, 0);
11596 
11597   // Try to slice up N to more direct loads if the slices are mapped to
11598   // different register banks or pairing can take place.
11599   if (SliceUpLoad(N))
11600     return SDValue(N, 0);
11601 
11602   return SDValue();
11603 }
11604 
11605 namespace {
11606 
11607 /// \brief Helper structure used to slice a load in smaller loads.
11608 /// Basically a slice is obtained from the following sequence:
11609 /// Origin = load Ty1, Base
11610 /// Shift = srl Ty1 Origin, CstTy Amount
11611 /// Inst = trunc Shift to Ty2
11612 ///
11613 /// Then, it will be rewritten into:
11614 /// Slice = load SliceTy, Base + SliceOffset
11615 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11616 ///
11617 /// SliceTy is deduced from the number of bits that are actually used to
11618 /// build Inst.
11619 struct LoadedSlice {
11620   /// \brief Helper structure used to compute the cost of a slice.
11621   struct Cost {
11622     /// Are we optimizing for code size.
11623     bool ForCodeSize;
11624 
11625     /// Various cost.
11626     unsigned Loads = 0;
11627     unsigned Truncates = 0;
11628     unsigned CrossRegisterBanksCopies = 0;
11629     unsigned ZExts = 0;
11630     unsigned Shift = 0;
11631 
11632     Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {}
11633 
11634     /// \brief Get the cost of one isolated slice.
11635     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11636         : ForCodeSize(ForCodeSize), Loads(1) {
11637       EVT TruncType = LS.Inst->getValueType(0);
11638       EVT LoadedType = LS.getLoadedType();
11639       if (TruncType != LoadedType &&
11640           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11641         ZExts = 1;
11642     }
11643 
11644     /// \brief Account for slicing gain in the current cost.
11645     /// Slicing provide a few gains like removing a shift or a
11646     /// truncate. This method allows to grow the cost of the original
11647     /// load with the gain from this slice.
11648     void addSliceGain(const LoadedSlice &LS) {
11649       // Each slice saves a truncate.
11650       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11651       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11652                               LS.Inst->getValueType(0)))
11653         ++Truncates;
11654       // If there is a shift amount, this slice gets rid of it.
11655       if (LS.Shift)
11656         ++Shift;
11657       // If this slice can merge a cross register bank copy, account for it.
11658       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11659         ++CrossRegisterBanksCopies;
11660     }
11661 
11662     Cost &operator+=(const Cost &RHS) {
11663       Loads += RHS.Loads;
11664       Truncates += RHS.Truncates;
11665       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11666       ZExts += RHS.ZExts;
11667       Shift += RHS.Shift;
11668       return *this;
11669     }
11670 
11671     bool operator==(const Cost &RHS) const {
11672       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11673              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11674              ZExts == RHS.ZExts && Shift == RHS.Shift;
11675     }
11676 
11677     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11678 
11679     bool operator<(const Cost &RHS) const {
11680       // Assume cross register banks copies are as expensive as loads.
11681       // FIXME: Do we want some more target hooks?
11682       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11683       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11684       // Unless we are optimizing for code size, consider the
11685       // expensive operation first.
11686       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11687         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11688       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11689              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11690     }
11691 
11692     bool operator>(const Cost &RHS) const { return RHS < *this; }
11693 
11694     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11695 
11696     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11697   };
11698 
11699   // The last instruction that represent the slice. This should be a
11700   // truncate instruction.
11701   SDNode *Inst;
11702 
11703   // The original load instruction.
11704   LoadSDNode *Origin;
11705 
11706   // The right shift amount in bits from the original load.
11707   unsigned Shift;
11708 
11709   // The DAG from which Origin came from.
11710   // This is used to get some contextual information about legal types, etc.
11711   SelectionDAG *DAG;
11712 
11713   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11714               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11715       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11716 
11717   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11718   /// \return Result is \p BitWidth and has used bits set to 1 and
11719   ///         not used bits set to 0.
11720   APInt getUsedBits() const {
11721     // Reproduce the trunc(lshr) sequence:
11722     // - Start from the truncated value.
11723     // - Zero extend to the desired bit width.
11724     // - Shift left.
11725     assert(Origin && "No original load to compare against.");
11726     unsigned BitWidth = Origin->getValueSizeInBits(0);
11727     assert(Inst && "This slice is not bound to an instruction");
11728     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11729            "Extracted slice is bigger than the whole type!");
11730     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11731     UsedBits.setAllBits();
11732     UsedBits = UsedBits.zext(BitWidth);
11733     UsedBits <<= Shift;
11734     return UsedBits;
11735   }
11736 
11737   /// \brief Get the size of the slice to be loaded in bytes.
11738   unsigned getLoadedSize() const {
11739     unsigned SliceSize = getUsedBits().countPopulation();
11740     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11741     return SliceSize / 8;
11742   }
11743 
11744   /// \brief Get the type that will be loaded for this slice.
11745   /// Note: This may not be the final type for the slice.
11746   EVT getLoadedType() const {
11747     assert(DAG && "Missing context");
11748     LLVMContext &Ctxt = *DAG->getContext();
11749     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11750   }
11751 
11752   /// \brief Get the alignment of the load used for this slice.
11753   unsigned getAlignment() const {
11754     unsigned Alignment = Origin->getAlignment();
11755     unsigned Offset = getOffsetFromBase();
11756     if (Offset != 0)
11757       Alignment = MinAlign(Alignment, Alignment + Offset);
11758     return Alignment;
11759   }
11760 
11761   /// \brief Check if this slice can be rewritten with legal operations.
11762   bool isLegal() const {
11763     // An invalid slice is not legal.
11764     if (!Origin || !Inst || !DAG)
11765       return false;
11766 
11767     // Offsets are for indexed load only, we do not handle that.
11768     if (!Origin->getOffset().isUndef())
11769       return false;
11770 
11771     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11772 
11773     // Check that the type is legal.
11774     EVT SliceType = getLoadedType();
11775     if (!TLI.isTypeLegal(SliceType))
11776       return false;
11777 
11778     // Check that the load is legal for this type.
11779     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11780       return false;
11781 
11782     // Check that the offset can be computed.
11783     // 1. Check its type.
11784     EVT PtrType = Origin->getBasePtr().getValueType();
11785     if (PtrType == MVT::Untyped || PtrType.isExtended())
11786       return false;
11787 
11788     // 2. Check that it fits in the immediate.
11789     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11790       return false;
11791 
11792     // 3. Check that the computation is legal.
11793     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11794       return false;
11795 
11796     // Check that the zext is legal if it needs one.
11797     EVT TruncateType = Inst->getValueType(0);
11798     if (TruncateType != SliceType &&
11799         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11800       return false;
11801 
11802     return true;
11803   }
11804 
11805   /// \brief Get the offset in bytes of this slice in the original chunk of
11806   /// bits.
11807   /// \pre DAG != nullptr.
11808   uint64_t getOffsetFromBase() const {
11809     assert(DAG && "Missing context.");
11810     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11811     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11812     uint64_t Offset = Shift / 8;
11813     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11814     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11815            "The size of the original loaded type is not a multiple of a"
11816            " byte.");
11817     // If Offset is bigger than TySizeInBytes, it means we are loading all
11818     // zeros. This should have been optimized before in the process.
11819     assert(TySizeInBytes > Offset &&
11820            "Invalid shift amount for given loaded size");
11821     if (IsBigEndian)
11822       Offset = TySizeInBytes - Offset - getLoadedSize();
11823     return Offset;
11824   }
11825 
11826   /// \brief Generate the sequence of instructions to load the slice
11827   /// represented by this object and redirect the uses of this slice to
11828   /// this new sequence of instructions.
11829   /// \pre this->Inst && this->Origin are valid Instructions and this
11830   /// object passed the legal check: LoadedSlice::isLegal returned true.
11831   /// \return The last instruction of the sequence used to load the slice.
11832   SDValue loadSlice() const {
11833     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11834     const SDValue &OldBaseAddr = Origin->getBasePtr();
11835     SDValue BaseAddr = OldBaseAddr;
11836     // Get the offset in that chunk of bytes w.r.t. the endianness.
11837     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11838     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11839     if (Offset) {
11840       // BaseAddr = BaseAddr + Offset.
11841       EVT ArithType = BaseAddr.getValueType();
11842       SDLoc DL(Origin);
11843       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11844                               DAG->getConstant(Offset, DL, ArithType));
11845     }
11846 
11847     // Create the type of the loaded slice according to its size.
11848     EVT SliceType = getLoadedType();
11849 
11850     // Create the load for the slice.
11851     SDValue LastInst =
11852         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11853                      Origin->getPointerInfo().getWithOffset(Offset),
11854                      getAlignment(), Origin->getMemOperand()->getFlags());
11855     // If the final type is not the same as the loaded type, this means that
11856     // we have to pad with zero. Create a zero extend for that.
11857     EVT FinalType = Inst->getValueType(0);
11858     if (SliceType != FinalType)
11859       LastInst =
11860           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11861     return LastInst;
11862   }
11863 
11864   /// \brief Check if this slice can be merged with an expensive cross register
11865   /// bank copy. E.g.,
11866   /// i = load i32
11867   /// f = bitcast i32 i to float
11868   bool canMergeExpensiveCrossRegisterBankCopy() const {
11869     if (!Inst || !Inst->hasOneUse())
11870       return false;
11871     SDNode *Use = *Inst->use_begin();
11872     if (Use->getOpcode() != ISD::BITCAST)
11873       return false;
11874     assert(DAG && "Missing context");
11875     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11876     EVT ResVT = Use->getValueType(0);
11877     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11878     const TargetRegisterClass *ArgRC =
11879         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11880     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11881       return false;
11882 
11883     // At this point, we know that we perform a cross-register-bank copy.
11884     // Check if it is expensive.
11885     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11886     // Assume bitcasts are cheap, unless both register classes do not
11887     // explicitly share a common sub class.
11888     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11889       return false;
11890 
11891     // Check if it will be merged with the load.
11892     // 1. Check the alignment constraint.
11893     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11894         ResVT.getTypeForEVT(*DAG->getContext()));
11895 
11896     if (RequiredAlignment > getAlignment())
11897       return false;
11898 
11899     // 2. Check that the load is a legal operation for that type.
11900     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11901       return false;
11902 
11903     // 3. Check that we do not have a zext in the way.
11904     if (Inst->getValueType(0) != getLoadedType())
11905       return false;
11906 
11907     return true;
11908   }
11909 };
11910 
11911 } // end anonymous namespace
11912 
11913 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11914 /// \p UsedBits looks like 0..0 1..1 0..0.
11915 static bool areUsedBitsDense(const APInt &UsedBits) {
11916   // If all the bits are one, this is dense!
11917   if (UsedBits.isAllOnesValue())
11918     return true;
11919 
11920   // Get rid of the unused bits on the right.
11921   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11922   // Get rid of the unused bits on the left.
11923   if (NarrowedUsedBits.countLeadingZeros())
11924     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11925   // Check that the chunk of bits is completely used.
11926   return NarrowedUsedBits.isAllOnesValue();
11927 }
11928 
11929 /// \brief Check whether or not \p First and \p Second are next to each other
11930 /// in memory. This means that there is no hole between the bits loaded
11931 /// by \p First and the bits loaded by \p Second.
11932 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11933                                      const LoadedSlice &Second) {
11934   assert(First.Origin == Second.Origin && First.Origin &&
11935          "Unable to match different memory origins.");
11936   APInt UsedBits = First.getUsedBits();
11937   assert((UsedBits & Second.getUsedBits()) == 0 &&
11938          "Slices are not supposed to overlap.");
11939   UsedBits |= Second.getUsedBits();
11940   return areUsedBitsDense(UsedBits);
11941 }
11942 
11943 /// \brief Adjust the \p GlobalLSCost according to the target
11944 /// paring capabilities and the layout of the slices.
11945 /// \pre \p GlobalLSCost should account for at least as many loads as
11946 /// there is in the slices in \p LoadedSlices.
11947 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11948                                  LoadedSlice::Cost &GlobalLSCost) {
11949   unsigned NumberOfSlices = LoadedSlices.size();
11950   // If there is less than 2 elements, no pairing is possible.
11951   if (NumberOfSlices < 2)
11952     return;
11953 
11954   // Sort the slices so that elements that are likely to be next to each
11955   // other in memory are next to each other in the list.
11956   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11957             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11958     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11959     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11960   });
11961   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11962   // First (resp. Second) is the first (resp. Second) potentially candidate
11963   // to be placed in a paired load.
11964   const LoadedSlice *First = nullptr;
11965   const LoadedSlice *Second = nullptr;
11966   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11967                 // Set the beginning of the pair.
11968                                                            First = Second) {
11969     Second = &LoadedSlices[CurrSlice];
11970 
11971     // If First is NULL, it means we start a new pair.
11972     // Get to the next slice.
11973     if (!First)
11974       continue;
11975 
11976     EVT LoadedType = First->getLoadedType();
11977 
11978     // If the types of the slices are different, we cannot pair them.
11979     if (LoadedType != Second->getLoadedType())
11980       continue;
11981 
11982     // Check if the target supplies paired loads for this type.
11983     unsigned RequiredAlignment = 0;
11984     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11985       // move to the next pair, this type is hopeless.
11986       Second = nullptr;
11987       continue;
11988     }
11989     // Check if we meet the alignment requirement.
11990     if (RequiredAlignment > First->getAlignment())
11991       continue;
11992 
11993     // Check that both loads are next to each other in memory.
11994     if (!areSlicesNextToEachOther(*First, *Second))
11995       continue;
11996 
11997     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11998     --GlobalLSCost.Loads;
11999     // Move to the next pair.
12000     Second = nullptr;
12001   }
12002 }
12003 
12004 /// \brief Check the profitability of all involved LoadedSlice.
12005 /// Currently, it is considered profitable if there is exactly two
12006 /// involved slices (1) which are (2) next to each other in memory, and
12007 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
12008 ///
12009 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
12010 /// the elements themselves.
12011 ///
12012 /// FIXME: When the cost model will be mature enough, we can relax
12013 /// constraints (1) and (2).
12014 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12015                                 const APInt &UsedBits, bool ForCodeSize) {
12016   unsigned NumberOfSlices = LoadedSlices.size();
12017   if (StressLoadSlicing)
12018     return NumberOfSlices > 1;
12019 
12020   // Check (1).
12021   if (NumberOfSlices != 2)
12022     return false;
12023 
12024   // Check (2).
12025   if (!areUsedBitsDense(UsedBits))
12026     return false;
12027 
12028   // Check (3).
12029   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
12030   // The original code has one big load.
12031   OrigCost.Loads = 1;
12032   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
12033     const LoadedSlice &LS = LoadedSlices[CurrSlice];
12034     // Accumulate the cost of all the slices.
12035     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
12036     GlobalSlicingCost += SliceCost;
12037 
12038     // Account as cost in the original configuration the gain obtained
12039     // with the current slices.
12040     OrigCost.addSliceGain(LS);
12041   }
12042 
12043   // If the target supports paired load, adjust the cost accordingly.
12044   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
12045   return OrigCost > GlobalSlicingCost;
12046 }
12047 
12048 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
12049 /// operations, split it in the various pieces being extracted.
12050 ///
12051 /// This sort of thing is introduced by SROA.
12052 /// This slicing takes care not to insert overlapping loads.
12053 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
12054 bool DAGCombiner::SliceUpLoad(SDNode *N) {
12055   if (Level < AfterLegalizeDAG)
12056     return false;
12057 
12058   LoadSDNode *LD = cast<LoadSDNode>(N);
12059   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
12060       !LD->getValueType(0).isInteger())
12061     return false;
12062 
12063   // Keep track of already used bits to detect overlapping values.
12064   // In that case, we will just abort the transformation.
12065   APInt UsedBits(LD->getValueSizeInBits(0), 0);
12066 
12067   SmallVector<LoadedSlice, 4> LoadedSlices;
12068 
12069   // Check if this load is used as several smaller chunks of bits.
12070   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
12071   // of computation for each trunc.
12072   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
12073        UI != UIEnd; ++UI) {
12074     // Skip the uses of the chain.
12075     if (UI.getUse().getResNo() != 0)
12076       continue;
12077 
12078     SDNode *User = *UI;
12079     unsigned Shift = 0;
12080 
12081     // Check if this is a trunc(lshr).
12082     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
12083         isa<ConstantSDNode>(User->getOperand(1))) {
12084       Shift = User->getConstantOperandVal(1);
12085       User = *User->use_begin();
12086     }
12087 
12088     // At this point, User is a Truncate, iff we encountered, trunc or
12089     // trunc(lshr).
12090     if (User->getOpcode() != ISD::TRUNCATE)
12091       return false;
12092 
12093     // The width of the type must be a power of 2 and greater than 8-bits.
12094     // Otherwise the load cannot be represented in LLVM IR.
12095     // Moreover, if we shifted with a non-8-bits multiple, the slice
12096     // will be across several bytes. We do not support that.
12097     unsigned Width = User->getValueSizeInBits(0);
12098     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
12099       return false;
12100 
12101     // Build the slice for this chain of computations.
12102     LoadedSlice LS(User, LD, Shift, &DAG);
12103     APInt CurrentUsedBits = LS.getUsedBits();
12104 
12105     // Check if this slice overlaps with another.
12106     if ((CurrentUsedBits & UsedBits) != 0)
12107       return false;
12108     // Update the bits used globally.
12109     UsedBits |= CurrentUsedBits;
12110 
12111     // Check if the new slice would be legal.
12112     if (!LS.isLegal())
12113       return false;
12114 
12115     // Record the slice.
12116     LoadedSlices.push_back(LS);
12117   }
12118 
12119   // Abort slicing if it does not seem to be profitable.
12120   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
12121     return false;
12122 
12123   ++SlicedLoads;
12124 
12125   // Rewrite each chain to use an independent load.
12126   // By construction, each chain can be represented by a unique load.
12127 
12128   // Prepare the argument for the new token factor for all the slices.
12129   SmallVector<SDValue, 8> ArgChains;
12130   for (SmallVectorImpl<LoadedSlice>::const_iterator
12131            LSIt = LoadedSlices.begin(),
12132            LSItEnd = LoadedSlices.end();
12133        LSIt != LSItEnd; ++LSIt) {
12134     SDValue SliceInst = LSIt->loadSlice();
12135     CombineTo(LSIt->Inst, SliceInst, true);
12136     if (SliceInst.getOpcode() != ISD::LOAD)
12137       SliceInst = SliceInst.getOperand(0);
12138     assert(SliceInst->getOpcode() == ISD::LOAD &&
12139            "It takes more than a zext to get to the loaded slice!!");
12140     ArgChains.push_back(SliceInst.getValue(1));
12141   }
12142 
12143   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
12144                               ArgChains);
12145   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
12146   AddToWorklist(Chain.getNode());
12147   return true;
12148 }
12149 
12150 /// Check to see if V is (and load (ptr), imm), where the load is having
12151 /// specific bytes cleared out.  If so, return the byte size being masked out
12152 /// and the shift amount.
12153 static std::pair<unsigned, unsigned>
12154 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
12155   std::pair<unsigned, unsigned> Result(0, 0);
12156 
12157   // Check for the structure we're looking for.
12158   if (V->getOpcode() != ISD::AND ||
12159       !isa<ConstantSDNode>(V->getOperand(1)) ||
12160       !ISD::isNormalLoad(V->getOperand(0).getNode()))
12161     return Result;
12162 
12163   // Check the chain and pointer.
12164   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
12165   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
12166 
12167   // The store should be chained directly to the load or be an operand of a
12168   // tokenfactor.
12169   if (LD == Chain.getNode())
12170     ; // ok.
12171   else if (Chain->getOpcode() != ISD::TokenFactor)
12172     return Result; // Fail.
12173   else {
12174     bool isOk = false;
12175     for (const SDValue &ChainOp : Chain->op_values())
12176       if (ChainOp.getNode() == LD) {
12177         isOk = true;
12178         break;
12179       }
12180     if (!isOk) return Result;
12181   }
12182 
12183   // This only handles simple types.
12184   if (V.getValueType() != MVT::i16 &&
12185       V.getValueType() != MVT::i32 &&
12186       V.getValueType() != MVT::i64)
12187     return Result;
12188 
12189   // Check the constant mask.  Invert it so that the bits being masked out are
12190   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
12191   // follow the sign bit for uniformity.
12192   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12193   unsigned NotMaskLZ = countLeadingZeros(NotMask);
12194   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
12195   unsigned NotMaskTZ = countTrailingZeros(NotMask);
12196   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
12197   if (NotMaskLZ == 64) return Result;  // All zero mask.
12198 
12199   // See if we have a continuous run of bits.  If so, we have 0*1+0*
12200   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12201     return Result;
12202 
12203   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12204   if (V.getValueType() != MVT::i64 && NotMaskLZ)
12205     NotMaskLZ -= 64-V.getValueSizeInBits();
12206 
12207   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12208   switch (MaskedBytes) {
12209   case 1:
12210   case 2:
12211   case 4: break;
12212   default: return Result; // All one mask, or 5-byte mask.
12213   }
12214 
12215   // Verify that the first bit starts at a multiple of mask so that the access
12216   // is aligned the same as the access width.
12217   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12218 
12219   Result.first = MaskedBytes;
12220   Result.second = NotMaskTZ/8;
12221   return Result;
12222 }
12223 
12224 /// Check to see if IVal is something that provides a value as specified by
12225 /// MaskInfo. If so, replace the specified store with a narrower store of
12226 /// truncated IVal.
12227 static SDNode *
12228 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12229                                 SDValue IVal, StoreSDNode *St,
12230                                 DAGCombiner *DC) {
12231   unsigned NumBytes = MaskInfo.first;
12232   unsigned ByteShift = MaskInfo.second;
12233   SelectionDAG &DAG = DC->getDAG();
12234 
12235   // Check to see if IVal is all zeros in the part being masked in by the 'or'
12236   // that uses this.  If not, this is not a replacement.
12237   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12238                                   ByteShift*8, (ByteShift+NumBytes)*8);
12239   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12240 
12241   // Check that it is legal on the target to do this.  It is legal if the new
12242   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12243   // legalization.
12244   MVT VT = MVT::getIntegerVT(NumBytes*8);
12245   if (!DC->isTypeLegal(VT))
12246     return nullptr;
12247 
12248   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12249   // shifted by ByteShift and truncated down to NumBytes.
12250   if (ByteShift) {
12251     SDLoc DL(IVal);
12252     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12253                        DAG.getConstant(ByteShift*8, DL,
12254                                     DC->getShiftAmountTy(IVal.getValueType())));
12255   }
12256 
12257   // Figure out the offset for the store and the alignment of the access.
12258   unsigned StOffset;
12259   unsigned NewAlign = St->getAlignment();
12260 
12261   if (DAG.getDataLayout().isLittleEndian())
12262     StOffset = ByteShift;
12263   else
12264     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12265 
12266   SDValue Ptr = St->getBasePtr();
12267   if (StOffset) {
12268     SDLoc DL(IVal);
12269     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12270                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12271     NewAlign = MinAlign(NewAlign, StOffset);
12272   }
12273 
12274   // Truncate down to the new size.
12275   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12276 
12277   ++OpsNarrowed;
12278   return DAG
12279       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12280                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12281       .getNode();
12282 }
12283 
12284 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12285 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12286 /// narrowing the load and store if it would end up being a win for performance
12287 /// or code size.
12288 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12289   StoreSDNode *ST  = cast<StoreSDNode>(N);
12290   if (ST->isVolatile())
12291     return SDValue();
12292 
12293   SDValue Chain = ST->getChain();
12294   SDValue Value = ST->getValue();
12295   SDValue Ptr   = ST->getBasePtr();
12296   EVT VT = Value.getValueType();
12297 
12298   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12299     return SDValue();
12300 
12301   unsigned Opc = Value.getOpcode();
12302 
12303   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12304   // is a byte mask indicating a consecutive number of bytes, check to see if
12305   // Y is known to provide just those bytes.  If so, we try to replace the
12306   // load + replace + store sequence with a single (narrower) store, which makes
12307   // the load dead.
12308   if (Opc == ISD::OR) {
12309     std::pair<unsigned, unsigned> MaskedLoad;
12310     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12311     if (MaskedLoad.first)
12312       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12313                                                   Value.getOperand(1), ST,this))
12314         return SDValue(NewST, 0);
12315 
12316     // Or is commutative, so try swapping X and Y.
12317     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12318     if (MaskedLoad.first)
12319       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12320                                                   Value.getOperand(0), ST,this))
12321         return SDValue(NewST, 0);
12322   }
12323 
12324   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12325       Value.getOperand(1).getOpcode() != ISD::Constant)
12326     return SDValue();
12327 
12328   SDValue N0 = Value.getOperand(0);
12329   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12330       Chain == SDValue(N0.getNode(), 1)) {
12331     LoadSDNode *LD = cast<LoadSDNode>(N0);
12332     if (LD->getBasePtr() != Ptr ||
12333         LD->getPointerInfo().getAddrSpace() !=
12334         ST->getPointerInfo().getAddrSpace())
12335       return SDValue();
12336 
12337     // Find the type to narrow it the load / op / store to.
12338     SDValue N1 = Value.getOperand(1);
12339     unsigned BitWidth = N1.getValueSizeInBits();
12340     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12341     if (Opc == ISD::AND)
12342       Imm ^= APInt::getAllOnesValue(BitWidth);
12343     if (Imm == 0 || Imm.isAllOnesValue())
12344       return SDValue();
12345     unsigned ShAmt = Imm.countTrailingZeros();
12346     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12347     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12348     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12349     // The narrowing should be profitable, the load/store operation should be
12350     // legal (or custom) and the store size should be equal to the NewVT width.
12351     while (NewBW < BitWidth &&
12352            (NewVT.getStoreSizeInBits() != NewBW ||
12353             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12354             !TLI.isNarrowingProfitable(VT, NewVT))) {
12355       NewBW = NextPowerOf2(NewBW);
12356       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12357     }
12358     if (NewBW >= BitWidth)
12359       return SDValue();
12360 
12361     // If the lsb changed does not start at the type bitwidth boundary,
12362     // start at the previous one.
12363     if (ShAmt % NewBW)
12364       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12365     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12366                                    std::min(BitWidth, ShAmt + NewBW));
12367     if ((Imm & Mask) == Imm) {
12368       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12369       if (Opc == ISD::AND)
12370         NewImm ^= APInt::getAllOnesValue(NewBW);
12371       uint64_t PtrOff = ShAmt / 8;
12372       // For big endian targets, we need to adjust the offset to the pointer to
12373       // load the correct bytes.
12374       if (DAG.getDataLayout().isBigEndian())
12375         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12376 
12377       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12378       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12379       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12380         return SDValue();
12381 
12382       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12383                                    Ptr.getValueType(), Ptr,
12384                                    DAG.getConstant(PtrOff, SDLoc(LD),
12385                                                    Ptr.getValueType()));
12386       SDValue NewLD =
12387           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12388                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12389                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12390       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12391                                    DAG.getConstant(NewImm, SDLoc(Value),
12392                                                    NewVT));
12393       SDValue NewST =
12394           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12395                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12396 
12397       AddToWorklist(NewPtr.getNode());
12398       AddToWorklist(NewLD.getNode());
12399       AddToWorklist(NewVal.getNode());
12400       WorklistRemover DeadNodes(*this);
12401       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12402       ++OpsNarrowed;
12403       return NewST;
12404     }
12405   }
12406 
12407   return SDValue();
12408 }
12409 
12410 /// For a given floating point load / store pair, if the load value isn't used
12411 /// by any other operations, then consider transforming the pair to integer
12412 /// load / store operations if the target deems the transformation profitable.
12413 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12414   StoreSDNode *ST  = cast<StoreSDNode>(N);
12415   SDValue Chain = ST->getChain();
12416   SDValue Value = ST->getValue();
12417   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12418       Value.hasOneUse() &&
12419       Chain == SDValue(Value.getNode(), 1)) {
12420     LoadSDNode *LD = cast<LoadSDNode>(Value);
12421     EVT VT = LD->getMemoryVT();
12422     if (!VT.isFloatingPoint() ||
12423         VT != ST->getMemoryVT() ||
12424         LD->isNonTemporal() ||
12425         ST->isNonTemporal() ||
12426         LD->getPointerInfo().getAddrSpace() != 0 ||
12427         ST->getPointerInfo().getAddrSpace() != 0)
12428       return SDValue();
12429 
12430     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12431     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12432         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12433         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12434         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12435       return SDValue();
12436 
12437     unsigned LDAlign = LD->getAlignment();
12438     unsigned STAlign = ST->getAlignment();
12439     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12440     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12441     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12442       return SDValue();
12443 
12444     SDValue NewLD =
12445         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12446                     LD->getPointerInfo(), LDAlign);
12447 
12448     SDValue NewST =
12449         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12450                      ST->getPointerInfo(), STAlign);
12451 
12452     AddToWorklist(NewLD.getNode());
12453     AddToWorklist(NewST.getNode());
12454     WorklistRemover DeadNodes(*this);
12455     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12456     ++LdStFP2Int;
12457     return NewST;
12458   }
12459 
12460   return SDValue();
12461 }
12462 
12463 // This is a helper function for visitMUL to check the profitability
12464 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12465 // MulNode is the original multiply, AddNode is (add x, c1),
12466 // and ConstNode is c2.
12467 //
12468 // If the (add x, c1) has multiple uses, we could increase
12469 // the number of adds if we make this transformation.
12470 // It would only be worth doing this if we can remove a
12471 // multiply in the process. Check for that here.
12472 // To illustrate:
12473 //     (A + c1) * c3
12474 //     (A + c2) * c3
12475 // We're checking for cases where we have common "c3 * A" expressions.
12476 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12477                                               SDValue &AddNode,
12478                                               SDValue &ConstNode) {
12479   APInt Val;
12480 
12481   // If the add only has one use, this would be OK to do.
12482   if (AddNode.getNode()->hasOneUse())
12483     return true;
12484 
12485   // Walk all the users of the constant with which we're multiplying.
12486   for (SDNode *Use : ConstNode->uses()) {
12487     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12488       continue;
12489 
12490     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12491       SDNode *OtherOp;
12492       SDNode *MulVar = AddNode.getOperand(0).getNode();
12493 
12494       // OtherOp is what we're multiplying against the constant.
12495       if (Use->getOperand(0) == ConstNode)
12496         OtherOp = Use->getOperand(1).getNode();
12497       else
12498         OtherOp = Use->getOperand(0).getNode();
12499 
12500       // Check to see if multiply is with the same operand of our "add".
12501       //
12502       //     ConstNode  = CONST
12503       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12504       //     ...
12505       //     AddNode  = (A + c1)  <-- MulVar is A.
12506       //         = AddNode * ConstNode   <-- current visiting instruction.
12507       //
12508       // If we make this transformation, we will have a common
12509       // multiply (ConstNode * A) that we can save.
12510       if (OtherOp == MulVar)
12511         return true;
12512 
12513       // Now check to see if a future expansion will give us a common
12514       // multiply.
12515       //
12516       //     ConstNode  = CONST
12517       //     AddNode    = (A + c1)
12518       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12519       //     ...
12520       //     OtherOp = (A + c2)
12521       //     Use     = OtherOp * ConstNode <-- visiting Use.
12522       //
12523       // If we make this transformation, we will have a common
12524       // multiply (CONST * A) after we also do the same transformation
12525       // to the "t2" instruction.
12526       if (OtherOp->getOpcode() == ISD::ADD &&
12527           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12528           OtherOp->getOperand(0).getNode() == MulVar)
12529         return true;
12530     }
12531   }
12532 
12533   // Didn't find a case where this would be profitable.
12534   return false;
12535 }
12536 
12537 static SDValue peekThroughBitcast(SDValue V) {
12538   while (V.getOpcode() == ISD::BITCAST)
12539     V = V.getOperand(0);
12540   return V;
12541 }
12542 
12543 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12544                                          unsigned NumStores) {
12545   SmallVector<SDValue, 8> Chains;
12546   SmallPtrSet<const SDNode *, 8> Visited;
12547   SDLoc StoreDL(StoreNodes[0].MemNode);
12548 
12549   for (unsigned i = 0; i < NumStores; ++i) {
12550     Visited.insert(StoreNodes[i].MemNode);
12551   }
12552 
12553   // don't include nodes that are children
12554   for (unsigned i = 0; i < NumStores; ++i) {
12555     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12556       Chains.push_back(StoreNodes[i].MemNode->getChain());
12557   }
12558 
12559   assert(Chains.size() > 0 && "Chain should have generated a chain");
12560   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12561 }
12562 
12563 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12564     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12565     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12566   // Make sure we have something to merge.
12567   if (NumStores < 2)
12568     return false;
12569 
12570   // The latest Node in the DAG.
12571   SDLoc DL(StoreNodes[0].MemNode);
12572 
12573   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12574   unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12575   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
12576 
12577   EVT StoreTy;
12578   if (UseVector) {
12579     unsigned Elts = NumStores * NumMemElts;
12580     // Get the type for the merged vector store.
12581     StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12582   } else
12583     StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12584 
12585   SDValue StoredVal;
12586   if (UseVector) {
12587     if (IsConstantSrc) {
12588       SmallVector<SDValue, 8> BuildVector;
12589       for (unsigned I = 0; I != NumStores; ++I) {
12590         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12591         SDValue Val = St->getValue();
12592         // If constant is of the wrong type, convert it now.
12593         if (MemVT != Val.getValueType()) {
12594           Val = peekThroughBitcast(Val);
12595           // Deal with constants of wrong size.
12596           if (ElementSizeBytes * 8 != Val.getValueSizeInBits()) {
12597             EVT IntMemVT =
12598                 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
12599             if (auto *CFP = dyn_cast<ConstantFPSDNode>(Val))
12600               Val = DAG.getConstant(
12601                   CFP->getValueAPF().bitcastToAPInt().zextOrTrunc(
12602                       8 * ElementSizeBytes),
12603                   SDLoc(CFP), IntMemVT);
12604             else if (auto *C = dyn_cast<ConstantSDNode>(Val))
12605               Val = DAG.getConstant(
12606                   C->getAPIntValue().zextOrTrunc(8 * ElementSizeBytes),
12607                   SDLoc(C), IntMemVT);
12608           }
12609           // Make sure correctly size type is the correct type.
12610           Val = DAG.getBitcast(MemVT, Val);
12611         }
12612         BuildVector.push_back(Val);
12613       }
12614       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12615                                                : ISD::BUILD_VECTOR,
12616                               DL, StoreTy, BuildVector);
12617     } else {
12618       SmallVector<SDValue, 8> Ops;
12619       for (unsigned i = 0; i < NumStores; ++i) {
12620         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12621         SDValue Val = peekThroughBitcast(St->getValue());
12622         // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
12623         // type MemVT. If the underlying value is not the correct
12624         // type, but it is an extraction of an appropriate vector we
12625         // can recast Val to be of the correct type. This may require
12626         // converting between EXTRACT_VECTOR_ELT and
12627         // EXTRACT_SUBVECTOR.
12628         if ((MemVT != Val.getValueType()) &&
12629             (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12630              Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
12631           SDValue Vec = Val.getOperand(0);
12632           EVT MemVTScalarTy = MemVT.getScalarType();
12633           // We may need to add a bitcast here to get types to line up.
12634           if (MemVTScalarTy != Vec.getValueType()) {
12635             unsigned Elts = Vec.getValueType().getSizeInBits() /
12636                             MemVTScalarTy.getSizeInBits();
12637             EVT NewVecTy =
12638                 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts);
12639             Vec = DAG.getBitcast(NewVecTy, Vec);
12640           }
12641           auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR
12642                                         : ISD::EXTRACT_VECTOR_ELT;
12643           Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1));
12644         }
12645         Ops.push_back(Val);
12646       }
12647 
12648       // Build the extracted vector elements back into a vector.
12649       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12650                                                : ISD::BUILD_VECTOR,
12651                               DL, StoreTy, Ops);
12652     }
12653   } else {
12654     // We should always use a vector store when merging extracted vector
12655     // elements, so this path implies a store of constants.
12656     assert(IsConstantSrc && "Merged vector elements should use vector store");
12657 
12658     APInt StoreInt(SizeInBits, 0);
12659 
12660     // Construct a single integer constant which is made of the smaller
12661     // constant inputs.
12662     bool IsLE = DAG.getDataLayout().isLittleEndian();
12663     for (unsigned i = 0; i < NumStores; ++i) {
12664       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12665       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12666 
12667       SDValue Val = St->getValue();
12668       StoreInt <<= ElementSizeBytes * 8;
12669       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12670         StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits);
12671       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12672         StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits);
12673       } else {
12674         llvm_unreachable("Invalid constant element type");
12675       }
12676     }
12677 
12678     // Create the new Load and Store operations.
12679     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12680   }
12681 
12682   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12683   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12684 
12685   // make sure we use trunc store if it's necessary to be legal.
12686   SDValue NewStore;
12687   if (!UseTrunc) {
12688     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
12689                             FirstInChain->getPointerInfo(),
12690                             FirstInChain->getAlignment());
12691   } else { // Must be realized as a trunc store
12692     EVT LegalizedStoredValueTy =
12693         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
12694     unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
12695     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
12696     SDValue ExtendedStoreVal =
12697         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
12698                         LegalizedStoredValueTy);
12699     NewStore = DAG.getTruncStore(
12700         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
12701         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
12702         FirstInChain->getAlignment(),
12703         FirstInChain->getMemOperand()->getFlags());
12704   }
12705 
12706   // Replace all merged stores with the new store.
12707   for (unsigned i = 0; i < NumStores; ++i)
12708     CombineTo(StoreNodes[i].MemNode, NewStore);
12709 
12710   AddToWorklist(NewChain.getNode());
12711   return true;
12712 }
12713 
12714 void DAGCombiner::getStoreMergeCandidates(
12715     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12716   // This holds the base pointer, index, and the offset in bytes from the base
12717   // pointer.
12718   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12719   EVT MemVT = St->getMemoryVT();
12720 
12721   SDValue Val = peekThroughBitcast(St->getValue());
12722   // We must have a base and an offset.
12723   if (!BasePtr.getBase().getNode())
12724     return;
12725 
12726   // Do not handle stores to undef base pointers.
12727   if (BasePtr.getBase().isUndef())
12728     return;
12729 
12730   bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
12731   bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12732                           Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12733   bool IsLoadSrc = isa<LoadSDNode>(Val);
12734   BaseIndexOffset LBasePtr;
12735   // Match on loadbaseptr if relevant.
12736   EVT LoadVT;
12737   if (IsLoadSrc) {
12738     auto *Ld = cast<LoadSDNode>(Val);
12739     LBasePtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12740     LoadVT = Ld->getMemoryVT();
12741     // Load and store should be the same type.
12742     if (MemVT != LoadVT)
12743       return;
12744   }
12745   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
12746                             int64_t &Offset) -> bool {
12747     if (Other->isVolatile() || Other->isIndexed())
12748       return false;
12749     SDValue Val = peekThroughBitcast(Other->getValue());
12750     // Allow merging constants of different types as integers.
12751     bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
12752                                            : Other->getMemoryVT() != MemVT;
12753     if (IsLoadSrc) {
12754       if (NoTypeMatch)
12755         return false;
12756       // The Load's Base Ptr must also match
12757       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) {
12758         auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG);
12759         if (LoadVT != OtherLd->getMemoryVT())
12760           return false;
12761         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
12762           return false;
12763       } else
12764         return false;
12765     }
12766     if (IsConstantSrc) {
12767       if (NoTypeMatch)
12768         return false;
12769       if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val)))
12770         return false;
12771     }
12772     if (IsExtractVecSrc) {
12773       // Do not merge truncated stores here.
12774       if (Other->isTruncatingStore())
12775         return false;
12776       if (!MemVT.bitsEq(Val.getValueType()))
12777         return false;
12778       if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
12779           Val.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12780         return false;
12781     }
12782     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12783     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
12784   };
12785 
12786   // We looking for a root node which is an ancestor to all mergable
12787   // stores. We search up through a load, to our root and then down
12788   // through all children. For instance we will find Store{1,2,3} if
12789   // St is Store1, Store2. or Store3 where the root is not a load
12790   // which always true for nonvolatile ops. TODO: Expand
12791   // the search to find all valid candidates through multiple layers of loads.
12792   //
12793   // Root
12794   // |-------|-------|
12795   // Load    Load    Store3
12796   // |       |
12797   // Store1   Store2
12798   //
12799   // FIXME: We should be able to climb and
12800   // descend TokenFactors to find candidates as well.
12801 
12802   SDNode *RootNode = (St->getChain()).getNode();
12803 
12804   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12805     RootNode = Ldn->getChain().getNode();
12806     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12807       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12808         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12809           if (I2.getOperandNo() == 0)
12810             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12811               BaseIndexOffset Ptr;
12812               int64_t PtrDiff;
12813               if (CandidateMatch(OtherST, Ptr, PtrDiff))
12814                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12815             }
12816   } else
12817     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12818       if (I.getOperandNo() == 0)
12819         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12820           BaseIndexOffset Ptr;
12821           int64_t PtrDiff;
12822           if (CandidateMatch(OtherST, Ptr, PtrDiff))
12823             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12824         }
12825 }
12826 
12827 // We need to check that merging these stores does not cause a loop in
12828 // the DAG. Any store candidate may depend on another candidate
12829 // indirectly through its operand (we already consider dependencies
12830 // through the chain). Check in parallel by searching up from
12831 // non-chain operands of candidates.
12832 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12833     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12834   // FIXME: We should be able to truncate a full search of
12835   // predecessors by doing a BFS and keeping tabs the originating
12836   // stores from which worklist nodes come from in a similar way to
12837   // TokenFactor simplfication.
12838 
12839   SmallPtrSet<const SDNode *, 16> Visited;
12840   SmallVector<const SDNode *, 8> Worklist;
12841   unsigned int Max = 8192;
12842   // Search Ops of store candidates.
12843   for (unsigned i = 0; i < NumStores; ++i) {
12844     SDNode *n = StoreNodes[i].MemNode;
12845     // Potential loops may happen only through non-chain operands
12846     for (unsigned j = 1; j < n->getNumOperands(); ++j)
12847       Worklist.push_back(n->getOperand(j).getNode());
12848   }
12849   // Search through DAG. We can stop early if we find a store node.
12850   for (unsigned i = 0; i < NumStores; ++i) {
12851     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
12852                                      Max))
12853       return false;
12854     // Check if we ended early, failing conservatively if so.
12855     if (Visited.size() >= Max)
12856       return false;
12857   }
12858   return true;
12859 }
12860 
12861 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12862   if (OptLevel == CodeGenOpt::None)
12863     return false;
12864 
12865   EVT MemVT = St->getMemoryVT();
12866   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12867   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
12868 
12869   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12870     return false;
12871 
12872   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12873       Attribute::NoImplicitFloat);
12874 
12875   // This function cannot currently deal with non-byte-sized memory sizes.
12876   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12877     return false;
12878 
12879   if (!MemVT.isSimple())
12880     return false;
12881 
12882   // Perform an early exit check. Do not bother looking at stored values that
12883   // are not constants, loads, or extracted vector elements.
12884   SDValue StoredVal = peekThroughBitcast(St->getValue());
12885   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12886   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12887                        isa<ConstantFPSDNode>(StoredVal);
12888   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12889                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12890 
12891   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12892     return false;
12893 
12894   SmallVector<MemOpLink, 8> StoreNodes;
12895   // Find potential store merge candidates by searching through chain sub-DAG
12896   getStoreMergeCandidates(St, StoreNodes);
12897 
12898   // Check if there is anything to merge.
12899   if (StoreNodes.size() < 2)
12900     return false;
12901 
12902   // Sort the memory operands according to their distance from the
12903   // base pointer.
12904   std::sort(StoreNodes.begin(), StoreNodes.end(),
12905             [](MemOpLink LHS, MemOpLink RHS) {
12906               return LHS.OffsetFromBase < RHS.OffsetFromBase;
12907             });
12908 
12909   // Store Merge attempts to merge the lowest stores. This generally
12910   // works out as if successful, as the remaining stores are checked
12911   // after the first collection of stores is merged. However, in the
12912   // case that a non-mergeable store is found first, e.g., {p[-2],
12913   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12914   // mergeable cases. To prevent this, we prune such stores from the
12915   // front of StoreNodes here.
12916 
12917   bool RV = false;
12918   while (StoreNodes.size() > 1) {
12919     unsigned StartIdx = 0;
12920     while ((StartIdx + 1 < StoreNodes.size()) &&
12921            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12922                StoreNodes[StartIdx + 1].OffsetFromBase)
12923       ++StartIdx;
12924 
12925     // Bail if we don't have enough candidates to merge.
12926     if (StartIdx + 1 >= StoreNodes.size())
12927       return RV;
12928 
12929     if (StartIdx)
12930       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12931 
12932     // Scan the memory operations on the chain and find the first
12933     // non-consecutive store memory address.
12934     unsigned NumConsecutiveStores = 1;
12935     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12936     // Check that the addresses are consecutive starting from the second
12937     // element in the list of stores.
12938     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12939       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12940       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12941         break;
12942       NumConsecutiveStores = i + 1;
12943     }
12944 
12945     if (NumConsecutiveStores < 2) {
12946       StoreNodes.erase(StoreNodes.begin(),
12947                        StoreNodes.begin() + NumConsecutiveStores);
12948       continue;
12949     }
12950 
12951     // Check that we can merge these candidates without causing a cycle
12952     if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
12953                                                   NumConsecutiveStores)) {
12954       StoreNodes.erase(StoreNodes.begin(),
12955                        StoreNodes.begin() + NumConsecutiveStores);
12956       continue;
12957     }
12958 
12959     // The node with the lowest store address.
12960     LLVMContext &Context = *DAG.getContext();
12961     const DataLayout &DL = DAG.getDataLayout();
12962 
12963     // Store the constants into memory as one consecutive store.
12964     if (IsConstantSrc) {
12965       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12966       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12967       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12968       unsigned LastLegalType = 1;
12969       unsigned LastLegalVectorType = 1;
12970       bool LastIntegerTrunc = false;
12971       bool NonZero = false;
12972       unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
12973       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12974         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12975         SDValue StoredVal = ST->getValue();
12976         bool IsElementZero = false;
12977         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
12978           IsElementZero = C->isNullValue();
12979         else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
12980           IsElementZero = C->getConstantFPValue()->isNullValue();
12981         if (IsElementZero) {
12982           if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
12983             FirstZeroAfterNonZero = i;
12984         }
12985         NonZero |= !IsElementZero;
12986 
12987         // Find a legal type for the constant store.
12988         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12989         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12990         bool IsFast = false;
12991         if (TLI.isTypeLegal(StoreTy) &&
12992             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
12993             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12994                                    FirstStoreAlign, &IsFast) &&
12995             IsFast) {
12996           LastIntegerTrunc = false;
12997           LastLegalType = i + 1;
12998           // Or check whether a truncstore is legal.
12999         } else if (TLI.getTypeAction(Context, StoreTy) ==
13000                    TargetLowering::TypePromoteInteger) {
13001           EVT LegalizedStoredValueTy =
13002               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
13003           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13004               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13005               TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13006                                      FirstStoreAlign, &IsFast) &&
13007               IsFast) {
13008             LastIntegerTrunc = true;
13009             LastLegalType = i + 1;
13010           }
13011         }
13012 
13013         // We only use vectors if the constant is known to be zero or the target
13014         // allows it and the function is not marked with the noimplicitfloat
13015         // attribute.
13016         if ((!NonZero ||
13017              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
13018             !NoVectors) {
13019           // Find a legal type for the vector store.
13020           unsigned Elts = (i + 1) * NumMemElts;
13021           EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13022           if (TLI.isTypeLegal(Ty) &&
13023               TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13024               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13025                                      FirstStoreAlign, &IsFast) &&
13026               IsFast)
13027             LastLegalVectorType = i + 1;
13028         }
13029       }
13030 
13031       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
13032       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
13033 
13034       // Check if we found a legal integer type that creates a meaningful merge.
13035       if (NumElem < 2) {
13036         // We know that candidate stores are in order and of correct
13037         // shape. While there is no mergeable sequence from the
13038         // beginning one may start later in the sequence. The only
13039         // reason a merge of size N could have failed where another of
13040         // the same size would not have, is if the alignment has
13041         // improved or we've dropped a non-zero value. Drop as many
13042         // candidates as we can here.
13043         unsigned NumSkip = 1;
13044         while (
13045             (NumSkip < NumConsecutiveStores) &&
13046             (NumSkip < FirstZeroAfterNonZero) &&
13047             (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) {
13048           NumSkip++;
13049         }
13050         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13051         continue;
13052       }
13053 
13054       bool Merged = MergeStoresOfConstantsOrVecElts(
13055           StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
13056       RV |= Merged;
13057 
13058       // Remove merged stores for next iteration.
13059       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13060       continue;
13061     }
13062 
13063     // When extracting multiple vector elements, try to store them
13064     // in one vector store rather than a sequence of scalar stores.
13065     if (IsExtractVecSrc) {
13066       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13067       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13068       unsigned FirstStoreAlign = FirstInChain->getAlignment();
13069       unsigned NumStoresToMerge = 1;
13070       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13071         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13072         SDValue StVal = peekThroughBitcast(St->getValue());
13073         // This restriction could be loosened.
13074         // Bail out if any stored values are not elements extracted from a
13075         // vector. It should be possible to handle mixed sources, but load
13076         // sources need more careful handling (see the block of code below that
13077         // handles consecutive loads).
13078         if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13079             StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13080           return RV;
13081 
13082         // Find a legal type for the vector store.
13083         unsigned Elts = (i + 1) * NumMemElts;
13084         EVT Ty =
13085             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
13086         bool IsFast;
13087         if (TLI.isTypeLegal(Ty) &&
13088             TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13089             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13090                                    FirstStoreAlign, &IsFast) &&
13091             IsFast)
13092           NumStoresToMerge = i + 1;
13093       }
13094 
13095       // Check if we found a legal integer type that creates a meaningful merge.
13096       if (NumStoresToMerge < 2) {
13097         // We know that candidate stores are in order and of correct
13098         // shape. While there is no mergeable sequence from the
13099         // beginning one may start later in the sequence. The only
13100         // reason a merge of size N could have failed where another of
13101         // the same size would not have, is if the alignment has
13102         // improved. Drop as many candidates as we can here.
13103         unsigned NumSkip = 1;
13104         while ((NumSkip < NumConsecutiveStores) &&
13105                (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13106           NumSkip++;
13107 
13108         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13109         continue;
13110       }
13111 
13112       bool Merged = MergeStoresOfConstantsOrVecElts(
13113           StoreNodes, MemVT, NumStoresToMerge, false, true, false);
13114       if (!Merged) {
13115         StoreNodes.erase(StoreNodes.begin(),
13116                          StoreNodes.begin() + NumStoresToMerge);
13117         continue;
13118       }
13119       // Remove merged stores for next iteration.
13120       StoreNodes.erase(StoreNodes.begin(),
13121                        StoreNodes.begin() + NumStoresToMerge);
13122       RV = true;
13123       continue;
13124     }
13125 
13126     // Below we handle the case of multiple consecutive stores that
13127     // come from multiple consecutive loads. We merge them into a single
13128     // wide load and a single wide store.
13129 
13130     // Look for load nodes which are used by the stored values.
13131     SmallVector<MemOpLink, 8> LoadNodes;
13132 
13133     // Find acceptable loads. Loads need to have the same chain (token factor),
13134     // must not be zext, volatile, indexed, and they must be consecutive.
13135     BaseIndexOffset LdBasePtr;
13136     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13137       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13138       SDValue Val = peekThroughBitcast(St->getValue());
13139       LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val);
13140       if (!Ld)
13141         break;
13142 
13143       // Loads must only have one use.
13144       if (!Ld->hasNUsesOfValue(1, 0))
13145         break;
13146 
13147       // The memory operands must not be volatile.
13148       if (Ld->isVolatile() || Ld->isIndexed())
13149         break;
13150 
13151       // The stored memory type must be the same.
13152       if (Ld->getMemoryVT() != MemVT)
13153         break;
13154 
13155       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
13156       // If this is not the first ptr that we check.
13157       int64_t LdOffset = 0;
13158       if (LdBasePtr.getBase().getNode()) {
13159         // The base ptr must be the same.
13160         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
13161           break;
13162       } else {
13163         // Check that all other base pointers are the same as this one.
13164         LdBasePtr = LdPtr;
13165       }
13166 
13167       // We found a potential memory operand to merge.
13168       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
13169     }
13170 
13171     if (LoadNodes.size() < 2) {
13172       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13173       continue;
13174     }
13175 
13176     // If we have load/store pair instructions and we only have two values,
13177     // don't bother merging.
13178     unsigned RequiredAlignment;
13179     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
13180         StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
13181       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
13182       continue;
13183     }
13184     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13185     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13186     unsigned FirstStoreAlign = FirstInChain->getAlignment();
13187     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
13188     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
13189     unsigned FirstLoadAlign = FirstLoad->getAlignment();
13190 
13191     // Scan the memory operations on the chain and find the first
13192     // non-consecutive load memory address. These variables hold the index in
13193     // the store node array.
13194     unsigned LastConsecutiveLoad = 1;
13195     // This variable refers to the size and not index in the array.
13196     unsigned LastLegalVectorType = 1;
13197     unsigned LastLegalIntegerType = 1;
13198     bool isDereferenceable = true;
13199     bool DoIntegerTruncate = false;
13200     StartAddress = LoadNodes[0].OffsetFromBase;
13201     SDValue FirstChain = FirstLoad->getChain();
13202     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
13203       // All loads must share the same chain.
13204       if (LoadNodes[i].MemNode->getChain() != FirstChain)
13205         break;
13206 
13207       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
13208       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13209         break;
13210       LastConsecutiveLoad = i;
13211 
13212       if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
13213         isDereferenceable = false;
13214 
13215       // Find a legal type for the vector store.
13216       unsigned Elts = (i + 1) * NumMemElts;
13217       EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13218 
13219       bool IsFastSt, IsFastLd;
13220       if (TLI.isTypeLegal(StoreTy) &&
13221           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13222           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13223                                  FirstStoreAlign, &IsFastSt) &&
13224           IsFastSt &&
13225           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13226                                  FirstLoadAlign, &IsFastLd) &&
13227           IsFastLd) {
13228         LastLegalVectorType = i + 1;
13229       }
13230 
13231       // Find a legal type for the integer store.
13232       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13233       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13234       if (TLI.isTypeLegal(StoreTy) &&
13235           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13236           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13237                                  FirstStoreAlign, &IsFastSt) &&
13238           IsFastSt &&
13239           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13240                                  FirstLoadAlign, &IsFastLd) &&
13241           IsFastLd) {
13242         LastLegalIntegerType = i + 1;
13243         DoIntegerTruncate = false;
13244         // Or check whether a truncstore and extload is legal.
13245       } else if (TLI.getTypeAction(Context, StoreTy) ==
13246                  TargetLowering::TypePromoteInteger) {
13247         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
13248         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13249             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13250             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13251                                StoreTy) &&
13252             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13253                                StoreTy) &&
13254             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13255             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13256                                    FirstStoreAlign, &IsFastSt) &&
13257             IsFastSt &&
13258             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13259                                    FirstLoadAlign, &IsFastLd) &&
13260             IsFastLd) {
13261           LastLegalIntegerType = i + 1;
13262           DoIntegerTruncate = true;
13263         }
13264       }
13265     }
13266 
13267     // Only use vector types if the vector type is larger than the integer type.
13268     // If they are the same, use integers.
13269     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13270     unsigned LastLegalType =
13271         std::max(LastLegalVectorType, LastLegalIntegerType);
13272 
13273     // We add +1 here because the LastXXX variables refer to location while
13274     // the NumElem refers to array/index size.
13275     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13276     NumElem = std::min(LastLegalType, NumElem);
13277 
13278     if (NumElem < 2) {
13279       // We know that candidate stores are in order and of correct
13280       // shape. While there is no mergeable sequence from the
13281       // beginning one may start later in the sequence. The only
13282       // reason a merge of size N could have failed where another of
13283       // the same size would not have is if the alignment or either
13284       // the load or store has improved. Drop as many candidates as we
13285       // can here.
13286       unsigned NumSkip = 1;
13287       while ((NumSkip < LoadNodes.size()) &&
13288              (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
13289              (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13290         NumSkip++;
13291       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13292       continue;
13293     }
13294 
13295     // Find if it is better to use vectors or integers to load and store
13296     // to memory.
13297     EVT JointMemOpVT;
13298     if (UseVectorTy) {
13299       // Find a legal type for the vector store.
13300       unsigned Elts = NumElem * NumMemElts;
13301       JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13302     } else {
13303       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13304       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13305     }
13306 
13307     SDLoc LoadDL(LoadNodes[0].MemNode);
13308     SDLoc StoreDL(StoreNodes[0].MemNode);
13309 
13310     // The merged loads are required to have the same incoming chain, so
13311     // using the first's chain is acceptable.
13312 
13313     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13314     AddToWorklist(NewStoreChain.getNode());
13315 
13316     MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13317                                           MachineMemOperand::MODereferenceable:
13318                                           MachineMemOperand::MONone;
13319 
13320     SDValue NewLoad, NewStore;
13321     if (UseVectorTy || !DoIntegerTruncate) {
13322       NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13323                             FirstLoad->getBasePtr(),
13324                             FirstLoad->getPointerInfo(), FirstLoadAlign,
13325                             MMOFlags);
13326       NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13327                               FirstInChain->getBasePtr(),
13328                               FirstInChain->getPointerInfo(), FirstStoreAlign);
13329     } else { // This must be the truncstore/extload case
13330       EVT ExtendedTy =
13331           TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13332       NewLoad =
13333           DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13334                          FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13335                          JointMemOpVT, FirstLoadAlign, MMOFlags);
13336       NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13337                                    FirstInChain->getBasePtr(),
13338                                    FirstInChain->getPointerInfo(), JointMemOpVT,
13339                                    FirstInChain->getAlignment(),
13340                                    FirstInChain->getMemOperand()->getFlags());
13341     }
13342 
13343     // Transfer chain users from old loads to the new load.
13344     for (unsigned i = 0; i < NumElem; ++i) {
13345       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13346       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13347                                     SDValue(NewLoad.getNode(), 1));
13348     }
13349 
13350     // Replace the all stores with the new store. Recursively remove
13351     // corresponding value if its no longer used.
13352     for (unsigned i = 0; i < NumElem; ++i) {
13353       SDValue Val = StoreNodes[i].MemNode->getOperand(1);
13354       CombineTo(StoreNodes[i].MemNode, NewStore);
13355       if (Val.getNode()->use_empty())
13356         recursivelyDeleteUnusedNodes(Val.getNode());
13357     }
13358 
13359     RV = true;
13360     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13361   }
13362   return RV;
13363 }
13364 
13365 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13366   SDLoc SL(ST);
13367   SDValue ReplStore;
13368 
13369   // Replace the chain to avoid dependency.
13370   if (ST->isTruncatingStore()) {
13371     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13372                                   ST->getBasePtr(), ST->getMemoryVT(),
13373                                   ST->getMemOperand());
13374   } else {
13375     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13376                              ST->getMemOperand());
13377   }
13378 
13379   // Create token to keep both nodes around.
13380   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13381                               MVT::Other, ST->getChain(), ReplStore);
13382 
13383   // Make sure the new and old chains are cleaned up.
13384   AddToWorklist(Token.getNode());
13385 
13386   // Don't add users to work list.
13387   return CombineTo(ST, Token, false);
13388 }
13389 
13390 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13391   SDValue Value = ST->getValue();
13392   if (Value.getOpcode() == ISD::TargetConstantFP)
13393     return SDValue();
13394 
13395   SDLoc DL(ST);
13396 
13397   SDValue Chain = ST->getChain();
13398   SDValue Ptr = ST->getBasePtr();
13399 
13400   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13401 
13402   // NOTE: If the original store is volatile, this transform must not increase
13403   // the number of stores.  For example, on x86-32 an f64 can be stored in one
13404   // processor operation but an i64 (which is not legal) requires two.  So the
13405   // transform should not be done in this case.
13406 
13407   SDValue Tmp;
13408   switch (CFP->getSimpleValueType(0).SimpleTy) {
13409   default:
13410     llvm_unreachable("Unknown FP type");
13411   case MVT::f16:    // We don't do this for these yet.
13412   case MVT::f80:
13413   case MVT::f128:
13414   case MVT::ppcf128:
13415     return SDValue();
13416   case MVT::f32:
13417     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13418         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13419       ;
13420       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13421                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13422                             MVT::i32);
13423       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13424     }
13425 
13426     return SDValue();
13427   case MVT::f64:
13428     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13429          !ST->isVolatile()) ||
13430         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13431       ;
13432       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13433                             getZExtValue(), SDLoc(CFP), MVT::i64);
13434       return DAG.getStore(Chain, DL, Tmp,
13435                           Ptr, ST->getMemOperand());
13436     }
13437 
13438     if (!ST->isVolatile() &&
13439         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13440       // Many FP stores are not made apparent until after legalize, e.g. for
13441       // argument passing.  Since this is so common, custom legalize the
13442       // 64-bit integer store into two 32-bit stores.
13443       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13444       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13445       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13446       if (DAG.getDataLayout().isBigEndian())
13447         std::swap(Lo, Hi);
13448 
13449       unsigned Alignment = ST->getAlignment();
13450       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13451       AAMDNodes AAInfo = ST->getAAInfo();
13452 
13453       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13454                                  ST->getAlignment(), MMOFlags, AAInfo);
13455       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13456                         DAG.getConstant(4, DL, Ptr.getValueType()));
13457       Alignment = MinAlign(Alignment, 4U);
13458       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13459                                  ST->getPointerInfo().getWithOffset(4),
13460                                  Alignment, MMOFlags, AAInfo);
13461       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13462                          St0, St1);
13463     }
13464 
13465     return SDValue();
13466   }
13467 }
13468 
13469 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13470   StoreSDNode *ST  = cast<StoreSDNode>(N);
13471   SDValue Chain = ST->getChain();
13472   SDValue Value = ST->getValue();
13473   SDValue Ptr   = ST->getBasePtr();
13474 
13475   // If this is a store of a bit convert, store the input value if the
13476   // resultant store does not need a higher alignment than the original.
13477   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13478       ST->isUnindexed()) {
13479     EVT SVT = Value.getOperand(0).getValueType();
13480     if (((!LegalOperations && !ST->isVolatile()) ||
13481          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13482         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13483       unsigned OrigAlign = ST->getAlignment();
13484       bool Fast = false;
13485       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13486                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13487           Fast) {
13488         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13489                             ST->getPointerInfo(), OrigAlign,
13490                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13491       }
13492     }
13493   }
13494 
13495   // Turn 'store undef, Ptr' -> nothing.
13496   if (Value.isUndef() && ST->isUnindexed())
13497     return Chain;
13498 
13499   // Try to infer better alignment information than the store already has.
13500   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13501     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13502       if (Align > ST->getAlignment()) {
13503         SDValue NewStore =
13504             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13505                               ST->getMemoryVT(), Align,
13506                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13507         if (NewStore.getNode() != N)
13508           return CombineTo(ST, NewStore, true);
13509       }
13510     }
13511   }
13512 
13513   // Try transforming a pair floating point load / store ops to integer
13514   // load / store ops.
13515   if (SDValue NewST = TransformFPLoadStorePair(N))
13516     return NewST;
13517 
13518   if (ST->isUnindexed()) {
13519     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13520     // adjacent stores.
13521     if (findBetterNeighborChains(ST)) {
13522       // replaceStoreChain uses CombineTo, which handled all of the worklist
13523       // manipulation. Return the original node to not do anything else.
13524       return SDValue(ST, 0);
13525     }
13526     Chain = ST->getChain();
13527   }
13528 
13529   // FIXME: is there such a thing as a truncating indexed store?
13530   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13531       Value.getValueType().isInteger()) {
13532     // See if we can simplify the input to this truncstore with knowledge that
13533     // only the low bits are being used.  For example:
13534     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13535     SDValue Shorter = DAG.GetDemandedBits(
13536         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13537                                     ST->getMemoryVT().getScalarSizeInBits()));
13538     AddToWorklist(Value.getNode());
13539     if (Shorter.getNode())
13540       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13541                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13542 
13543     // Otherwise, see if we can simplify the operation with
13544     // SimplifyDemandedBits, which only works if the value has a single use.
13545     if (SimplifyDemandedBits(
13546             Value,
13547             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13548                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13549       // Re-visit the store if anything changed and the store hasn't been merged
13550       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13551       // node back to the worklist if necessary, but we also need to re-visit
13552       // the Store node itself.
13553       if (N->getOpcode() != ISD::DELETED_NODE)
13554         AddToWorklist(N);
13555       return SDValue(N, 0);
13556     }
13557   }
13558 
13559   // If this is a load followed by a store to the same location, then the store
13560   // is dead/noop.
13561   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13562     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13563         ST->isUnindexed() && !ST->isVolatile() &&
13564         // There can't be any side effects between the load and store, such as
13565         // a call or store.
13566         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13567       // The store is dead, remove it.
13568       return Chain;
13569     }
13570   }
13571 
13572   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13573     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13574         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13575         ST->getMemoryVT() == ST1->getMemoryVT()) {
13576       // If this is a store followed by a store with the same value to the same
13577       // location, then the store is dead/noop.
13578       if (ST1->getValue() == Value) {
13579         // The store is dead, remove it.
13580         return Chain;
13581       }
13582 
13583       // If this is a store who's preceeding store to the same location
13584       // and no one other node is chained to that store we can effectively
13585       // drop the store. Do not remove stores to undef as they may be used as
13586       // data sinks.
13587       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13588           !ST1->getBasePtr().isUndef()) {
13589         // ST1 is fully overwritten and can be elided. Combine with it's chain
13590         // value.
13591         CombineTo(ST1, ST1->getChain());
13592         return SDValue();
13593       }
13594     }
13595   }
13596 
13597   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13598   // truncating store.  We can do this even if this is already a truncstore.
13599   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13600       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13601       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13602                             ST->getMemoryVT())) {
13603     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13604                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13605   }
13606 
13607   // Always perform this optimization before types are legal. If the target
13608   // prefers, also try this after legalization to catch stores that were created
13609   // by intrinsics or other nodes.
13610   if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) {
13611     while (true) {
13612       // There can be multiple store sequences on the same chain.
13613       // Keep trying to merge store sequences until we are unable to do so
13614       // or until we merge the last store on the chain.
13615       bool Changed = MergeConsecutiveStores(ST);
13616       if (!Changed) break;
13617       // Return N as merge only uses CombineTo and no worklist clean
13618       // up is necessary.
13619       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13620         return SDValue(N, 0);
13621     }
13622   }
13623 
13624   // Try transforming N to an indexed store.
13625   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13626     return SDValue(N, 0);
13627 
13628   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13629   //
13630   // Make sure to do this only after attempting to merge stores in order to
13631   //  avoid changing the types of some subset of stores due to visit order,
13632   //  preventing their merging.
13633   if (isa<ConstantFPSDNode>(ST->getValue())) {
13634     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13635       return NewSt;
13636   }
13637 
13638   if (SDValue NewSt = splitMergedValStore(ST))
13639     return NewSt;
13640 
13641   return ReduceLoadOpStoreWidth(N);
13642 }
13643 
13644 /// For the instruction sequence of store below, F and I values
13645 /// are bundled together as an i64 value before being stored into memory.
13646 /// Sometimes it is more efficent to generate separate stores for F and I,
13647 /// which can remove the bitwise instructions or sink them to colder places.
13648 ///
13649 ///   (store (or (zext (bitcast F to i32) to i64),
13650 ///              (shl (zext I to i64), 32)), addr)  -->
13651 ///   (store F, addr) and (store I, addr+4)
13652 ///
13653 /// Similarly, splitting for other merged store can also be beneficial, like:
13654 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13655 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13656 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13657 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13658 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13659 ///
13660 /// We allow each target to determine specifically which kind of splitting is
13661 /// supported.
13662 ///
13663 /// The store patterns are commonly seen from the simple code snippet below
13664 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13665 ///   void goo(const std::pair<int, float> &);
13666 ///   hoo() {
13667 ///     ...
13668 ///     goo(std::make_pair(tmp, ftmp));
13669 ///     ...
13670 ///   }
13671 ///
13672 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13673   if (OptLevel == CodeGenOpt::None)
13674     return SDValue();
13675 
13676   SDValue Val = ST->getValue();
13677   SDLoc DL(ST);
13678 
13679   // Match OR operand.
13680   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13681     return SDValue();
13682 
13683   // Match SHL operand and get Lower and Higher parts of Val.
13684   SDValue Op1 = Val.getOperand(0);
13685   SDValue Op2 = Val.getOperand(1);
13686   SDValue Lo, Hi;
13687   if (Op1.getOpcode() != ISD::SHL) {
13688     std::swap(Op1, Op2);
13689     if (Op1.getOpcode() != ISD::SHL)
13690       return SDValue();
13691   }
13692   Lo = Op2;
13693   Hi = Op1.getOperand(0);
13694   if (!Op1.hasOneUse())
13695     return SDValue();
13696 
13697   // Match shift amount to HalfValBitSize.
13698   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13699   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13700   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13701     return SDValue();
13702 
13703   // Lo and Hi are zero-extended from int with size less equal than 32
13704   // to i64.
13705   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13706       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13707       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13708       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13709       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13710       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13711     return SDValue();
13712 
13713   // Use the EVT of low and high parts before bitcast as the input
13714   // of target query.
13715   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13716                   ? Lo.getOperand(0).getValueType()
13717                   : Lo.getValueType();
13718   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13719                    ? Hi.getOperand(0).getValueType()
13720                    : Hi.getValueType();
13721   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13722     return SDValue();
13723 
13724   // Start to split store.
13725   unsigned Alignment = ST->getAlignment();
13726   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13727   AAMDNodes AAInfo = ST->getAAInfo();
13728 
13729   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13730   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13731   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13732   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13733 
13734   SDValue Chain = ST->getChain();
13735   SDValue Ptr = ST->getBasePtr();
13736   // Lower value store.
13737   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13738                              ST->getAlignment(), MMOFlags, AAInfo);
13739   Ptr =
13740       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13741                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13742   // Higher value store.
13743   SDValue St1 =
13744       DAG.getStore(St0, DL, Hi, Ptr,
13745                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13746                    Alignment / 2, MMOFlags, AAInfo);
13747   return St1;
13748 }
13749 
13750 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13751   SDValue InVec = N->getOperand(0);
13752   SDValue InVal = N->getOperand(1);
13753   SDValue EltNo = N->getOperand(2);
13754   SDLoc DL(N);
13755 
13756   // If the inserted element is an UNDEF, just use the input vector.
13757   if (InVal.isUndef())
13758     return InVec;
13759 
13760   EVT VT = InVec.getValueType();
13761 
13762   // Remove redundant insertions:
13763   // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
13764   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
13765       InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
13766     return InVec;
13767 
13768   // Check that we know which element is being inserted
13769   if (!isa<ConstantSDNode>(EltNo))
13770     return SDValue();
13771   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13772 
13773   // Canonicalize insert_vector_elt dag nodes.
13774   // Example:
13775   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13776   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13777   //
13778   // Do this only if the child insert_vector node has one use; also
13779   // do this only if indices are both constants and Idx1 < Idx0.
13780   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13781       && isa<ConstantSDNode>(InVec.getOperand(2))) {
13782     unsigned OtherElt = InVec.getConstantOperandVal(2);
13783     if (Elt < OtherElt) {
13784       // Swap nodes.
13785       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13786                                   InVec.getOperand(0), InVal, EltNo);
13787       AddToWorklist(NewOp.getNode());
13788       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13789                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13790     }
13791   }
13792 
13793   // If we can't generate a legal BUILD_VECTOR, exit
13794   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13795     return SDValue();
13796 
13797   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13798   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
13799   // vector elements.
13800   SmallVector<SDValue, 8> Ops;
13801   // Do not combine these two vectors if the output vector will not replace
13802   // the input vector.
13803   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13804     Ops.append(InVec.getNode()->op_begin(),
13805                InVec.getNode()->op_end());
13806   } else if (InVec.isUndef()) {
13807     unsigned NElts = VT.getVectorNumElements();
13808     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13809   } else {
13810     return SDValue();
13811   }
13812 
13813   // Insert the element
13814   if (Elt < Ops.size()) {
13815     // All the operands of BUILD_VECTOR must have the same type;
13816     // we enforce that here.
13817     EVT OpVT = Ops[0].getValueType();
13818     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13819   }
13820 
13821   // Return the new vector
13822   return DAG.getBuildVector(VT, DL, Ops);
13823 }
13824 
13825 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13826     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13827   assert(!OriginalLoad->isVolatile());
13828 
13829   EVT ResultVT = EVE->getValueType(0);
13830   EVT VecEltVT = InVecVT.getVectorElementType();
13831   unsigned Align = OriginalLoad->getAlignment();
13832   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13833       VecEltVT.getTypeForEVT(*DAG.getContext()));
13834 
13835   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13836     return SDValue();
13837 
13838   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13839     ISD::NON_EXTLOAD : ISD::EXTLOAD;
13840   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13841     return SDValue();
13842 
13843   Align = NewAlign;
13844 
13845   SDValue NewPtr = OriginalLoad->getBasePtr();
13846   SDValue Offset;
13847   EVT PtrType = NewPtr.getValueType();
13848   MachinePointerInfo MPI;
13849   SDLoc DL(EVE);
13850   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13851     int Elt = ConstEltNo->getZExtValue();
13852     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13853     Offset = DAG.getConstant(PtrOff, DL, PtrType);
13854     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13855   } else {
13856     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13857     Offset = DAG.getNode(
13858         ISD::MUL, DL, PtrType, Offset,
13859         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13860     MPI = OriginalLoad->getPointerInfo();
13861   }
13862   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13863 
13864   // The replacement we need to do here is a little tricky: we need to
13865   // replace an extractelement of a load with a load.
13866   // Use ReplaceAllUsesOfValuesWith to do the replacement.
13867   // Note that this replacement assumes that the extractvalue is the only
13868   // use of the load; that's okay because we don't want to perform this
13869   // transformation in other cases anyway.
13870   SDValue Load;
13871   SDValue Chain;
13872   if (ResultVT.bitsGT(VecEltVT)) {
13873     // If the result type of vextract is wider than the load, then issue an
13874     // extending load instead.
13875     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13876                                                   VecEltVT)
13877                                    ? ISD::ZEXTLOAD
13878                                    : ISD::EXTLOAD;
13879     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13880                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13881                           Align, OriginalLoad->getMemOperand()->getFlags(),
13882                           OriginalLoad->getAAInfo());
13883     Chain = Load.getValue(1);
13884   } else {
13885     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13886                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13887                        OriginalLoad->getAAInfo());
13888     Chain = Load.getValue(1);
13889     if (ResultVT.bitsLT(VecEltVT))
13890       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13891     else
13892       Load = DAG.getBitcast(ResultVT, Load);
13893   }
13894   WorklistRemover DeadNodes(*this);
13895   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13896   SDValue To[] = { Load, Chain };
13897   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13898   // Since we're explicitly calling ReplaceAllUses, add the new node to the
13899   // worklist explicitly as well.
13900   AddToWorklist(Load.getNode());
13901   AddUsersToWorklist(Load.getNode()); // Add users too
13902   // Make sure to revisit this node to clean it up; it will usually be dead.
13903   AddToWorklist(EVE);
13904   ++OpsNarrowed;
13905   return SDValue(EVE, 0);
13906 }
13907 
13908 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13909   // (vextract (scalar_to_vector val, 0) -> val
13910   SDValue InVec = N->getOperand(0);
13911   EVT VT = InVec.getValueType();
13912   EVT NVT = N->getValueType(0);
13913 
13914   if (InVec.isUndef())
13915     return DAG.getUNDEF(NVT);
13916 
13917   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13918     // Check if the result type doesn't match the inserted element type. A
13919     // SCALAR_TO_VECTOR may truncate the inserted element and the
13920     // EXTRACT_VECTOR_ELT may widen the extracted vector.
13921     SDValue InOp = InVec.getOperand(0);
13922     if (InOp.getValueType() != NVT) {
13923       assert(InOp.getValueType().isInteger() && NVT.isInteger());
13924       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13925     }
13926     return InOp;
13927   }
13928 
13929   SDValue EltNo = N->getOperand(1);
13930   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13931 
13932   // extract_vector_elt (build_vector x, y), 1 -> y
13933   if (ConstEltNo &&
13934       InVec.getOpcode() == ISD::BUILD_VECTOR &&
13935       TLI.isTypeLegal(VT) &&
13936       (InVec.hasOneUse() ||
13937        TLI.aggressivelyPreferBuildVectorSources(VT))) {
13938     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13939     EVT InEltVT = Elt.getValueType();
13940 
13941     // Sometimes build_vector's scalar input types do not match result type.
13942     if (NVT == InEltVT)
13943       return Elt;
13944 
13945     // TODO: It may be useful to truncate if free if the build_vector implicitly
13946     // converts.
13947   }
13948 
13949   // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x)
13950   bool isLE = DAG.getDataLayout().isLittleEndian();
13951   unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1;
13952   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13953       ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) {
13954     SDValue BCSrc = InVec.getOperand(0);
13955     if (BCSrc.getValueType().isScalarInteger())
13956       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13957   }
13958 
13959   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13960   //
13961   // This only really matters if the index is non-constant since other combines
13962   // on the constant elements already work.
13963   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13964       EltNo == InVec.getOperand(2)) {
13965     SDValue Elt = InVec.getOperand(1);
13966     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13967   }
13968 
13969   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13970   // We only perform this optimization before the op legalization phase because
13971   // we may introduce new vector instructions which are not backed by TD
13972   // patterns. For example on AVX, extracting elements from a wide vector
13973   // without using extract_subvector. However, if we can find an underlying
13974   // scalar value, then we can always use that.
13975   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13976     int NumElem = VT.getVectorNumElements();
13977     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13978     // Find the new index to extract from.
13979     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13980 
13981     // Extracting an undef index is undef.
13982     if (OrigElt == -1)
13983       return DAG.getUNDEF(NVT);
13984 
13985     // Select the right vector half to extract from.
13986     SDValue SVInVec;
13987     if (OrigElt < NumElem) {
13988       SVInVec = InVec->getOperand(0);
13989     } else {
13990       SVInVec = InVec->getOperand(1);
13991       OrigElt -= NumElem;
13992     }
13993 
13994     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13995       SDValue InOp = SVInVec.getOperand(OrigElt);
13996       if (InOp.getValueType() != NVT) {
13997         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13998         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13999       }
14000 
14001       return InOp;
14002     }
14003 
14004     // FIXME: We should handle recursing on other vector shuffles and
14005     // scalar_to_vector here as well.
14006 
14007     if (!LegalOperations ||
14008         // FIXME: Should really be just isOperationLegalOrCustom.
14009         TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) ||
14010         TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) {
14011       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14012       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
14013                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
14014     }
14015   }
14016 
14017   bool BCNumEltsChanged = false;
14018   EVT ExtVT = VT.getVectorElementType();
14019   EVT LVT = ExtVT;
14020 
14021   // If the result of load has to be truncated, then it's not necessarily
14022   // profitable.
14023   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
14024     return SDValue();
14025 
14026   if (InVec.getOpcode() == ISD::BITCAST) {
14027     // Don't duplicate a load with other uses.
14028     if (!InVec.hasOneUse())
14029       return SDValue();
14030 
14031     EVT BCVT = InVec.getOperand(0).getValueType();
14032     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
14033       return SDValue();
14034     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
14035       BCNumEltsChanged = true;
14036     InVec = InVec.getOperand(0);
14037     ExtVT = BCVT.getVectorElementType();
14038   }
14039 
14040   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
14041   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
14042       ISD::isNormalLoad(InVec.getNode()) &&
14043       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
14044     SDValue Index = N->getOperand(1);
14045     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
14046       if (!OrigLoad->isVolatile()) {
14047         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
14048                                                              OrigLoad);
14049       }
14050     }
14051   }
14052 
14053   // Perform only after legalization to ensure build_vector / vector_shuffle
14054   // optimizations have already been done.
14055   if (!LegalOperations) return SDValue();
14056 
14057   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
14058   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
14059   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
14060 
14061   if (ConstEltNo) {
14062     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14063 
14064     LoadSDNode *LN0 = nullptr;
14065     const ShuffleVectorSDNode *SVN = nullptr;
14066     if (ISD::isNormalLoad(InVec.getNode())) {
14067       LN0 = cast<LoadSDNode>(InVec);
14068     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14069                InVec.getOperand(0).getValueType() == ExtVT &&
14070                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
14071       // Don't duplicate a load with other uses.
14072       if (!InVec.hasOneUse())
14073         return SDValue();
14074 
14075       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
14076     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
14077       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
14078       // =>
14079       // (load $addr+1*size)
14080 
14081       // Don't duplicate a load with other uses.
14082       if (!InVec.hasOneUse())
14083         return SDValue();
14084 
14085       // If the bit convert changed the number of elements, it is unsafe
14086       // to examine the mask.
14087       if (BCNumEltsChanged)
14088         return SDValue();
14089 
14090       // Select the input vector, guarding against out of range extract vector.
14091       unsigned NumElems = VT.getVectorNumElements();
14092       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
14093       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
14094 
14095       if (InVec.getOpcode() == ISD::BITCAST) {
14096         // Don't duplicate a load with other uses.
14097         if (!InVec.hasOneUse())
14098           return SDValue();
14099 
14100         InVec = InVec.getOperand(0);
14101       }
14102       if (ISD::isNormalLoad(InVec.getNode())) {
14103         LN0 = cast<LoadSDNode>(InVec);
14104         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
14105         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
14106       }
14107     }
14108 
14109     // Make sure we found a non-volatile load and the extractelement is
14110     // the only use.
14111     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
14112       return SDValue();
14113 
14114     // If Idx was -1 above, Elt is going to be -1, so just return undef.
14115     if (Elt == -1)
14116       return DAG.getUNDEF(LVT);
14117 
14118     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
14119   }
14120 
14121   return SDValue();
14122 }
14123 
14124 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
14125 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
14126   // We perform this optimization post type-legalization because
14127   // the type-legalizer often scalarizes integer-promoted vectors.
14128   // Performing this optimization before may create bit-casts which
14129   // will be type-legalized to complex code sequences.
14130   // We perform this optimization only before the operation legalizer because we
14131   // may introduce illegal operations.
14132   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
14133     return SDValue();
14134 
14135   unsigned NumInScalars = N->getNumOperands();
14136   SDLoc DL(N);
14137   EVT VT = N->getValueType(0);
14138 
14139   // Check to see if this is a BUILD_VECTOR of a bunch of values
14140   // which come from any_extend or zero_extend nodes. If so, we can create
14141   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
14142   // optimizations. We do not handle sign-extend because we can't fill the sign
14143   // using shuffles.
14144   EVT SourceType = MVT::Other;
14145   bool AllAnyExt = true;
14146 
14147   for (unsigned i = 0; i != NumInScalars; ++i) {
14148     SDValue In = N->getOperand(i);
14149     // Ignore undef inputs.
14150     if (In.isUndef()) continue;
14151 
14152     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
14153     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
14154 
14155     // Abort if the element is not an extension.
14156     if (!ZeroExt && !AnyExt) {
14157       SourceType = MVT::Other;
14158       break;
14159     }
14160 
14161     // The input is a ZeroExt or AnyExt. Check the original type.
14162     EVT InTy = In.getOperand(0).getValueType();
14163 
14164     // Check that all of the widened source types are the same.
14165     if (SourceType == MVT::Other)
14166       // First time.
14167       SourceType = InTy;
14168     else if (InTy != SourceType) {
14169       // Multiple income types. Abort.
14170       SourceType = MVT::Other;
14171       break;
14172     }
14173 
14174     // Check if all of the extends are ANY_EXTENDs.
14175     AllAnyExt &= AnyExt;
14176   }
14177 
14178   // In order to have valid types, all of the inputs must be extended from the
14179   // same source type and all of the inputs must be any or zero extend.
14180   // Scalar sizes must be a power of two.
14181   EVT OutScalarTy = VT.getScalarType();
14182   bool ValidTypes = SourceType != MVT::Other &&
14183                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
14184                  isPowerOf2_32(SourceType.getSizeInBits());
14185 
14186   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
14187   // turn into a single shuffle instruction.
14188   if (!ValidTypes)
14189     return SDValue();
14190 
14191   bool isLE = DAG.getDataLayout().isLittleEndian();
14192   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
14193   assert(ElemRatio > 1 && "Invalid element size ratio");
14194   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
14195                                DAG.getConstant(0, DL, SourceType);
14196 
14197   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
14198   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
14199 
14200   // Populate the new build_vector
14201   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14202     SDValue Cast = N->getOperand(i);
14203     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
14204             Cast.getOpcode() == ISD::ZERO_EXTEND ||
14205             Cast.isUndef()) && "Invalid cast opcode");
14206     SDValue In;
14207     if (Cast.isUndef())
14208       In = DAG.getUNDEF(SourceType);
14209     else
14210       In = Cast->getOperand(0);
14211     unsigned Index = isLE ? (i * ElemRatio) :
14212                             (i * ElemRatio + (ElemRatio - 1));
14213 
14214     assert(Index < Ops.size() && "Invalid index");
14215     Ops[Index] = In;
14216   }
14217 
14218   // The type of the new BUILD_VECTOR node.
14219   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
14220   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
14221          "Invalid vector size");
14222   // Check if the new vector type is legal.
14223   if (!isTypeLegal(VecVT)) return SDValue();
14224 
14225   // Make the new BUILD_VECTOR.
14226   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
14227 
14228   // The new BUILD_VECTOR node has the potential to be further optimized.
14229   AddToWorklist(BV.getNode());
14230   // Bitcast to the desired type.
14231   return DAG.getBitcast(VT, BV);
14232 }
14233 
14234 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
14235   EVT VT = N->getValueType(0);
14236 
14237   unsigned NumInScalars = N->getNumOperands();
14238   SDLoc DL(N);
14239 
14240   EVT SrcVT = MVT::Other;
14241   unsigned Opcode = ISD::DELETED_NODE;
14242   unsigned NumDefs = 0;
14243 
14244   for (unsigned i = 0; i != NumInScalars; ++i) {
14245     SDValue In = N->getOperand(i);
14246     unsigned Opc = In.getOpcode();
14247 
14248     if (Opc == ISD::UNDEF)
14249       continue;
14250 
14251     // If all scalar values are floats and converted from integers.
14252     if (Opcode == ISD::DELETED_NODE &&
14253         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
14254       Opcode = Opc;
14255     }
14256 
14257     if (Opc != Opcode)
14258       return SDValue();
14259 
14260     EVT InVT = In.getOperand(0).getValueType();
14261 
14262     // If all scalar values are typed differently, bail out. It's chosen to
14263     // simplify BUILD_VECTOR of integer types.
14264     if (SrcVT == MVT::Other)
14265       SrcVT = InVT;
14266     if (SrcVT != InVT)
14267       return SDValue();
14268     NumDefs++;
14269   }
14270 
14271   // If the vector has just one element defined, it's not worth to fold it into
14272   // a vectorized one.
14273   if (NumDefs < 2)
14274     return SDValue();
14275 
14276   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
14277          && "Should only handle conversion from integer to float.");
14278   assert(SrcVT != MVT::Other && "Cannot determine source type!");
14279 
14280   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14281 
14282   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14283     return SDValue();
14284 
14285   // Just because the floating-point vector type is legal does not necessarily
14286   // mean that the corresponding integer vector type is.
14287   if (!isTypeLegal(NVT))
14288     return SDValue();
14289 
14290   SmallVector<SDValue, 8> Opnds;
14291   for (unsigned i = 0; i != NumInScalars; ++i) {
14292     SDValue In = N->getOperand(i);
14293 
14294     if (In.isUndef())
14295       Opnds.push_back(DAG.getUNDEF(SrcVT));
14296     else
14297       Opnds.push_back(In.getOperand(0));
14298   }
14299   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14300   AddToWorklist(BV.getNode());
14301 
14302   return DAG.getNode(Opcode, DL, VT, BV);
14303 }
14304 
14305 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14306                                            ArrayRef<int> VectorMask,
14307                                            SDValue VecIn1, SDValue VecIn2,
14308                                            unsigned LeftIdx) {
14309   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14310   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14311 
14312   EVT VT = N->getValueType(0);
14313   EVT InVT1 = VecIn1.getValueType();
14314   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14315 
14316   unsigned Vec2Offset = 0;
14317   unsigned NumElems = VT.getVectorNumElements();
14318   unsigned ShuffleNumElems = NumElems;
14319 
14320   // In case both the input vectors are extracted from same base
14321   // vector we do not need extra addend (Vec2Offset) while
14322   // computing shuffle mask.
14323   if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14324       !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14325       !(VecIn1.getOperand(0) == VecIn2.getOperand(0)))
14326     Vec2Offset = InVT1.getVectorNumElements();
14327 
14328   // We can't generate a shuffle node with mismatched input and output types.
14329   // Try to make the types match the type of the output.
14330   if (InVT1 != VT || InVT2 != VT) {
14331     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14332       // If the output vector length is a multiple of both input lengths,
14333       // we can concatenate them and pad the rest with undefs.
14334       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14335       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
14336       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14337       ConcatOps[0] = VecIn1;
14338       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14339       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14340       VecIn2 = SDValue();
14341     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14342       if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
14343         return SDValue();
14344 
14345       if (!VecIn2.getNode()) {
14346         // If we only have one input vector, and it's twice the size of the
14347         // output, split it in two.
14348         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14349                              DAG.getConstant(NumElems, DL, IdxTy));
14350         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14351         // Since we now have shorter input vectors, adjust the offset of the
14352         // second vector's start.
14353         Vec2Offset = NumElems;
14354       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14355         // VecIn1 is wider than the output, and we have another, possibly
14356         // smaller input. Pad the smaller input with undefs, shuffle at the
14357         // input vector width, and extract the output.
14358         // The shuffle type is different than VT, so check legality again.
14359         if (LegalOperations &&
14360             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14361           return SDValue();
14362 
14363         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14364         // lower it back into a BUILD_VECTOR. So if the inserted type is
14365         // illegal, don't even try.
14366         if (InVT1 != InVT2) {
14367           if (!TLI.isTypeLegal(InVT2))
14368             return SDValue();
14369           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14370                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14371         }
14372         ShuffleNumElems = NumElems * 2;
14373       } else {
14374         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14375         // than VecIn1. We can't handle this for now - this case will disappear
14376         // when we start sorting the vectors by type.
14377         return SDValue();
14378       }
14379     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14380                InVT1.getSizeInBits() == VT.getSizeInBits()) {
14381       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14382       ConcatOps[0] = VecIn2;
14383       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14384     } else {
14385       // TODO: Support cases where the length mismatch isn't exactly by a
14386       // factor of 2.
14387       // TODO: Move this check upwards, so that if we have bad type
14388       // mismatches, we don't create any DAG nodes.
14389       return SDValue();
14390     }
14391   }
14392 
14393   // Initialize mask to undef.
14394   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14395 
14396   // Only need to run up to the number of elements actually used, not the
14397   // total number of elements in the shuffle - if we are shuffling a wider
14398   // vector, the high lanes should be set to undef.
14399   for (unsigned i = 0; i != NumElems; ++i) {
14400     if (VectorMask[i] <= 0)
14401       continue;
14402 
14403     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14404     if (VectorMask[i] == (int)LeftIdx) {
14405       Mask[i] = ExtIndex;
14406     } else if (VectorMask[i] == (int)LeftIdx + 1) {
14407       Mask[i] = Vec2Offset + ExtIndex;
14408     }
14409   }
14410 
14411   // The type the input vectors may have changed above.
14412   InVT1 = VecIn1.getValueType();
14413 
14414   // If we already have a VecIn2, it should have the same type as VecIn1.
14415   // If we don't, get an undef/zero vector of the appropriate type.
14416   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14417   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14418 
14419   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14420   if (ShuffleNumElems > NumElems)
14421     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14422 
14423   return Shuffle;
14424 }
14425 
14426 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14427 // operations. If the types of the vectors we're extracting from allow it,
14428 // turn this into a vector_shuffle node.
14429 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14430   SDLoc DL(N);
14431   EVT VT = N->getValueType(0);
14432 
14433   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14434   if (!isTypeLegal(VT))
14435     return SDValue();
14436 
14437   // May only combine to shuffle after legalize if shuffle is legal.
14438   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14439     return SDValue();
14440 
14441   bool UsesZeroVector = false;
14442   unsigned NumElems = N->getNumOperands();
14443 
14444   // Record, for each element of the newly built vector, which input vector
14445   // that element comes from. -1 stands for undef, 0 for the zero vector,
14446   // and positive values for the input vectors.
14447   // VectorMask maps each element to its vector number, and VecIn maps vector
14448   // numbers to their initial SDValues.
14449 
14450   SmallVector<int, 8> VectorMask(NumElems, -1);
14451   SmallVector<SDValue, 8> VecIn;
14452   VecIn.push_back(SDValue());
14453 
14454   for (unsigned i = 0; i != NumElems; ++i) {
14455     SDValue Op = N->getOperand(i);
14456 
14457     if (Op.isUndef())
14458       continue;
14459 
14460     // See if we can use a blend with a zero vector.
14461     // TODO: Should we generalize this to a blend with an arbitrary constant
14462     // vector?
14463     if (isNullConstant(Op) || isNullFPConstant(Op)) {
14464       UsesZeroVector = true;
14465       VectorMask[i] = 0;
14466       continue;
14467     }
14468 
14469     // Not an undef or zero. If the input is something other than an
14470     // EXTRACT_VECTOR_ELT with a constant index, bail out.
14471     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14472         !isa<ConstantSDNode>(Op.getOperand(1)))
14473       return SDValue();
14474     SDValue ExtractedFromVec = Op.getOperand(0);
14475 
14476     // All inputs must have the same element type as the output.
14477     if (VT.getVectorElementType() !=
14478         ExtractedFromVec.getValueType().getVectorElementType())
14479       return SDValue();
14480 
14481     // Have we seen this input vector before?
14482     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14483     // a map back from SDValues to numbers isn't worth it.
14484     unsigned Idx = std::distance(
14485         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14486     if (Idx == VecIn.size())
14487       VecIn.push_back(ExtractedFromVec);
14488 
14489     VectorMask[i] = Idx;
14490   }
14491 
14492   // If we didn't find at least one input vector, bail out.
14493   if (VecIn.size() < 2)
14494     return SDValue();
14495 
14496   // If all the Operands of BUILD_VECTOR extract from same
14497   // vector, then split the vector efficiently based on the maximum
14498   // vector access index and adjust the VectorMask and
14499   // VecIn accordingly.
14500   if (VecIn.size() == 2) {
14501     unsigned MaxIndex = 0;
14502     unsigned NearestPow2 = 0;
14503     SDValue Vec = VecIn.back();
14504     EVT InVT = Vec.getValueType();
14505     MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14506     SmallVector<unsigned, 8> IndexVec(NumElems, 0);
14507 
14508     for (unsigned i = 0; i < NumElems; i++) {
14509       if (VectorMask[i] <= 0)
14510         continue;
14511       unsigned Index = N->getOperand(i).getConstantOperandVal(1);
14512       IndexVec[i] = Index;
14513       MaxIndex = std::max(MaxIndex, Index);
14514     }
14515 
14516     NearestPow2 = PowerOf2Ceil(MaxIndex);
14517     if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
14518         NumElems * 2 < NearestPow2) {
14519       unsigned SplitSize = NearestPow2 / 2;
14520       EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
14521                                      InVT.getVectorElementType(), SplitSize);
14522       if (TLI.isTypeLegal(SplitVT)) {
14523         SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14524                                      DAG.getConstant(SplitSize, DL, IdxTy));
14525         SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14526                                      DAG.getConstant(0, DL, IdxTy));
14527         VecIn.pop_back();
14528         VecIn.push_back(VecIn1);
14529         VecIn.push_back(VecIn2);
14530 
14531         for (unsigned i = 0; i < NumElems; i++) {
14532           if (VectorMask[i] <= 0)
14533             continue;
14534           VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
14535         }
14536       }
14537     }
14538   }
14539 
14540   // TODO: We want to sort the vectors by descending length, so that adjacent
14541   // pairs have similar length, and the longer vector is always first in the
14542   // pair.
14543 
14544   // TODO: Should this fire if some of the input vectors has illegal type (like
14545   // it does now), or should we let legalization run its course first?
14546 
14547   // Shuffle phase:
14548   // Take pairs of vectors, and shuffle them so that the result has elements
14549   // from these vectors in the correct places.
14550   // For example, given:
14551   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14552   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14553   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14554   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14555   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14556   // We will generate:
14557   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14558   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14559   SmallVector<SDValue, 4> Shuffles;
14560   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14561     unsigned LeftIdx = 2 * In + 1;
14562     SDValue VecLeft = VecIn[LeftIdx];
14563     SDValue VecRight =
14564         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14565 
14566     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14567                                                 VecRight, LeftIdx))
14568       Shuffles.push_back(Shuffle);
14569     else
14570       return SDValue();
14571   }
14572 
14573   // If we need the zero vector as an "ingredient" in the blend tree, add it
14574   // to the list of shuffles.
14575   if (UsesZeroVector)
14576     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14577                                       : DAG.getConstantFP(0.0, DL, VT));
14578 
14579   // If we only have one shuffle, we're done.
14580   if (Shuffles.size() == 1)
14581     return Shuffles[0];
14582 
14583   // Update the vector mask to point to the post-shuffle vectors.
14584   for (int &Vec : VectorMask)
14585     if (Vec == 0)
14586       Vec = Shuffles.size() - 1;
14587     else
14588       Vec = (Vec - 1) / 2;
14589 
14590   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14591   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14592   // generate:
14593   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14594   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14595   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14596   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14597   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14598   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14599   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14600 
14601   // Make sure the initial size of the shuffle list is even.
14602   if (Shuffles.size() % 2)
14603     Shuffles.push_back(DAG.getUNDEF(VT));
14604 
14605   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14606     if (CurSize % 2) {
14607       Shuffles[CurSize] = DAG.getUNDEF(VT);
14608       CurSize++;
14609     }
14610     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14611       int Left = 2 * In;
14612       int Right = 2 * In + 1;
14613       SmallVector<int, 8> Mask(NumElems, -1);
14614       for (unsigned i = 0; i != NumElems; ++i) {
14615         if (VectorMask[i] == Left) {
14616           Mask[i] = i;
14617           VectorMask[i] = In;
14618         } else if (VectorMask[i] == Right) {
14619           Mask[i] = i + NumElems;
14620           VectorMask[i] = In;
14621         }
14622       }
14623 
14624       Shuffles[In] =
14625           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14626     }
14627   }
14628   return Shuffles[0];
14629 }
14630 
14631 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14632 // operations which can be matched to a truncate or to a shuffle-truncate.
14633 SDValue DAGCombiner::reduceBuildVecToTrunc(SDNode *N) {
14634   // TODO: Add support for big-endian.
14635   if (DAG.getDataLayout().isBigEndian())
14636     return SDValue();
14637   if (N->getNumOperands() < 2)
14638     return SDValue();
14639   SDLoc DL(N);
14640   EVT VT = N->getValueType(0);
14641   unsigned NumElems = N->getNumOperands();
14642 
14643   if (!isTypeLegal(VT))
14644     return SDValue();
14645 
14646   // If the input is something other than an EXTRACT_VECTOR_ELT with a constant
14647   // index, bail out.
14648   // TODO: Allow undef elements in some cases?
14649   if (llvm::any_of(N->ops(), [VT](SDValue Op) {
14650         return Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14651                !isa<ConstantSDNode>(Op.getOperand(1)) ||
14652                Op.getValueType() != VT.getVectorElementType();
14653       }))
14654     return SDValue();
14655 
14656   // Helper for obtaining an EXTRACT_VECTOR_ELT's constant index
14657   auto GetExtractIdx = [](SDValue Extract) {
14658     return cast<ConstantSDNode>(Extract.getOperand(1))->getSExtValue();
14659   };
14660 
14661   // The offset is defined to be the BUILD_VECTOR's first operand (assuming no
14662   // undef and little-endian).
14663   int Offset = GetExtractIdx(N->getOperand(0));
14664 
14665   // Compute the stride from the next operand.
14666   int Stride = GetExtractIdx(N->getOperand(1)) - Offset;
14667   SDValue ExtractedFromVec = N->getOperand(0).getOperand(0);
14668 
14669   // Proceed only if the stride and the types can be matched to a truncate.
14670   if ((Stride == 1 || !isPowerOf2_32(Stride)) ||
14671       (ExtractedFromVec.getValueType().getVectorNumElements() !=
14672        Stride * NumElems) ||
14673       (VT.getScalarSizeInBits() * Stride > 64))
14674     return SDValue();
14675 
14676   // Check remaining operands are consistent with the computed stride.
14677   for (unsigned i = 1; i != NumElems; ++i) {
14678     SDValue Op = N->getOperand(i);
14679 
14680     if ((Op.getOperand(0) != ExtractedFromVec) ||
14681         (GetExtractIdx(Op) != Stride * i + Offset))
14682       return SDValue();
14683   }
14684 
14685   SDValue Res = ExtractedFromVec;
14686   EVT TruncVT =
14687       VT.isFloatingPoint() ? VT.changeVectorElementTypeToInteger() : VT;
14688   if (Offset) {
14689     // If the first index is non-zero, need to shuffle elements of interest to
14690     // lower parts of the vector's elements the truncate will act upon.
14691     // TODO: Generalize to compute the permute-shuffle that will prepare any
14692     // element permutation for the truncate, and let the target decide if
14693     // profitable.
14694     EVT ExtractedVT = ExtractedFromVec.getValueType();
14695     SmallVector<int, 64> Mask;
14696     for (unsigned i = 0; i != NumElems; ++i) {
14697       Mask.push_back(Offset + i * Stride);
14698       // Pad the elements that will be lost after the truncate with undefs.
14699       Mask.append(Stride - 1, -1);
14700     }
14701     if (!TLI.isShuffleMaskLegal(Mask, ExtractedVT) ||
14702         !TLI.isDesirableToCombineBuildVectorToShuffleTruncate(Mask, ExtractedVT,
14703                                                               TruncVT))
14704       return SDValue();
14705     Res = DAG.getVectorShuffle(ExtractedVT, SDLoc(N), Res,
14706                                DAG.getUNDEF(ExtractedVT), Mask);
14707   }
14708   // Construct the truncate.
14709   LLVMContext &Ctx = *DAG.getContext();
14710   EVT NewVT = VT.getVectorVT(
14711       Ctx, EVT::getIntegerVT(Ctx, VT.getScalarSizeInBits() * Stride), NumElems);
14712 
14713   Res = DAG.getBitcast(NewVT, Res);
14714   Res = DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, Res);
14715   return DAG.getBitcast(VT, Res);
14716 }
14717 
14718 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14719   EVT VT = N->getValueType(0);
14720 
14721   // A vector built entirely of undefs is undef.
14722   if (ISD::allOperandsUndef(N))
14723     return DAG.getUNDEF(VT);
14724 
14725   // Check if we can express BUILD VECTOR via subvector extract.
14726   if (!LegalTypes && (N->getNumOperands() > 1)) {
14727     SDValue Op0 = N->getOperand(0);
14728     auto checkElem = [&](SDValue Op) -> uint64_t {
14729       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14730           (Op0.getOperand(0) == Op.getOperand(0)))
14731         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14732           return CNode->getZExtValue();
14733       return -1;
14734     };
14735 
14736     int Offset = checkElem(Op0);
14737     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14738       if (Offset + i != checkElem(N->getOperand(i))) {
14739         Offset = -1;
14740         break;
14741       }
14742     }
14743 
14744     if ((Offset == 0) &&
14745         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14746       return Op0.getOperand(0);
14747     if ((Offset != -1) &&
14748         ((Offset % N->getValueType(0).getVectorNumElements()) ==
14749          0)) // IDX must be multiple of output size.
14750       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14751                          Op0.getOperand(0), Op0.getOperand(1));
14752   }
14753 
14754   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14755     return V;
14756 
14757   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14758     return V;
14759 
14760   if (TLI.isDesirableToCombineBuildVectorToTruncate())
14761     if (SDValue V = reduceBuildVecToTrunc(N))
14762       return V;
14763 
14764   if (SDValue V = reduceBuildVecToShuffle(N))
14765     return V;
14766 
14767   return SDValue();
14768 }
14769 
14770 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14771   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14772   EVT OpVT = N->getOperand(0).getValueType();
14773 
14774   // If the operands are legal vectors, leave them alone.
14775   if (TLI.isTypeLegal(OpVT))
14776     return SDValue();
14777 
14778   SDLoc DL(N);
14779   EVT VT = N->getValueType(0);
14780   SmallVector<SDValue, 8> Ops;
14781 
14782   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14783   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14784 
14785   // Keep track of what we encounter.
14786   bool AnyInteger = false;
14787   bool AnyFP = false;
14788   for (const SDValue &Op : N->ops()) {
14789     if (ISD::BITCAST == Op.getOpcode() &&
14790         !Op.getOperand(0).getValueType().isVector())
14791       Ops.push_back(Op.getOperand(0));
14792     else if (ISD::UNDEF == Op.getOpcode())
14793       Ops.push_back(ScalarUndef);
14794     else
14795       return SDValue();
14796 
14797     // Note whether we encounter an integer or floating point scalar.
14798     // If it's neither, bail out, it could be something weird like x86mmx.
14799     EVT LastOpVT = Ops.back().getValueType();
14800     if (LastOpVT.isFloatingPoint())
14801       AnyFP = true;
14802     else if (LastOpVT.isInteger())
14803       AnyInteger = true;
14804     else
14805       return SDValue();
14806   }
14807 
14808   // If any of the operands is a floating point scalar bitcast to a vector,
14809   // use floating point types throughout, and bitcast everything.
14810   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14811   if (AnyFP) {
14812     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14813     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14814     if (AnyInteger) {
14815       for (SDValue &Op : Ops) {
14816         if (Op.getValueType() == SVT)
14817           continue;
14818         if (Op.isUndef())
14819           Op = ScalarUndef;
14820         else
14821           Op = DAG.getBitcast(SVT, Op);
14822       }
14823     }
14824   }
14825 
14826   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14827                                VT.getSizeInBits() / SVT.getSizeInBits());
14828   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14829 }
14830 
14831 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14832 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14833 // most two distinct vectors the same size as the result, attempt to turn this
14834 // into a legal shuffle.
14835 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14836   EVT VT = N->getValueType(0);
14837   EVT OpVT = N->getOperand(0).getValueType();
14838   int NumElts = VT.getVectorNumElements();
14839   int NumOpElts = OpVT.getVectorNumElements();
14840 
14841   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14842   SmallVector<int, 8> Mask;
14843 
14844   for (SDValue Op : N->ops()) {
14845     // Peek through any bitcast.
14846     Op = peekThroughBitcast(Op);
14847 
14848     // UNDEF nodes convert to UNDEF shuffle mask values.
14849     if (Op.isUndef()) {
14850       Mask.append((unsigned)NumOpElts, -1);
14851       continue;
14852     }
14853 
14854     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14855       return SDValue();
14856 
14857     // What vector are we extracting the subvector from and at what index?
14858     SDValue ExtVec = Op.getOperand(0);
14859 
14860     // We want the EVT of the original extraction to correctly scale the
14861     // extraction index.
14862     EVT ExtVT = ExtVec.getValueType();
14863 
14864     // Peek through any bitcast.
14865     ExtVec = peekThroughBitcast(ExtVec);
14866 
14867     // UNDEF nodes convert to UNDEF shuffle mask values.
14868     if (ExtVec.isUndef()) {
14869       Mask.append((unsigned)NumOpElts, -1);
14870       continue;
14871     }
14872 
14873     if (!isa<ConstantSDNode>(Op.getOperand(1)))
14874       return SDValue();
14875     int ExtIdx = Op.getConstantOperandVal(1);
14876 
14877     // Ensure that we are extracting a subvector from a vector the same
14878     // size as the result.
14879     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14880       return SDValue();
14881 
14882     // Scale the subvector index to account for any bitcast.
14883     int NumExtElts = ExtVT.getVectorNumElements();
14884     if (0 == (NumExtElts % NumElts))
14885       ExtIdx /= (NumExtElts / NumElts);
14886     else if (0 == (NumElts % NumExtElts))
14887       ExtIdx *= (NumElts / NumExtElts);
14888     else
14889       return SDValue();
14890 
14891     // At most we can reference 2 inputs in the final shuffle.
14892     if (SV0.isUndef() || SV0 == ExtVec) {
14893       SV0 = ExtVec;
14894       for (int i = 0; i != NumOpElts; ++i)
14895         Mask.push_back(i + ExtIdx);
14896     } else if (SV1.isUndef() || SV1 == ExtVec) {
14897       SV1 = ExtVec;
14898       for (int i = 0; i != NumOpElts; ++i)
14899         Mask.push_back(i + ExtIdx + NumElts);
14900     } else {
14901       return SDValue();
14902     }
14903   }
14904 
14905   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14906     return SDValue();
14907 
14908   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14909                               DAG.getBitcast(VT, SV1), Mask);
14910 }
14911 
14912 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14913   // If we only have one input vector, we don't need to do any concatenation.
14914   if (N->getNumOperands() == 1)
14915     return N->getOperand(0);
14916 
14917   // Check if all of the operands are undefs.
14918   EVT VT = N->getValueType(0);
14919   if (ISD::allOperandsUndef(N))
14920     return DAG.getUNDEF(VT);
14921 
14922   // Optimize concat_vectors where all but the first of the vectors are undef.
14923   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14924         return Op.isUndef();
14925       })) {
14926     SDValue In = N->getOperand(0);
14927     assert(In.getValueType().isVector() && "Must concat vectors");
14928 
14929     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14930     if (In->getOpcode() == ISD::BITCAST &&
14931         !In->getOperand(0)->getValueType(0).isVector()) {
14932       SDValue Scalar = In->getOperand(0);
14933 
14934       // If the bitcast type isn't legal, it might be a trunc of a legal type;
14935       // look through the trunc so we can still do the transform:
14936       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14937       if (Scalar->getOpcode() == ISD::TRUNCATE &&
14938           !TLI.isTypeLegal(Scalar.getValueType()) &&
14939           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14940         Scalar = Scalar->getOperand(0);
14941 
14942       EVT SclTy = Scalar->getValueType(0);
14943 
14944       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14945         return SDValue();
14946 
14947       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14948       if (VNTNumElms < 2)
14949         return SDValue();
14950 
14951       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14952       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14953         return SDValue();
14954 
14955       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14956       return DAG.getBitcast(VT, Res);
14957     }
14958   }
14959 
14960   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14961   // We have already tested above for an UNDEF only concatenation.
14962   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14963   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14964   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14965     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14966   };
14967   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14968     SmallVector<SDValue, 8> Opnds;
14969     EVT SVT = VT.getScalarType();
14970 
14971     EVT MinVT = SVT;
14972     if (!SVT.isFloatingPoint()) {
14973       // If BUILD_VECTOR are from built from integer, they may have different
14974       // operand types. Get the smallest type and truncate all operands to it.
14975       bool FoundMinVT = false;
14976       for (const SDValue &Op : N->ops())
14977         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14978           EVT OpSVT = Op.getOperand(0)->getValueType(0);
14979           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14980           FoundMinVT = true;
14981         }
14982       assert(FoundMinVT && "Concat vector type mismatch");
14983     }
14984 
14985     for (const SDValue &Op : N->ops()) {
14986       EVT OpVT = Op.getValueType();
14987       unsigned NumElts = OpVT.getVectorNumElements();
14988 
14989       if (ISD::UNDEF == Op.getOpcode())
14990         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14991 
14992       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14993         if (SVT.isFloatingPoint()) {
14994           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14995           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14996         } else {
14997           for (unsigned i = 0; i != NumElts; ++i)
14998             Opnds.push_back(
14999                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
15000         }
15001       }
15002     }
15003 
15004     assert(VT.getVectorNumElements() == Opnds.size() &&
15005            "Concat vector type mismatch");
15006     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
15007   }
15008 
15009   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
15010   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
15011     return V;
15012 
15013   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
15014   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15015     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
15016       return V;
15017 
15018   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
15019   // nodes often generate nop CONCAT_VECTOR nodes.
15020   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
15021   // place the incoming vectors at the exact same location.
15022   SDValue SingleSource = SDValue();
15023   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
15024 
15025   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15026     SDValue Op = N->getOperand(i);
15027 
15028     if (Op.isUndef())
15029       continue;
15030 
15031     // Check if this is the identity extract:
15032     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15033       return SDValue();
15034 
15035     // Find the single incoming vector for the extract_subvector.
15036     if (SingleSource.getNode()) {
15037       if (Op.getOperand(0) != SingleSource)
15038         return SDValue();
15039     } else {
15040       SingleSource = Op.getOperand(0);
15041 
15042       // Check the source type is the same as the type of the result.
15043       // If not, this concat may extend the vector, so we can not
15044       // optimize it away.
15045       if (SingleSource.getValueType() != N->getValueType(0))
15046         return SDValue();
15047     }
15048 
15049     unsigned IdentityIndex = i * PartNumElem;
15050     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15051     // The extract index must be constant.
15052     if (!CS)
15053       return SDValue();
15054 
15055     // Check that we are reading from the identity index.
15056     if (CS->getZExtValue() != IdentityIndex)
15057       return SDValue();
15058   }
15059 
15060   if (SingleSource.getNode())
15061     return SingleSource;
15062 
15063   return SDValue();
15064 }
15065 
15066 /// If we are extracting a subvector produced by a wide binary operator with at
15067 /// at least one operand that was the result of a vector concatenation, then try
15068 /// to use the narrow vector operands directly to avoid the concatenation and
15069 /// extraction.
15070 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
15071   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
15072   // some of these bailouts with other transforms.
15073 
15074   // The extract index must be a constant, so we can map it to a concat operand.
15075   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15076   if (!ExtractIndex)
15077     return SDValue();
15078 
15079   // Only handle the case where we are doubling and then halving. A larger ratio
15080   // may require more than two narrow binops to replace the wide binop.
15081   EVT VT = Extract->getValueType(0);
15082   unsigned NumElems = VT.getVectorNumElements();
15083   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
15084          "Extract index is not a multiple of the vector length.");
15085   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
15086     return SDValue();
15087 
15088   // We are looking for an optionally bitcasted wide vector binary operator
15089   // feeding an extract subvector.
15090   SDValue BinOp = peekThroughBitcast(Extract->getOperand(0));
15091 
15092   // TODO: The motivating case for this transform is an x86 AVX1 target. That
15093   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
15094   // flavors, but no other 256-bit integer support. This could be extended to
15095   // handle any binop, but that may require fixing/adding other folds to avoid
15096   // codegen regressions.
15097   unsigned BOpcode = BinOp.getOpcode();
15098   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
15099     return SDValue();
15100 
15101   // The binop must be a vector type, so we can chop it in half.
15102   EVT WideBVT = BinOp.getValueType();
15103   if (!WideBVT.isVector())
15104     return SDValue();
15105 
15106   // Bail out if the target does not support a narrower version of the binop.
15107   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
15108                                    WideBVT.getVectorNumElements() / 2);
15109   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15110   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
15111     return SDValue();
15112 
15113   // Peek through bitcasts of the binary operator operands if needed.
15114   SDValue LHS = peekThroughBitcast(BinOp.getOperand(0));
15115   SDValue RHS = peekThroughBitcast(BinOp.getOperand(1));
15116 
15117   // We need at least one concatenation operation of a binop operand to make
15118   // this transform worthwhile. The concat must double the input vector sizes.
15119   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
15120   bool ConcatL =
15121       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
15122   bool ConcatR =
15123       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
15124   if (!ConcatL && !ConcatR)
15125     return SDValue();
15126 
15127   // If one of the binop operands was not the result of a concat, we must
15128   // extract a half-sized operand for our new narrow binop. We can't just reuse
15129   // the original extract index operand because we may have bitcasted.
15130   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
15131   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
15132   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
15133   SDLoc DL(Extract);
15134 
15135   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
15136   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
15137   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
15138   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
15139                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15140                                     BinOp.getOperand(0),
15141                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15142 
15143   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
15144                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15145                                     BinOp.getOperand(1),
15146                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15147 
15148   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
15149   return DAG.getBitcast(VT, NarrowBinOp);
15150 }
15151 
15152 /// If we are extracting a subvector from a wide vector load, convert to a
15153 /// narrow load to eliminate the extraction:
15154 /// (extract_subvector (load wide vector)) --> (load narrow vector)
15155 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
15156   // TODO: Add support for big-endian. The offset calculation must be adjusted.
15157   if (DAG.getDataLayout().isBigEndian())
15158     return SDValue();
15159 
15160   // TODO: The one-use check is overly conservative. Check the cost of the
15161   // extract instead or remove that condition entirely.
15162   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
15163   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15164   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
15165       !ExtIdx)
15166     return SDValue();
15167 
15168   // The narrow load will be offset from the base address of the old load if
15169   // we are extracting from something besides index 0 (little-endian).
15170   EVT VT = Extract->getValueType(0);
15171   SDLoc DL(Extract);
15172   SDValue BaseAddr = Ld->getOperand(1);
15173   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
15174 
15175   // TODO: Use "BaseIndexOffset" to make this more effective.
15176   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
15177   MachineFunction &MF = DAG.getMachineFunction();
15178   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
15179                                                    VT.getStoreSize());
15180   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
15181   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
15182   return NewLd;
15183 }
15184 
15185 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
15186   EVT NVT = N->getValueType(0);
15187   SDValue V = N->getOperand(0);
15188 
15189   // Extract from UNDEF is UNDEF.
15190   if (V.isUndef())
15191     return DAG.getUNDEF(NVT);
15192 
15193   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
15194     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
15195       return NarrowLoad;
15196 
15197   // Combine:
15198   //    (extract_subvec (concat V1, V2, ...), i)
15199   // Into:
15200   //    Vi if possible
15201   // Only operand 0 is checked as 'concat' assumes all inputs of the same
15202   // type.
15203   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
15204       isa<ConstantSDNode>(N->getOperand(1)) &&
15205       V->getOperand(0).getValueType() == NVT) {
15206     unsigned Idx = N->getConstantOperandVal(1);
15207     unsigned NumElems = NVT.getVectorNumElements();
15208     assert((Idx % NumElems) == 0 &&
15209            "IDX in concat is not a multiple of the result vector length.");
15210     return V->getOperand(Idx / NumElems);
15211   }
15212 
15213   // Skip bitcasting
15214   V = peekThroughBitcast(V);
15215 
15216   // If the input is a build vector. Try to make a smaller build vector.
15217   if (V->getOpcode() == ISD::BUILD_VECTOR) {
15218     if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
15219       EVT InVT = V->getValueType(0);
15220       unsigned ExtractSize = NVT.getSizeInBits();
15221       unsigned EltSize = InVT.getScalarSizeInBits();
15222       // Only do this if we won't split any elements.
15223       if (ExtractSize % EltSize == 0) {
15224         unsigned NumElems = ExtractSize / EltSize;
15225         EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(),
15226                                          InVT.getVectorElementType(), NumElems);
15227         if ((!LegalOperations ||
15228              TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT)) &&
15229             (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
15230           unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) /
15231                             EltSize;
15232 
15233           // Extract the pieces from the original build_vector.
15234           SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N),
15235                                             makeArrayRef(V->op_begin() + IdxVal,
15236                                                          NumElems));
15237           return DAG.getBitcast(NVT, BuildVec);
15238         }
15239       }
15240     }
15241   }
15242 
15243   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
15244     // Handle only simple case where vector being inserted and vector
15245     // being extracted are of same size.
15246     EVT SmallVT = V->getOperand(1).getValueType();
15247     if (!NVT.bitsEq(SmallVT))
15248       return SDValue();
15249 
15250     // Only handle cases where both indexes are constants.
15251     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
15252     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
15253 
15254     if (InsIdx && ExtIdx) {
15255       // Combine:
15256       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
15257       // Into:
15258       //    indices are equal or bit offsets are equal => V1
15259       //    otherwise => (extract_subvec V1, ExtIdx)
15260       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
15261           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
15262         return DAG.getBitcast(NVT, V->getOperand(1));
15263       return DAG.getNode(
15264           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
15265           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
15266           N->getOperand(1));
15267     }
15268   }
15269 
15270   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
15271     return NarrowBOp;
15272 
15273   return SDValue();
15274 }
15275 
15276 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
15277                                                  SDValue V, SelectionDAG &DAG) {
15278   SDLoc DL(V);
15279   EVT VT = V.getValueType();
15280 
15281   switch (V.getOpcode()) {
15282   default:
15283     return V;
15284 
15285   case ISD::CONCAT_VECTORS: {
15286     EVT OpVT = V->getOperand(0).getValueType();
15287     int OpSize = OpVT.getVectorNumElements();
15288     SmallBitVector OpUsedElements(OpSize, false);
15289     bool FoundSimplification = false;
15290     SmallVector<SDValue, 4> NewOps;
15291     NewOps.reserve(V->getNumOperands());
15292     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
15293       SDValue Op = V->getOperand(i);
15294       bool OpUsed = false;
15295       for (int j = 0; j < OpSize; ++j)
15296         if (UsedElements[i * OpSize + j]) {
15297           OpUsedElements[j] = true;
15298           OpUsed = true;
15299         }
15300       NewOps.push_back(
15301           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
15302                  : DAG.getUNDEF(OpVT));
15303       FoundSimplification |= Op == NewOps.back();
15304       OpUsedElements.reset();
15305     }
15306     if (FoundSimplification)
15307       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
15308     return V;
15309   }
15310 
15311   case ISD::INSERT_SUBVECTOR: {
15312     SDValue BaseV = V->getOperand(0);
15313     SDValue SubV = V->getOperand(1);
15314     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
15315     if (!IdxN)
15316       return V;
15317 
15318     int SubSize = SubV.getValueType().getVectorNumElements();
15319     int Idx = IdxN->getZExtValue();
15320     bool SubVectorUsed = false;
15321     SmallBitVector SubUsedElements(SubSize, false);
15322     for (int i = 0; i < SubSize; ++i)
15323       if (UsedElements[i + Idx]) {
15324         SubVectorUsed = true;
15325         SubUsedElements[i] = true;
15326         UsedElements[i + Idx] = false;
15327       }
15328 
15329     // Now recurse on both the base and sub vectors.
15330     SDValue SimplifiedSubV =
15331         SubVectorUsed
15332             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
15333             : DAG.getUNDEF(SubV.getValueType());
15334     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
15335     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
15336       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15337                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
15338     return V;
15339   }
15340   }
15341 }
15342 
15343 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
15344                                        SDValue N1, SelectionDAG &DAG) {
15345   EVT VT = SVN->getValueType(0);
15346   int NumElts = VT.getVectorNumElements();
15347   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
15348   for (int M : SVN->getMask())
15349     if (M >= 0 && M < NumElts)
15350       N0UsedElements[M] = true;
15351     else if (M >= NumElts)
15352       N1UsedElements[M - NumElts] = true;
15353 
15354   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
15355   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
15356   if (S0 == N0 && S1 == N1)
15357     return SDValue();
15358 
15359   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
15360 }
15361 
15362 static SDValue simplifyShuffleMask(ShuffleVectorSDNode *SVN, SDValue N0,
15363                                    SDValue N1, SelectionDAG &DAG) {
15364   auto isUndefElt = [](SDValue V, int Idx) {
15365     // TODO - handle more cases as required.
15366     if (V.getOpcode() == ISD::BUILD_VECTOR)
15367       return V.getOperand(Idx).isUndef();
15368     return false;
15369   };
15370 
15371   EVT VT = SVN->getValueType(0);
15372   unsigned NumElts = VT.getVectorNumElements();
15373 
15374   bool Changed = false;
15375   SmallVector<int, 8> NewMask;
15376   for (unsigned i = 0; i != NumElts; ++i) {
15377     int Idx = SVN->getMaskElt(i);
15378     if ((0 <= Idx && Idx < (int)NumElts && isUndefElt(N0, Idx)) ||
15379         ((int)NumElts < Idx && isUndefElt(N1, Idx - NumElts))) {
15380       Changed = true;
15381       Idx = -1;
15382     }
15383     NewMask.push_back(Idx);
15384   }
15385   if (Changed)
15386     return DAG.getVectorShuffle(VT, SDLoc(SVN), N0, N1, NewMask);
15387 
15388   return SDValue();
15389 }
15390 
15391 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
15392 // or turn a shuffle of a single concat into simpler shuffle then concat.
15393 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
15394   EVT VT = N->getValueType(0);
15395   unsigned NumElts = VT.getVectorNumElements();
15396 
15397   SDValue N0 = N->getOperand(0);
15398   SDValue N1 = N->getOperand(1);
15399   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15400 
15401   SmallVector<SDValue, 4> Ops;
15402   EVT ConcatVT = N0.getOperand(0).getValueType();
15403   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15404   unsigned NumConcats = NumElts / NumElemsPerConcat;
15405 
15406   // Special case: shuffle(concat(A,B)) can be more efficiently represented
15407   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15408   // half vector elements.
15409   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15410       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15411                   SVN->getMask().end(), [](int i) { return i == -1; })) {
15412     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15413                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15414     N1 = DAG.getUNDEF(ConcatVT);
15415     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15416   }
15417 
15418   // Look at every vector that's inserted. We're looking for exact
15419   // subvector-sized copies from a concatenated vector
15420   for (unsigned I = 0; I != NumConcats; ++I) {
15421     // Make sure we're dealing with a copy.
15422     unsigned Begin = I * NumElemsPerConcat;
15423     bool AllUndef = true, NoUndef = true;
15424     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15425       if (SVN->getMaskElt(J) >= 0)
15426         AllUndef = false;
15427       else
15428         NoUndef = false;
15429     }
15430 
15431     if (NoUndef) {
15432       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15433         return SDValue();
15434 
15435       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15436         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15437           return SDValue();
15438 
15439       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15440       if (FirstElt < N0.getNumOperands())
15441         Ops.push_back(N0.getOperand(FirstElt));
15442       else
15443         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15444 
15445     } else if (AllUndef) {
15446       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15447     } else { // Mixed with general masks and undefs, can't do optimization.
15448       return SDValue();
15449     }
15450   }
15451 
15452   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15453 }
15454 
15455 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15456 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15457 //
15458 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15459 // a simplification in some sense, but it isn't appropriate in general: some
15460 // BUILD_VECTORs are substantially cheaper than others. The general case
15461 // of a BUILD_VECTOR requires inserting each element individually (or
15462 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15463 // all constants is a single constant pool load.  A BUILD_VECTOR where each
15464 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
15465 // are undef lowers to a small number of element insertions.
15466 //
15467 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15468 // We don't fold shuffles where one side is a non-zero constant, and we don't
15469 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
15470 // non-constant operands. This seems to work out reasonably well in practice.
15471 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15472                                        SelectionDAG &DAG,
15473                                        const TargetLowering &TLI) {
15474   EVT VT = SVN->getValueType(0);
15475   unsigned NumElts = VT.getVectorNumElements();
15476   SDValue N0 = SVN->getOperand(0);
15477   SDValue N1 = SVN->getOperand(1);
15478 
15479   if (!N0->hasOneUse() || !N1->hasOneUse())
15480     return SDValue();
15481   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15482   // discussed above.
15483   if (!N1.isUndef()) {
15484     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15485     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15486     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15487       return SDValue();
15488     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15489       return SDValue();
15490   }
15491 
15492   SmallVector<SDValue, 8> Ops;
15493   SmallSet<SDValue, 16> DuplicateOps;
15494   for (int M : SVN->getMask()) {
15495     SDValue Op = DAG.getUNDEF(VT.getScalarType());
15496     if (M >= 0) {
15497       int Idx = M < (int)NumElts ? M : M - NumElts;
15498       SDValue &S = (M < (int)NumElts ? N0 : N1);
15499       if (S.getOpcode() == ISD::BUILD_VECTOR) {
15500         Op = S.getOperand(Idx);
15501       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
15502         if (Idx == 0)
15503           Op = S.getOperand(0);
15504       } else {
15505         // Operand can't be combined - bail out.
15506         return SDValue();
15507       }
15508     }
15509 
15510     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
15511     // fine, but it's likely to generate low-quality code if the target can't
15512     // reconstruct an appropriate shuffle.
15513     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
15514       if (!DuplicateOps.insert(Op).second)
15515         return SDValue();
15516 
15517     Ops.push_back(Op);
15518   }
15519   // BUILD_VECTOR requires all inputs to be of the same type, find the
15520   // maximum type and extend them all.
15521   EVT SVT = VT.getScalarType();
15522   if (SVT.isInteger())
15523     for (SDValue &Op : Ops)
15524       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
15525   if (SVT != VT.getScalarType())
15526     for (SDValue &Op : Ops)
15527       Op = TLI.isZExtFree(Op.getValueType(), SVT)
15528                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
15529                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
15530   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
15531 }
15532 
15533 // Match shuffles that can be converted to any_vector_extend_in_reg.
15534 // This is often generated during legalization.
15535 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
15536 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15537 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15538                                             SelectionDAG &DAG,
15539                                             const TargetLowering &TLI,
15540                                             bool LegalOperations,
15541                                             bool LegalTypes) {
15542   EVT VT = SVN->getValueType(0);
15543   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15544 
15545   // TODO Add support for big-endian when we have a test case.
15546   if (!VT.isInteger() || IsBigEndian)
15547     return SDValue();
15548 
15549   unsigned NumElts = VT.getVectorNumElements();
15550   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15551   ArrayRef<int> Mask = SVN->getMask();
15552   SDValue N0 = SVN->getOperand(0);
15553 
15554   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15555   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15556     for (unsigned i = 0; i != NumElts; ++i) {
15557       if (Mask[i] < 0)
15558         continue;
15559       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15560         continue;
15561       return false;
15562     }
15563     return true;
15564   };
15565 
15566   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15567   // power-of-2 extensions as they are the most likely.
15568   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15569     if (!isAnyExtend(Scale))
15570       continue;
15571 
15572     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15573     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15574     if (!LegalTypes || TLI.isTypeLegal(OutVT))
15575       if (!LegalOperations ||
15576           TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15577         return DAG.getBitcast(VT,
15578                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15579   }
15580 
15581   return SDValue();
15582 }
15583 
15584 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15585 // each source element of a large type into the lowest elements of a smaller
15586 // destination type. This is often generated during legalization.
15587 // If the source node itself was a '*_extend_vector_inreg' node then we should
15588 // then be able to remove it.
15589 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15590                                         SelectionDAG &DAG) {
15591   EVT VT = SVN->getValueType(0);
15592   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15593 
15594   // TODO Add support for big-endian when we have a test case.
15595   if (!VT.isInteger() || IsBigEndian)
15596     return SDValue();
15597 
15598   SDValue N0 = peekThroughBitcast(SVN->getOperand(0));
15599 
15600   unsigned Opcode = N0.getOpcode();
15601   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15602       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15603       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15604     return SDValue();
15605 
15606   SDValue N00 = N0.getOperand(0);
15607   ArrayRef<int> Mask = SVN->getMask();
15608   unsigned NumElts = VT.getVectorNumElements();
15609   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15610   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15611   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15612 
15613   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15614     return SDValue();
15615   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15616 
15617   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15618   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15619   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15620   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15621     for (unsigned i = 0; i != NumElts; ++i) {
15622       if (Mask[i] < 0)
15623         continue;
15624       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15625         continue;
15626       return false;
15627     }
15628     return true;
15629   };
15630 
15631   // At the moment we just handle the case where we've truncated back to the
15632   // same size as before the extension.
15633   // TODO: handle more extension/truncation cases as cases arise.
15634   if (EltSizeInBits != ExtSrcSizeInBits)
15635     return SDValue();
15636 
15637   // We can remove *extend_vector_inreg only if the truncation happens at
15638   // the same scale as the extension.
15639   if (isTruncate(ExtScale))
15640     return DAG.getBitcast(VT, N00);
15641 
15642   return SDValue();
15643 }
15644 
15645 // Combine shuffles of splat-shuffles of the form:
15646 // shuffle (shuffle V, undef, splat-mask), undef, M
15647 // If splat-mask contains undef elements, we need to be careful about
15648 // introducing undef's in the folded mask which are not the result of composing
15649 // the masks of the shuffles.
15650 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15651                                      ShuffleVectorSDNode *Splat,
15652                                      SelectionDAG &DAG) {
15653   ArrayRef<int> SplatMask = Splat->getMask();
15654   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15655 
15656   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15657   // every undef mask element in the splat-shuffle has a corresponding undef
15658   // element in the user-shuffle's mask or if the composition of mask elements
15659   // would result in undef.
15660   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15661   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15662   //   In this case it is not legal to simplify to the splat-shuffle because we
15663   //   may be exposing the users of the shuffle an undef element at index 1
15664   //   which was not there before the combine.
15665   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15666   //   In this case the composition of masks yields SplatMask, so it's ok to
15667   //   simplify to the splat-shuffle.
15668   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15669   //   In this case the composed mask includes all undef elements of SplatMask
15670   //   and in addition sets element zero to undef. It is safe to simplify to
15671   //   the splat-shuffle.
15672   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15673                                        ArrayRef<int> SplatMask) {
15674     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15675       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15676           SplatMask[UserMask[i]] != -1)
15677         return false;
15678     return true;
15679   };
15680   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15681     return SDValue(Splat, 0);
15682 
15683   // Create a new shuffle with a mask that is composed of the two shuffles'
15684   // masks.
15685   SmallVector<int, 32> NewMask;
15686   for (int Idx : UserMask)
15687     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15688 
15689   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15690                               Splat->getOperand(0), Splat->getOperand(1),
15691                               NewMask);
15692 }
15693 
15694 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
15695   EVT VT = N->getValueType(0);
15696   unsigned NumElts = VT.getVectorNumElements();
15697 
15698   SDValue N0 = N->getOperand(0);
15699   SDValue N1 = N->getOperand(1);
15700 
15701   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
15702 
15703   // Canonicalize shuffle undef, undef -> undef
15704   if (N0.isUndef() && N1.isUndef())
15705     return DAG.getUNDEF(VT);
15706 
15707   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15708 
15709   // Canonicalize shuffle v, v -> v, undef
15710   if (N0 == N1) {
15711     SmallVector<int, 8> NewMask;
15712     for (unsigned i = 0; i != NumElts; ++i) {
15713       int Idx = SVN->getMaskElt(i);
15714       if (Idx >= (int)NumElts) Idx -= NumElts;
15715       NewMask.push_back(Idx);
15716     }
15717     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
15718   }
15719 
15720   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
15721   if (N0.isUndef())
15722     return DAG.getCommutedVectorShuffle(*SVN);
15723 
15724   // Remove references to rhs if it is undef
15725   if (N1.isUndef()) {
15726     bool Changed = false;
15727     SmallVector<int, 8> NewMask;
15728     for (unsigned i = 0; i != NumElts; ++i) {
15729       int Idx = SVN->getMaskElt(i);
15730       if (Idx >= (int)NumElts) {
15731         Idx = -1;
15732         Changed = true;
15733       }
15734       NewMask.push_back(Idx);
15735     }
15736     if (Changed)
15737       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
15738   }
15739 
15740   // Simplify shuffle mask if a referenced element is UNDEF.
15741   if (SDValue V = simplifyShuffleMask(SVN, N0, N1, DAG))
15742     return V;
15743 
15744   // A shuffle of a single vector that is a splat can always be folded.
15745   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
15746     if (N1->isUndef() && N0Shuf->isSplat())
15747       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
15748 
15749   // If it is a splat, check if the argument vector is another splat or a
15750   // build_vector.
15751   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
15752     SDNode *V = N0.getNode();
15753 
15754     // If this is a bit convert that changes the element type of the vector but
15755     // not the number of vector elements, look through it.  Be careful not to
15756     // look though conversions that change things like v4f32 to v2f64.
15757     if (V->getOpcode() == ISD::BITCAST) {
15758       SDValue ConvInput = V->getOperand(0);
15759       if (ConvInput.getValueType().isVector() &&
15760           ConvInput.getValueType().getVectorNumElements() == NumElts)
15761         V = ConvInput.getNode();
15762     }
15763 
15764     if (V->getOpcode() == ISD::BUILD_VECTOR) {
15765       assert(V->getNumOperands() == NumElts &&
15766              "BUILD_VECTOR has wrong number of operands");
15767       SDValue Base;
15768       bool AllSame = true;
15769       for (unsigned i = 0; i != NumElts; ++i) {
15770         if (!V->getOperand(i).isUndef()) {
15771           Base = V->getOperand(i);
15772           break;
15773         }
15774       }
15775       // Splat of <u, u, u, u>, return <u, u, u, u>
15776       if (!Base.getNode())
15777         return N0;
15778       for (unsigned i = 0; i != NumElts; ++i) {
15779         if (V->getOperand(i) != Base) {
15780           AllSame = false;
15781           break;
15782         }
15783       }
15784       // Splat of <x, x, x, x>, return <x, x, x, x>
15785       if (AllSame)
15786         return N0;
15787 
15788       // Canonicalize any other splat as a build_vector.
15789       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
15790       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
15791       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
15792 
15793       // We may have jumped through bitcasts, so the type of the
15794       // BUILD_VECTOR may not match the type of the shuffle.
15795       if (V->getValueType(0) != VT)
15796         NewBV = DAG.getBitcast(VT, NewBV);
15797       return NewBV;
15798     }
15799   }
15800 
15801   // There are various patterns used to build up a vector from smaller vectors,
15802   // subvectors, or elements. Scan chains of these and replace unused insertions
15803   // or components with undef.
15804   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
15805     return S;
15806 
15807   // Match shuffles that can be converted to any_vector_extend_in_reg.
15808   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes))
15809     return V;
15810 
15811   // Combine "truncate_vector_in_reg" style shuffles.
15812   if (SDValue V = combineTruncationShuffle(SVN, DAG))
15813     return V;
15814 
15815   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
15816       Level < AfterLegalizeVectorOps &&
15817       (N1.isUndef() ||
15818       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
15819        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
15820     if (SDValue V = partitionShuffleOfConcats(N, DAG))
15821       return V;
15822   }
15823 
15824   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15825   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15826   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15827     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
15828       return Res;
15829 
15830   // If this shuffle only has a single input that is a bitcasted shuffle,
15831   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
15832   // back to their original types.
15833   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
15834       N1.isUndef() && Level < AfterLegalizeVectorOps &&
15835       TLI.isTypeLegal(VT)) {
15836 
15837     // Peek through the bitcast only if there is one user.
15838     SDValue BC0 = N0;
15839     while (BC0.getOpcode() == ISD::BITCAST) {
15840       if (!BC0.hasOneUse())
15841         break;
15842       BC0 = BC0.getOperand(0);
15843     }
15844 
15845     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
15846       if (Scale == 1)
15847         return SmallVector<int, 8>(Mask.begin(), Mask.end());
15848 
15849       SmallVector<int, 8> NewMask;
15850       for (int M : Mask)
15851         for (int s = 0; s != Scale; ++s)
15852           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15853       return NewMask;
15854     };
15855 
15856     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15857       EVT SVT = VT.getScalarType();
15858       EVT InnerVT = BC0->getValueType(0);
15859       EVT InnerSVT = InnerVT.getScalarType();
15860 
15861       // Determine which shuffle works with the smaller scalar type.
15862       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15863       EVT ScaleSVT = ScaleVT.getScalarType();
15864 
15865       if (TLI.isTypeLegal(ScaleVT) &&
15866           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15867           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15868         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15869         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15870 
15871         // Scale the shuffle masks to the smaller scalar type.
15872         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15873         SmallVector<int, 8> InnerMask =
15874             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15875         SmallVector<int, 8> OuterMask =
15876             ScaleShuffleMask(SVN->getMask(), OuterScale);
15877 
15878         // Merge the shuffle masks.
15879         SmallVector<int, 8> NewMask;
15880         for (int M : OuterMask)
15881           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15882 
15883         // Test for shuffle mask legality over both commutations.
15884         SDValue SV0 = BC0->getOperand(0);
15885         SDValue SV1 = BC0->getOperand(1);
15886         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15887         if (!LegalMask) {
15888           std::swap(SV0, SV1);
15889           ShuffleVectorSDNode::commuteMask(NewMask);
15890           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15891         }
15892 
15893         if (LegalMask) {
15894           SV0 = DAG.getBitcast(ScaleVT, SV0);
15895           SV1 = DAG.getBitcast(ScaleVT, SV1);
15896           return DAG.getBitcast(
15897               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15898         }
15899       }
15900     }
15901   }
15902 
15903   // Canonicalize shuffles according to rules:
15904   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15905   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15906   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15907   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15908       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15909       TLI.isTypeLegal(VT)) {
15910     // The incoming shuffle must be of the same type as the result of the
15911     // current shuffle.
15912     assert(N1->getOperand(0).getValueType() == VT &&
15913            "Shuffle types don't match");
15914 
15915     SDValue SV0 = N1->getOperand(0);
15916     SDValue SV1 = N1->getOperand(1);
15917     bool HasSameOp0 = N0 == SV0;
15918     bool IsSV1Undef = SV1.isUndef();
15919     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15920       // Commute the operands of this shuffle so that next rule
15921       // will trigger.
15922       return DAG.getCommutedVectorShuffle(*SVN);
15923   }
15924 
15925   // Try to fold according to rules:
15926   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15927   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15928   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15929   // Don't try to fold shuffles with illegal type.
15930   // Only fold if this shuffle is the only user of the other shuffle.
15931   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15932       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15933     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15934 
15935     // Don't try to fold splats; they're likely to simplify somehow, or they
15936     // might be free.
15937     if (OtherSV->isSplat())
15938       return SDValue();
15939 
15940     // The incoming shuffle must be of the same type as the result of the
15941     // current shuffle.
15942     assert(OtherSV->getOperand(0).getValueType() == VT &&
15943            "Shuffle types don't match");
15944 
15945     SDValue SV0, SV1;
15946     SmallVector<int, 4> Mask;
15947     // Compute the combined shuffle mask for a shuffle with SV0 as the first
15948     // operand, and SV1 as the second operand.
15949     for (unsigned i = 0; i != NumElts; ++i) {
15950       int Idx = SVN->getMaskElt(i);
15951       if (Idx < 0) {
15952         // Propagate Undef.
15953         Mask.push_back(Idx);
15954         continue;
15955       }
15956 
15957       SDValue CurrentVec;
15958       if (Idx < (int)NumElts) {
15959         // This shuffle index refers to the inner shuffle N0. Lookup the inner
15960         // shuffle mask to identify which vector is actually referenced.
15961         Idx = OtherSV->getMaskElt(Idx);
15962         if (Idx < 0) {
15963           // Propagate Undef.
15964           Mask.push_back(Idx);
15965           continue;
15966         }
15967 
15968         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15969                                            : OtherSV->getOperand(1);
15970       } else {
15971         // This shuffle index references an element within N1.
15972         CurrentVec = N1;
15973       }
15974 
15975       // Simple case where 'CurrentVec' is UNDEF.
15976       if (CurrentVec.isUndef()) {
15977         Mask.push_back(-1);
15978         continue;
15979       }
15980 
15981       // Canonicalize the shuffle index. We don't know yet if CurrentVec
15982       // will be the first or second operand of the combined shuffle.
15983       Idx = Idx % NumElts;
15984       if (!SV0.getNode() || SV0 == CurrentVec) {
15985         // Ok. CurrentVec is the left hand side.
15986         // Update the mask accordingly.
15987         SV0 = CurrentVec;
15988         Mask.push_back(Idx);
15989         continue;
15990       }
15991 
15992       // Bail out if we cannot convert the shuffle pair into a single shuffle.
15993       if (SV1.getNode() && SV1 != CurrentVec)
15994         return SDValue();
15995 
15996       // Ok. CurrentVec is the right hand side.
15997       // Update the mask accordingly.
15998       SV1 = CurrentVec;
15999       Mask.push_back(Idx + NumElts);
16000     }
16001 
16002     // Check if all indices in Mask are Undef. In case, propagate Undef.
16003     bool isUndefMask = true;
16004     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
16005       isUndefMask &= Mask[i] < 0;
16006 
16007     if (isUndefMask)
16008       return DAG.getUNDEF(VT);
16009 
16010     if (!SV0.getNode())
16011       SV0 = DAG.getUNDEF(VT);
16012     if (!SV1.getNode())
16013       SV1 = DAG.getUNDEF(VT);
16014 
16015     // Avoid introducing shuffles with illegal mask.
16016     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
16017       ShuffleVectorSDNode::commuteMask(Mask);
16018 
16019       if (!TLI.isShuffleMaskLegal(Mask, VT))
16020         return SDValue();
16021 
16022       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
16023       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
16024       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
16025       std::swap(SV0, SV1);
16026     }
16027 
16028     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16029     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16030     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16031     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
16032   }
16033 
16034   return SDValue();
16035 }
16036 
16037 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
16038   SDValue InVal = N->getOperand(0);
16039   EVT VT = N->getValueType(0);
16040 
16041   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
16042   // with a VECTOR_SHUFFLE and possible truncate.
16043   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16044     SDValue InVec = InVal->getOperand(0);
16045     SDValue EltNo = InVal->getOperand(1);
16046     auto InVecT = InVec.getValueType();
16047     if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
16048       SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
16049       int Elt = C0->getZExtValue();
16050       NewMask[0] = Elt;
16051       SDValue Val;
16052       // If we have an implict truncate do truncate here as long as it's legal.
16053       // if it's not legal, this should
16054       if (VT.getScalarType() != InVal.getValueType() &&
16055           InVal.getValueType().isScalarInteger() &&
16056           isTypeLegal(VT.getScalarType())) {
16057         Val =
16058             DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
16059         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
16060       }
16061       if (VT.getScalarType() == InVecT.getScalarType() &&
16062           VT.getVectorNumElements() <= InVecT.getVectorNumElements() &&
16063           TLI.isShuffleMaskLegal(NewMask, VT)) {
16064         Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec,
16065                                    DAG.getUNDEF(InVecT), NewMask);
16066         // If the initial vector is the correct size this shuffle is a
16067         // valid result.
16068         if (VT == InVecT)
16069           return Val;
16070         // If not we must truncate the vector.
16071         if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
16072           MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
16073           SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy);
16074           EVT SubVT =
16075               EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(),
16076                                VT.getVectorNumElements());
16077           Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val,
16078                             ZeroIdx);
16079           return Val;
16080         }
16081       }
16082     }
16083   }
16084 
16085   return SDValue();
16086 }
16087 
16088 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
16089   EVT VT = N->getValueType(0);
16090   SDValue N0 = N->getOperand(0);
16091   SDValue N1 = N->getOperand(1);
16092   SDValue N2 = N->getOperand(2);
16093 
16094   // If inserting an UNDEF, just return the original vector.
16095   if (N1.isUndef())
16096     return N0;
16097 
16098   // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow
16099   // us to pull BITCASTs from input to output.
16100   if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR)
16101     if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode()))
16102       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2);
16103 
16104   // If this is an insert of an extracted vector into an undef vector, we can
16105   // just use the input to the extract.
16106   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16107       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
16108     return N1.getOperand(0);
16109 
16110   // If we are inserting a bitcast value into an undef, with the same
16111   // number of elements, just use the bitcast input of the extract.
16112   // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
16113   //        BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
16114   if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
16115       N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16116       N1.getOperand(0).getOperand(1) == N2 &&
16117       N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
16118           VT.getVectorNumElements()) {
16119     return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
16120   }
16121 
16122   // If both N1 and N2 are bitcast values on which insert_subvector
16123   // would makes sense, pull the bitcast through.
16124   // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
16125   //        BITCAST (INSERT_SUBVECTOR N0 N1 N2)
16126   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
16127     SDValue CN0 = N0.getOperand(0);
16128     SDValue CN1 = N1.getOperand(0);
16129     if (CN0.getValueType().getVectorElementType() ==
16130             CN1.getValueType().getVectorElementType() &&
16131         CN0.getValueType().getVectorNumElements() ==
16132             VT.getVectorNumElements()) {
16133       SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
16134                                       CN0.getValueType(), CN0, CN1, N2);
16135       return DAG.getBitcast(VT, NewINSERT);
16136     }
16137   }
16138 
16139   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
16140   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
16141   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
16142   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
16143       N0.getOperand(1).getValueType() == N1.getValueType() &&
16144       N0.getOperand(2) == N2)
16145     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
16146                        N1, N2);
16147 
16148   if (!isa<ConstantSDNode>(N2))
16149     return SDValue();
16150 
16151   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
16152 
16153   // Canonicalize insert_subvector dag nodes.
16154   // Example:
16155   // (insert_subvector (insert_subvector A, Idx0), Idx1)
16156   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
16157   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
16158       N1.getValueType() == N0.getOperand(1).getValueType() &&
16159       isa<ConstantSDNode>(N0.getOperand(2))) {
16160     unsigned OtherIdx = N0.getConstantOperandVal(2);
16161     if (InsIdx < OtherIdx) {
16162       // Swap nodes.
16163       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
16164                                   N0.getOperand(0), N1, N2);
16165       AddToWorklist(NewOp.getNode());
16166       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
16167                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
16168     }
16169   }
16170 
16171   // If the input vector is a concatenation, and the insert replaces
16172   // one of the pieces, we can optimize into a single concat_vectors.
16173   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
16174       N0.getOperand(0).getValueType() == N1.getValueType()) {
16175     unsigned Factor = N1.getValueType().getVectorNumElements();
16176 
16177     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
16178     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
16179 
16180     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
16181   }
16182 
16183   return SDValue();
16184 }
16185 
16186 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
16187   SDValue N0 = N->getOperand(0);
16188 
16189   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
16190   if (N0->getOpcode() == ISD::FP16_TO_FP)
16191     return N0->getOperand(0);
16192 
16193   return SDValue();
16194 }
16195 
16196 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
16197   SDValue N0 = N->getOperand(0);
16198 
16199   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
16200   if (N0->getOpcode() == ISD::AND) {
16201     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
16202     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
16203       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
16204                          N0.getOperand(0));
16205     }
16206   }
16207 
16208   return SDValue();
16209 }
16210 
16211 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
16212 /// with the destination vector and a zero vector.
16213 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
16214 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
16215 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
16216   EVT VT = N->getValueType(0);
16217   SDValue LHS = N->getOperand(0);
16218   SDValue RHS = peekThroughBitcast(N->getOperand(1));
16219   SDLoc DL(N);
16220 
16221   // Make sure we're not running after operation legalization where it
16222   // may have custom lowered the vector shuffles.
16223   if (LegalOperations)
16224     return SDValue();
16225 
16226   if (N->getOpcode() != ISD::AND)
16227     return SDValue();
16228 
16229   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
16230     return SDValue();
16231 
16232   EVT RVT = RHS.getValueType();
16233   unsigned NumElts = RHS.getNumOperands();
16234 
16235   // Attempt to create a valid clear mask, splitting the mask into
16236   // sub elements and checking to see if each is
16237   // all zeros or all ones - suitable for shuffle masking.
16238   auto BuildClearMask = [&](int Split) {
16239     int NumSubElts = NumElts * Split;
16240     int NumSubBits = RVT.getScalarSizeInBits() / Split;
16241 
16242     SmallVector<int, 8> Indices;
16243     for (int i = 0; i != NumSubElts; ++i) {
16244       int EltIdx = i / Split;
16245       int SubIdx = i % Split;
16246       SDValue Elt = RHS.getOperand(EltIdx);
16247       if (Elt.isUndef()) {
16248         Indices.push_back(-1);
16249         continue;
16250       }
16251 
16252       APInt Bits;
16253       if (isa<ConstantSDNode>(Elt))
16254         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
16255       else if (isa<ConstantFPSDNode>(Elt))
16256         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
16257       else
16258         return SDValue();
16259 
16260       // Extract the sub element from the constant bit mask.
16261       if (DAG.getDataLayout().isBigEndian()) {
16262         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
16263       } else {
16264         Bits.lshrInPlace(SubIdx * NumSubBits);
16265       }
16266 
16267       if (Split > 1)
16268         Bits = Bits.trunc(NumSubBits);
16269 
16270       if (Bits.isAllOnesValue())
16271         Indices.push_back(i);
16272       else if (Bits == 0)
16273         Indices.push_back(i + NumSubElts);
16274       else
16275         return SDValue();
16276     }
16277 
16278     // Let's see if the target supports this vector_shuffle.
16279     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
16280     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
16281     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
16282       return SDValue();
16283 
16284     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
16285     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
16286                                                    DAG.getBitcast(ClearVT, LHS),
16287                                                    Zero, Indices));
16288   };
16289 
16290   // Determine maximum split level (byte level masking).
16291   int MaxSplit = 1;
16292   if (RVT.getScalarSizeInBits() % 8 == 0)
16293     MaxSplit = RVT.getScalarSizeInBits() / 8;
16294 
16295   for (int Split = 1; Split <= MaxSplit; ++Split)
16296     if (RVT.getScalarSizeInBits() % Split == 0)
16297       if (SDValue S = BuildClearMask(Split))
16298         return S;
16299 
16300   return SDValue();
16301 }
16302 
16303 /// Visit a binary vector operation, like ADD.
16304 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
16305   assert(N->getValueType(0).isVector() &&
16306          "SimplifyVBinOp only works on vectors!");
16307 
16308   SDValue LHS = N->getOperand(0);
16309   SDValue RHS = N->getOperand(1);
16310   SDValue Ops[] = {LHS, RHS};
16311 
16312   // See if we can constant fold the vector operation.
16313   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
16314           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
16315     return Fold;
16316 
16317   // Try to convert a constant mask AND into a shuffle clear mask.
16318   if (SDValue Shuffle = XformToShuffleWithZero(N))
16319     return Shuffle;
16320 
16321   // Type legalization might introduce new shuffles in the DAG.
16322   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
16323   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
16324   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
16325       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
16326       LHS.getOperand(1).isUndef() &&
16327       RHS.getOperand(1).isUndef()) {
16328     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
16329     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
16330 
16331     if (SVN0->getMask().equals(SVN1->getMask())) {
16332       EVT VT = N->getValueType(0);
16333       SDValue UndefVector = LHS.getOperand(1);
16334       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
16335                                      LHS.getOperand(0), RHS.getOperand(0),
16336                                      N->getFlags());
16337       AddUsersToWorklist(N);
16338       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
16339                                   SVN0->getMask());
16340     }
16341   }
16342 
16343   return SDValue();
16344 }
16345 
16346 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
16347                                     SDValue N2) {
16348   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
16349 
16350   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
16351                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
16352 
16353   // If we got a simplified select_cc node back from SimplifySelectCC, then
16354   // break it down into a new SETCC node, and a new SELECT node, and then return
16355   // the SELECT node, since we were called with a SELECT node.
16356   if (SCC.getNode()) {
16357     // Check to see if we got a select_cc back (to turn into setcc/select).
16358     // Otherwise, just return whatever node we got back, like fabs.
16359     if (SCC.getOpcode() == ISD::SELECT_CC) {
16360       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
16361                                   N0.getValueType(),
16362                                   SCC.getOperand(0), SCC.getOperand(1),
16363                                   SCC.getOperand(4));
16364       AddToWorklist(SETCC.getNode());
16365       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
16366                            SCC.getOperand(2), SCC.getOperand(3));
16367     }
16368 
16369     return SCC;
16370   }
16371   return SDValue();
16372 }
16373 
16374 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
16375 /// being selected between, see if we can simplify the select.  Callers of this
16376 /// should assume that TheSelect is deleted if this returns true.  As such, they
16377 /// should return the appropriate thing (e.g. the node) back to the top-level of
16378 /// the DAG combiner loop to avoid it being looked at.
16379 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
16380                                     SDValue RHS) {
16381   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16382   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
16383   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
16384     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
16385       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
16386       SDValue Sqrt = RHS;
16387       ISD::CondCode CC;
16388       SDValue CmpLHS;
16389       const ConstantFPSDNode *Zero = nullptr;
16390 
16391       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
16392         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
16393         CmpLHS = TheSelect->getOperand(0);
16394         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
16395       } else {
16396         // SELECT or VSELECT
16397         SDValue Cmp = TheSelect->getOperand(0);
16398         if (Cmp.getOpcode() == ISD::SETCC) {
16399           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
16400           CmpLHS = Cmp.getOperand(0);
16401           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
16402         }
16403       }
16404       if (Zero && Zero->isZero() &&
16405           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
16406           CC == ISD::SETULT || CC == ISD::SETLT)) {
16407         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16408         CombineTo(TheSelect, Sqrt);
16409         return true;
16410       }
16411     }
16412   }
16413   // Cannot simplify select with vector condition
16414   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
16415 
16416   // If this is a select from two identical things, try to pull the operation
16417   // through the select.
16418   if (LHS.getOpcode() != RHS.getOpcode() ||
16419       !LHS.hasOneUse() || !RHS.hasOneUse())
16420     return false;
16421 
16422   // If this is a load and the token chain is identical, replace the select
16423   // of two loads with a load through a select of the address to load from.
16424   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
16425   // constants have been dropped into the constant pool.
16426   if (LHS.getOpcode() == ISD::LOAD) {
16427     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
16428     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
16429 
16430     // Token chains must be identical.
16431     if (LHS.getOperand(0) != RHS.getOperand(0) ||
16432         // Do not let this transformation reduce the number of volatile loads.
16433         LLD->isVolatile() || RLD->isVolatile() ||
16434         // FIXME: If either is a pre/post inc/dec load,
16435         // we'd need to split out the address adjustment.
16436         LLD->isIndexed() || RLD->isIndexed() ||
16437         // If this is an EXTLOAD, the VT's must match.
16438         LLD->getMemoryVT() != RLD->getMemoryVT() ||
16439         // If this is an EXTLOAD, the kind of extension must match.
16440         (LLD->getExtensionType() != RLD->getExtensionType() &&
16441          // The only exception is if one of the extensions is anyext.
16442          LLD->getExtensionType() != ISD::EXTLOAD &&
16443          RLD->getExtensionType() != ISD::EXTLOAD) ||
16444         // FIXME: this discards src value information.  This is
16445         // over-conservative. It would be beneficial to be able to remember
16446         // both potential memory locations.  Since we are discarding
16447         // src value info, don't do the transformation if the memory
16448         // locations are not in the default address space.
16449         LLD->getPointerInfo().getAddrSpace() != 0 ||
16450         RLD->getPointerInfo().getAddrSpace() != 0 ||
16451         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
16452                                       LLD->getBasePtr().getValueType()))
16453       return false;
16454 
16455     // Check that the select condition doesn't reach either load.  If so,
16456     // folding this will induce a cycle into the DAG.  If not, this is safe to
16457     // xform, so create a select of the addresses.
16458     SDValue Addr;
16459     if (TheSelect->getOpcode() == ISD::SELECT) {
16460       SDNode *CondNode = TheSelect->getOperand(0).getNode();
16461       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
16462           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
16463         return false;
16464       // The loads must not depend on one another.
16465       if (LLD->isPredecessorOf(RLD) ||
16466           RLD->isPredecessorOf(LLD))
16467         return false;
16468       Addr = DAG.getSelect(SDLoc(TheSelect),
16469                            LLD->getBasePtr().getValueType(),
16470                            TheSelect->getOperand(0), LLD->getBasePtr(),
16471                            RLD->getBasePtr());
16472     } else {  // Otherwise SELECT_CC
16473       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
16474       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
16475 
16476       if ((LLD->hasAnyUseOfValue(1) &&
16477            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
16478           (RLD->hasAnyUseOfValue(1) &&
16479            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
16480         return false;
16481 
16482       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
16483                          LLD->getBasePtr().getValueType(),
16484                          TheSelect->getOperand(0),
16485                          TheSelect->getOperand(1),
16486                          LLD->getBasePtr(), RLD->getBasePtr(),
16487                          TheSelect->getOperand(4));
16488     }
16489 
16490     SDValue Load;
16491     // It is safe to replace the two loads if they have different alignments,
16492     // but the new load must be the minimum (most restrictive) alignment of the
16493     // inputs.
16494     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
16495     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
16496     if (!RLD->isInvariant())
16497       MMOFlags &= ~MachineMemOperand::MOInvariant;
16498     if (!RLD->isDereferenceable())
16499       MMOFlags &= ~MachineMemOperand::MODereferenceable;
16500     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
16501       // FIXME: Discards pointer and AA info.
16502       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
16503                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
16504                          MMOFlags);
16505     } else {
16506       // FIXME: Discards pointer and AA info.
16507       Load = DAG.getExtLoad(
16508           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
16509                                                   : LLD->getExtensionType(),
16510           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
16511           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
16512     }
16513 
16514     // Users of the select now use the result of the load.
16515     CombineTo(TheSelect, Load);
16516 
16517     // Users of the old loads now use the new load's chain.  We know the
16518     // old-load value is dead now.
16519     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
16520     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
16521     return true;
16522   }
16523 
16524   return false;
16525 }
16526 
16527 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
16528 /// bitwise 'and'.
16529 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
16530                                             SDValue N1, SDValue N2, SDValue N3,
16531                                             ISD::CondCode CC) {
16532   // If this is a select where the false operand is zero and the compare is a
16533   // check of the sign bit, see if we can perform the "gzip trick":
16534   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
16535   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
16536   EVT XType = N0.getValueType();
16537   EVT AType = N2.getValueType();
16538   if (!isNullConstant(N3) || !XType.bitsGE(AType))
16539     return SDValue();
16540 
16541   // If the comparison is testing for a positive value, we have to invert
16542   // the sign bit mask, so only do that transform if the target has a bitwise
16543   // 'and not' instruction (the invert is free).
16544   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
16545     // (X > -1) ? A : 0
16546     // (X >  0) ? X : 0 <-- This is canonical signed max.
16547     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
16548       return SDValue();
16549   } else if (CC == ISD::SETLT) {
16550     // (X <  0) ? A : 0
16551     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
16552     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
16553       return SDValue();
16554   } else {
16555     return SDValue();
16556   }
16557 
16558   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
16559   // constant.
16560   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
16561   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16562   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
16563     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
16564     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
16565     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
16566     AddToWorklist(Shift.getNode());
16567 
16568     if (XType.bitsGT(AType)) {
16569       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16570       AddToWorklist(Shift.getNode());
16571     }
16572 
16573     if (CC == ISD::SETGT)
16574       Shift = DAG.getNOT(DL, Shift, AType);
16575 
16576     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16577   }
16578 
16579   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
16580   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
16581   AddToWorklist(Shift.getNode());
16582 
16583   if (XType.bitsGT(AType)) {
16584     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16585     AddToWorklist(Shift.getNode());
16586   }
16587 
16588   if (CC == ISD::SETGT)
16589     Shift = DAG.getNOT(DL, Shift, AType);
16590 
16591   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16592 }
16593 
16594 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
16595 /// where 'cond' is the comparison specified by CC.
16596 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
16597                                       SDValue N2, SDValue N3, ISD::CondCode CC,
16598                                       bool NotExtCompare) {
16599   // (x ? y : y) -> y.
16600   if (N2 == N3) return N2;
16601 
16602   EVT VT = N2.getValueType();
16603   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16604   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16605 
16606   // Determine if the condition we're dealing with is constant
16607   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16608                               N0, N1, CC, DL, false);
16609   if (SCC.getNode()) AddToWorklist(SCC.getNode());
16610 
16611   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16612     // fold select_cc true, x, y -> x
16613     // fold select_cc false, x, y -> y
16614     return !SCCC->isNullValue() ? N2 : N3;
16615   }
16616 
16617   // Check to see if we can simplify the select into an fabs node
16618   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16619     // Allow either -0.0 or 0.0
16620     if (CFP->isZero()) {
16621       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
16622       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
16623           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
16624           N2 == N3.getOperand(0))
16625         return DAG.getNode(ISD::FABS, DL, VT, N0);
16626 
16627       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
16628       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
16629           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
16630           N2.getOperand(0) == N3)
16631         return DAG.getNode(ISD::FABS, DL, VT, N3);
16632     }
16633   }
16634 
16635   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
16636   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
16637   // in it.  This is a win when the constant is not otherwise available because
16638   // it replaces two constant pool loads with one.  We only do this if the FP
16639   // type is known to be legal, because if it isn't, then we are before legalize
16640   // types an we want the other legalization to happen first (e.g. to avoid
16641   // messing with soft float) and if the ConstantFP is not legal, because if
16642   // it is legal, we may not need to store the FP constant in a constant pool.
16643   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
16644     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
16645       if (TLI.isTypeLegal(N2.getValueType()) &&
16646           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
16647                TargetLowering::Legal &&
16648            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
16649            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
16650           // If both constants have multiple uses, then we won't need to do an
16651           // extra load, they are likely around in registers for other users.
16652           (TV->hasOneUse() || FV->hasOneUse())) {
16653         Constant *Elts[] = {
16654           const_cast<ConstantFP*>(FV->getConstantFPValue()),
16655           const_cast<ConstantFP*>(TV->getConstantFPValue())
16656         };
16657         Type *FPTy = Elts[0]->getType();
16658         const DataLayout &TD = DAG.getDataLayout();
16659 
16660         // Create a ConstantArray of the two constants.
16661         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
16662         SDValue CPIdx =
16663             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
16664                                 TD.getPrefTypeAlignment(FPTy));
16665         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
16666 
16667         // Get the offsets to the 0 and 1 element of the array so that we can
16668         // select between them.
16669         SDValue Zero = DAG.getIntPtrConstant(0, DL);
16670         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
16671         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
16672 
16673         SDValue Cond = DAG.getSetCC(DL,
16674                                     getSetCCResultType(N0.getValueType()),
16675                                     N0, N1, CC);
16676         AddToWorklist(Cond.getNode());
16677         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
16678                                           Cond, One, Zero);
16679         AddToWorklist(CstOffset.getNode());
16680         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
16681                             CstOffset);
16682         AddToWorklist(CPIdx.getNode());
16683         return DAG.getLoad(
16684             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
16685             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
16686             Alignment);
16687       }
16688     }
16689 
16690   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
16691     return V;
16692 
16693   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
16694   // where y is has a single bit set.
16695   // A plaintext description would be, we can turn the SELECT_CC into an AND
16696   // when the condition can be materialized as an all-ones register.  Any
16697   // single bit-test can be materialized as an all-ones register with
16698   // shift-left and shift-right-arith.
16699   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
16700       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
16701     SDValue AndLHS = N0->getOperand(0);
16702     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16703     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
16704       // Shift the tested bit over the sign bit.
16705       const APInt &AndMask = ConstAndRHS->getAPIntValue();
16706       SDValue ShlAmt =
16707         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
16708                         getShiftAmountTy(AndLHS.getValueType()));
16709       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
16710 
16711       // Now arithmetic right shift it all the way over, so the result is either
16712       // all-ones, or zero.
16713       SDValue ShrAmt =
16714         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
16715                         getShiftAmountTy(Shl.getValueType()));
16716       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
16717 
16718       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
16719     }
16720   }
16721 
16722   // fold select C, 16, 0 -> shl C, 4
16723   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
16724       TLI.getBooleanContents(N0.getValueType()) ==
16725           TargetLowering::ZeroOrOneBooleanContent) {
16726 
16727     // If the caller doesn't want us to simplify this into a zext of a compare,
16728     // don't do it.
16729     if (NotExtCompare && N2C->isOne())
16730       return SDValue();
16731 
16732     // Get a SetCC of the condition
16733     // NOTE: Don't create a SETCC if it's not legal on this target.
16734     if (!LegalOperations ||
16735         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
16736       SDValue Temp, SCC;
16737       // cast from setcc result type to select result type
16738       if (LegalTypes) {
16739         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
16740                             N0, N1, CC);
16741         if (N2.getValueType().bitsLT(SCC.getValueType()))
16742           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
16743                                         N2.getValueType());
16744         else
16745           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16746                              N2.getValueType(), SCC);
16747       } else {
16748         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
16749         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16750                            N2.getValueType(), SCC);
16751       }
16752 
16753       AddToWorklist(SCC.getNode());
16754       AddToWorklist(Temp.getNode());
16755 
16756       if (N2C->isOne())
16757         return Temp;
16758 
16759       // shl setcc result by log2 n2c
16760       return DAG.getNode(
16761           ISD::SHL, DL, N2.getValueType(), Temp,
16762           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
16763                           getShiftAmountTy(Temp.getValueType())));
16764     }
16765   }
16766 
16767   // Check to see if this is an integer abs.
16768   // select_cc setg[te] X,  0,  X, -X ->
16769   // select_cc setgt    X, -1,  X, -X ->
16770   // select_cc setl[te] X,  0, -X,  X ->
16771   // select_cc setlt    X,  1, -X,  X ->
16772   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
16773   if (N1C) {
16774     ConstantSDNode *SubC = nullptr;
16775     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
16776          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
16777         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
16778       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
16779     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
16780               (N1C->isOne() && CC == ISD::SETLT)) &&
16781              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
16782       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
16783 
16784     EVT XType = N0.getValueType();
16785     if (SubC && SubC->isNullValue() && XType.isInteger()) {
16786       SDLoc DL(N0);
16787       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
16788                                   N0,
16789                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
16790                                          getShiftAmountTy(N0.getValueType())));
16791       SDValue Add = DAG.getNode(ISD::ADD, DL,
16792                                 XType, N0, Shift);
16793       AddToWorklist(Shift.getNode());
16794       AddToWorklist(Add.getNode());
16795       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
16796     }
16797   }
16798 
16799   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
16800   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
16801   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
16802   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
16803   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
16804   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
16805   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
16806   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
16807   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
16808     SDValue ValueOnZero = N2;
16809     SDValue Count = N3;
16810     // If the condition is NE instead of E, swap the operands.
16811     if (CC == ISD::SETNE)
16812       std::swap(ValueOnZero, Count);
16813     // Check if the value on zero is a constant equal to the bits in the type.
16814     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
16815       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
16816         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
16817         // legal, combine to just cttz.
16818         if ((Count.getOpcode() == ISD::CTTZ ||
16819              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
16820             N0 == Count.getOperand(0) &&
16821             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
16822           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
16823         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
16824         // legal, combine to just ctlz.
16825         if ((Count.getOpcode() == ISD::CTLZ ||
16826              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
16827             N0 == Count.getOperand(0) &&
16828             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
16829           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
16830       }
16831     }
16832   }
16833 
16834   return SDValue();
16835 }
16836 
16837 /// This is a stub for TargetLowering::SimplifySetCC.
16838 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
16839                                    ISD::CondCode Cond, const SDLoc &DL,
16840                                    bool foldBooleans) {
16841   TargetLowering::DAGCombinerInfo
16842     DagCombineInfo(DAG, Level, false, this);
16843   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
16844 }
16845 
16846 /// Given an ISD::SDIV node expressing a divide by constant, return
16847 /// a DAG expression to select that will generate the same value by multiplying
16848 /// by a magic number.
16849 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16850 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
16851   // when optimising for minimum size, we don't want to expand a div to a mul
16852   // and a shift.
16853   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16854     return SDValue();
16855 
16856   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16857   if (!C)
16858     return SDValue();
16859 
16860   // Avoid division by zero.
16861   if (C->isNullValue())
16862     return SDValue();
16863 
16864   std::vector<SDNode *> Built;
16865   SDValue S =
16866       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16867 
16868   for (SDNode *N : Built)
16869     AddToWorklist(N);
16870   return S;
16871 }
16872 
16873 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
16874 /// DAG expression that will generate the same value by right shifting.
16875 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
16876   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16877   if (!C)
16878     return SDValue();
16879 
16880   // Avoid division by zero.
16881   if (C->isNullValue())
16882     return SDValue();
16883 
16884   std::vector<SDNode *> Built;
16885   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
16886 
16887   for (SDNode *N : Built)
16888     AddToWorklist(N);
16889   return S;
16890 }
16891 
16892 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
16893 /// expression that will generate the same value by multiplying by a magic
16894 /// number.
16895 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16896 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
16897   // when optimising for minimum size, we don't want to expand a div to a mul
16898   // and a shift.
16899   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16900     return SDValue();
16901 
16902   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16903   if (!C)
16904     return SDValue();
16905 
16906   // Avoid division by zero.
16907   if (C->isNullValue())
16908     return SDValue();
16909 
16910   std::vector<SDNode *> Built;
16911   SDValue S =
16912       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16913 
16914   for (SDNode *N : Built)
16915     AddToWorklist(N);
16916   return S;
16917 }
16918 
16919 /// Determines the LogBase2 value for a non-null input value using the
16920 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16921 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16922   EVT VT = V.getValueType();
16923   unsigned EltBits = VT.getScalarSizeInBits();
16924   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16925   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16926   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16927   return LogBase2;
16928 }
16929 
16930 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16931 /// For the reciprocal, we need to find the zero of the function:
16932 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
16933 ///     =>
16934 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16935 ///     does not require additional intermediate precision]
16936 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16937   if (Level >= AfterLegalizeDAG)
16938     return SDValue();
16939 
16940   // TODO: Handle half and/or extended types?
16941   EVT VT = Op.getValueType();
16942   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16943     return SDValue();
16944 
16945   // If estimates are explicitly disabled for this function, we're done.
16946   MachineFunction &MF = DAG.getMachineFunction();
16947   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16948   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16949     return SDValue();
16950 
16951   // Estimates may be explicitly enabled for this type with a custom number of
16952   // refinement steps.
16953   int Iterations = TLI.getDivRefinementSteps(VT, MF);
16954   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16955     AddToWorklist(Est.getNode());
16956 
16957     if (Iterations) {
16958       EVT VT = Op.getValueType();
16959       SDLoc DL(Op);
16960       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16961 
16962       // Newton iterations: Est = Est + Est (1 - Arg * Est)
16963       for (int i = 0; i < Iterations; ++i) {
16964         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16965         AddToWorklist(NewEst.getNode());
16966 
16967         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16968         AddToWorklist(NewEst.getNode());
16969 
16970         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16971         AddToWorklist(NewEst.getNode());
16972 
16973         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16974         AddToWorklist(Est.getNode());
16975       }
16976     }
16977     return Est;
16978   }
16979 
16980   return SDValue();
16981 }
16982 
16983 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16984 /// For the reciprocal sqrt, we need to find the zero of the function:
16985 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16986 ///     =>
16987 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16988 /// As a result, we precompute A/2 prior to the iteration loop.
16989 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16990                                          unsigned Iterations,
16991                                          SDNodeFlags Flags, bool Reciprocal) {
16992   EVT VT = Arg.getValueType();
16993   SDLoc DL(Arg);
16994   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16995 
16996   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16997   // this entire sequence requires only one FP constant.
16998   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16999   AddToWorklist(HalfArg.getNode());
17000 
17001   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
17002   AddToWorklist(HalfArg.getNode());
17003 
17004   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
17005   for (unsigned i = 0; i < Iterations; ++i) {
17006     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
17007     AddToWorklist(NewEst.getNode());
17008 
17009     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
17010     AddToWorklist(NewEst.getNode());
17011 
17012     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
17013     AddToWorklist(NewEst.getNode());
17014 
17015     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17016     AddToWorklist(Est.getNode());
17017   }
17018 
17019   // If non-reciprocal square root is requested, multiply the result by Arg.
17020   if (!Reciprocal) {
17021     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
17022     AddToWorklist(Est.getNode());
17023   }
17024 
17025   return Est;
17026 }
17027 
17028 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17029 /// For the reciprocal sqrt, we need to find the zero of the function:
17030 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17031 ///     =>
17032 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
17033 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
17034                                          unsigned Iterations,
17035                                          SDNodeFlags Flags, bool Reciprocal) {
17036   EVT VT = Arg.getValueType();
17037   SDLoc DL(Arg);
17038   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
17039   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
17040 
17041   // This routine must enter the loop below to work correctly
17042   // when (Reciprocal == false).
17043   assert(Iterations > 0);
17044 
17045   // Newton iterations for reciprocal square root:
17046   // E = (E * -0.5) * ((A * E) * E + -3.0)
17047   for (unsigned i = 0; i < Iterations; ++i) {
17048     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
17049     AddToWorklist(AE.getNode());
17050 
17051     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
17052     AddToWorklist(AEE.getNode());
17053 
17054     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
17055     AddToWorklist(RHS.getNode());
17056 
17057     // When calculating a square root at the last iteration build:
17058     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
17059     // (notice a common subexpression)
17060     SDValue LHS;
17061     if (Reciprocal || (i + 1) < Iterations) {
17062       // RSQRT: LHS = (E * -0.5)
17063       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
17064     } else {
17065       // SQRT: LHS = (A * E) * -0.5
17066       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
17067     }
17068     AddToWorklist(LHS.getNode());
17069 
17070     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
17071     AddToWorklist(Est.getNode());
17072   }
17073 
17074   return Est;
17075 }
17076 
17077 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
17078 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
17079 /// Op can be zero.
17080 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
17081                                            bool Reciprocal) {
17082   if (Level >= AfterLegalizeDAG)
17083     return SDValue();
17084 
17085   // TODO: Handle half and/or extended types?
17086   EVT VT = Op.getValueType();
17087   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17088     return SDValue();
17089 
17090   // If estimates are explicitly disabled for this function, we're done.
17091   MachineFunction &MF = DAG.getMachineFunction();
17092   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
17093   if (Enabled == TLI.ReciprocalEstimate::Disabled)
17094     return SDValue();
17095 
17096   // Estimates may be explicitly enabled for this type with a custom number of
17097   // refinement steps.
17098   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
17099 
17100   bool UseOneConstNR = false;
17101   if (SDValue Est =
17102       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
17103                           Reciprocal)) {
17104     AddToWorklist(Est.getNode());
17105 
17106     if (Iterations) {
17107       Est = UseOneConstNR
17108             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
17109             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
17110 
17111       if (!Reciprocal) {
17112         // Unfortunately, Est is now NaN if the input was exactly 0.0.
17113         // Select out this case and force the answer to 0.0.
17114         EVT VT = Op.getValueType();
17115         SDLoc DL(Op);
17116 
17117         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17118         EVT CCVT = getSetCCResultType(VT);
17119         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
17120         AddToWorklist(ZeroCmp.getNode());
17121 
17122         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
17123                           ZeroCmp, FPZero, Est);
17124         AddToWorklist(Est.getNode());
17125       }
17126     }
17127     return Est;
17128   }
17129 
17130   return SDValue();
17131 }
17132 
17133 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17134   return buildSqrtEstimateImpl(Op, Flags, true);
17135 }
17136 
17137 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17138   return buildSqrtEstimateImpl(Op, Flags, false);
17139 }
17140 
17141 /// Return true if base is a frame index, which is known not to alias with
17142 /// anything but itself.  Provides base object and offset as results.
17143 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
17144                            const GlobalValue *&GV, const void *&CV) {
17145   // Assume it is a primitive operation.
17146   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
17147 
17148   // If it's an adding a simple constant then integrate the offset.
17149   if (Base.getOpcode() == ISD::ADD) {
17150     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
17151       Base = Base.getOperand(0);
17152       Offset += C->getSExtValue();
17153     }
17154   }
17155 
17156   // Return the underlying GlobalValue, and update the Offset.  Return false
17157   // for GlobalAddressSDNode since the same GlobalAddress may be represented
17158   // by multiple nodes with different offsets.
17159   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
17160     GV = G->getGlobal();
17161     Offset += G->getOffset();
17162     return false;
17163   }
17164 
17165   // Return the underlying Constant value, and update the Offset.  Return false
17166   // for ConstantSDNodes since the same constant pool entry may be represented
17167   // by multiple nodes with different offsets.
17168   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
17169     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
17170                                          : (const void *)C->getConstVal();
17171     Offset += C->getOffset();
17172     return false;
17173   }
17174   // If it's any of the following then it can't alias with anything but itself.
17175   return isa<FrameIndexSDNode>(Base);
17176 }
17177 
17178 /// Return true if there is any possibility that the two addresses overlap.
17179 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
17180   // If they are the same then they must be aliases.
17181   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
17182 
17183   // If they are both volatile then they cannot be reordered.
17184   if (Op0->isVolatile() && Op1->isVolatile()) return true;
17185 
17186   // If one operation reads from invariant memory, and the other may store, they
17187   // cannot alias. These should really be checking the equivalent of mayWrite,
17188   // but it only matters for memory nodes other than load /store.
17189   if (Op0->isInvariant() && Op1->writeMem())
17190     return false;
17191 
17192   if (Op1->isInvariant() && Op0->writeMem())
17193     return false;
17194 
17195   unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
17196   unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
17197 
17198   // Check for BaseIndexOffset matching.
17199   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
17200   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
17201   int64_t PtrDiff;
17202   if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
17203     return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
17204 
17205   // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
17206   // able to calculate their relative offset if at least one arises
17207   // from an alloca. However, these allocas cannot overlap and we
17208   // can infer there is no alias.
17209   if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
17210     if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
17211       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17212       // If the base are the same frame index but the we couldn't find a
17213       // constant offset, (indices are different) be conservative.
17214       if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
17215                      !MFI.isFixedObjectIndex(B->getIndex())))
17216         return false;
17217     }
17218 
17219   // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
17220   // modified to use BaseIndexOffset.
17221 
17222   // Gather base node and offset information.
17223   SDValue Base0, Base1;
17224   int64_t Offset0, Offset1;
17225   const GlobalValue *GV0, *GV1;
17226   const void *CV0, *CV1;
17227   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
17228                                       Base0, Offset0, GV0, CV0);
17229   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
17230                                       Base1, Offset1, GV1, CV1);
17231 
17232   // If they have the same base address, then check to see if they overlap.
17233   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
17234     return !((Offset0 + NumBytes0) <= Offset1 ||
17235              (Offset1 + NumBytes1) <= Offset0);
17236 
17237   // It is possible for different frame indices to alias each other, mostly
17238   // when tail call optimization reuses return address slots for arguments.
17239   // To catch this case, look up the actual index of frame indices to compute
17240   // the real alias relationship.
17241   if (IsFrameIndex0 && IsFrameIndex1) {
17242     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17243     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
17244     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
17245     return !((Offset0 + NumBytes0) <= Offset1 ||
17246              (Offset1 + NumBytes1) <= Offset0);
17247   }
17248 
17249   // Otherwise, if we know what the bases are, and they aren't identical, then
17250   // we know they cannot alias.
17251   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
17252     return false;
17253 
17254   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
17255   // compared to the size and offset of the access, we may be able to prove they
17256   // do not alias. This check is conservative for now to catch cases created by
17257   // splitting vector types.
17258   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
17259   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
17260   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
17261   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
17262   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
17263       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
17264     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
17265     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
17266 
17267     // There is no overlap between these relatively aligned accesses of similar
17268     // size. Return no alias.
17269     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
17270         (OffAlign1 + NumBytes1) <= OffAlign0)
17271       return false;
17272   }
17273 
17274   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
17275                    ? CombinerGlobalAA
17276                    : DAG.getSubtarget().useAA();
17277 #ifndef NDEBUG
17278   if (CombinerAAOnlyFunc.getNumOccurrences() &&
17279       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
17280     UseAA = false;
17281 #endif
17282 
17283   if (UseAA && AA &&
17284       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
17285     // Use alias analysis information.
17286     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
17287     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
17288     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
17289     AliasResult AAResult =
17290         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
17291                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
17292                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
17293                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
17294     if (AAResult == NoAlias)
17295       return false;
17296   }
17297 
17298   // Otherwise we have to assume they alias.
17299   return true;
17300 }
17301 
17302 /// Walk up chain skipping non-aliasing memory nodes,
17303 /// looking for aliasing nodes and adding them to the Aliases vector.
17304 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
17305                                    SmallVectorImpl<SDValue> &Aliases) {
17306   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
17307   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
17308 
17309   // Get alias information for node.
17310   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
17311 
17312   // Starting off.
17313   Chains.push_back(OriginalChain);
17314   unsigned Depth = 0;
17315 
17316   // Look at each chain and determine if it is an alias.  If so, add it to the
17317   // aliases list.  If not, then continue up the chain looking for the next
17318   // candidate.
17319   while (!Chains.empty()) {
17320     SDValue Chain = Chains.pop_back_val();
17321 
17322     // For TokenFactor nodes, look at each operand and only continue up the
17323     // chain until we reach the depth limit.
17324     //
17325     // FIXME: The depth check could be made to return the last non-aliasing
17326     // chain we found before we hit a tokenfactor rather than the original
17327     // chain.
17328     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
17329       Aliases.clear();
17330       Aliases.push_back(OriginalChain);
17331       return;
17332     }
17333 
17334     // Don't bother if we've been before.
17335     if (!Visited.insert(Chain.getNode()).second)
17336       continue;
17337 
17338     switch (Chain.getOpcode()) {
17339     case ISD::EntryToken:
17340       // Entry token is ideal chain operand, but handled in FindBetterChain.
17341       break;
17342 
17343     case ISD::LOAD:
17344     case ISD::STORE: {
17345       // Get alias information for Chain.
17346       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
17347           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
17348 
17349       // If chain is alias then stop here.
17350       if (!(IsLoad && IsOpLoad) &&
17351           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
17352         Aliases.push_back(Chain);
17353       } else {
17354         // Look further up the chain.
17355         Chains.push_back(Chain.getOperand(0));
17356         ++Depth;
17357       }
17358       break;
17359     }
17360 
17361     case ISD::TokenFactor:
17362       // We have to check each of the operands of the token factor for "small"
17363       // token factors, so we queue them up.  Adding the operands to the queue
17364       // (stack) in reverse order maintains the original order and increases the
17365       // likelihood that getNode will find a matching token factor (CSE.)
17366       if (Chain.getNumOperands() > 16) {
17367         Aliases.push_back(Chain);
17368         break;
17369       }
17370       for (unsigned n = Chain.getNumOperands(); n;)
17371         Chains.push_back(Chain.getOperand(--n));
17372       ++Depth;
17373       break;
17374 
17375     case ISD::CopyFromReg:
17376       // Forward past CopyFromReg.
17377       Chains.push_back(Chain.getOperand(0));
17378       ++Depth;
17379       break;
17380 
17381     default:
17382       // For all other instructions we will just have to take what we can get.
17383       Aliases.push_back(Chain);
17384       break;
17385     }
17386   }
17387 }
17388 
17389 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
17390 /// (aliasing node.)
17391 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
17392   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
17393 
17394   // Accumulate all the aliases to this node.
17395   GatherAllAliases(N, OldChain, Aliases);
17396 
17397   // If no operands then chain to entry token.
17398   if (Aliases.size() == 0)
17399     return DAG.getEntryNode();
17400 
17401   // If a single operand then chain to it.  We don't need to revisit it.
17402   if (Aliases.size() == 1)
17403     return Aliases[0];
17404 
17405   // Construct a custom tailored token factor.
17406   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
17407 }
17408 
17409 // This function tries to collect a bunch of potentially interesting
17410 // nodes to improve the chains of, all at once. This might seem
17411 // redundant, as this function gets called when visiting every store
17412 // node, so why not let the work be done on each store as it's visited?
17413 //
17414 // I believe this is mainly important because MergeConsecutiveStores
17415 // is unable to deal with merging stores of different sizes, so unless
17416 // we improve the chains of all the potential candidates up-front
17417 // before running MergeConsecutiveStores, it might only see some of
17418 // the nodes that will eventually be candidates, and then not be able
17419 // to go from a partially-merged state to the desired final
17420 // fully-merged state.
17421 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
17422   // This holds the base pointer, index, and the offset in bytes from the base
17423   // pointer.
17424   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
17425 
17426   // We must have a base and an offset.
17427   if (!BasePtr.getBase().getNode())
17428     return false;
17429 
17430   // Do not handle stores to undef base pointers.
17431   if (BasePtr.getBase().isUndef())
17432     return false;
17433 
17434   SmallVector<StoreSDNode *, 8> ChainedStores;
17435   ChainedStores.push_back(St);
17436 
17437   // Walk up the chain and look for nodes with offsets from the same
17438   // base pointer. Stop when reaching an instruction with a different kind
17439   // or instruction which has a different base pointer.
17440   StoreSDNode *Index = St;
17441   while (Index) {
17442     // If the chain has more than one use, then we can't reorder the mem ops.
17443     if (Index != St && !SDValue(Index, 0)->hasOneUse())
17444       break;
17445 
17446     if (Index->isVolatile() || Index->isIndexed())
17447       break;
17448 
17449     // Find the base pointer and offset for this memory node.
17450     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
17451 
17452     // Check that the base pointer is the same as the original one.
17453     if (!BasePtr.equalBaseIndex(Ptr, DAG))
17454       break;
17455 
17456     // Walk up the chain to find the next store node, ignoring any
17457     // intermediate loads. Any other kind of node will halt the loop.
17458     SDNode *NextInChain = Index->getChain().getNode();
17459     while (true) {
17460       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
17461         // We found a store node. Use it for the next iteration.
17462         if (STn->isVolatile() || STn->isIndexed()) {
17463           Index = nullptr;
17464           break;
17465         }
17466         ChainedStores.push_back(STn);
17467         Index = STn;
17468         break;
17469       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
17470         NextInChain = Ldn->getChain().getNode();
17471         continue;
17472       } else {
17473         Index = nullptr;
17474         break;
17475       }
17476     } // end while
17477   }
17478 
17479   // At this point, ChainedStores lists all of the Store nodes
17480   // reachable by iterating up through chain nodes matching the above
17481   // conditions.  For each such store identified, try to find an
17482   // earlier chain to attach the store to which won't violate the
17483   // required ordering.
17484   bool MadeChangeToSt = false;
17485   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
17486 
17487   for (StoreSDNode *ChainedStore : ChainedStores) {
17488     SDValue Chain = ChainedStore->getChain();
17489     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
17490 
17491     if (Chain != BetterChain) {
17492       if (ChainedStore == St)
17493         MadeChangeToSt = true;
17494       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
17495     }
17496   }
17497 
17498   // Do all replacements after finding the replacements to make to avoid making
17499   // the chains more complicated by introducing new TokenFactors.
17500   for (auto Replacement : BetterChains)
17501     replaceStoreChain(Replacement.first, Replacement.second);
17502 
17503   return MadeChangeToSt;
17504 }
17505 
17506 /// This is the entry point for the file.
17507 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
17508                            CodeGenOpt::Level OptLevel) {
17509   /// This is the main entry point to this class.
17510   DAGCombiner(*this, AA, OptLevel).Run(Level);
17511 }
17512