1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/KnownBits.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
46 #define DEBUG_TYPE "dagcombine"
48 STATISTIC(NodesCombined , "Number of dag nodes combined");
49 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
50 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
51 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
52 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
53 STATISTIC(SlicedLoads, "Number of load sliced");
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58 cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62 cl::desc("Enable DAG combiner's use of TBAA"));
65 static cl::opt<std::string>
66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67 cl::desc("Only use DAG-combiner alias analysis in this"
71 /// Hidden option to stress test load slicing, i.e., when this option
72 /// is enabled, load slicing bypasses most of its profitability guards.
74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75 cl::desc("Bypass the profitability model of load "
80 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
81 cl::desc("DAG combiner may split indexing from loads"));
83 //------------------------------ DAGCombiner ---------------------------------//
87 const TargetLowering &TLI;
89 CodeGenOpt::Level OptLevel;
94 /// \brief Worklist of all of the nodes that need to be simplified.
96 /// This must behave as a stack -- new nodes to process are pushed onto the
97 /// back and when processing we pop off of the back.
99 /// The worklist will not contain duplicates but may contain null entries
100 /// due to nodes being deleted from the underlying DAG.
101 SmallVector<SDNode *, 64> Worklist;
103 /// \brief Mapping from an SDNode to its position on the worklist.
105 /// This is used to find and remove nodes from the worklist (by nulling
106 /// them) when they are deleted from the underlying DAG. It relies on
107 /// stable indices of nodes within the worklist.
108 DenseMap<SDNode *, unsigned> WorklistMap;
110 /// \brief Set of nodes which have been combined (at least once).
112 /// This is used to allow us to reliably add any operands of a DAG node
113 /// which have not yet been combined to the worklist.
114 SmallPtrSet<SDNode *, 32> CombinedNodes;
116 // AA - Used for DAG load/store alias analysis.
119 /// When an instruction is simplified, add all users of the instruction to
120 /// the work lists because they might get more simplified now.
121 void AddUsersToWorklist(SDNode *N) {
122 for (SDNode *Node : N->uses())
126 /// Call the node-specific routine that folds each particular type of node.
127 SDValue visit(SDNode *N);
130 /// Add to the worklist making sure its instance is at the back (next to be
132 void AddToWorklist(SDNode *N) {
133 assert(N->getOpcode() != ISD::DELETED_NODE &&
134 "Deleted Node added to Worklist");
136 // Skip handle nodes as they can't usefully be combined and confuse the
137 // zero-use deletion strategy.
138 if (N->getOpcode() == ISD::HANDLENODE)
141 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
142 Worklist.push_back(N);
145 /// Remove all instances of N from the worklist.
146 void removeFromWorklist(SDNode *N) {
147 CombinedNodes.erase(N);
149 auto It = WorklistMap.find(N);
150 if (It == WorklistMap.end())
151 return; // Not in the worklist.
153 // Null out the entry rather than erasing it to avoid a linear operation.
154 Worklist[It->second] = nullptr;
155 WorklistMap.erase(It);
158 void deleteAndRecombine(SDNode *N);
159 bool recursivelyDeleteUnusedNodes(SDNode *N);
161 /// Replaces all uses of the results of one DAG node with new values.
162 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
165 /// Replaces all uses of the results of one DAG node with new values.
166 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
167 return CombineTo(N, &Res, 1, AddTo);
170 /// Replaces all uses of the results of one DAG node with new values.
171 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
173 SDValue To[] = { Res0, Res1 };
174 return CombineTo(N, To, 2, AddTo);
177 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
180 unsigned MaximumLegalStoreInBits;
182 /// Check the specified integer node value to see if it can be simplified or
183 /// if things it uses can be simplified by bit propagation.
184 /// If so, return true.
185 bool SimplifyDemandedBits(SDValue Op) {
186 unsigned BitWidth = Op.getScalarValueSizeInBits();
187 APInt Demanded = APInt::getAllOnesValue(BitWidth);
188 return SimplifyDemandedBits(Op, Demanded);
191 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
193 bool CombineToPreIndexedLoadStore(SDNode *N);
194 bool CombineToPostIndexedLoadStore(SDNode *N);
195 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
196 bool SliceUpLoad(SDNode *N);
198 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
201 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
202 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
203 /// \param EltNo index of the vector element to load.
204 /// \param OriginalLoad load that EVE came from to be replaced.
205 /// \returns EVE on success SDValue() on failure.
206 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
207 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
208 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
209 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
210 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
211 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
212 SDValue PromoteIntBinOp(SDValue Op);
213 SDValue PromoteIntShiftOp(SDValue Op);
214 SDValue PromoteExtend(SDValue Op);
215 bool PromoteLoad(SDValue Op);
217 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
218 SDValue ExtLoad, const SDLoc &DL,
219 ISD::NodeType ExtType);
221 /// Call the node-specific routine that knows how to fold each
222 /// particular type of node. If that doesn't do anything, try the
223 /// target-specific DAG combines.
224 SDValue combine(SDNode *N);
226 // Visitation implementation - Implement dag node combining for different
227 // node types. The semantics are as follows:
229 // SDValue.getNode() == 0 - No change was made
230 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
231 // otherwise - N should be replaced by the returned Operand.
233 SDValue visitTokenFactor(SDNode *N);
234 SDValue visitMERGE_VALUES(SDNode *N);
235 SDValue visitADD(SDNode *N);
236 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
237 SDValue visitSUB(SDNode *N);
238 SDValue visitADDC(SDNode *N);
239 SDValue visitUADDO(SDNode *N);
240 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
241 SDValue visitSUBC(SDNode *N);
242 SDValue visitUSUBO(SDNode *N);
243 SDValue visitADDE(SDNode *N);
244 SDValue visitADDCARRY(SDNode *N);
245 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
246 SDValue visitSUBE(SDNode *N);
247 SDValue visitSUBCARRY(SDNode *N);
248 SDValue visitMUL(SDNode *N);
249 SDValue useDivRem(SDNode *N);
250 SDValue visitSDIV(SDNode *N);
251 SDValue visitUDIV(SDNode *N);
252 SDValue visitREM(SDNode *N);
253 SDValue visitMULHU(SDNode *N);
254 SDValue visitMULHS(SDNode *N);
255 SDValue visitSMUL_LOHI(SDNode *N);
256 SDValue visitUMUL_LOHI(SDNode *N);
257 SDValue visitSMULO(SDNode *N);
258 SDValue visitUMULO(SDNode *N);
259 SDValue visitIMINMAX(SDNode *N);
260 SDValue visitAND(SDNode *N);
261 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
262 SDValue visitOR(SDNode *N);
263 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
264 SDValue visitXOR(SDNode *N);
265 SDValue SimplifyVBinOp(SDNode *N);
266 SDValue visitSHL(SDNode *N);
267 SDValue visitSRA(SDNode *N);
268 SDValue visitSRL(SDNode *N);
269 SDValue visitRotate(SDNode *N);
270 SDValue visitABS(SDNode *N);
271 SDValue visitBSWAP(SDNode *N);
272 SDValue visitBITREVERSE(SDNode *N);
273 SDValue visitCTLZ(SDNode *N);
274 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
275 SDValue visitCTTZ(SDNode *N);
276 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
277 SDValue visitCTPOP(SDNode *N);
278 SDValue visitSELECT(SDNode *N);
279 SDValue visitVSELECT(SDNode *N);
280 SDValue visitSELECT_CC(SDNode *N);
281 SDValue visitSETCC(SDNode *N);
282 SDValue visitSETCCE(SDNode *N);
283 SDValue visitSIGN_EXTEND(SDNode *N);
284 SDValue visitZERO_EXTEND(SDNode *N);
285 SDValue visitANY_EXTEND(SDNode *N);
286 SDValue visitAssertZext(SDNode *N);
287 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
288 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
289 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
290 SDValue visitTRUNCATE(SDNode *N);
291 SDValue visitBITCAST(SDNode *N);
292 SDValue visitBUILD_PAIR(SDNode *N);
293 SDValue visitFADD(SDNode *N);
294 SDValue visitFSUB(SDNode *N);
295 SDValue visitFMUL(SDNode *N);
296 SDValue visitFMA(SDNode *N);
297 SDValue visitFDIV(SDNode *N);
298 SDValue visitFREM(SDNode *N);
299 SDValue visitFSQRT(SDNode *N);
300 SDValue visitFCOPYSIGN(SDNode *N);
301 SDValue visitSINT_TO_FP(SDNode *N);
302 SDValue visitUINT_TO_FP(SDNode *N);
303 SDValue visitFP_TO_SINT(SDNode *N);
304 SDValue visitFP_TO_UINT(SDNode *N);
305 SDValue visitFP_ROUND(SDNode *N);
306 SDValue visitFP_ROUND_INREG(SDNode *N);
307 SDValue visitFP_EXTEND(SDNode *N);
308 SDValue visitFNEG(SDNode *N);
309 SDValue visitFABS(SDNode *N);
310 SDValue visitFCEIL(SDNode *N);
311 SDValue visitFTRUNC(SDNode *N);
312 SDValue visitFFLOOR(SDNode *N);
313 SDValue visitFMINNUM(SDNode *N);
314 SDValue visitFMAXNUM(SDNode *N);
315 SDValue visitBRCOND(SDNode *N);
316 SDValue visitBR_CC(SDNode *N);
317 SDValue visitLOAD(SDNode *N);
319 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
320 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
322 SDValue visitSTORE(SDNode *N);
323 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
324 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
325 SDValue visitBUILD_VECTOR(SDNode *N);
326 SDValue visitCONCAT_VECTORS(SDNode *N);
327 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
328 SDValue visitVECTOR_SHUFFLE(SDNode *N);
329 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
330 SDValue visitINSERT_SUBVECTOR(SDNode *N);
331 SDValue visitMLOAD(SDNode *N);
332 SDValue visitMSTORE(SDNode *N);
333 SDValue visitMGATHER(SDNode *N);
334 SDValue visitMSCATTER(SDNode *N);
335 SDValue visitFP_TO_FP16(SDNode *N);
336 SDValue visitFP16_TO_FP(SDNode *N);
338 SDValue visitFADDForFMACombine(SDNode *N);
339 SDValue visitFSUBForFMACombine(SDNode *N);
340 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
342 SDValue XformToShuffleWithZero(SDNode *N);
343 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
346 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
348 SDValue foldSelectOfConstants(SDNode *N);
349 SDValue foldBinOpIntoSelect(SDNode *BO);
350 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
351 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
352 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
353 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
354 SDValue N2, SDValue N3, ISD::CondCode CC,
355 bool NotExtCompare = false);
356 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
357 SDValue N2, SDValue N3, ISD::CondCode CC);
358 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
360 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
361 const SDLoc &DL, bool foldBooleans = true);
363 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
365 bool isOneUseSetCC(SDValue N) const;
367 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
369 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
370 SDValue CombineExtLoad(SDNode *N);
371 SDValue combineRepeatedFPDivisors(SDNode *N);
372 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
373 SDValue BuildSDIV(SDNode *N);
374 SDValue BuildSDIVPow2(SDNode *N);
375 SDValue BuildUDIV(SDNode *N);
376 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
377 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
378 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
379 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
380 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
381 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
382 SDNodeFlags Flags, bool Reciprocal);
383 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
384 SDNodeFlags Flags, bool Reciprocal);
385 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
386 bool DemandHighBits = true);
387 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
388 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
389 SDValue InnerPos, SDValue InnerNeg,
390 unsigned PosOpcode, unsigned NegOpcode,
392 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
393 SDValue MatchLoadCombine(SDNode *N);
394 SDValue ReduceLoadWidth(SDNode *N);
395 SDValue ReduceLoadOpStoreWidth(SDNode *N);
396 SDValue splitMergedValStore(StoreSDNode *ST);
397 SDValue TransformFPLoadStorePair(SDNode *N);
398 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
399 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
400 SDValue reduceBuildVecToShuffle(SDNode *N);
401 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
402 ArrayRef<int> VectorMask, SDValue VecIn1,
403 SDValue VecIn2, unsigned LeftIdx);
404 SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
406 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
408 /// Walk up chain skipping non-aliasing memory nodes,
409 /// looking for aliasing nodes and adding them to the Aliases vector.
410 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
411 SmallVectorImpl<SDValue> &Aliases);
413 /// Return true if there is any possibility that the two addresses overlap.
414 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
416 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
417 /// chain (aliasing node.)
418 SDValue FindBetterChain(SDNode *N, SDValue Chain);
420 /// Try to replace a store and any possibly adjacent stores on
421 /// consecutive chains with better chains. Return true only if St is
424 /// Notice that other chains may still be replaced even if the function
426 bool findBetterNeighborChains(StoreSDNode *St);
428 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
429 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
431 /// Holds a pointer to an LSBaseSDNode as well as information on where it
432 /// is located in a sequence of memory operations connected by a chain.
434 MemOpLink(LSBaseSDNode *N, int64_t Offset)
435 : MemNode(N), OffsetFromBase(Offset) {}
436 // Ptr to the mem node.
437 LSBaseSDNode *MemNode;
438 // Offset from the base ptr.
439 int64_t OffsetFromBase;
442 /// This is a helper function for visitMUL to check the profitability
443 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
444 /// MulNode is the original multiply, AddNode is (add x, c1),
445 /// and ConstNode is c2.
446 bool isMulAddWithConstProfitable(SDNode *MulNode,
451 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
452 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
453 /// the type of the loaded value to be extended. LoadedVT returns the type
454 /// of the original loaded value. NarrowLoad returns whether the load would
455 /// need to be narrowed in order to match.
456 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
457 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
460 /// Helper function for MergeConsecutiveStores which merges the
461 /// component store chains.
462 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
465 /// This is a helper function for MergeConsecutiveStores. When the source
466 /// elements of the consecutive stores are all constants or all extracted
467 /// vector elements, try to merge them into one larger store.
468 /// \return True if a merged store was created.
469 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
470 EVT MemVT, unsigned NumStores,
471 bool IsConstantSrc, bool UseVector);
473 /// This is a helper function for MergeConsecutiveStores.
474 /// Stores that may be merged are placed in StoreNodes.
475 void getStoreMergeCandidates(StoreSDNode *St,
476 SmallVectorImpl<MemOpLink> &StoreNodes);
478 /// Helper function for MergeConsecutiveStores. Checks if
479 /// Candidate stores have indirect dependency through their
480 /// operands. \return True if safe to merge
481 bool checkMergeStoreCandidatesForDependencies(
482 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
484 /// Merge consecutive store operations into a wide store.
485 /// This optimization uses wide integers or vectors when possible.
486 /// \return number of stores that were merged into a merged store (the
487 /// affected nodes are stored as a prefix in \p StoreNodes).
488 bool MergeConsecutiveStores(StoreSDNode *N);
490 /// \brief Try to transform a truncation where C is a constant:
491 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
493 /// \p N needs to be a truncation and its first operand an AND. Other
494 /// requirements are checked by the function (e.g. that trunc is
495 /// single-use) and if missed an empty SDValue is returned.
496 SDValue distributeTruncateThroughAnd(SDNode *N);
499 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
500 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
501 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
502 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
504 MaximumLegalStoreInBits = 0;
505 for (MVT VT : MVT::all_valuetypes())
506 if (EVT(VT).isSimple() && VT != MVT::Other &&
507 TLI.isTypeLegal(EVT(VT)) &&
508 VT.getSizeInBits() >= MaximumLegalStoreInBits)
509 MaximumLegalStoreInBits = VT.getSizeInBits();
512 /// Runs the dag combiner on all nodes in the work list
513 void Run(CombineLevel AtLevel);
515 SelectionDAG &getDAG() const { return DAG; }
517 /// Returns a type large enough to hold any valid shift amount - before type
518 /// legalization these can be huge.
519 EVT getShiftAmountTy(EVT LHSTy) {
520 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
521 if (LHSTy.isVector())
523 auto &DL = DAG.getDataLayout();
524 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
525 : TLI.getPointerTy(DL);
528 /// This method returns true if we are running before type legalization or
529 /// if the specified VT is legal.
530 bool isTypeLegal(const EVT &VT) {
531 if (!LegalTypes) return true;
532 return TLI.isTypeLegal(VT);
535 /// Convenience wrapper around TargetLowering::getSetCCResultType
536 EVT getSetCCResultType(EVT VT) const {
537 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
544 /// This class is a DAGUpdateListener that removes any deleted
545 /// nodes from the worklist.
546 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
549 explicit WorklistRemover(DAGCombiner &dc)
550 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
552 void NodeDeleted(SDNode *N, SDNode *E) override {
553 DC.removeFromWorklist(N);
558 //===----------------------------------------------------------------------===//
559 // TargetLowering::DAGCombinerInfo implementation
560 //===----------------------------------------------------------------------===//
562 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
563 ((DAGCombiner*)DC)->AddToWorklist(N);
566 SDValue TargetLowering::DAGCombinerInfo::
567 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
568 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
571 SDValue TargetLowering::DAGCombinerInfo::
572 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
573 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
577 SDValue TargetLowering::DAGCombinerInfo::
578 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
579 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
582 void TargetLowering::DAGCombinerInfo::
583 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
584 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
587 //===----------------------------------------------------------------------===//
589 //===----------------------------------------------------------------------===//
591 void DAGCombiner::deleteAndRecombine(SDNode *N) {
592 removeFromWorklist(N);
594 // If the operands of this node are only used by the node, they will now be
595 // dead. Make sure to re-visit them and recursively delete dead nodes.
596 for (const SDValue &Op : N->ops())
597 // For an operand generating multiple values, one of the values may
598 // become dead allowing further simplification (e.g. split index
599 // arithmetic from an indexed load).
600 if (Op->hasOneUse() || Op->getNumValues() > 1)
601 AddToWorklist(Op.getNode());
606 /// Return 1 if we can compute the negated form of the specified expression for
607 /// the same cost as the expression itself, or 2 if we can compute the negated
608 /// form more cheaply than the expression itself.
609 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
610 const TargetLowering &TLI,
611 const TargetOptions *Options,
612 unsigned Depth = 0) {
613 // fneg is removable even if it has multiple uses.
614 if (Op.getOpcode() == ISD::FNEG) return 2;
616 // Don't allow anything with multiple uses.
617 if (!Op.hasOneUse()) return 0;
619 // Don't recurse exponentially.
620 if (Depth > 6) return 0;
622 switch (Op.getOpcode()) {
623 default: return false;
624 case ISD::ConstantFP: {
625 if (!LegalOperations)
628 // Don't invert constant FP values after legalization unless the target says
629 // the negated constant is legal.
630 EVT VT = Op.getValueType();
631 return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
632 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
635 // FIXME: determine better conditions for this xform.
636 if (!Options->UnsafeFPMath) return 0;
638 // After operation legalization, it might not be legal to create new FSUBs.
639 if (LegalOperations &&
640 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
643 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
644 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
647 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
648 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
651 // We can't turn -(A-B) into B-A when we honor signed zeros.
652 if (!Options->NoSignedZerosFPMath &&
653 !Op.getNode()->getFlags().hasNoSignedZeros())
656 // fold (fneg (fsub A, B)) -> (fsub B, A)
661 if (Options->HonorSignDependentRoundingFPMath()) return 0;
663 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
664 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
668 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
674 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
679 /// If isNegatibleForFree returns true, return the newly negated expression.
680 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
681 bool LegalOperations, unsigned Depth = 0) {
682 const TargetOptions &Options = DAG.getTarget().Options;
683 // fneg is removable even if it has multiple uses.
684 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
686 // Don't allow anything with multiple uses.
687 assert(Op.hasOneUse() && "Unknown reuse!");
689 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
691 const SDNodeFlags Flags = Op.getNode()->getFlags();
693 switch (Op.getOpcode()) {
694 default: llvm_unreachable("Unknown code");
695 case ISD::ConstantFP: {
696 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
698 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
701 // FIXME: determine better conditions for this xform.
702 assert(Options.UnsafeFPMath);
704 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
705 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
706 DAG.getTargetLoweringInfo(), &Options, Depth+1))
707 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
708 GetNegatedExpression(Op.getOperand(0), DAG,
709 LegalOperations, Depth+1),
710 Op.getOperand(1), Flags);
711 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
712 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
713 GetNegatedExpression(Op.getOperand(1), DAG,
714 LegalOperations, Depth+1),
715 Op.getOperand(0), Flags);
717 // fold (fneg (fsub 0, B)) -> B
718 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
720 return Op.getOperand(1);
722 // fold (fneg (fsub A, B)) -> (fsub B, A)
723 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
724 Op.getOperand(1), Op.getOperand(0), Flags);
728 assert(!Options.HonorSignDependentRoundingFPMath());
730 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
731 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
732 DAG.getTargetLoweringInfo(), &Options, Depth+1))
733 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
734 GetNegatedExpression(Op.getOperand(0), DAG,
735 LegalOperations, Depth+1),
736 Op.getOperand(1), Flags);
738 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
739 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
741 GetNegatedExpression(Op.getOperand(1), DAG,
742 LegalOperations, Depth+1), Flags);
746 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
747 GetNegatedExpression(Op.getOperand(0), DAG,
748 LegalOperations, Depth+1));
750 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
751 GetNegatedExpression(Op.getOperand(0), DAG,
752 LegalOperations, Depth+1),
757 // APInts must be the same size for most operations, this helper
758 // function zero extends the shorter of the pair so that they match.
759 // We provide an Offset so that we can create bitwidths that won't overflow.
760 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
761 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
762 LHS = LHS.zextOrSelf(Bits);
763 RHS = RHS.zextOrSelf(Bits);
766 // Return true if this node is a setcc, or is a select_cc
767 // that selects between the target values used for true and false, making it
768 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
769 // the appropriate nodes based on the type of node we are checking. This
770 // simplifies life a bit for the callers.
771 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
773 if (N.getOpcode() == ISD::SETCC) {
774 LHS = N.getOperand(0);
775 RHS = N.getOperand(1);
776 CC = N.getOperand(2);
780 if (N.getOpcode() != ISD::SELECT_CC ||
781 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
782 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
785 if (TLI.getBooleanContents(N.getValueType()) ==
786 TargetLowering::UndefinedBooleanContent)
789 LHS = N.getOperand(0);
790 RHS = N.getOperand(1);
791 CC = N.getOperand(4);
795 /// Return true if this is a SetCC-equivalent operation with only one use.
796 /// If this is true, it allows the users to invert the operation for free when
797 /// it is profitable to do so.
798 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
800 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
805 // \brief Returns the SDNode if it is a constant float BuildVector
806 // or constant float.
807 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
808 if (isa<ConstantFPSDNode>(N))
810 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
815 // Determines if it is a constant integer or a build vector of constant
816 // integers (and undefs).
817 // Do not permit build vector implicit truncation.
818 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
819 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
820 return !(Const->isOpaque() && NoOpaques);
821 if (N.getOpcode() != ISD::BUILD_VECTOR)
823 unsigned BitWidth = N.getScalarValueSizeInBits();
824 for (const SDValue &Op : N->op_values()) {
827 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
828 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
829 (Const->isOpaque() && NoOpaques))
835 // Determines if it is a constant null integer or a splatted vector of a
836 // constant null integer (with no undefs).
837 // Build vector implicit truncation is not an issue for null values.
838 static bool isNullConstantOrNullSplatConstant(SDValue N) {
839 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
840 return Splat->isNullValue();
844 // Determines if it is a constant integer of one or a splatted vector of a
845 // constant integer of one (with no undefs).
846 // Do not permit build vector implicit truncation.
847 static bool isOneConstantOrOneSplatConstant(SDValue N) {
848 unsigned BitWidth = N.getScalarValueSizeInBits();
849 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
850 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
854 // Determines if it is a constant integer of all ones or a splatted vector of a
855 // constant integer of all ones (with no undefs).
856 // Do not permit build vector implicit truncation.
857 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
858 unsigned BitWidth = N.getScalarValueSizeInBits();
859 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
860 return Splat->isAllOnesValue() &&
861 Splat->getAPIntValue().getBitWidth() == BitWidth;
865 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
867 static bool isAnyConstantBuildVector(const SDNode *N) {
868 return ISD::isBuildVectorOfConstantSDNodes(N) ||
869 ISD::isBuildVectorOfConstantFPSDNodes(N);
872 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
874 EVT VT = N0.getValueType();
875 if (N0.getOpcode() == Opc) {
876 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
877 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
878 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
879 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
880 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
883 if (N0.hasOneUse()) {
884 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
886 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
887 if (!OpNode.getNode())
889 AddToWorklist(OpNode.getNode());
890 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
895 if (N1.getOpcode() == Opc) {
896 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
897 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
898 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
899 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
900 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
903 if (N1.hasOneUse()) {
904 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
906 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
907 if (!OpNode.getNode())
909 AddToWorklist(OpNode.getNode());
910 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
918 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
920 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
922 DEBUG(dbgs() << "\nReplacing.1 ";
924 dbgs() << "\nWith: ";
925 To[0].getNode()->dump(&DAG);
926 dbgs() << " and " << NumTo-1 << " other values\n");
927 for (unsigned i = 0, e = NumTo; i != e; ++i)
928 assert((!To[i].getNode() ||
929 N->getValueType(i) == To[i].getValueType()) &&
930 "Cannot combine value to value of different type!");
932 WorklistRemover DeadNodes(*this);
933 DAG.ReplaceAllUsesWith(N, To);
935 // Push the new nodes and any users onto the worklist
936 for (unsigned i = 0, e = NumTo; i != e; ++i) {
937 if (To[i].getNode()) {
938 AddToWorklist(To[i].getNode());
939 AddUsersToWorklist(To[i].getNode());
944 // Finally, if the node is now dead, remove it from the graph. The node
945 // may not be dead if the replacement process recursively simplified to
946 // something else needing this node.
948 deleteAndRecombine(N);
949 return SDValue(N, 0);
953 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
954 // Replace all uses. If any nodes become isomorphic to other nodes and
955 // are deleted, make sure to remove them from our worklist.
956 WorklistRemover DeadNodes(*this);
957 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
959 // Push the new node and any (possibly new) users onto the worklist.
960 AddToWorklist(TLO.New.getNode());
961 AddUsersToWorklist(TLO.New.getNode());
963 // Finally, if the node is now dead, remove it from the graph. The node
964 // may not be dead if the replacement process recursively simplified to
965 // something else needing this node.
966 if (TLO.Old.getNode()->use_empty())
967 deleteAndRecombine(TLO.Old.getNode());
970 /// Check the specified integer node value to see if it can be simplified or if
971 /// things it uses can be simplified by bit propagation. If so, return true.
972 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
973 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
975 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
979 AddToWorklist(Op.getNode());
981 // Replace the old value with the new one.
983 DEBUG(dbgs() << "\nReplacing.2 ";
984 TLO.Old.getNode()->dump(&DAG);
985 dbgs() << "\nWith: ";
986 TLO.New.getNode()->dump(&DAG);
989 CommitTargetLoweringOpt(TLO);
993 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
995 EVT VT = Load->getValueType(0);
996 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
998 DEBUG(dbgs() << "\nReplacing.9 ";
1000 dbgs() << "\nWith: ";
1001 Trunc.getNode()->dump(&DAG);
1003 WorklistRemover DeadNodes(*this);
1004 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1005 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1006 deleteAndRecombine(Load);
1007 AddToWorklist(Trunc.getNode());
1010 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1013 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1014 LoadSDNode *LD = cast<LoadSDNode>(Op);
1015 EVT MemVT = LD->getMemoryVT();
1016 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1017 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1019 : LD->getExtensionType();
1021 return DAG.getExtLoad(ExtType, DL, PVT,
1022 LD->getChain(), LD->getBasePtr(),
1023 MemVT, LD->getMemOperand());
1026 unsigned Opc = Op.getOpcode();
1029 case ISD::AssertSext:
1030 return DAG.getNode(ISD::AssertSext, DL, PVT,
1031 SExtPromoteOperand(Op.getOperand(0), PVT),
1033 case ISD::AssertZext:
1034 return DAG.getNode(ISD::AssertZext, DL, PVT,
1035 ZExtPromoteOperand(Op.getOperand(0), PVT),
1037 case ISD::Constant: {
1039 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1040 return DAG.getNode(ExtOpc, DL, PVT, Op);
1044 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1046 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1049 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1050 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1052 EVT OldVT = Op.getValueType();
1054 bool Replace = false;
1055 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1056 if (!NewOp.getNode())
1058 AddToWorklist(NewOp.getNode());
1061 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1062 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1063 DAG.getValueType(OldVT));
1066 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1067 EVT OldVT = Op.getValueType();
1069 bool Replace = false;
1070 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1071 if (!NewOp.getNode())
1073 AddToWorklist(NewOp.getNode());
1076 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1077 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1080 /// Promote the specified integer binary operation if the target indicates it is
1081 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1082 /// i32 since i16 instructions are longer.
1083 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1084 if (!LegalOperations)
1087 EVT VT = Op.getValueType();
1088 if (VT.isVector() || !VT.isInteger())
1091 // If operation type is 'undesirable', e.g. i16 on x86, consider
1093 unsigned Opc = Op.getOpcode();
1094 if (TLI.isTypeDesirableForOp(Opc, VT))
1098 // Consult target whether it is a good idea to promote this operation and
1099 // what's the right type to promote it to.
1100 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1101 assert(PVT != VT && "Don't know what type to promote to!");
1103 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1105 bool Replace0 = false;
1106 SDValue N0 = Op.getOperand(0);
1107 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1109 bool Replace1 = false;
1110 SDValue N1 = Op.getOperand(1);
1111 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1115 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1117 // New replace instances of N0 and N1
1118 if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
1119 NN0.getOpcode() != ISD::DELETED_NODE) {
1120 AddToWorklist(NN0.getNode());
1121 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1124 if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
1125 NN1.getOpcode() != ISD::DELETED_NODE) {
1126 AddToWorklist(NN1.getNode());
1127 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1130 // Deal with Op being deleted.
1131 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1137 /// Promote the specified integer shift operation if the target indicates it is
1138 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1139 /// i32 since i16 instructions are longer.
1140 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1141 if (!LegalOperations)
1144 EVT VT = Op.getValueType();
1145 if (VT.isVector() || !VT.isInteger())
1148 // If operation type is 'undesirable', e.g. i16 on x86, consider
1150 unsigned Opc = Op.getOpcode();
1151 if (TLI.isTypeDesirableForOp(Opc, VT))
1155 // Consult target whether it is a good idea to promote this operation and
1156 // what's the right type to promote it to.
1157 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1158 assert(PVT != VT && "Don't know what type to promote to!");
1160 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1162 bool Replace = false;
1163 SDValue N0 = Op.getOperand(0);
1164 SDValue N1 = Op.getOperand(1);
1165 if (Opc == ISD::SRA)
1166 N0 = SExtPromoteOperand(N0, PVT);
1167 else if (Opc == ISD::SRL)
1168 N0 = ZExtPromoteOperand(N0, PVT);
1170 N0 = PromoteOperand(N0, PVT, Replace);
1177 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1179 AddToWorklist(N0.getNode());
1181 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1183 // Deal with Op being deleted.
1184 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1190 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1191 if (!LegalOperations)
1194 EVT VT = Op.getValueType();
1195 if (VT.isVector() || !VT.isInteger())
1198 // If operation type is 'undesirable', e.g. i16 on x86, consider
1200 unsigned Opc = Op.getOpcode();
1201 if (TLI.isTypeDesirableForOp(Opc, VT))
1205 // Consult target whether it is a good idea to promote this operation and
1206 // what's the right type to promote it to.
1207 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1208 assert(PVT != VT && "Don't know what type to promote to!");
1209 // fold (aext (aext x)) -> (aext x)
1210 // fold (aext (zext x)) -> (zext x)
1211 // fold (aext (sext x)) -> (sext x)
1212 DEBUG(dbgs() << "\nPromoting ";
1213 Op.getNode()->dump(&DAG));
1214 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1219 bool DAGCombiner::PromoteLoad(SDValue Op) {
1220 if (!LegalOperations)
1223 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1226 EVT VT = Op.getValueType();
1227 if (VT.isVector() || !VT.isInteger())
1230 // If operation type is 'undesirable', e.g. i16 on x86, consider
1232 unsigned Opc = Op.getOpcode();
1233 if (TLI.isTypeDesirableForOp(Opc, VT))
1237 // Consult target whether it is a good idea to promote this operation and
1238 // what's the right type to promote it to.
1239 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1240 assert(PVT != VT && "Don't know what type to promote to!");
1243 SDNode *N = Op.getNode();
1244 LoadSDNode *LD = cast<LoadSDNode>(N);
1245 EVT MemVT = LD->getMemoryVT();
1246 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1247 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1249 : LD->getExtensionType();
1250 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1251 LD->getChain(), LD->getBasePtr(),
1252 MemVT, LD->getMemOperand());
1253 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1255 DEBUG(dbgs() << "\nPromoting ";
1258 Result.getNode()->dump(&DAG);
1260 WorklistRemover DeadNodes(*this);
1261 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1262 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1263 deleteAndRecombine(N);
1264 AddToWorklist(Result.getNode());
1270 /// \brief Recursively delete a node which has no uses and any operands for
1271 /// which it is the only use.
1273 /// Note that this both deletes the nodes and removes them from the worklist.
1274 /// It also adds any nodes who have had a user deleted to the worklist as they
1275 /// may now have only one use and subject to other combines.
1276 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1277 if (!N->use_empty())
1280 SmallSetVector<SDNode *, 16> Nodes;
1283 N = Nodes.pop_back_val();
1287 if (N->use_empty()) {
1288 for (const SDValue &ChildN : N->op_values())
1289 Nodes.insert(ChildN.getNode());
1291 removeFromWorklist(N);
1296 } while (!Nodes.empty());
1300 //===----------------------------------------------------------------------===//
1301 // Main DAG Combiner implementation
1302 //===----------------------------------------------------------------------===//
1304 void DAGCombiner::Run(CombineLevel AtLevel) {
1305 // set the instance variables, so that the various visit routines may use it.
1307 LegalOperations = Level >= AfterLegalizeVectorOps;
1308 LegalTypes = Level >= AfterLegalizeTypes;
1310 // Add all the dag nodes to the worklist.
1311 for (SDNode &Node : DAG.allnodes())
1312 AddToWorklist(&Node);
1314 // Create a dummy node (which is not added to allnodes), that adds a reference
1315 // to the root node, preventing it from being deleted, and tracking any
1316 // changes of the root.
1317 HandleSDNode Dummy(DAG.getRoot());
1319 // While the worklist isn't empty, find a node and try to combine it.
1320 while (!WorklistMap.empty()) {
1322 // The Worklist holds the SDNodes in order, but it may contain null entries.
1324 N = Worklist.pop_back_val();
1327 bool GoodWorklistEntry = WorklistMap.erase(N);
1328 (void)GoodWorklistEntry;
1329 assert(GoodWorklistEntry &&
1330 "Found a worklist entry without a corresponding map entry!");
1332 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1333 // N is deleted from the DAG, since they too may now be dead or may have a
1334 // reduced number of uses, allowing other xforms.
1335 if (recursivelyDeleteUnusedNodes(N))
1338 WorklistRemover DeadNodes(*this);
1340 // If this combine is running after legalizing the DAG, re-legalize any
1341 // nodes pulled off the worklist.
1342 if (Level == AfterLegalizeDAG) {
1343 SmallSetVector<SDNode *, 16> UpdatedNodes;
1344 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1346 for (SDNode *LN : UpdatedNodes) {
1348 AddUsersToWorklist(LN);
1354 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1356 // Add any operands of the new node which have not yet been combined to the
1357 // worklist as well. Because the worklist uniques things already, this
1358 // won't repeatedly process the same operand.
1359 CombinedNodes.insert(N);
1360 for (const SDValue &ChildN : N->op_values())
1361 if (!CombinedNodes.count(ChildN.getNode()))
1362 AddToWorklist(ChildN.getNode());
1364 SDValue RV = combine(N);
1371 // If we get back the same node we passed in, rather than a new node or
1372 // zero, we know that the node must have defined multiple values and
1373 // CombineTo was used. Since CombineTo takes care of the worklist
1374 // mechanics for us, we have no work to do in this case.
1375 if (RV.getNode() == N)
1378 assert(N->getOpcode() != ISD::DELETED_NODE &&
1379 RV.getOpcode() != ISD::DELETED_NODE &&
1380 "Node was deleted but visit returned new node!");
1382 DEBUG(dbgs() << " ... into: ";
1383 RV.getNode()->dump(&DAG));
1385 if (N->getNumValues() == RV.getNode()->getNumValues())
1386 DAG.ReplaceAllUsesWith(N, RV.getNode());
1388 assert(N->getValueType(0) == RV.getValueType() &&
1389 N->getNumValues() == 1 && "Type mismatch");
1390 DAG.ReplaceAllUsesWith(N, &RV);
1393 // Push the new node and any users onto the worklist
1394 AddToWorklist(RV.getNode());
1395 AddUsersToWorklist(RV.getNode());
1397 // Finally, if the node is now dead, remove it from the graph. The node
1398 // may not be dead if the replacement process recursively simplified to
1399 // something else needing this node. This will also take care of adding any
1400 // operands which have lost a user to the worklist.
1401 recursivelyDeleteUnusedNodes(N);
1404 // If the root changed (e.g. it was a dead load, update the root).
1405 DAG.setRoot(Dummy.getValue());
1406 DAG.RemoveDeadNodes();
1409 SDValue DAGCombiner::visit(SDNode *N) {
1410 switch (N->getOpcode()) {
1412 case ISD::TokenFactor: return visitTokenFactor(N);
1413 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1414 case ISD::ADD: return visitADD(N);
1415 case ISD::SUB: return visitSUB(N);
1416 case ISD::ADDC: return visitADDC(N);
1417 case ISD::UADDO: return visitUADDO(N);
1418 case ISD::SUBC: return visitSUBC(N);
1419 case ISD::USUBO: return visitUSUBO(N);
1420 case ISD::ADDE: return visitADDE(N);
1421 case ISD::ADDCARRY: return visitADDCARRY(N);
1422 case ISD::SUBE: return visitSUBE(N);
1423 case ISD::SUBCARRY: return visitSUBCARRY(N);
1424 case ISD::MUL: return visitMUL(N);
1425 case ISD::SDIV: return visitSDIV(N);
1426 case ISD::UDIV: return visitUDIV(N);
1428 case ISD::UREM: return visitREM(N);
1429 case ISD::MULHU: return visitMULHU(N);
1430 case ISD::MULHS: return visitMULHS(N);
1431 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1432 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1433 case ISD::SMULO: return visitSMULO(N);
1434 case ISD::UMULO: return visitUMULO(N);
1438 case ISD::UMAX: return visitIMINMAX(N);
1439 case ISD::AND: return visitAND(N);
1440 case ISD::OR: return visitOR(N);
1441 case ISD::XOR: return visitXOR(N);
1442 case ISD::SHL: return visitSHL(N);
1443 case ISD::SRA: return visitSRA(N);
1444 case ISD::SRL: return visitSRL(N);
1446 case ISD::ROTL: return visitRotate(N);
1447 case ISD::ABS: return visitABS(N);
1448 case ISD::BSWAP: return visitBSWAP(N);
1449 case ISD::BITREVERSE: return visitBITREVERSE(N);
1450 case ISD::CTLZ: return visitCTLZ(N);
1451 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1452 case ISD::CTTZ: return visitCTTZ(N);
1453 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1454 case ISD::CTPOP: return visitCTPOP(N);
1455 case ISD::SELECT: return visitSELECT(N);
1456 case ISD::VSELECT: return visitVSELECT(N);
1457 case ISD::SELECT_CC: return visitSELECT_CC(N);
1458 case ISD::SETCC: return visitSETCC(N);
1459 case ISD::SETCCE: return visitSETCCE(N);
1460 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1461 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1462 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1463 case ISD::AssertZext: return visitAssertZext(N);
1464 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1465 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1466 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1467 case ISD::TRUNCATE: return visitTRUNCATE(N);
1468 case ISD::BITCAST: return visitBITCAST(N);
1469 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1470 case ISD::FADD: return visitFADD(N);
1471 case ISD::FSUB: return visitFSUB(N);
1472 case ISD::FMUL: return visitFMUL(N);
1473 case ISD::FMA: return visitFMA(N);
1474 case ISD::FDIV: return visitFDIV(N);
1475 case ISD::FREM: return visitFREM(N);
1476 case ISD::FSQRT: return visitFSQRT(N);
1477 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1478 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1479 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1480 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1481 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1482 case ISD::FP_ROUND: return visitFP_ROUND(N);
1483 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1484 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1485 case ISD::FNEG: return visitFNEG(N);
1486 case ISD::FABS: return visitFABS(N);
1487 case ISD::FFLOOR: return visitFFLOOR(N);
1488 case ISD::FMINNUM: return visitFMINNUM(N);
1489 case ISD::FMAXNUM: return visitFMAXNUM(N);
1490 case ISD::FCEIL: return visitFCEIL(N);
1491 case ISD::FTRUNC: return visitFTRUNC(N);
1492 case ISD::BRCOND: return visitBRCOND(N);
1493 case ISD::BR_CC: return visitBR_CC(N);
1494 case ISD::LOAD: return visitLOAD(N);
1495 case ISD::STORE: return visitSTORE(N);
1496 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1497 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1498 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1499 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1500 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1501 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1502 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1503 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1504 case ISD::MGATHER: return visitMGATHER(N);
1505 case ISD::MLOAD: return visitMLOAD(N);
1506 case ISD::MSCATTER: return visitMSCATTER(N);
1507 case ISD::MSTORE: return visitMSTORE(N);
1508 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1509 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1514 SDValue DAGCombiner::combine(SDNode *N) {
1515 SDValue RV = visit(N);
1517 // If nothing happened, try a target-specific DAG combine.
1518 if (!RV.getNode()) {
1519 assert(N->getOpcode() != ISD::DELETED_NODE &&
1520 "Node was deleted but visit returned NULL!");
1522 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1523 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1525 // Expose the DAG combiner to the target combiner impls.
1526 TargetLowering::DAGCombinerInfo
1527 DagCombineInfo(DAG, Level, false, this);
1529 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1533 // If nothing happened still, try promoting the operation.
1534 if (!RV.getNode()) {
1535 switch (N->getOpcode()) {
1543 RV = PromoteIntBinOp(SDValue(N, 0));
1548 RV = PromoteIntShiftOp(SDValue(N, 0));
1550 case ISD::SIGN_EXTEND:
1551 case ISD::ZERO_EXTEND:
1552 case ISD::ANY_EXTEND:
1553 RV = PromoteExtend(SDValue(N, 0));
1556 if (PromoteLoad(SDValue(N, 0)))
1562 // If N is a commutative binary node, try commuting it to enable more
1564 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1565 N->getNumValues() == 1) {
1566 SDValue N0 = N->getOperand(0);
1567 SDValue N1 = N->getOperand(1);
1569 // Constant operands are canonicalized to RHS.
1570 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1571 SDValue Ops[] = {N1, N0};
1572 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1575 return SDValue(CSENode, 0);
1582 /// Given a node, return its input chain if it has one, otherwise return a null
1584 static SDValue getInputChainForNode(SDNode *N) {
1585 if (unsigned NumOps = N->getNumOperands()) {
1586 if (N->getOperand(0).getValueType() == MVT::Other)
1587 return N->getOperand(0);
1588 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1589 return N->getOperand(NumOps-1);
1590 for (unsigned i = 1; i < NumOps-1; ++i)
1591 if (N->getOperand(i).getValueType() == MVT::Other)
1592 return N->getOperand(i);
1597 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1598 // If N has two operands, where one has an input chain equal to the other,
1599 // the 'other' chain is redundant.
1600 if (N->getNumOperands() == 2) {
1601 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1602 return N->getOperand(0);
1603 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1604 return N->getOperand(1);
1607 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1608 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1609 SmallPtrSet<SDNode*, 16> SeenOps;
1610 bool Changed = false; // If we should replace this token factor.
1612 // Start out with this token factor.
1615 // Iterate through token factors. The TFs grows when new token factors are
1617 for (unsigned i = 0; i < TFs.size(); ++i) {
1618 SDNode *TF = TFs[i];
1620 // Check each of the operands.
1621 for (const SDValue &Op : TF->op_values()) {
1623 switch (Op.getOpcode()) {
1624 case ISD::EntryToken:
1625 // Entry tokens don't need to be added to the list. They are
1630 case ISD::TokenFactor:
1631 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1632 // Queue up for processing.
1633 TFs.push_back(Op.getNode());
1634 // Clean up in case the token factor is removed.
1635 AddToWorklist(Op.getNode());
1642 // Only add if it isn't already in the list.
1643 if (SeenOps.insert(Op.getNode()).second)
1652 // Remove Nodes that are chained to another node in the list. Do so
1653 // by walking up chains breath-first stopping when we've seen
1654 // another operand. In general we must climb to the EntryNode, but we can exit
1655 // early if we find all remaining work is associated with just one operand as
1656 // no further pruning is possible.
1658 // List of nodes to search through and original Ops from which they originate.
1659 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1660 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1661 SmallPtrSet<SDNode *, 16> SeenChains;
1662 bool DidPruneOps = false;
1664 unsigned NumLeftToConsider = 0;
1665 for (const SDValue &Op : Ops) {
1666 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1667 OpWorkCount.push_back(1);
1670 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1671 // If this is an Op, we can remove the op from the list. Remark any
1672 // search associated with it as from the current OpNumber.
1673 if (SeenOps.count(Op) != 0) {
1676 unsigned OrigOpNumber = 0;
1677 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1679 assert((OrigOpNumber != Ops.size()) &&
1680 "expected to find TokenFactor Operand");
1681 // Re-mark worklist from OrigOpNumber to OpNumber
1682 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1683 if (Worklist[i].second == OrigOpNumber) {
1684 Worklist[i].second = OpNumber;
1687 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1688 OpWorkCount[OrigOpNumber] = 0;
1689 NumLeftToConsider--;
1691 // Add if it's a new chain
1692 if (SeenChains.insert(Op).second) {
1693 OpWorkCount[OpNumber]++;
1694 Worklist.push_back(std::make_pair(Op, OpNumber));
1698 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1699 // We need at least be consider at least 2 Ops to prune.
1700 if (NumLeftToConsider <= 1)
1702 auto CurNode = Worklist[i].first;
1703 auto CurOpNumber = Worklist[i].second;
1704 assert((OpWorkCount[CurOpNumber] > 0) &&
1705 "Node should not appear in worklist");
1706 switch (CurNode->getOpcode()) {
1707 case ISD::EntryToken:
1708 // Hitting EntryToken is the only way for the search to terminate without
1710 // another operand's search. Prevent us from marking this operand
1712 NumLeftToConsider++;
1714 case ISD::TokenFactor:
1715 for (const SDValue &Op : CurNode->op_values())
1716 AddToWorklist(i, Op.getNode(), CurOpNumber);
1718 case ISD::CopyFromReg:
1719 case ISD::CopyToReg:
1720 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1723 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1724 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1727 OpWorkCount[CurOpNumber]--;
1728 if (OpWorkCount[CurOpNumber] == 0)
1729 NumLeftToConsider--;
1734 // If we've changed things around then replace token factor.
1737 // The entry token is the only possible outcome.
1738 Result = DAG.getEntryNode();
1741 SmallVector<SDValue, 8> PrunedOps;
1743 for (const SDValue &Op : Ops) {
1744 if (SeenChains.count(Op.getNode()) == 0)
1745 PrunedOps.push_back(Op);
1747 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1749 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1753 // Add users to worklist, since we may introduce a lot of new
1754 // chained token factors while removing memory deps.
1755 return CombineTo(N, Result, true /*add to worklist*/);
1761 /// MERGE_VALUES can always be eliminated.
1762 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1763 WorklistRemover DeadNodes(*this);
1764 // Replacing results may cause a different MERGE_VALUES to suddenly
1765 // be CSE'd with N, and carry its uses with it. Iterate until no
1766 // uses remain, to ensure that the node can be safely deleted.
1767 // First add the users of this node to the work list so that they
1768 // can be tried again once they have new operands.
1769 AddUsersToWorklist(N);
1771 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1772 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1773 } while (!N->use_empty());
1774 deleteAndRecombine(N);
1775 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1778 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1779 /// ConstantSDNode pointer else nullptr.
1780 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1781 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1782 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1785 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1786 auto BinOpcode = BO->getOpcode();
1787 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1788 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1789 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1790 BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1791 BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1792 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1793 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1794 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1795 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1796 "Unexpected binary operator");
1798 // Bail out if any constants are opaque because we can't constant fold those.
1799 SDValue C1 = BO->getOperand(1);
1800 if (!isConstantOrConstantVector(C1, true) &&
1801 !isConstantFPBuildVectorOrConstantFP(C1))
1804 // Don't do this unless the old select is going away. We want to eliminate the
1805 // binary operator, not replace a binop with a select.
1806 // TODO: Handle ISD::SELECT_CC.
1807 SDValue Sel = BO->getOperand(0);
1808 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1811 SDValue CT = Sel.getOperand(1);
1812 if (!isConstantOrConstantVector(CT, true) &&
1813 !isConstantFPBuildVectorOrConstantFP(CT))
1816 SDValue CF = Sel.getOperand(2);
1817 if (!isConstantOrConstantVector(CF, true) &&
1818 !isConstantFPBuildVectorOrConstantFP(CF))
1821 // We have a select-of-constants followed by a binary operator with a
1822 // constant. Eliminate the binop by pulling the constant math into the select.
1823 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1824 EVT VT = Sel.getValueType();
1826 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1827 assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1828 isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1829 "Failed to constant fold a binop with constant operands");
1831 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1832 assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1833 isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1834 "Failed to constant fold a binop with constant operands");
1836 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1839 SDValue DAGCombiner::visitADD(SDNode *N) {
1840 SDValue N0 = N->getOperand(0);
1841 SDValue N1 = N->getOperand(1);
1842 EVT VT = N0.getValueType();
1846 if (VT.isVector()) {
1847 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1850 // fold (add x, 0) -> x, vector edition
1851 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1853 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1857 // fold (add x, undef) -> undef
1864 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1865 // canonicalize constant to RHS
1866 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1867 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1868 // fold (add c1, c2) -> c1+c2
1869 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1873 // fold (add x, 0) -> x
1874 if (isNullConstant(N1))
1877 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1878 // fold ((c1-A)+c2) -> (c1+c2)-A
1879 if (N0.getOpcode() == ISD::SUB &&
1880 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1881 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1882 return DAG.getNode(ISD::SUB, DL, VT,
1883 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1887 // add (sext i1 X), 1 -> zext (not i1 X)
1888 // We don't transform this pattern:
1889 // add (zext i1 X), -1 -> sext (not i1 X)
1890 // because most (?) targets generate better code for the zext form.
1891 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1892 isOneConstantOrOneSplatConstant(N1)) {
1893 SDValue X = N0.getOperand(0);
1894 if ((!LegalOperations ||
1895 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1896 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1897 X.getScalarValueSizeInBits() == 1) {
1898 SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1899 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1904 if (SDValue NewSel = foldBinOpIntoSelect(N))
1908 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1911 // fold ((0-A) + B) -> B-A
1912 if (N0.getOpcode() == ISD::SUB &&
1913 isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1914 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1916 // fold (A + (0-B)) -> A-B
1917 if (N1.getOpcode() == ISD::SUB &&
1918 isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1919 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1921 // fold (A+(B-A)) -> B
1922 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1923 return N1.getOperand(0);
1925 // fold ((B-A)+A) -> B
1926 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1927 return N0.getOperand(0);
1929 // fold (A+(B-(A+C))) to (B-C)
1930 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1931 N0 == N1.getOperand(1).getOperand(0))
1932 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1933 N1.getOperand(1).getOperand(1));
1935 // fold (A+(B-(C+A))) to (B-C)
1936 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1937 N0 == N1.getOperand(1).getOperand(1))
1938 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1939 N1.getOperand(1).getOperand(0));
1941 // fold (A+((B-A)+or-C)) to (B+or-C)
1942 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1943 N1.getOperand(0).getOpcode() == ISD::SUB &&
1944 N0 == N1.getOperand(0).getOperand(1))
1945 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1948 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1949 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1950 SDValue N00 = N0.getOperand(0);
1951 SDValue N01 = N0.getOperand(1);
1952 SDValue N10 = N1.getOperand(0);
1953 SDValue N11 = N1.getOperand(1);
1955 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1956 return DAG.getNode(ISD::SUB, DL, VT,
1957 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1958 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1961 if (SimplifyDemandedBits(SDValue(N, 0)))
1962 return SDValue(N, 0);
1964 // fold (a+b) -> (a|b) iff a and b share no bits.
1965 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1966 VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1967 return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1969 if (SDValue Combined = visitADDLike(N0, N1, N))
1972 if (SDValue Combined = visitADDLike(N1, N0, N))
1978 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
1979 EVT VT = N0.getValueType();
1980 SDLoc DL(LocReference);
1982 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1983 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1984 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1985 return DAG.getNode(ISD::SUB, DL, VT, N0,
1986 DAG.getNode(ISD::SHL, DL, VT,
1987 N1.getOperand(0).getOperand(1),
1990 if (N1.getOpcode() == ISD::AND) {
1991 SDValue AndOp0 = N1.getOperand(0);
1992 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1993 unsigned DestBits = VT.getScalarSizeInBits();
1995 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1996 // and similar xforms where the inner op is either ~0 or 0.
1997 if (NumSignBits == DestBits &&
1998 isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1999 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2002 // add (sext i1), X -> sub X, (zext i1)
2003 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2004 N0.getOperand(0).getValueType() == MVT::i1 &&
2005 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2006 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2007 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2010 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2011 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2012 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2013 if (TN->getVT() == MVT::i1) {
2014 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2015 DAG.getConstant(1, DL, VT));
2016 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2020 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2021 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2022 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2023 N0, N1.getOperand(0), N1.getOperand(2));
2028 SDValue DAGCombiner::visitADDC(SDNode *N) {
2029 SDValue N0 = N->getOperand(0);
2030 SDValue N1 = N->getOperand(1);
2031 EVT VT = N0.getValueType();
2034 // If the flag result is dead, turn this into an ADD.
2035 if (!N->hasAnyUseOfValue(1))
2036 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2037 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2039 // canonicalize constant to RHS.
2040 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2041 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2043 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2045 // fold (addc x, 0) -> x + no carry out
2046 if (isNullConstant(N1))
2047 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2050 // If it cannot overflow, transform into an add.
2051 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2052 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2053 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2058 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2059 SDValue N0 = N->getOperand(0);
2060 SDValue N1 = N->getOperand(1);
2061 EVT VT = N0.getValueType();
2065 EVT CarryVT = N->getValueType(1);
2068 // If the flag result is dead, turn this into an ADD.
2069 if (!N->hasAnyUseOfValue(1))
2070 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2071 DAG.getUNDEF(CarryVT));
2073 // canonicalize constant to RHS.
2074 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2075 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2077 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2079 // fold (uaddo x, 0) -> x + no carry out
2080 if (isNullConstant(N1))
2081 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2083 // If it cannot overflow, transform into an add.
2084 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2085 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2086 DAG.getConstant(0, DL, CarryVT));
2088 if (SDValue Combined = visitUADDOLike(N0, N1, N))
2091 if (SDValue Combined = visitUADDOLike(N1, N0, N))
2097 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2098 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2099 // If Y + 1 cannot overflow.
2100 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2101 SDValue Y = N1.getOperand(0);
2102 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2103 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2104 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2111 SDValue DAGCombiner::visitADDE(SDNode *N) {
2112 SDValue N0 = N->getOperand(0);
2113 SDValue N1 = N->getOperand(1);
2114 SDValue CarryIn = N->getOperand(2);
2116 // canonicalize constant to RHS
2117 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2118 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2120 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2123 // fold (adde x, y, false) -> (addc x, y)
2124 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2125 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2130 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2131 SDValue N0 = N->getOperand(0);
2132 SDValue N1 = N->getOperand(1);
2133 SDValue CarryIn = N->getOperand(2);
2135 // canonicalize constant to RHS
2136 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2137 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2139 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2142 // fold (addcarry x, y, false) -> (uaddo x, y)
2143 if (isNullConstant(CarryIn))
2144 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), N0, N1);
2146 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2149 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2155 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2157 // Iff the flag result is dead:
2158 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2159 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::UADDO) &&
2160 isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2161 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2162 N0.getOperand(0), N0.getOperand(1), CarryIn);
2167 // Since it may not be valid to emit a fold to zero for vector initializers
2168 // check if we can before folding.
2169 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2170 SelectionDAG &DAG, bool LegalOperations,
2173 return DAG.getConstant(0, DL, VT);
2174 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2175 return DAG.getConstant(0, DL, VT);
2179 SDValue DAGCombiner::visitSUB(SDNode *N) {
2180 SDValue N0 = N->getOperand(0);
2181 SDValue N1 = N->getOperand(1);
2182 EVT VT = N0.getValueType();
2186 if (VT.isVector()) {
2187 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2190 // fold (sub x, 0) -> x, vector edition
2191 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2195 // fold (sub x, x) -> 0
2196 // FIXME: Refactor this and xor and other similar operations together.
2198 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2199 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2200 DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2201 // fold (sub c1, c2) -> c1-c2
2202 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2206 if (SDValue NewSel = foldBinOpIntoSelect(N))
2209 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2211 // fold (sub x, c) -> (add x, -c)
2213 return DAG.getNode(ISD::ADD, DL, VT, N0,
2214 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2217 if (isNullConstantOrNullSplatConstant(N0)) {
2218 unsigned BitWidth = VT.getScalarSizeInBits();
2219 // Right-shifting everything out but the sign bit followed by negation is
2220 // the same as flipping arithmetic/logical shift type without the negation:
2221 // -(X >>u 31) -> (X >>s 31)
2222 // -(X >>s 31) -> (X >>u 31)
2223 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2224 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2225 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2226 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2227 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2228 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2232 // 0 - X --> 0 if the sub is NUW.
2233 if (N->getFlags().hasNoUnsignedWrap())
2236 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2237 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2238 // N1 must be 0 because negating the minimum signed value is undefined.
2239 if (N->getFlags().hasNoSignedWrap())
2242 // 0 - X --> X if X is 0 or the minimum signed value.
2247 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2248 if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2249 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2251 // fold A-(A-B) -> B
2252 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2253 return N1.getOperand(1);
2255 // fold (A+B)-A -> B
2256 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2257 return N0.getOperand(1);
2259 // fold (A+B)-B -> A
2260 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2261 return N0.getOperand(0);
2263 // fold C2-(A+C1) -> (C2-C1)-A
2264 if (N1.getOpcode() == ISD::ADD) {
2265 SDValue N11 = N1.getOperand(1);
2266 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2267 isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2268 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2269 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2273 // fold ((A+(B+or-C))-B) -> A+or-C
2274 if (N0.getOpcode() == ISD::ADD &&
2275 (N0.getOperand(1).getOpcode() == ISD::SUB ||
2276 N0.getOperand(1).getOpcode() == ISD::ADD) &&
2277 N0.getOperand(1).getOperand(0) == N1)
2278 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2279 N0.getOperand(1).getOperand(1));
2281 // fold ((A+(C+B))-B) -> A+C
2282 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2283 N0.getOperand(1).getOperand(1) == N1)
2284 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2285 N0.getOperand(1).getOperand(0));
2287 // fold ((A-(B-C))-C) -> A-B
2288 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2289 N0.getOperand(1).getOperand(1) == N1)
2290 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2291 N0.getOperand(1).getOperand(0));
2293 // If either operand of a sub is undef, the result is undef
2299 // If the relocation model supports it, consider symbol offsets.
2300 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2301 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2302 // fold (sub Sym, c) -> Sym-c
2303 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2304 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2306 (uint64_t)N1C->getSExtValue());
2307 // fold (sub Sym+c1, Sym+c2) -> c1-c2
2308 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2309 if (GA->getGlobal() == GB->getGlobal())
2310 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2314 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2315 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2316 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2317 if (TN->getVT() == MVT::i1) {
2318 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2319 DAG.getConstant(1, DL, VT));
2320 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2327 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2328 SDValue N0 = N->getOperand(0);
2329 SDValue N1 = N->getOperand(1);
2330 EVT VT = N0.getValueType();
2333 // If the flag result is dead, turn this into an SUB.
2334 if (!N->hasAnyUseOfValue(1))
2335 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2336 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2338 // fold (subc x, x) -> 0 + no borrow
2340 return CombineTo(N, DAG.getConstant(0, DL, VT),
2341 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2343 // fold (subc x, 0) -> x + no borrow
2344 if (isNullConstant(N1))
2345 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2347 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2348 if (isAllOnesConstant(N0))
2349 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2350 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2355 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2356 SDValue N0 = N->getOperand(0);
2357 SDValue N1 = N->getOperand(1);
2358 EVT VT = N0.getValueType();
2362 EVT CarryVT = N->getValueType(1);
2365 // If the flag result is dead, turn this into an SUB.
2366 if (!N->hasAnyUseOfValue(1))
2367 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2368 DAG.getUNDEF(CarryVT));
2370 // fold (usubo x, x) -> 0 + no borrow
2372 return CombineTo(N, DAG.getConstant(0, DL, VT),
2373 DAG.getConstant(0, DL, CarryVT));
2375 // fold (usubo x, 0) -> x + no borrow
2376 if (isNullConstant(N1))
2377 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2379 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2380 if (isAllOnesConstant(N0))
2381 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2382 DAG.getConstant(0, DL, CarryVT));
2387 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2388 SDValue N0 = N->getOperand(0);
2389 SDValue N1 = N->getOperand(1);
2390 SDValue CarryIn = N->getOperand(2);
2392 // fold (sube x, y, false) -> (subc x, y)
2393 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2394 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2399 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2400 SDValue N0 = N->getOperand(0);
2401 SDValue N1 = N->getOperand(1);
2402 SDValue CarryIn = N->getOperand(2);
2404 // fold (subcarry x, y, false) -> (usubo x, y)
2405 if (isNullConstant(CarryIn))
2406 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2411 SDValue DAGCombiner::visitMUL(SDNode *N) {
2412 SDValue N0 = N->getOperand(0);
2413 SDValue N1 = N->getOperand(1);
2414 EVT VT = N0.getValueType();
2416 // fold (mul x, undef) -> 0
2417 if (N0.isUndef() || N1.isUndef())
2418 return DAG.getConstant(0, SDLoc(N), VT);
2420 bool N0IsConst = false;
2421 bool N1IsConst = false;
2422 bool N1IsOpaqueConst = false;
2423 bool N0IsOpaqueConst = false;
2424 APInt ConstValue0, ConstValue1;
2426 if (VT.isVector()) {
2427 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2430 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2431 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2433 N0IsConst = isa<ConstantSDNode>(N0);
2435 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2436 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2438 N1IsConst = isa<ConstantSDNode>(N1);
2440 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2441 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2445 // fold (mul c1, c2) -> c1*c2
2446 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2447 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2448 N0.getNode(), N1.getNode());
2450 // canonicalize constant to RHS (vector doesn't have to splat)
2451 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2452 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2453 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2454 // fold (mul x, 0) -> 0
2455 if (N1IsConst && ConstValue1 == 0)
2457 // We require a splat of the entire scalar bit width for non-contiguous
2460 ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2461 // fold (mul x, 1) -> x
2462 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2465 if (SDValue NewSel = foldBinOpIntoSelect(N))
2468 // fold (mul x, -1) -> 0-x
2469 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2471 return DAG.getNode(ISD::SUB, DL, VT,
2472 DAG.getConstant(0, DL, VT), N0);
2474 // fold (mul x, (1 << c)) -> x << c
2475 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2478 return DAG.getNode(ISD::SHL, DL, VT, N0,
2479 DAG.getConstant(ConstValue1.logBase2(), DL,
2480 getShiftAmountTy(N0.getValueType())));
2482 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2483 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2485 unsigned Log2Val = (-ConstValue1).logBase2();
2487 // FIXME: If the input is something that is easily negated (e.g. a
2488 // single-use add), we should put the negate there.
2489 return DAG.getNode(ISD::SUB, DL, VT,
2490 DAG.getConstant(0, DL, VT),
2491 DAG.getNode(ISD::SHL, DL, VT, N0,
2492 DAG.getConstant(Log2Val, DL,
2493 getShiftAmountTy(N0.getValueType()))));
2496 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2497 if (N0.getOpcode() == ISD::SHL &&
2498 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2499 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2500 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2501 if (isConstantOrConstantVector(C3))
2502 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2505 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2508 SDValue Sh(nullptr, 0), Y(nullptr, 0);
2510 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2511 if (N0.getOpcode() == ISD::SHL &&
2512 isConstantOrConstantVector(N0.getOperand(1)) &&
2513 N0.getNode()->hasOneUse()) {
2515 } else if (N1.getOpcode() == ISD::SHL &&
2516 isConstantOrConstantVector(N1.getOperand(1)) &&
2517 N1.getNode()->hasOneUse()) {
2522 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2523 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2527 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2528 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2529 N0.getOpcode() == ISD::ADD &&
2530 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2531 isMulAddWithConstProfitable(N, N0, N1))
2532 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2533 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2534 N0.getOperand(0), N1),
2535 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2536 N0.getOperand(1), N1));
2539 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2545 /// Return true if divmod libcall is available.
2546 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2547 const TargetLowering &TLI) {
2549 EVT NodeType = Node->getValueType(0);
2550 if (!NodeType.isSimple())
2552 switch (NodeType.getSimpleVT().SimpleTy) {
2553 default: return false; // No libcall for vector types.
2554 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2555 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2556 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2557 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2558 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2561 return TLI.getLibcallName(LC) != nullptr;
2564 /// Issue divrem if both quotient and remainder are needed.
2565 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2566 if (Node->use_empty())
2567 return SDValue(); // This is a dead node, leave it alone.
2569 unsigned Opcode = Node->getOpcode();
2570 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2571 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2573 // DivMod lib calls can still work on non-legal types if using lib-calls.
2574 EVT VT = Node->getValueType(0);
2575 if (VT.isVector() || !VT.isInteger())
2578 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2581 // If DIVREM is going to get expanded into a libcall,
2582 // but there is no libcall available, then don't combine.
2583 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2584 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2587 // If div is legal, it's better to do the normal expansion
2588 unsigned OtherOpcode = 0;
2589 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2590 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2591 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2594 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2595 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2599 SDValue Op0 = Node->getOperand(0);
2600 SDValue Op1 = Node->getOperand(1);
2602 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2603 UE = Op0.getNode()->use_end(); UI != UE;) {
2604 SDNode *User = *UI++;
2605 if (User == Node || User->use_empty())
2607 // Convert the other matching node(s), too;
2608 // otherwise, the DIVREM may get target-legalized into something
2609 // target-specific that we won't be able to recognize.
2610 unsigned UserOpc = User->getOpcode();
2611 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2612 User->getOperand(0) == Op0 &&
2613 User->getOperand(1) == Op1) {
2615 if (UserOpc == OtherOpcode) {
2616 SDVTList VTs = DAG.getVTList(VT, VT);
2617 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2618 } else if (UserOpc == DivRemOpc) {
2619 combined = SDValue(User, 0);
2621 assert(UserOpc == Opcode);
2625 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2626 CombineTo(User, combined);
2627 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2628 CombineTo(User, combined.getValue(1));
2634 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2635 SDValue N0 = N->getOperand(0);
2636 SDValue N1 = N->getOperand(1);
2637 EVT VT = N->getValueType(0);
2640 if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2641 return DAG.getUNDEF(VT);
2646 return DAG.getConstant(0, DL, VT);
2651 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2652 SDValue N0 = N->getOperand(0);
2653 SDValue N1 = N->getOperand(1);
2654 EVT VT = N->getValueType(0);
2658 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2663 // fold (sdiv c1, c2) -> c1/c2
2664 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2665 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2666 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2667 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2668 // fold (sdiv X, 1) -> X
2669 if (N1C && N1C->isOne())
2671 // fold (sdiv X, -1) -> 0-X
2672 if (N1C && N1C->isAllOnesValue())
2673 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2675 if (SDValue V = simplifyDivRem(N, DAG))
2678 if (SDValue NewSel = foldBinOpIntoSelect(N))
2681 // If we know the sign bits of both operands are zero, strength reduce to a
2682 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2683 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2684 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2686 // fold (sdiv X, pow2) -> simple ops after legalize
2687 // FIXME: We check for the exact bit here because the generic lowering gives
2688 // better results in that case. The target-specific lowering should learn how
2689 // to handle exact sdivs efficiently.
2690 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2691 !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2692 (-N1C->getAPIntValue()).isPowerOf2())) {
2693 // Target-specific implementation of sdiv x, pow2.
2694 if (SDValue Res = BuildSDIVPow2(N))
2697 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2699 // Splat the sign bit into the register
2701 DAG.getNode(ISD::SRA, DL, VT, N0,
2702 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2703 getShiftAmountTy(N0.getValueType())));
2704 AddToWorklist(SGN.getNode());
2706 // Add (N0 < 0) ? abs2 - 1 : 0;
2708 DAG.getNode(ISD::SRL, DL, VT, SGN,
2709 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2710 getShiftAmountTy(SGN.getValueType())));
2711 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2712 AddToWorklist(SRL.getNode());
2713 AddToWorklist(ADD.getNode()); // Divide by pow2
2714 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2715 DAG.getConstant(lg2, DL,
2716 getShiftAmountTy(ADD.getValueType())));
2718 // If we're dividing by a positive value, we're done. Otherwise, we must
2719 // negate the result.
2720 if (N1C->getAPIntValue().isNonNegative())
2723 AddToWorklist(SRA.getNode());
2724 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2727 // If integer divide is expensive and we satisfy the requirements, emit an
2728 // alternate sequence. Targets may check function attributes for size/speed
2730 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2731 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2732 if (SDValue Op = BuildSDIV(N))
2735 // sdiv, srem -> sdivrem
2736 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2737 // true. Otherwise, we break the simplification logic in visitREM().
2738 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2739 if (SDValue DivRem = useDivRem(N))
2745 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2746 SDValue N0 = N->getOperand(0);
2747 SDValue N1 = N->getOperand(1);
2748 EVT VT = N->getValueType(0);
2752 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2757 // fold (udiv c1, c2) -> c1/c2
2758 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2759 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2761 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2765 if (SDValue V = simplifyDivRem(N, DAG))
2768 if (SDValue NewSel = foldBinOpIntoSelect(N))
2771 // fold (udiv x, (1 << c)) -> x >>u c
2772 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2773 DAG.isKnownToBeAPowerOfTwo(N1)) {
2774 SDValue LogBase2 = BuildLogBase2(N1, DL);
2775 AddToWorklist(LogBase2.getNode());
2777 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2778 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2779 AddToWorklist(Trunc.getNode());
2780 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2783 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2784 if (N1.getOpcode() == ISD::SHL) {
2785 SDValue N10 = N1.getOperand(0);
2786 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2787 DAG.isKnownToBeAPowerOfTwo(N10)) {
2788 SDValue LogBase2 = BuildLogBase2(N10, DL);
2789 AddToWorklist(LogBase2.getNode());
2791 EVT ADDVT = N1.getOperand(1).getValueType();
2792 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2793 AddToWorklist(Trunc.getNode());
2794 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2795 AddToWorklist(Add.getNode());
2796 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2800 // fold (udiv x, c) -> alternate
2801 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2802 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2803 if (SDValue Op = BuildUDIV(N))
2806 // sdiv, srem -> sdivrem
2807 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2808 // true. Otherwise, we break the simplification logic in visitREM().
2809 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2810 if (SDValue DivRem = useDivRem(N))
2816 // handles ISD::SREM and ISD::UREM
2817 SDValue DAGCombiner::visitREM(SDNode *N) {
2818 unsigned Opcode = N->getOpcode();
2819 SDValue N0 = N->getOperand(0);
2820 SDValue N1 = N->getOperand(1);
2821 EVT VT = N->getValueType(0);
2822 bool isSigned = (Opcode == ISD::SREM);
2825 // fold (rem c1, c2) -> c1%c2
2826 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2827 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2829 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2832 if (SDValue V = simplifyDivRem(N, DAG))
2835 if (SDValue NewSel = foldBinOpIntoSelect(N))
2839 // If we know the sign bits of both operands are zero, strength reduce to a
2840 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2841 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2842 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2844 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2845 if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2846 // fold (urem x, pow2) -> (and x, pow2-1)
2847 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2848 AddToWorklist(Add.getNode());
2849 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2851 if (N1.getOpcode() == ISD::SHL &&
2852 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2853 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2854 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2855 AddToWorklist(Add.getNode());
2856 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2860 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2862 // If X/C can be simplified by the division-by-constant logic, lower
2863 // X%C to the equivalent of X-X/C*C.
2864 // To avoid mangling nodes, this simplification requires that the combine()
2865 // call for the speculative DIV must not cause a DIVREM conversion. We guard
2866 // against this by skipping the simplification if isIntDivCheap(). When
2867 // div is not cheap, combine will not return a DIVREM. Regardless,
2868 // checking cheapness here makes sense since the simplification results in
2870 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2871 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2872 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2873 AddToWorklist(Div.getNode());
2874 SDValue OptimizedDiv = combine(Div.getNode());
2875 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2876 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2877 (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2878 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2879 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2880 AddToWorklist(Mul.getNode());
2885 // sdiv, srem -> sdivrem
2886 if (SDValue DivRem = useDivRem(N))
2887 return DivRem.getValue(1);
2892 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2893 SDValue N0 = N->getOperand(0);
2894 SDValue N1 = N->getOperand(1);
2895 EVT VT = N->getValueType(0);
2898 // fold (mulhs x, 0) -> 0
2899 if (isNullConstant(N1))
2901 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2902 if (isOneConstant(N1)) {
2904 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2905 DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2906 getShiftAmountTy(N0.getValueType())));
2908 // fold (mulhs x, undef) -> 0
2909 if (N0.isUndef() || N1.isUndef())
2910 return DAG.getConstant(0, SDLoc(N), VT);
2912 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2914 if (VT.isSimple() && !VT.isVector()) {
2915 MVT Simple = VT.getSimpleVT();
2916 unsigned SimpleSize = Simple.getSizeInBits();
2917 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2918 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2919 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2920 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2921 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2922 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2923 DAG.getConstant(SimpleSize, DL,
2924 getShiftAmountTy(N1.getValueType())));
2925 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2932 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2933 SDValue N0 = N->getOperand(0);
2934 SDValue N1 = N->getOperand(1);
2935 EVT VT = N->getValueType(0);
2938 // fold (mulhu x, 0) -> 0
2939 if (isNullConstant(N1))
2941 // fold (mulhu x, 1) -> 0
2942 if (isOneConstant(N1))
2943 return DAG.getConstant(0, DL, N0.getValueType());
2944 // fold (mulhu x, undef) -> 0
2945 if (N0.isUndef() || N1.isUndef())
2946 return DAG.getConstant(0, DL, VT);
2948 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2950 if (VT.isSimple() && !VT.isVector()) {
2951 MVT Simple = VT.getSimpleVT();
2952 unsigned SimpleSize = Simple.getSizeInBits();
2953 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2954 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2955 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2956 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2957 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2958 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2959 DAG.getConstant(SimpleSize, DL,
2960 getShiftAmountTy(N1.getValueType())));
2961 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2968 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2969 /// give the opcodes for the two computations that are being performed. Return
2970 /// true if a simplification was made.
2971 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2973 // If the high half is not needed, just compute the low half.
2974 bool HiExists = N->hasAnyUseOfValue(1);
2976 (!LegalOperations ||
2977 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2978 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2979 return CombineTo(N, Res, Res);
2982 // If the low half is not needed, just compute the high half.
2983 bool LoExists = N->hasAnyUseOfValue(0);
2985 (!LegalOperations ||
2986 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2987 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2988 return CombineTo(N, Res, Res);
2991 // If both halves are used, return as it is.
2992 if (LoExists && HiExists)
2995 // If the two computed results can be simplified separately, separate them.
2997 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2998 AddToWorklist(Lo.getNode());
2999 SDValue LoOpt = combine(Lo.getNode());
3000 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3001 (!LegalOperations ||
3002 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3003 return CombineTo(N, LoOpt, LoOpt);
3007 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3008 AddToWorklist(Hi.getNode());
3009 SDValue HiOpt = combine(Hi.getNode());
3010 if (HiOpt.getNode() && HiOpt != Hi &&
3011 (!LegalOperations ||
3012 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3013 return CombineTo(N, HiOpt, HiOpt);
3019 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3020 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3023 EVT VT = N->getValueType(0);
3026 // If the type is twice as wide is legal, transform the mulhu to a wider
3027 // multiply plus a shift.
3028 if (VT.isSimple() && !VT.isVector()) {
3029 MVT Simple = VT.getSimpleVT();
3030 unsigned SimpleSize = Simple.getSizeInBits();
3031 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3032 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3033 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3034 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3035 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3036 // Compute the high part as N1.
3037 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3038 DAG.getConstant(SimpleSize, DL,
3039 getShiftAmountTy(Lo.getValueType())));
3040 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3041 // Compute the low part as N0.
3042 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3043 return CombineTo(N, Lo, Hi);
3050 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3051 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3054 EVT VT = N->getValueType(0);
3057 // If the type is twice as wide is legal, transform the mulhu to a wider
3058 // multiply plus a shift.
3059 if (VT.isSimple() && !VT.isVector()) {
3060 MVT Simple = VT.getSimpleVT();
3061 unsigned SimpleSize = Simple.getSizeInBits();
3062 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3063 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3064 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3065 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3066 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3067 // Compute the high part as N1.
3068 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3069 DAG.getConstant(SimpleSize, DL,
3070 getShiftAmountTy(Lo.getValueType())));
3071 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3072 // Compute the low part as N0.
3073 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3074 return CombineTo(N, Lo, Hi);
3081 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3082 // (smulo x, 2) -> (saddo x, x)
3083 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3084 if (C2->getAPIntValue() == 2)
3085 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3086 N->getOperand(0), N->getOperand(0));
3091 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3092 // (umulo x, 2) -> (uaddo x, x)
3093 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3094 if (C2->getAPIntValue() == 2)
3095 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3096 N->getOperand(0), N->getOperand(0));
3101 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3102 SDValue N0 = N->getOperand(0);
3103 SDValue N1 = N->getOperand(1);
3104 EVT VT = N0.getValueType();
3108 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3111 // fold (add c1, c2) -> c1+c2
3112 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3113 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3115 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3117 // canonicalize constant to RHS
3118 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3119 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3120 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3125 /// If this is a binary operator with two operands of the same opcode, try to
3127 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3128 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3129 EVT VT = N0.getValueType();
3130 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3132 // Bail early if none of these transforms apply.
3133 if (N0.getNumOperands() == 0) return SDValue();
3135 // For each of OP in AND/OR/XOR:
3136 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3137 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3138 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3139 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3140 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3142 // do not sink logical op inside of a vector extend, since it may combine
3144 EVT Op0VT = N0.getOperand(0).getValueType();
3145 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3146 N0.getOpcode() == ISD::SIGN_EXTEND ||
3147 N0.getOpcode() == ISD::BSWAP ||
3148 // Avoid infinite looping with PromoteIntBinOp.
3149 (N0.getOpcode() == ISD::ANY_EXTEND &&
3150 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3151 (N0.getOpcode() == ISD::TRUNCATE &&
3152 (!TLI.isZExtFree(VT, Op0VT) ||
3153 !TLI.isTruncateFree(Op0VT, VT)) &&
3154 TLI.isTypeLegal(Op0VT))) &&
3156 Op0VT == N1.getOperand(0).getValueType() &&
3157 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3158 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3159 N0.getOperand(0).getValueType(),
3160 N0.getOperand(0), N1.getOperand(0));
3161 AddToWorklist(ORNode.getNode());
3162 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3165 // For each of OP in SHL/SRL/SRA/AND...
3166 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3167 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
3168 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3169 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3170 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3171 N0.getOperand(1) == N1.getOperand(1)) {
3172 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3173 N0.getOperand(0).getValueType(),
3174 N0.getOperand(0), N1.getOperand(0));
3175 AddToWorklist(ORNode.getNode());
3176 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3177 ORNode, N0.getOperand(1));
3180 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3181 // Only perform this optimization up until type legalization, before
3182 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3183 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3184 // we don't want to undo this promotion.
3185 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3187 if ((N0.getOpcode() == ISD::BITCAST ||
3188 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3189 Level <= AfterLegalizeTypes) {
3190 SDValue In0 = N0.getOperand(0);
3191 SDValue In1 = N1.getOperand(0);
3192 EVT In0Ty = In0.getValueType();
3193 EVT In1Ty = In1.getValueType();
3195 // If both incoming values are integers, and the original types are the
3197 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3198 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3199 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3200 AddToWorklist(Op.getNode());
3205 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3206 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3207 // If both shuffles use the same mask, and both shuffle within a single
3208 // vector, then it is worthwhile to move the swizzle after the operation.
3209 // The type-legalizer generates this pattern when loading illegal
3210 // vector types from memory. In many cases this allows additional shuffle
3212 // There are other cases where moving the shuffle after the xor/and/or
3213 // is profitable even if shuffles don't perform a swizzle.
3214 // If both shuffles use the same mask, and both shuffles have the same first
3215 // or second operand, then it might still be profitable to move the shuffle
3216 // after the xor/and/or operation.
3217 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3218 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3219 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3221 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3222 "Inputs to shuffles are not the same type");
3224 // Check that both shuffles use the same mask. The masks are known to be of
3225 // the same length because the result vector type is the same.
3226 // Check also that shuffles have only one use to avoid introducing extra
3228 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3229 SVN0->getMask().equals(SVN1->getMask())) {
3230 SDValue ShOp = N0->getOperand(1);
3232 // Don't try to fold this node if it requires introducing a
3233 // build vector of all zeros that might be illegal at this stage.
3234 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3236 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3241 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3242 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
3243 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3244 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3245 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3246 N0->getOperand(0), N1->getOperand(0));
3247 AddToWorklist(NewNode.getNode());
3248 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3252 // Don't try to fold this node if it requires introducing a
3253 // build vector of all zeros that might be illegal at this stage.
3254 ShOp = N0->getOperand(0);
3255 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3257 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3262 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3263 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
3264 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3265 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3266 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3267 N0->getOperand(1), N1->getOperand(1));
3268 AddToWorklist(NewNode.getNode());
3269 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3278 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3279 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3281 SDValue LL, LR, RL, RR, N0CC, N1CC;
3282 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3283 !isSetCCEquivalent(N1, RL, RR, N1CC))
3286 assert(N0.getValueType() == N1.getValueType() &&
3287 "Unexpected operand types for bitwise logic op");
3288 assert(LL.getValueType() == LR.getValueType() &&
3289 RL.getValueType() == RR.getValueType() &&
3290 "Unexpected operand types for setcc");
3292 // If we're here post-legalization or the logic op type is not i1, the logic
3293 // op type must match a setcc result type. Also, all folds require new
3294 // operations on the left and right operands, so those types must match.
3295 EVT VT = N0.getValueType();
3296 EVT OpVT = LL.getValueType();
3297 if (LegalOperations || VT != MVT::i1)
3298 if (VT != getSetCCResultType(OpVT))
3300 if (OpVT != RL.getValueType())
3303 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3304 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3305 bool IsInteger = OpVT.isInteger();
3306 if (LR == RR && CC0 == CC1 && IsInteger) {
3307 bool IsZero = isNullConstantOrNullSplatConstant(LR);
3308 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3311 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3312 // All sign bits clear?
3313 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3315 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3316 // Any sign bits set?
3317 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3319 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
3320 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3321 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
3322 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
3323 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3324 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3325 AddToWorklist(Or.getNode());
3326 return DAG.getSetCC(DL, VT, Or, LR, CC1);
3330 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3331 // All sign bits set?
3332 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3334 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3335 // Any sign bits clear?
3336 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3338 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3339 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
3340 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3341 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
3342 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3343 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3344 AddToWorklist(And.getNode());
3345 return DAG.getSetCC(DL, VT, And, LR, CC1);
3349 // TODO: What is the 'or' equivalent of this fold?
3350 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3351 if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3352 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3353 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3354 SDValue One = DAG.getConstant(1, DL, OpVT);
3355 SDValue Two = DAG.getConstant(2, DL, OpVT);
3356 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3357 AddToWorklist(Add.getNode());
3358 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3361 // Try more general transforms if the predicates match and the only user of
3362 // the compares is the 'and' or 'or'.
3363 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3364 N0.hasOneUse() && N1.hasOneUse()) {
3365 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3366 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3367 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3368 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3369 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3370 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3371 SDValue Zero = DAG.getConstant(0, DL, OpVT);
3372 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3376 // Canonicalize equivalent operands to LL == RL.
3377 if (LL == RR && LR == RL) {
3378 CC1 = ISD::getSetCCSwappedOperands(CC1);
3382 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3383 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3384 if (LL == RL && LR == RR) {
3385 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3386 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3387 if (NewCC != ISD::SETCC_INVALID &&
3388 (!LegalOperations ||
3389 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3390 TLI.isOperationLegal(ISD::SETCC, OpVT))))
3391 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3397 /// This contains all DAGCombine rules which reduce two values combined by
3398 /// an And operation to a single value. This makes them reusable in the context
3399 /// of visitSELECT(). Rules involving constants are not included as
3400 /// visitSELECT() already handles those cases.
3401 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3402 EVT VT = N1.getValueType();
3405 // fold (and x, undef) -> 0
3406 if (N0.isUndef() || N1.isUndef())
3407 return DAG.getConstant(0, DL, VT);
3409 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3412 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3413 VT.getSizeInBits() <= 64) {
3414 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3415 APInt ADDC = ADDI->getAPIntValue();
3416 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3417 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3418 // immediate for an add, but it is legal if its top c2 bits are set,
3419 // transform the ADD so the immediate doesn't need to be materialized
3421 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3422 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3423 SRLI->getZExtValue());
3424 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3426 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3429 DAG.getNode(ISD::ADD, DL0, VT,
3430 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3431 CombineTo(N0.getNode(), NewAdd);
3432 // Return N so it doesn't get rechecked!
3433 return SDValue(N, 0);
3441 // Reduce bit extract of low half of an integer to the narrower type.
3442 // (and (srl i64:x, K), KMask) ->
3443 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3444 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3445 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3446 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3447 unsigned Size = VT.getSizeInBits();
3448 const APInt &AndMask = CAnd->getAPIntValue();
3449 unsigned ShiftBits = CShift->getZExtValue();
3451 // Bail out, this node will probably disappear anyway.
3455 unsigned MaskBits = AndMask.countTrailingOnes();
3456 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3458 if (AndMask.isMask() &&
3459 // Required bits must not span the two halves of the integer and
3460 // must fit in the half size type.
3461 (ShiftBits + MaskBits <= Size / 2) &&
3462 TLI.isNarrowingProfitable(VT, HalfVT) &&
3463 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3464 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3465 TLI.isTruncateFree(VT, HalfVT) &&
3466 TLI.isZExtFree(HalfVT, VT)) {
3467 // The isNarrowingProfitable is to avoid regressions on PPC and
3468 // AArch64 which match a few 64-bit bit insert / bit extract patterns
3469 // on downstream users of this. Those patterns could probably be
3470 // extended to handle extensions mixed in.
3473 assert(MaskBits <= Size);
3475 // Extracting the highest bit of the low half.
3476 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3477 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3480 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3481 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3482 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3483 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3484 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3493 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3494 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3496 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3498 if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3501 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3502 LoadedVT = LoadN->getMemoryVT();
3504 if (ExtVT == LoadedVT &&
3505 (!LegalOperations ||
3506 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3507 // ZEXTLOAD will match without needing to change the size of the value being
3513 // Do not change the width of a volatile load.
3514 if (LoadN->isVolatile())
3517 // Do not generate loads of non-round integer types since these can
3518 // be expensive (and would be wrong if the type is not byte sized).
3519 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3522 if (LegalOperations &&
3523 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3526 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3533 SDValue DAGCombiner::visitAND(SDNode *N) {
3534 SDValue N0 = N->getOperand(0);
3535 SDValue N1 = N->getOperand(1);
3536 EVT VT = N1.getValueType();
3543 if (VT.isVector()) {
3544 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3547 // fold (and x, 0) -> 0, vector edition
3548 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3549 // do not return N0, because undef node may exist in N0
3550 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3551 SDLoc(N), N0.getValueType());
3552 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3553 // do not return N1, because undef node may exist in N1
3554 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3555 SDLoc(N), N1.getValueType());
3557 // fold (and x, -1) -> x, vector edition
3558 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3560 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3564 // fold (and c1, c2) -> c1&c2
3565 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3566 ConstantSDNode *N1C = isConstOrConstSplat(N1);
3567 if (N0C && N1C && !N1C->isOpaque())
3568 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3569 // canonicalize constant to RHS
3570 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3571 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3572 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3573 // fold (and x, -1) -> x
3574 if (isAllOnesConstant(N1))
3576 // if (and x, c) is known to be zero, return 0
3577 unsigned BitWidth = VT.getScalarSizeInBits();
3578 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3579 APInt::getAllOnesValue(BitWidth)))
3580 return DAG.getConstant(0, SDLoc(N), VT);
3582 if (SDValue NewSel = foldBinOpIntoSelect(N))
3586 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3588 // fold (and (or x, C), D) -> D if (C & D) == D
3589 if (N1C && N0.getOpcode() == ISD::OR)
3590 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3591 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3593 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3594 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3595 SDValue N0Op0 = N0.getOperand(0);
3596 APInt Mask = ~N1C->getAPIntValue();
3597 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3598 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3599 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3600 N0.getValueType(), N0Op0);
3602 // Replace uses of the AND with uses of the Zero extend node.
3605 // We actually want to replace all uses of the any_extend with the
3606 // zero_extend, to avoid duplicating things. This will later cause this
3607 // AND to be folded.
3608 CombineTo(N0.getNode(), Zext);
3609 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3612 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3613 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3614 // already be zero by virtue of the width of the base type of the load.
3616 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3618 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3619 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3620 N0.getOperand(0).getOpcode() == ISD::LOAD &&
3621 N0.getOperand(0).getResNo() == 0) ||
3622 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3623 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3624 N0 : N0.getOperand(0) );
3626 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3627 // This can be a pure constant or a vector splat, in which case we treat the
3628 // vector as a scalar and use the splat value.
3629 APInt Constant = APInt::getNullValue(1);
3630 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3631 Constant = C->getAPIntValue();
3632 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3633 APInt SplatValue, SplatUndef;
3634 unsigned SplatBitSize;
3636 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3637 SplatBitSize, HasAnyUndefs);
3639 // Undef bits can contribute to a possible optimisation if set, so
3641 SplatValue |= SplatUndef;
3643 // The splat value may be something like "0x00FFFFFF", which means 0 for
3644 // the first vector value and FF for the rest, repeating. We need a mask
3645 // that will apply equally to all members of the vector, so AND all the
3646 // lanes of the constant together.
3647 EVT VT = Vector->getValueType(0);
3648 unsigned BitWidth = VT.getScalarSizeInBits();
3650 // If the splat value has been compressed to a bitlength lower
3651 // than the size of the vector lane, we need to re-expand it to
3653 if (BitWidth > SplatBitSize)
3654 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3655 SplatBitSize < BitWidth;
3656 SplatBitSize = SplatBitSize * 2)
3657 SplatValue |= SplatValue.shl(SplatBitSize);
3659 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3660 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3661 if (SplatBitSize % BitWidth == 0) {
3662 Constant = APInt::getAllOnesValue(BitWidth);
3663 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3664 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3669 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3670 // actually legal and isn't going to get expanded, else this is a false
3672 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3673 Load->getValueType(0),
3674 Load->getMemoryVT());
3676 // Resize the constant to the same size as the original memory access before
3677 // extension. If it is still the AllOnesValue then this AND is completely
3679 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3682 switch (Load->getExtensionType()) {
3683 default: B = false; break;
3684 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3686 case ISD::NON_EXTLOAD: B = true; break;
3689 if (B && Constant.isAllOnesValue()) {
3690 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3691 // preserve semantics once we get rid of the AND.
3692 SDValue NewLoad(Load, 0);
3694 // Fold the AND away. NewLoad may get replaced immediately.
3695 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3697 if (Load->getExtensionType() == ISD::EXTLOAD) {
3698 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3699 Load->getValueType(0), SDLoc(Load),
3700 Load->getChain(), Load->getBasePtr(),
3701 Load->getOffset(), Load->getMemoryVT(),
3702 Load->getMemOperand());
3703 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3704 if (Load->getNumValues() == 3) {
3705 // PRE/POST_INC loads have 3 values.
3706 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3707 NewLoad.getValue(2) };
3708 CombineTo(Load, To, 3, true);
3710 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3714 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3718 // fold (and (load x), 255) -> (zextload x, i8)
3719 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3720 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3721 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3722 (N0.getOpcode() == ISD::ANY_EXTEND &&
3723 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3724 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3725 LoadSDNode *LN0 = HasAnyExt
3726 ? cast<LoadSDNode>(N0.getOperand(0))
3727 : cast<LoadSDNode>(N0);
3728 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3729 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3730 auto NarrowLoad = false;
3731 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3732 EVT ExtVT, LoadedVT;
3733 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3737 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3738 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3739 LN0->getMemOperand());
3741 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3742 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3744 EVT PtrType = LN0->getOperand(1).getValueType();
3746 unsigned Alignment = LN0->getAlignment();
3747 SDValue NewPtr = LN0->getBasePtr();
3749 // For big endian targets, we need to add an offset to the pointer
3750 // to load the correct bytes. For little endian systems, we merely
3751 // need to read fewer bytes from the same pointer.
3752 if (DAG.getDataLayout().isBigEndian()) {
3753 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3754 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3755 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3757 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3758 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3759 Alignment = MinAlign(Alignment, PtrOff);
3762 AddToWorklist(NewPtr.getNode());
3764 SDValue Load = DAG.getExtLoad(
3765 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3766 LN0->getPointerInfo(), ExtVT, Alignment,
3767 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3769 CombineTo(LN0, Load, Load.getValue(1));
3770 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3776 if (SDValue Combined = visitANDLike(N0, N1, N))
3779 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3780 if (N0.getOpcode() == N1.getOpcode())
3781 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3784 // Masking the negated extension of a boolean is just the zero-extended
3786 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3787 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3789 // Note: the SimplifyDemandedBits fold below can make an information-losing
3790 // transform, and then we have no way to find this better fold.
3791 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3792 ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3793 SDValue SubRHS = N0.getOperand(1);
3794 if (SubLHS && SubLHS->isNullValue()) {
3795 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3796 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3798 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3799 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3800 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3804 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3805 // fold (and (sra)) -> (and (srl)) when possible.
3806 if (SimplifyDemandedBits(SDValue(N, 0)))
3807 return SDValue(N, 0);
3809 // fold (zext_inreg (extload x)) -> (zextload x)
3810 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3811 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3812 EVT MemVT = LN0->getMemoryVT();
3813 // If we zero all the possible extended bits, then we can turn this into
3814 // a zextload if we are running before legalize or the operation is legal.
3815 unsigned BitWidth = N1.getScalarValueSizeInBits();
3816 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3817 BitWidth - MemVT.getScalarSizeInBits())) &&
3818 ((!LegalOperations && !LN0->isVolatile()) ||
3819 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3820 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3821 LN0->getChain(), LN0->getBasePtr(),
3822 MemVT, LN0->getMemOperand());
3824 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3825 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3828 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3829 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3831 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3832 EVT MemVT = LN0->getMemoryVT();
3833 // If we zero all the possible extended bits, then we can turn this into
3834 // a zextload if we are running before legalize or the operation is legal.
3835 unsigned BitWidth = N1.getScalarValueSizeInBits();
3836 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3837 BitWidth - MemVT.getScalarSizeInBits())) &&
3838 ((!LegalOperations && !LN0->isVolatile()) ||
3839 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3840 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3841 LN0->getChain(), LN0->getBasePtr(),
3842 MemVT, LN0->getMemOperand());
3844 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3845 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3848 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3849 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3850 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3851 N0.getOperand(1), false))
3858 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3859 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3860 bool DemandHighBits) {
3861 if (!LegalOperations)
3864 EVT VT = N->getValueType(0);
3865 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3867 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
3870 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3871 bool LookPassAnd0 = false;
3872 bool LookPassAnd1 = false;
3873 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3875 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3877 if (N0.getOpcode() == ISD::AND) {
3878 if (!N0.getNode()->hasOneUse())
3880 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3881 if (!N01C || N01C->getZExtValue() != 0xFF00)
3883 N0 = N0.getOperand(0);
3884 LookPassAnd0 = true;
3887 if (N1.getOpcode() == ISD::AND) {
3888 if (!N1.getNode()->hasOneUse())
3890 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3891 if (!N11C || N11C->getZExtValue() != 0xFF)
3893 N1 = N1.getOperand(0);
3894 LookPassAnd1 = true;
3897 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3899 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3901 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3904 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3905 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3908 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3911 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3912 SDValue N00 = N0->getOperand(0);
3913 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3914 if (!N00.getNode()->hasOneUse())
3916 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3917 if (!N001C || N001C->getZExtValue() != 0xFF)
3919 N00 = N00.getOperand(0);
3920 LookPassAnd0 = true;
3923 SDValue N10 = N1->getOperand(0);
3924 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3925 if (!N10.getNode()->hasOneUse())
3927 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3928 if (!N101C || N101C->getZExtValue() != 0xFF00)
3930 N10 = N10.getOperand(0);
3931 LookPassAnd1 = true;
3937 // Make sure everything beyond the low halfword gets set to zero since the SRL
3938 // 16 will clear the top bits.
3939 unsigned OpSizeInBits = VT.getSizeInBits();
3940 if (DemandHighBits && OpSizeInBits > 16) {
3941 // If the left-shift isn't masked out then the only way this is a bswap is
3942 // if all bits beyond the low 8 are 0. In that case the entire pattern
3943 // reduces to a left shift anyway: leave it for other parts of the combiner.
3947 // However, if the right shift isn't masked out then it might be because
3948 // it's not needed. See if we can spot that too.
3949 if (!LookPassAnd1 &&
3950 !DAG.MaskedValueIsZero(
3951 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3955 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3956 if (OpSizeInBits > 16) {
3958 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3959 DAG.getConstant(OpSizeInBits - 16, DL,
3960 getShiftAmountTy(VT)));
3965 /// Return true if the specified node is an element that makes up a 32-bit
3966 /// packed halfword byteswap.
3967 /// ((x & 0x000000ff) << 8) |
3968 /// ((x & 0x0000ff00) >> 8) |
3969 /// ((x & 0x00ff0000) << 8) |
3970 /// ((x & 0xff000000) >> 8)
3971 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3972 if (!N.getNode()->hasOneUse())
3975 unsigned Opc = N.getOpcode();
3976 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3979 SDValue N0 = N.getOperand(0);
3980 unsigned Opc0 = N0.getOpcode();
3981 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
3984 ConstantSDNode *N1C = nullptr;
3985 // SHL or SRL: look upstream for AND mask operand
3986 if (Opc == ISD::AND)
3987 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3988 else if (Opc0 == ISD::AND)
3989 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3993 unsigned MaskByteOffset;
3994 switch (N1C->getZExtValue()) {
3997 case 0xFF: MaskByteOffset = 0; break;
3998 case 0xFF00: MaskByteOffset = 1; break;
3999 case 0xFF0000: MaskByteOffset = 2; break;
4000 case 0xFF000000: MaskByteOffset = 3; break;
4003 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4004 if (Opc == ISD::AND) {
4005 if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4007 // (x >> 8) & 0xff0000
4008 if (Opc0 != ISD::SRL)
4010 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4011 if (!C || C->getZExtValue() != 8)
4014 // (x << 8) & 0xff00
4015 // (x << 8) & 0xff000000
4016 if (Opc0 != ISD::SHL)
4018 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4019 if (!C || C->getZExtValue() != 8)
4022 } else if (Opc == ISD::SHL) {
4024 // (x & 0xff0000) << 8
4025 if (MaskByteOffset != 0 && MaskByteOffset != 2)
4027 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4028 if (!C || C->getZExtValue() != 8)
4030 } else { // Opc == ISD::SRL
4031 // (x & 0xff00) >> 8
4032 // (x & 0xff000000) >> 8
4033 if (MaskByteOffset != 1 && MaskByteOffset != 3)
4035 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4036 if (!C || C->getZExtValue() != 8)
4040 if (Parts[MaskByteOffset])
4043 Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4047 /// Match a 32-bit packed halfword bswap. That is
4048 /// ((x & 0x000000ff) << 8) |
4049 /// ((x & 0x0000ff00) >> 8) |
4050 /// ((x & 0x00ff0000) << 8) |
4051 /// ((x & 0xff000000) >> 8)
4052 /// => (rotl (bswap x), 16)
4053 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4054 if (!LegalOperations)
4057 EVT VT = N->getValueType(0);
4060 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4064 // (or (or (and), (and)), (or (and), (and)))
4065 // (or (or (or (and), (and)), (and)), (and))
4066 if (N0.getOpcode() != ISD::OR)
4068 SDValue N00 = N0.getOperand(0);
4069 SDValue N01 = N0.getOperand(1);
4070 SDNode *Parts[4] = {};
4072 if (N1.getOpcode() == ISD::OR &&
4073 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4074 // (or (or (and), (and)), (or (and), (and)))
4075 if (!isBSwapHWordElement(N00, Parts))
4078 if (!isBSwapHWordElement(N01, Parts))
4080 SDValue N10 = N1.getOperand(0);
4081 if (!isBSwapHWordElement(N10, Parts))
4083 SDValue N11 = N1.getOperand(1);
4084 if (!isBSwapHWordElement(N11, Parts))
4087 // (or (or (or (and), (and)), (and)), (and))
4088 if (!isBSwapHWordElement(N1, Parts))
4090 if (!isBSwapHWordElement(N01, Parts))
4092 if (N00.getOpcode() != ISD::OR)
4094 SDValue N000 = N00.getOperand(0);
4095 if (!isBSwapHWordElement(N000, Parts))
4097 SDValue N001 = N00.getOperand(1);
4098 if (!isBSwapHWordElement(N001, Parts))
4102 // Make sure the parts are all coming from the same node.
4103 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4107 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4108 SDValue(Parts[0], 0));
4110 // Result of the bswap should be rotated by 16. If it's not legal, then
4111 // do (x << 16) | (x >> 16).
4112 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4113 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4114 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4115 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4116 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4117 return DAG.getNode(ISD::OR, DL, VT,
4118 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4119 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4122 /// This contains all DAGCombine rules which reduce two values combined by
4123 /// an Or operation to a single value \see visitANDLike().
4124 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4125 EVT VT = N1.getValueType();
4128 // fold (or x, undef) -> -1
4129 if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4130 return DAG.getAllOnesConstant(DL, VT);
4132 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4135 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
4136 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4137 // Don't increase # computations.
4138 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4139 // We can only do this xform if we know that bits from X that are set in C2
4140 // but not in C1 are already zero. Likewise for Y.
4141 if (const ConstantSDNode *N0O1C =
4142 getAsNonOpaqueConstant(N0.getOperand(1))) {
4143 if (const ConstantSDNode *N1O1C =
4144 getAsNonOpaqueConstant(N1.getOperand(1))) {
4145 // We can only do this xform if we know that bits from X that are set in
4146 // C2 but not in C1 are already zero. Likewise for Y.
4147 const APInt &LHSMask = N0O1C->getAPIntValue();
4148 const APInt &RHSMask = N1O1C->getAPIntValue();
4150 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4151 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4152 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4153 N0.getOperand(0), N1.getOperand(0));
4154 return DAG.getNode(ISD::AND, DL, VT, X,
4155 DAG.getConstant(LHSMask | RHSMask, DL, VT));
4161 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4162 if (N0.getOpcode() == ISD::AND &&
4163 N1.getOpcode() == ISD::AND &&
4164 N0.getOperand(0) == N1.getOperand(0) &&
4165 // Don't increase # computations.
4166 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4167 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4168 N0.getOperand(1), N1.getOperand(1));
4169 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4175 SDValue DAGCombiner::visitOR(SDNode *N) {
4176 SDValue N0 = N->getOperand(0);
4177 SDValue N1 = N->getOperand(1);
4178 EVT VT = N1.getValueType();
4185 if (VT.isVector()) {
4186 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4189 // fold (or x, 0) -> x, vector edition
4190 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4192 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4195 // fold (or x, -1) -> -1, vector edition
4196 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4197 // do not return N0, because undef node may exist in N0
4198 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4199 if (ISD::isBuildVectorAllOnes(N1.getNode()))
4200 // do not return N1, because undef node may exist in N1
4201 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4203 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4204 // Do this only if the resulting shuffle is legal.
4205 if (isa<ShuffleVectorSDNode>(N0) &&
4206 isa<ShuffleVectorSDNode>(N1) &&
4207 // Avoid folding a node with illegal type.
4208 TLI.isTypeLegal(VT)) {
4209 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4210 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4211 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4212 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4213 // Ensure both shuffles have a zero input.
4214 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4215 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4216 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4217 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4218 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4219 bool CanFold = true;
4220 int NumElts = VT.getVectorNumElements();
4221 SmallVector<int, 4> Mask(NumElts);
4223 for (int i = 0; i != NumElts; ++i) {
4224 int M0 = SV0->getMaskElt(i);
4225 int M1 = SV1->getMaskElt(i);
4227 // Determine if either index is pointing to a zero vector.
4228 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4229 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4231 // If one element is zero and the otherside is undef, keep undef.
4232 // This also handles the case that both are undef.
4233 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4238 // Make sure only one of the elements is zero.
4239 if (M0Zero == M1Zero) {
4244 assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4246 // We have a zero and non-zero element. If the non-zero came from
4247 // SV0 make the index a LHS index. If it came from SV1, make it
4248 // a RHS index. We need to mod by NumElts because we don't care
4249 // which operand it came from in the original shuffles.
4250 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4254 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4255 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4257 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4259 std::swap(NewLHS, NewRHS);
4260 ShuffleVectorSDNode::commuteMask(Mask);
4261 LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4265 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4271 // fold (or c1, c2) -> c1|c2
4272 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4273 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4274 if (N0C && N1C && !N1C->isOpaque())
4275 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4276 // canonicalize constant to RHS
4277 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4278 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4279 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4280 // fold (or x, 0) -> x
4281 if (isNullConstant(N1))
4283 // fold (or x, -1) -> -1
4284 if (isAllOnesConstant(N1))
4287 if (SDValue NewSel = foldBinOpIntoSelect(N))
4290 // fold (or x, c) -> c iff (x & ~c) == 0
4291 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4294 if (SDValue Combined = visitORLike(N0, N1, N))
4297 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4298 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4300 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4304 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4307 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4308 // iff (c1 & c2) != 0.
4309 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4310 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4311 if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4313 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4315 ISD::AND, SDLoc(N), VT,
4316 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4322 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
4323 if (N0.getOpcode() == N1.getOpcode())
4324 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4327 // See if this is some rotate idiom.
4328 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4329 return SDValue(Rot, 0);
4331 if (SDValue Load = MatchLoadCombine(N))
4334 // Simplify the operands using demanded-bits information.
4335 if (SimplifyDemandedBits(SDValue(N, 0)))
4336 return SDValue(N, 0);
4341 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4342 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4343 if (Op.getOpcode() == ISD::AND) {
4344 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4345 Mask = Op.getOperand(1);
4346 Op = Op.getOperand(0);
4352 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4360 // Return true if we can prove that, whenever Neg and Pos are both in the
4361 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
4362 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4364 // (or (shift1 X, Neg), (shift2 X, Pos))
4366 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4367 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
4368 // to consider shift amounts with defined behavior.
4369 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4370 // If EltSize is a power of 2 then:
4372 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4373 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4375 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4376 // for the stronger condition:
4378 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
4380 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4381 // we can just replace Neg with Neg' for the rest of the function.
4383 // In other cases we check for the even stronger condition:
4385 // Neg == EltSize - Pos [B]
4387 // for all Neg and Pos. Note that the (or ...) then invokes undefined
4388 // behavior if Pos == 0 (and consequently Neg == EltSize).
4390 // We could actually use [A] whenever EltSize is a power of 2, but the
4391 // only extra cases that it would match are those uninteresting ones
4392 // where Neg and Pos are never in range at the same time. E.g. for
4393 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4394 // as well as (sub 32, Pos), but:
4396 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4398 // always invokes undefined behavior for 32-bit X.
4400 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4401 unsigned MaskLoBits = 0;
4402 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4403 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4404 if (NegC->getAPIntValue() == EltSize - 1) {
4405 Neg = Neg.getOperand(0);
4406 MaskLoBits = Log2_64(EltSize);
4411 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4412 if (Neg.getOpcode() != ISD::SUB)
4414 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4417 SDValue NegOp1 = Neg.getOperand(1);
4419 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4420 // Pos'. The truncation is redundant for the purpose of the equality.
4421 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4422 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4423 if (PosC->getAPIntValue() == EltSize - 1)
4424 Pos = Pos.getOperand(0);
4426 // The condition we need is now:
4428 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4430 // If NegOp1 == Pos then we need:
4432 // EltSize & Mask == NegC & Mask
4434 // (because "x & Mask" is a truncation and distributes through subtraction).
4437 Width = NegC->getAPIntValue();
4439 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4440 // Then the condition we want to prove becomes:
4442 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4444 // which, again because "x & Mask" is a truncation, becomes:
4446 // NegC & Mask == (EltSize - PosC) & Mask
4447 // EltSize & Mask == (NegC + PosC) & Mask
4448 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4449 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4450 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4456 // Now we just need to check that EltSize & Mask == Width & Mask.
4458 // EltSize & Mask is 0 since Mask is EltSize - 1.
4459 return Width.getLoBits(MaskLoBits) == 0;
4460 return Width == EltSize;
4463 // A subroutine of MatchRotate used once we have found an OR of two opposite
4464 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
4465 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4466 // former being preferred if supported. InnerPos and InnerNeg are Pos and
4467 // Neg with outer conversions stripped away.
4468 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4469 SDValue Neg, SDValue InnerPos,
4470 SDValue InnerNeg, unsigned PosOpcode,
4471 unsigned NegOpcode, const SDLoc &DL) {
4472 // fold (or (shl x, (*ext y)),
4473 // (srl x, (*ext (sub 32, y)))) ->
4474 // (rotl x, y) or (rotr x, (sub 32, y))
4476 // fold (or (shl x, (*ext (sub 32, y))),
4477 // (srl x, (*ext y))) ->
4478 // (rotr x, y) or (rotl x, (sub 32, y))
4479 EVT VT = Shifted.getValueType();
4480 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4481 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4482 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4483 HasPos ? Pos : Neg).getNode();
4489 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
4490 // idioms for rotate, and if the target supports rotation instructions, generate
4492 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4493 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
4494 EVT VT = LHS.getValueType();
4495 if (!TLI.isTypeLegal(VT)) return nullptr;
4497 // The target must have at least one rotate flavor.
4498 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4499 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4500 if (!HasROTL && !HasROTR) return nullptr;
4502 // Match "(X shl/srl V1) & V2" where V2 may not be present.
4503 SDValue LHSShift; // The shift.
4504 SDValue LHSMask; // AND value if any.
4505 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4506 return nullptr; // Not part of a rotate.
4508 SDValue RHSShift; // The shift.
4509 SDValue RHSMask; // AND value if any.
4510 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4511 return nullptr; // Not part of a rotate.
4513 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4514 return nullptr; // Not shifting the same value.
4516 if (LHSShift.getOpcode() == RHSShift.getOpcode())
4517 return nullptr; // Shifts must disagree.
4519 // Canonicalize shl to left side in a shl/srl pair.
4520 if (RHSShift.getOpcode() == ISD::SHL) {
4521 std::swap(LHS, RHS);
4522 std::swap(LHSShift, RHSShift);
4523 std::swap(LHSMask, RHSMask);
4526 unsigned EltSizeInBits = VT.getScalarSizeInBits();
4527 SDValue LHSShiftArg = LHSShift.getOperand(0);
4528 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4529 SDValue RHSShiftArg = RHSShift.getOperand(0);
4530 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4532 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4533 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4534 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4535 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4536 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4537 if ((LShVal + RShVal) != EltSizeInBits)
4540 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4541 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4543 // If there is an AND of either shifted operand, apply it to the result.
4544 if (LHSMask.getNode() || RHSMask.getNode()) {
4545 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
4547 if (LHSMask.getNode()) {
4548 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4549 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4550 DAG.getNode(ISD::OR, DL, VT, LHSMask,
4551 DAG.getConstant(RHSBits, DL, VT)));
4553 if (RHSMask.getNode()) {
4554 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4555 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4556 DAG.getNode(ISD::OR, DL, VT, RHSMask,
4557 DAG.getConstant(LHSBits, DL, VT)));
4560 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4563 return Rot.getNode();
4566 // If there is a mask here, and we have a variable shift, we can't be sure
4567 // that we're masking out the right stuff.
4568 if (LHSMask.getNode() || RHSMask.getNode())
4571 // If the shift amount is sign/zext/any-extended just peel it off.
4572 SDValue LExtOp0 = LHSShiftAmt;
4573 SDValue RExtOp0 = RHSShiftAmt;
4574 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4575 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4576 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4577 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4578 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4579 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4580 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4581 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4582 LExtOp0 = LHSShiftAmt.getOperand(0);
4583 RExtOp0 = RHSShiftAmt.getOperand(0);
4586 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4587 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4591 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4592 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4600 /// Helper struct to parse and store a memory address as base + index + offset.
4601 /// We ignore sign extensions when it is safe to do so.
4602 /// The following two expressions are not equivalent. To differentiate we need
4603 /// to store whether there was a sign extension involved in the index
4605 /// (load (i64 add (i64 copyfromreg %c)
4606 /// (i64 signextend (add (i8 load %index)
4610 /// (load (i64 add (i64 copyfromreg %c)
4611 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
4613 struct BaseIndexOffset {
4617 bool IsIndexSignExt;
4619 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
4621 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
4622 bool IsIndexSignExt) :
4623 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
4625 bool equalBaseIndex(const BaseIndexOffset &Other) {
4626 return Other.Base == Base && Other.Index == Index &&
4627 Other.IsIndexSignExt == IsIndexSignExt;
4630 /// Parses tree in Ptr for base, index, offset addresses.
4631 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG,
4632 int64_t PartialOffset = 0) {
4633 bool IsIndexSignExt = false;
4635 // Split up a folded GlobalAddress+Offset into its component parts.
4636 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
4637 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
4638 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
4640 GA->getValueType(0),
4641 /*Offset=*/PartialOffset,
4642 /*isTargetGA=*/false,
4643 GA->getTargetFlags()),
4649 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
4650 // instruction, then it could be just the BASE or everything else we don't
4651 // know how to handle. Just use Ptr as BASE and give up.
4652 if (Ptr->getOpcode() != ISD::ADD)
4653 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4655 // We know that we have at least an ADD instruction. Try to pattern match
4656 // the simple case of BASE + OFFSET.
4657 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
4658 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
4659 return match(Ptr->getOperand(0), DAG, Offset + PartialOffset);
4662 // Inside a loop the current BASE pointer is calculated using an ADD and a
4663 // MUL instruction. In this case Ptr is the actual BASE pointer.
4664 // (i64 add (i64 %array_ptr)
4665 // (i64 mul (i64 %induction_var)
4666 // (i64 %element_size)))
4667 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
4668 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4670 // Look at Base + Index + Offset cases.
4671 SDValue Base = Ptr->getOperand(0);
4672 SDValue IndexOffset = Ptr->getOperand(1);
4674 // Skip signextends.
4675 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
4676 IndexOffset = IndexOffset->getOperand(0);
4677 IsIndexSignExt = true;
4680 // Either the case of Base + Index (no offset) or something else.
4681 if (IndexOffset->getOpcode() != ISD::ADD)
4682 return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt);
4684 // Now we have the case of Base + Index + offset.
4685 SDValue Index = IndexOffset->getOperand(0);
4686 SDValue Offset = IndexOffset->getOperand(1);
4688 if (!isa<ConstantSDNode>(Offset))
4689 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4691 // Ignore signextends.
4692 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
4693 Index = Index->getOperand(0);
4694 IsIndexSignExt = true;
4695 } else IsIndexSignExt = false;
4697 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
4698 return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt);
4704 /// Represents known origin of an individual byte in load combine pattern. The
4705 /// value of the byte is either constant zero or comes from memory.
4706 struct ByteProvider {
4707 // For constant zero providers Load is set to nullptr. For memory providers
4708 // Load represents the node which loads the byte from memory.
4709 // ByteOffset is the offset of the byte in the value produced by the load.
4711 unsigned ByteOffset;
4713 ByteProvider() : Load(nullptr), ByteOffset(0) {}
4715 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4716 return ByteProvider(Load, ByteOffset);
4718 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4720 bool isConstantZero() const { return !Load; }
4721 bool isMemory() const { return Load; }
4723 bool operator==(const ByteProvider &Other) const {
4724 return Other.Load == Load && Other.ByteOffset == ByteOffset;
4728 ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4729 : Load(Load), ByteOffset(ByteOffset) {}
4732 /// Recursively traverses the expression calculating the origin of the requested
4733 /// byte of the given value. Returns None if the provider can't be calculated.
4735 /// For all the values except the root of the expression verifies that the value
4736 /// has exactly one use and if it's not true return None. This way if the origin
4737 /// of the byte is returned it's guaranteed that the values which contribute to
4738 /// the byte are not used outside of this expression.
4740 /// Because the parts of the expression are not allowed to have more than one
4741 /// use this function iterates over trees, not DAGs. So it never visits the same
4742 /// node more than once.
4743 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4745 bool Root = false) {
4746 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4750 if (!Root && !Op.hasOneUse())
4753 assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4754 unsigned BitWidth = Op.getValueSizeInBits();
4755 if (BitWidth % 8 != 0)
4757 unsigned ByteWidth = BitWidth / 8;
4758 assert(Index < ByteWidth && "invalid index requested");
4761 switch (Op.getOpcode()) {
4763 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4766 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4770 if (LHS->isConstantZero())
4772 if (RHS->isConstantZero())
4777 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4781 uint64_t BitShift = ShiftOp->getZExtValue();
4782 if (BitShift % 8 != 0)
4784 uint64_t ByteShift = BitShift / 8;
4786 return Index < ByteShift
4787 ? ByteProvider::getConstantZero()
4788 : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4791 case ISD::ANY_EXTEND:
4792 case ISD::SIGN_EXTEND:
4793 case ISD::ZERO_EXTEND: {
4794 SDValue NarrowOp = Op->getOperand(0);
4795 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4796 if (NarrowBitWidth % 8 != 0)
4798 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4800 if (Index >= NarrowByteWidth)
4801 return Op.getOpcode() == ISD::ZERO_EXTEND
4802 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4804 return calculateByteProvider(NarrowOp, Index, Depth + 1);
4807 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4810 auto L = cast<LoadSDNode>(Op.getNode());
4811 if (L->isVolatile() || L->isIndexed())
4814 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4815 if (NarrowBitWidth % 8 != 0)
4817 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4819 if (Index >= NarrowByteWidth)
4820 return L->getExtensionType() == ISD::ZEXTLOAD
4821 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4823 return ByteProvider::getMemory(L, Index);
4831 /// Match a pattern where a wide type scalar value is loaded by several narrow
4832 /// loads and combined by shifts and ors. Fold it into a single load or a load
4833 /// and a BSWAP if the targets supports it.
4835 /// Assuming little endian target:
4837 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4839 /// i32 val = *((i32)a)
4842 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4844 /// i32 val = BSWAP(*((i32)a))
4846 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4847 /// interact well with the worklist mechanism. When a part of the pattern is
4848 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4849 /// but the root node of the pattern which triggers the load combine is not
4850 /// necessarily a direct user of the changed node. For example, once the address
4851 /// of t28 load is reassociated load combine won't be triggered:
4852 /// t25: i32 = add t4, Constant:i32<2>
4853 /// t26: i64 = sign_extend t25
4854 /// t27: i64 = add t2, t26
4855 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4856 /// t29: i32 = zero_extend t28
4857 /// t32: i32 = shl t29, Constant:i8<8>
4858 /// t33: i32 = or t23, t32
4859 /// As a possible fix visitLoad can check if the load can be a part of a load
4860 /// combine pattern and add corresponding OR roots to the worklist.
4861 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4862 assert(N->getOpcode() == ISD::OR &&
4863 "Can only match load combining against OR nodes");
4865 // Handles simple types only
4866 EVT VT = N->getValueType(0);
4867 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4869 unsigned ByteWidth = VT.getSizeInBits() / 8;
4871 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4872 // Before legalize we can introduce too wide illegal loads which will be later
4873 // split into legal sized loads. This enables us to combine i64 load by i8
4874 // patterns to a couple of i32 loads on 32 bit targets.
4875 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4878 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4879 unsigned BW, unsigned i) { return i; };
4880 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4881 unsigned BW, unsigned i) { return BW - i - 1; };
4883 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4884 auto MemoryByteOffset = [&] (ByteProvider P) {
4885 assert(P.isMemory() && "Must be a memory byte provider");
4886 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4887 assert(LoadBitWidth % 8 == 0 &&
4888 "can only analyze providers for individual bytes not bit");
4889 unsigned LoadByteWidth = LoadBitWidth / 8;
4890 return IsBigEndianTarget
4891 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4892 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4895 Optional<BaseIndexOffset> Base;
4898 SmallSet<LoadSDNode *, 8> Loads;
4899 Optional<ByteProvider> FirstByteProvider;
4900 int64_t FirstOffset = INT64_MAX;
4902 // Check if all the bytes of the OR we are looking at are loaded from the same
4903 // base address. Collect bytes offsets from Base address in ByteOffsets.
4904 SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4905 for (unsigned i = 0; i < ByteWidth; i++) {
4906 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4907 if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4910 LoadSDNode *L = P->Load;
4911 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4912 "Must be enforced by calculateByteProvider");
4913 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4915 // All loads must share the same chain
4916 SDValue LChain = L->getChain();
4919 else if (Chain != LChain)
4922 // Loads must share the same base address
4923 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4926 else if (!Base->equalBaseIndex(Ptr))
4929 // Calculate the offset of the current byte from the base address
4930 int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P);
4931 ByteOffsets[i] = ByteOffsetFromBase;
4933 // Remember the first byte load
4934 if (ByteOffsetFromBase < FirstOffset) {
4935 FirstByteProvider = P;
4936 FirstOffset = ByteOffsetFromBase;
4941 assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4942 "memory, so there must be at least one load which produces the value");
4943 assert(Base && "Base address of the accessed memory location must be set");
4944 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4946 // Check if the bytes of the OR we are looking at match with either big or
4947 // little endian value load
4948 bool BigEndian = true, LittleEndian = true;
4949 for (unsigned i = 0; i < ByteWidth; i++) {
4950 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
4951 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
4952 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
4953 if (!BigEndian && !LittleEndian)
4956 assert((BigEndian != LittleEndian) && "should be either or");
4957 assert(FirstByteProvider && "must be set");
4959 // Ensure that the first byte is loaded from zero offset of the first load.
4960 // So the combined value can be loaded from the first load address.
4961 if (MemoryByteOffset(*FirstByteProvider) != 0)
4963 LoadSDNode *FirstLoad = FirstByteProvider->Load;
4965 // The node we are looking at matches with the pattern, check if we can
4966 // replace it with a single load and bswap if needed.
4968 // If the load needs byte swap check if the target supports it
4969 bool NeedsBswap = IsBigEndianTarget != BigEndian;
4971 // Before legalize we can introduce illegal bswaps which will be later
4972 // converted to an explicit bswap sequence. This way we end up with a single
4973 // load and byte shuffling instead of several loads and byte shuffling.
4974 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4977 // Check that a load of the wide type is both allowed and fast on the target
4979 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4980 VT, FirstLoad->getAddressSpace(),
4981 FirstLoad->getAlignment(), &Fast);
4982 if (!Allowed || !Fast)
4986 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4987 FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
4989 // Transfer chain users from old loads to the new load.
4990 for (LoadSDNode *L : Loads)
4991 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
4993 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
4996 SDValue DAGCombiner::visitXOR(SDNode *N) {
4997 SDValue N0 = N->getOperand(0);
4998 SDValue N1 = N->getOperand(1);
4999 EVT VT = N0.getValueType();
5002 if (VT.isVector()) {
5003 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5006 // fold (xor x, 0) -> x, vector edition
5007 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5009 if (ISD::isBuildVectorAllZeros(N1.getNode()))
5013 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5014 if (N0.isUndef() && N1.isUndef())
5015 return DAG.getConstant(0, SDLoc(N), VT);
5016 // fold (xor x, undef) -> undef
5021 // fold (xor c1, c2) -> c1^c2
5022 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5023 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5025 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5026 // canonicalize constant to RHS
5027 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5028 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5029 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5030 // fold (xor x, 0) -> x
5031 if (isNullConstant(N1))
5034 if (SDValue NewSel = foldBinOpIntoSelect(N))
5038 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5041 // fold !(x cc y) -> (x !cc y)
5042 SDValue LHS, RHS, CC;
5043 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5044 bool isInt = LHS.getValueType().isInteger();
5045 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5048 if (!LegalOperations ||
5049 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5050 switch (N0.getOpcode()) {
5052 llvm_unreachable("Unhandled SetCC Equivalent!");
5054 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5055 case ISD::SELECT_CC:
5056 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5057 N0.getOperand(3), NotCC);
5062 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5063 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5064 N0.getNode()->hasOneUse() &&
5065 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5066 SDValue V = N0.getOperand(0);
5068 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5069 DAG.getConstant(1, DL, V.getValueType()));
5070 AddToWorklist(V.getNode());
5071 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5074 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5075 if (isOneConstant(N1) && VT == MVT::i1 &&
5076 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5077 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5078 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5079 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5080 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5081 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5082 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5083 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5086 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5087 if (isAllOnesConstant(N1) &&
5088 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5089 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5090 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5091 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5092 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5093 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5094 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5095 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5098 // fold (xor (and x, y), y) -> (and (not x), y)
5099 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5100 N0->getOperand(1) == N1) {
5101 SDValue X = N0->getOperand(0);
5102 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5103 AddToWorklist(NotX.getNode());
5104 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5106 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5107 if (N1C && N0.getOpcode() == ISD::XOR) {
5108 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5110 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5111 DAG.getConstant(N1C->getAPIntValue() ^
5112 N00C->getAPIntValue(), DL, VT));
5114 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5116 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5117 DAG.getConstant(N1C->getAPIntValue() ^
5118 N01C->getAPIntValue(), DL, VT));
5122 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5123 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5124 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5125 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5126 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5127 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5128 if (C->getAPIntValue() == (OpSizeInBits - 1))
5129 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5132 // fold (xor x, x) -> 0
5134 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5136 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5137 // Here is a concrete example of this equivalence:
5139 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
5140 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5144 // i16 ~1 == 0b1111111111111110
5145 // i16 rol(~1, 14) == 0b1011111111111111
5147 // Some additional tips to help conceptualize this transform:
5148 // - Try to see the operation as placing a single zero in a value of all ones.
5149 // - There exists no value for x which would allow the result to contain zero.
5150 // - Values of x larger than the bitwidth are undefined and do not require a
5151 // consistent result.
5152 // - Pushing the zero left requires shifting one bits in from the right.
5153 // A rotate left of ~1 is a nice way of achieving the desired result.
5154 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5155 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5157 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5161 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
5162 if (N0.getOpcode() == N1.getOpcode())
5163 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5166 // Simplify the expression using non-local knowledge.
5167 if (SimplifyDemandedBits(SDValue(N, 0)))
5168 return SDValue(N, 0);
5173 /// Handle transforms common to the three shifts, when the shift amount is a
5175 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5176 SDNode *LHS = N->getOperand(0).getNode();
5177 if (!LHS->hasOneUse()) return SDValue();
5179 // We want to pull some binops through shifts, so that we have (and (shift))
5180 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
5181 // thing happens with address calculations, so it's important to canonicalize
5183 bool HighBitSet = false; // Can we transform this if the high bit is set?
5185 switch (LHS->getOpcode()) {
5186 default: return SDValue();
5189 HighBitSet = false; // We can only transform sra if the high bit is clear.
5192 HighBitSet = true; // We can only transform sra if the high bit is set.
5195 if (N->getOpcode() != ISD::SHL)
5196 return SDValue(); // only shl(add) not sr[al](add).
5197 HighBitSet = false; // We can only transform sra if the high bit is clear.
5201 // We require the RHS of the binop to be a constant and not opaque as well.
5202 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5203 if (!BinOpCst) return SDValue();
5205 // FIXME: disable this unless the input to the binop is a shift by a constant
5206 // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5207 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5208 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5209 BinOpLHSVal->getOpcode() == ISD::SRA ||
5210 BinOpLHSVal->getOpcode() == ISD::SRL;
5211 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5212 BinOpLHSVal->getOpcode() == ISD::SELECT;
5214 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5218 if (isCopyOrSelect && N->hasOneUse())
5221 EVT VT = N->getValueType(0);
5223 // If this is a signed shift right, and the high bit is modified by the
5224 // logical operation, do not perform the transformation. The highBitSet
5225 // boolean indicates the value of the high bit of the constant which would
5226 // cause it to be modified for this operation.
5227 if (N->getOpcode() == ISD::SRA) {
5228 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5229 if (BinOpRHSSignSet != HighBitSet)
5233 if (!TLI.isDesirableToCommuteWithShift(LHS))
5236 // Fold the constants, shifting the binop RHS by the shift amount.
5237 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5239 LHS->getOperand(1), N->getOperand(1));
5240 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5242 // Create the new shift.
5243 SDValue NewShift = DAG.getNode(N->getOpcode(),
5244 SDLoc(LHS->getOperand(0)),
5245 VT, LHS->getOperand(0), N->getOperand(1));
5247 // Create the new binop.
5248 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5251 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5252 assert(N->getOpcode() == ISD::TRUNCATE);
5253 assert(N->getOperand(0).getOpcode() == ISD::AND);
5255 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5256 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5257 SDValue N01 = N->getOperand(0).getOperand(1);
5258 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5260 EVT TruncVT = N->getValueType(0);
5261 SDValue N00 = N->getOperand(0).getOperand(0);
5262 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5263 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5264 AddToWorklist(Trunc00.getNode());
5265 AddToWorklist(Trunc01.getNode());
5266 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5273 SDValue DAGCombiner::visitRotate(SDNode *N) {
5274 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5275 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
5276 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
5277 if (SDValue NewOp1 =
5278 distributeTruncateThroughAnd(N->getOperand(1).getNode()))
5279 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
5280 N->getOperand(0), NewOp1);
5285 SDValue DAGCombiner::visitSHL(SDNode *N) {
5286 SDValue N0 = N->getOperand(0);
5287 SDValue N1 = N->getOperand(1);
5288 EVT VT = N0.getValueType();
5289 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5292 if (VT.isVector()) {
5293 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5296 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5297 // If setcc produces all-one true value then:
5298 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5299 if (N1CV && N1CV->isConstant()) {
5300 if (N0.getOpcode() == ISD::AND) {
5301 SDValue N00 = N0->getOperand(0);
5302 SDValue N01 = N0->getOperand(1);
5303 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5305 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5306 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5307 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5308 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5310 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5316 // If the target supports masking y in (shl, y),
5317 // fold (shl x, (and y, ((1 << numbits(x)) - 1))) -> (shl x, y)
5318 if (TLI.isOperationLegal(ISD::SHL, VT) &&
5319 TLI.supportsModuloShift(ISD::SHL, VT) && N1->getOpcode() == ISD::AND) {
5320 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) {
5321 if (Mask->getZExtValue() == OpSizeInBits - 1) {
5322 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N1->getOperand(0));
5327 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5329 // fold (shl c1, c2) -> c1<<c2
5330 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5331 if (N0C && N1C && !N1C->isOpaque())
5332 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5333 // fold (shl 0, x) -> 0
5334 if (isNullConstant(N0))
5336 // fold (shl x, c >= size(x)) -> undef
5337 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5338 return DAG.getUNDEF(VT);
5339 // fold (shl x, 0) -> x
5340 if (N1C && N1C->isNullValue())
5342 // fold (shl undef, x) -> 0
5344 return DAG.getConstant(0, SDLoc(N), VT);
5346 if (SDValue NewSel = foldBinOpIntoSelect(N))
5349 // if (shl x, c) is known to be zero, return 0
5350 if (DAG.MaskedValueIsZero(SDValue(N, 0),
5351 APInt::getAllOnesValue(OpSizeInBits)))
5352 return DAG.getConstant(0, SDLoc(N), VT);
5353 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5354 if (N1.getOpcode() == ISD::TRUNCATE &&
5355 N1.getOperand(0).getOpcode() == ISD::AND) {
5356 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5357 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5360 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5361 return SDValue(N, 0);
5363 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5364 if (N1C && N0.getOpcode() == ISD::SHL) {
5365 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5367 APInt c1 = N0C1->getAPIntValue();
5368 APInt c2 = N1C->getAPIntValue();
5369 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5371 APInt Sum = c1 + c2;
5372 if (Sum.uge(OpSizeInBits))
5373 return DAG.getConstant(0, DL, VT);
5376 ISD::SHL, DL, VT, N0.getOperand(0),
5377 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5381 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5382 // For this to be valid, the second form must not preserve any of the bits
5383 // that are shifted out by the inner shift in the first form. This means
5384 // the outer shift size must be >= the number of bits added by the ext.
5385 // As a corollary, we don't care what kind of ext it is.
5386 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5387 N0.getOpcode() == ISD::ANY_EXTEND ||
5388 N0.getOpcode() == ISD::SIGN_EXTEND) &&
5389 N0.getOperand(0).getOpcode() == ISD::SHL) {
5390 SDValue N0Op0 = N0.getOperand(0);
5391 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5392 APInt c1 = N0Op0C1->getAPIntValue();
5393 APInt c2 = N1C->getAPIntValue();
5394 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5396 EVT InnerShiftVT = N0Op0.getValueType();
5397 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5398 if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5400 APInt Sum = c1 + c2;
5401 if (Sum.uge(OpSizeInBits))
5402 return DAG.getConstant(0, DL, VT);
5406 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5407 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5412 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5413 // Only fold this if the inner zext has no other uses to avoid increasing
5414 // the total number of instructions.
5415 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5416 N0.getOperand(0).getOpcode() == ISD::SRL) {
5417 SDValue N0Op0 = N0.getOperand(0);
5418 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5419 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5420 uint64_t c1 = N0Op0C1->getZExtValue();
5421 uint64_t c2 = N1C->getZExtValue();
5423 SDValue NewOp0 = N0.getOperand(0);
5424 EVT CountVT = NewOp0.getOperand(1).getValueType();
5426 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5428 DAG.getConstant(c2, DL, CountVT));
5429 AddToWorklist(NewSHL.getNode());
5430 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5436 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
5437 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
5438 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5439 N0->getFlags().hasExact()) {
5440 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5441 uint64_t C1 = N0C1->getZExtValue();
5442 uint64_t C2 = N1C->getZExtValue();
5445 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5446 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5447 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5448 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5452 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5453 // (and (srl x, (sub c1, c2), MASK)
5454 // Only fold this if the inner shift has no other uses -- if it does, folding
5455 // this will increase the total number of instructions.
5456 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5457 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5458 uint64_t c1 = N0C1->getZExtValue();
5459 if (c1 < OpSizeInBits) {
5460 uint64_t c2 = N1C->getZExtValue();
5461 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5466 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5467 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5469 Mask.lshrInPlace(c1 - c2);
5471 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5472 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5475 return DAG.getNode(ISD::AND, DL, VT, Shift,
5476 DAG.getConstant(Mask, DL, VT));
5481 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5482 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5483 isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5485 SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5486 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5487 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5490 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5491 // Variant of version done on multiply, except mul by a power of 2 is turned
5493 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5494 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5495 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5496 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5497 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5498 AddToWorklist(Shl0.getNode());
5499 AddToWorklist(Shl1.getNode());
5500 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5503 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5504 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5505 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5506 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5507 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5508 if (isConstantOrConstantVector(Shl))
5509 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5512 if (N1C && !N1C->isOpaque())
5513 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5519 SDValue DAGCombiner::visitSRA(SDNode *N) {
5520 SDValue N0 = N->getOperand(0);
5521 SDValue N1 = N->getOperand(1);
5522 EVT VT = N0.getValueType();
5523 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5525 // If the target supports masking y in (sra, y),
5526 // fold (sra x, (and y, ((1 << numbits(x)) - 1))) -> (sra x, y)
5527 if (TLI.isOperationLegal(ISD::SRA, VT) &&
5528 TLI.supportsModuloShift(ISD::SRA, VT) && N1->getOpcode() == ISD::AND) {
5529 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) {
5530 if (Mask->getZExtValue() == OpSizeInBits - 1) {
5531 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, N1->getOperand(0));
5536 // Arithmetic shifting an all-sign-bit value is a no-op.
5537 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5542 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5545 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5547 // fold (sra c1, c2) -> (sra c1, c2)
5548 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5549 if (N0C && N1C && !N1C->isOpaque())
5550 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5551 // fold (sra 0, x) -> 0
5552 if (isNullConstant(N0))
5554 // fold (sra -1, x) -> -1
5555 if (isAllOnesConstant(N0))
5557 // fold (sra x, c >= size(x)) -> undef
5558 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5559 return DAG.getUNDEF(VT);
5560 // fold (sra x, 0) -> x
5561 if (N1C && N1C->isNullValue())
5564 if (SDValue NewSel = foldBinOpIntoSelect(N))
5567 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5569 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5570 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5571 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5573 ExtVT = EVT::getVectorVT(*DAG.getContext(),
5574 ExtVT, VT.getVectorNumElements());
5575 if ((!LegalOperations ||
5576 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5577 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5578 N0.getOperand(0), DAG.getValueType(ExtVT));
5581 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5582 if (N1C && N0.getOpcode() == ISD::SRA) {
5583 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5585 APInt c1 = N0C1->getAPIntValue();
5586 APInt c2 = N1C->getAPIntValue();
5587 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5589 APInt Sum = c1 + c2;
5590 if (Sum.uge(OpSizeInBits))
5591 Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5594 ISD::SRA, DL, VT, N0.getOperand(0),
5595 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5599 // fold (sra (shl X, m), (sub result_size, n))
5600 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5601 // result_size - n != m.
5602 // If truncate is free for the target sext(shl) is likely to result in better
5604 if (N0.getOpcode() == ISD::SHL && N1C) {
5605 // Get the two constanst of the shifts, CN0 = m, CN = n.
5606 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5608 LLVMContext &Ctx = *DAG.getContext();
5609 // Determine what the truncate's result bitsize and type would be.
5610 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5613 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5615 // Determine the residual right-shift amount.
5616 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5618 // If the shift is not a no-op (in which case this should be just a sign
5619 // extend already), the truncated to type is legal, sign_extend is legal
5620 // on that type, and the truncate to that type is both legal and free,
5621 // perform the transform.
5622 if ((ShiftAmt > 0) &&
5623 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5624 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5625 TLI.isTruncateFree(VT, TruncVT)) {
5628 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5629 getShiftAmountTy(N0.getOperand(0).getValueType()));
5630 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5631 N0.getOperand(0), Amt);
5632 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5634 return DAG.getNode(ISD::SIGN_EXTEND, DL,
5635 N->getValueType(0), Trunc);
5640 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5641 if (N1.getOpcode() == ISD::TRUNCATE &&
5642 N1.getOperand(0).getOpcode() == ISD::AND) {
5643 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5644 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5647 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5648 // if c1 is equal to the number of bits the trunc removes
5649 if (N0.getOpcode() == ISD::TRUNCATE &&
5650 (N0.getOperand(0).getOpcode() == ISD::SRL ||
5651 N0.getOperand(0).getOpcode() == ISD::SRA) &&
5652 N0.getOperand(0).hasOneUse() &&
5653 N0.getOperand(0).getOperand(1).hasOneUse() &&
5655 SDValue N0Op0 = N0.getOperand(0);
5656 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5657 unsigned LargeShiftVal = LargeShift->getZExtValue();
5658 EVT LargeVT = N0Op0.getValueType();
5660 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5663 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5664 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5665 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5666 N0Op0.getOperand(0), Amt);
5667 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5672 // Simplify, based on bits shifted out of the LHS.
5673 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5674 return SDValue(N, 0);
5677 // If the sign bit is known to be zero, switch this to a SRL.
5678 if (DAG.SignBitIsZero(N0))
5679 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5681 if (N1C && !N1C->isOpaque())
5682 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5688 SDValue DAGCombiner::visitSRL(SDNode *N) {
5689 SDValue N0 = N->getOperand(0);
5690 SDValue N1 = N->getOperand(1);
5691 EVT VT = N0.getValueType();
5692 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5694 // If the target supports masking y in (srl, y),
5695 // fold (srl x, (and y, ((1 << numbits(x)) - 1))) -> (srl x, y)
5696 if (TLI.isOperationLegal(ISD::SRL, VT) &&
5697 TLI.supportsModuloShift(ISD::SRL, VT) && N1->getOpcode() == ISD::AND) {
5698 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) {
5699 if (Mask->getZExtValue() == OpSizeInBits - 1) {
5700 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1->getOperand(0));
5707 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5710 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5712 // fold (srl c1, c2) -> c1 >>u c2
5713 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5714 if (N0C && N1C && !N1C->isOpaque())
5715 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5716 // fold (srl 0, x) -> 0
5717 if (isNullConstant(N0))
5719 // fold (srl x, c >= size(x)) -> undef
5720 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5721 return DAG.getUNDEF(VT);
5722 // fold (srl x, 0) -> x
5723 if (N1C && N1C->isNullValue())
5726 if (SDValue NewSel = foldBinOpIntoSelect(N))
5729 // if (srl x, c) is known to be zero, return 0
5730 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5731 APInt::getAllOnesValue(OpSizeInBits)))
5732 return DAG.getConstant(0, SDLoc(N), VT);
5734 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5735 if (N1C && N0.getOpcode() == ISD::SRL) {
5736 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5738 APInt c1 = N0C1->getAPIntValue();
5739 APInt c2 = N1C->getAPIntValue();
5740 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5742 APInt Sum = c1 + c2;
5743 if (Sum.uge(OpSizeInBits))
5744 return DAG.getConstant(0, DL, VT);
5747 ISD::SRL, DL, VT, N0.getOperand(0),
5748 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5752 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5753 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5754 N0.getOperand(0).getOpcode() == ISD::SRL) {
5755 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5756 uint64_t c1 = N001C->getZExtValue();
5757 uint64_t c2 = N1C->getZExtValue();
5758 EVT InnerShiftVT = N0.getOperand(0).getValueType();
5759 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5760 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5761 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5762 if (c1 + OpSizeInBits == InnerShiftSize) {
5764 if (c1 + c2 >= InnerShiftSize)
5765 return DAG.getConstant(0, DL, VT);
5766 return DAG.getNode(ISD::TRUNCATE, DL, VT,
5767 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5768 N0.getOperand(0).getOperand(0),
5769 DAG.getConstant(c1 + c2, DL,
5775 // fold (srl (shl x, c), c) -> (and x, cst2)
5776 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5777 isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5780 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5781 AddToWorklist(Mask.getNode());
5782 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5785 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5786 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5787 // Shifting in all undef bits?
5788 EVT SmallVT = N0.getOperand(0).getValueType();
5789 unsigned BitSize = SmallVT.getScalarSizeInBits();
5790 if (N1C->getZExtValue() >= BitSize)
5791 return DAG.getUNDEF(VT);
5793 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5794 uint64_t ShiftAmt = N1C->getZExtValue();
5796 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5798 DAG.getConstant(ShiftAmt, DL0,
5799 getShiftAmountTy(SmallVT)));
5800 AddToWorklist(SmallShift.getNode());
5801 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5803 return DAG.getNode(ISD::AND, DL, VT,
5804 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5805 DAG.getConstant(Mask, DL, VT));
5809 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
5810 // bit, which is unmodified by sra.
5811 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5812 if (N0.getOpcode() == ISD::SRA)
5813 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5816 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
5817 if (N1C && N0.getOpcode() == ISD::CTLZ &&
5818 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5820 DAG.computeKnownBits(N0.getOperand(0), Known);
5822 // If any of the input bits are KnownOne, then the input couldn't be all
5823 // zeros, thus the result of the srl will always be zero.
5824 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5826 // If all of the bits input the to ctlz node are known to be zero, then
5827 // the result of the ctlz is "32" and the result of the shift is one.
5828 APInt UnknownBits = ~Known.Zero;
5829 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5831 // Otherwise, check to see if there is exactly one bit input to the ctlz.
5832 if (UnknownBits.isPowerOf2()) {
5833 // Okay, we know that only that the single bit specified by UnknownBits
5834 // could be set on input to the CTLZ node. If this bit is set, the SRL
5835 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5836 // to an SRL/XOR pair, which is likely to simplify more.
5837 unsigned ShAmt = UnknownBits.countTrailingZeros();
5838 SDValue Op = N0.getOperand(0);
5842 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5843 DAG.getConstant(ShAmt, DL,
5844 getShiftAmountTy(Op.getValueType())));
5845 AddToWorklist(Op.getNode());
5849 return DAG.getNode(ISD::XOR, DL, VT,
5850 Op, DAG.getConstant(1, DL, VT));
5854 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5855 if (N1.getOpcode() == ISD::TRUNCATE &&
5856 N1.getOperand(0).getOpcode() == ISD::AND) {
5857 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5858 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5861 // fold operands of srl based on knowledge that the low bits are not
5863 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5864 return SDValue(N, 0);
5866 if (N1C && !N1C->isOpaque())
5867 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5870 // Attempt to convert a srl of a load into a narrower zero-extending load.
5871 if (SDValue NarrowLoad = ReduceLoadWidth(N))
5874 // Here is a common situation. We want to optimize:
5877 // %b = and i32 %a, 2
5878 // %c = srl i32 %b, 1
5879 // brcond i32 %c ...
5885 // %c = setcc eq %b, 0
5888 // However when after the source operand of SRL is optimized into AND, the SRL
5889 // itself may not be optimized further. Look for it and add the BRCOND into
5891 if (N->hasOneUse()) {
5892 SDNode *Use = *N->use_begin();
5893 if (Use->getOpcode() == ISD::BRCOND)
5895 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5896 // Also look pass the truncate.
5897 Use = *Use->use_begin();
5898 if (Use->getOpcode() == ISD::BRCOND)
5906 SDValue DAGCombiner::visitABS(SDNode *N) {
5907 SDValue N0 = N->getOperand(0);
5908 EVT VT = N->getValueType(0);
5910 // fold (abs c1) -> c2
5911 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5912 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5913 // fold (abs (abs x)) -> (abs x)
5914 if (N0.getOpcode() == ISD::ABS)
5916 // fold (abs x) -> x iff not-negative
5917 if (DAG.SignBitIsZero(N0))
5922 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5923 SDValue N0 = N->getOperand(0);
5924 EVT VT = N->getValueType(0);
5926 // fold (bswap c1) -> c2
5927 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5928 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5929 // fold (bswap (bswap x)) -> x
5930 if (N0.getOpcode() == ISD::BSWAP)
5931 return N0->getOperand(0);
5935 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5936 SDValue N0 = N->getOperand(0);
5937 EVT VT = N->getValueType(0);
5939 // fold (bitreverse c1) -> c2
5940 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5941 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5942 // fold (bitreverse (bitreverse x)) -> x
5943 if (N0.getOpcode() == ISD::BITREVERSE)
5944 return N0.getOperand(0);
5948 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5949 SDValue N0 = N->getOperand(0);
5950 EVT VT = N->getValueType(0);
5952 // fold (ctlz c1) -> c2
5953 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5954 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5958 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5959 SDValue N0 = N->getOperand(0);
5960 EVT VT = N->getValueType(0);
5962 // fold (ctlz_zero_undef c1) -> c2
5963 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5964 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5968 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5969 SDValue N0 = N->getOperand(0);
5970 EVT VT = N->getValueType(0);
5972 // fold (cttz c1) -> c2
5973 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5974 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5978 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5979 SDValue N0 = N->getOperand(0);
5980 EVT VT = N->getValueType(0);
5982 // fold (cttz_zero_undef c1) -> c2
5983 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5984 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5988 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5989 SDValue N0 = N->getOperand(0);
5990 EVT VT = N->getValueType(0);
5992 // fold (ctpop c1) -> c2
5993 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5994 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5999 /// \brief Generate Min/Max node
6000 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6001 SDValue RHS, SDValue True, SDValue False,
6002 ISD::CondCode CC, const TargetLowering &TLI,
6003 SelectionDAG &DAG) {
6004 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6014 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6015 if (TLI.isOperationLegal(Opcode, VT))
6016 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6025 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6026 if (TLI.isOperationLegal(Opcode, VT))
6027 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6035 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6036 SDValue Cond = N->getOperand(0);
6037 SDValue N1 = N->getOperand(1);
6038 SDValue N2 = N->getOperand(2);
6039 EVT VT = N->getValueType(0);
6040 EVT CondVT = Cond.getValueType();
6043 if (!VT.isInteger())
6046 auto *C1 = dyn_cast<ConstantSDNode>(N1);
6047 auto *C2 = dyn_cast<ConstantSDNode>(N2);
6051 // Only do this before legalization to avoid conflicting with target-specific
6052 // transforms in the other direction (create a select from a zext/sext). There
6053 // is also a target-independent combine here in DAGCombiner in the other
6054 // direction for (select Cond, -1, 0) when the condition is not i1.
6055 if (CondVT == MVT::i1 && !LegalOperations) {
6056 if (C1->isNullValue() && C2->isOne()) {
6057 // select Cond, 0, 1 --> zext (!Cond)
6058 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6060 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6063 if (C1->isNullValue() && C2->isAllOnesValue()) {
6064 // select Cond, 0, -1 --> sext (!Cond)
6065 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6067 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6070 if (C1->isOne() && C2->isNullValue()) {
6071 // select Cond, 1, 0 --> zext (Cond)
6073 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6076 if (C1->isAllOnesValue() && C2->isNullValue()) {
6077 // select Cond, -1, 0 --> sext (Cond)
6079 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6083 // For any constants that differ by 1, we can transform the select into an
6084 // extend and add. Use a target hook because some targets may prefer to
6085 // transform in the other direction.
6086 if (TLI.convertSelectOfConstantsToMath()) {
6087 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6088 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6090 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6091 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6093 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6094 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6096 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6097 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6104 // fold (select Cond, 0, 1) -> (xor Cond, 1)
6105 // We can't do this reliably if integer based booleans have different contents
6106 // to floating point based booleans. This is because we can't tell whether we
6107 // have an integer-based boolean or a floating-point-based boolean unless we
6108 // can find the SETCC that produced it and inspect its operands. This is
6109 // fairly easy if C is the SETCC node, but it can potentially be
6110 // undiscoverable (or not reasonably discoverable). For example, it could be
6111 // in another basic block or it could require searching a complicated
6113 if (CondVT.isInteger() &&
6114 TLI.getBooleanContents(false, true) ==
6115 TargetLowering::ZeroOrOneBooleanContent &&
6116 TLI.getBooleanContents(false, false) ==
6117 TargetLowering::ZeroOrOneBooleanContent &&
6118 C1->isNullValue() && C2->isOne()) {
6120 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6121 if (VT.bitsEq(CondVT))
6123 return DAG.getZExtOrTrunc(NotCond, DL, VT);
6129 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6130 SDValue N0 = N->getOperand(0);
6131 SDValue N1 = N->getOperand(1);
6132 SDValue N2 = N->getOperand(2);
6133 EVT VT = N->getValueType(0);
6134 EVT VT0 = N0.getValueType();
6136 // fold (select C, X, X) -> X
6139 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6140 // fold (select true, X, Y) -> X
6141 // fold (select false, X, Y) -> Y
6142 return !N0C->isNullValue() ? N1 : N2;
6144 // fold (select X, X, Y) -> (or X, Y)
6145 // fold (select X, 1, Y) -> (or C, Y)
6146 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6147 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
6149 if (SDValue V = foldSelectOfConstants(N))
6152 // fold (select C, 0, X) -> (and (not C), X)
6153 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6154 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6155 AddToWorklist(NOTNode.getNode());
6156 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
6158 // fold (select C, X, 1) -> (or (not C), X)
6159 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6160 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6161 AddToWorklist(NOTNode.getNode());
6162 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
6164 // fold (select X, Y, X) -> (and X, Y)
6165 // fold (select X, Y, 0) -> (and X, Y)
6166 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6167 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
6169 // If we can fold this based on the true/false value, do so.
6170 if (SimplifySelectOps(N, N1, N2))
6171 return SDValue(N, 0); // Don't revisit N.
6173 if (VT0 == MVT::i1) {
6174 // The code in this block deals with the following 2 equivalences:
6175 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6176 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6177 // The target can specify its preferred form with the
6178 // shouldNormalizeToSelectSequence() callback. However we always transform
6179 // to the right anyway if we find the inner select exists in the DAG anyway
6180 // and we always transform to the left side if we know that we can further
6181 // optimize the combination of the conditions.
6182 bool normalizeToSequence
6183 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6184 // select (and Cond0, Cond1), X, Y
6185 // -> select Cond0, (select Cond1, X, Y), Y
6186 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6187 SDValue Cond0 = N0->getOperand(0);
6188 SDValue Cond1 = N0->getOperand(1);
6189 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6190 N1.getValueType(), Cond1, N1, N2);
6191 if (normalizeToSequence || !InnerSelect.use_empty())
6192 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
6195 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6196 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6197 SDValue Cond0 = N0->getOperand(0);
6198 SDValue Cond1 = N0->getOperand(1);
6199 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6200 N1.getValueType(), Cond1, N1, N2);
6201 if (normalizeToSequence || !InnerSelect.use_empty())
6202 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
6206 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6207 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6208 SDValue N1_0 = N1->getOperand(0);
6209 SDValue N1_1 = N1->getOperand(1);
6210 SDValue N1_2 = N1->getOperand(2);
6211 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6212 // Create the actual and node if we can generate good code for it.
6213 if (!normalizeToSequence) {
6214 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
6216 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
6219 // Otherwise see if we can optimize the "and" to a better pattern.
6220 if (SDValue Combined = visitANDLike(N0, N1_0, N))
6221 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6225 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6226 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6227 SDValue N2_0 = N2->getOperand(0);
6228 SDValue N2_1 = N2->getOperand(1);
6229 SDValue N2_2 = N2->getOperand(2);
6230 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6231 // Create the actual or node if we can generate good code for it.
6232 if (!normalizeToSequence) {
6233 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
6235 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
6238 // Otherwise see if we can optimize to a better pattern.
6239 if (SDValue Combined = visitORLike(N0, N2_0, N))
6240 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6246 // select (xor Cond, 1), X, Y -> select Cond, Y, X
6247 if (VT0 == MVT::i1) {
6248 if (N0->getOpcode() == ISD::XOR) {
6249 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6250 SDValue Cond0 = N0->getOperand(0);
6252 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
6258 // fold selects based on a setcc into other things, such as min/max/abs
6259 if (N0.getOpcode() == ISD::SETCC) {
6260 // select x, y (fcmp lt x, y) -> fminnum x, y
6261 // select x, y (fcmp gt x, y) -> fmaxnum x, y
6263 // This is OK if we don't care about what happens if either operand is a
6267 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6268 // no signed zeros as well as no nans.
6269 const TargetOptions &Options = DAG.getTarget().Options;
6270 if (Options.UnsafeFPMath &&
6271 VT.isFloatingPoint() && N0.hasOneUse() &&
6272 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6273 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6275 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
6276 N0.getOperand(1), N1, N2, CC,
6281 if ((!LegalOperations &&
6282 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6283 TLI.isOperationLegal(ISD::SELECT_CC, VT))
6284 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
6285 N0.getOperand(0), N0.getOperand(1),
6286 N1, N2, N0.getOperand(2));
6287 return SimplifySelect(SDLoc(N), N0, N1, N2);
6294 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6297 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6299 // Split the inputs.
6300 SDValue Lo, Hi, LL, LH, RL, RH;
6301 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6302 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6304 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6305 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6307 return std::make_pair(Lo, Hi);
6310 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6311 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6312 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6314 SDValue Cond = N->getOperand(0);
6315 SDValue LHS = N->getOperand(1);
6316 SDValue RHS = N->getOperand(2);
6317 EVT VT = N->getValueType(0);
6318 int NumElems = VT.getVectorNumElements();
6319 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6320 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6321 Cond.getOpcode() == ISD::BUILD_VECTOR);
6323 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6324 // binary ones here.
6325 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6328 // We're sure we have an even number of elements due to the
6329 // concat_vectors we have as arguments to vselect.
6330 // Skip BV elements until we find one that's not an UNDEF
6331 // After we find an UNDEF element, keep looping until we get to half the
6332 // length of the BV and see if all the non-undef nodes are the same.
6333 ConstantSDNode *BottomHalf = nullptr;
6334 for (int i = 0; i < NumElems / 2; ++i) {
6335 if (Cond->getOperand(i)->isUndef())
6338 if (BottomHalf == nullptr)
6339 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6340 else if (Cond->getOperand(i).getNode() != BottomHalf)
6344 // Do the same for the second half of the BuildVector
6345 ConstantSDNode *TopHalf = nullptr;
6346 for (int i = NumElems / 2; i < NumElems; ++i) {
6347 if (Cond->getOperand(i)->isUndef())
6350 if (TopHalf == nullptr)
6351 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6352 else if (Cond->getOperand(i).getNode() != TopHalf)
6356 assert(TopHalf && BottomHalf &&
6357 "One half of the selector was all UNDEFs and the other was all the "
6358 "same value. This should have been addressed before this function.");
6360 ISD::CONCAT_VECTORS, DL, VT,
6361 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6362 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6365 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6367 if (Level >= AfterLegalizeTypes)
6370 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6371 SDValue Mask = MSC->getMask();
6372 SDValue Data = MSC->getValue();
6375 // If the MSCATTER data type requires splitting and the mask is provided by a
6376 // SETCC, then split both nodes and its operands before legalization. This
6377 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6378 // and enables future optimizations (e.g. min/max pattern matching on X86).
6379 if (Mask.getOpcode() != ISD::SETCC)
6382 // Check if any splitting is required.
6383 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6384 TargetLowering::TypeSplitVector)
6386 SDValue MaskLo, MaskHi, Lo, Hi;
6387 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6390 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6392 SDValue Chain = MSC->getChain();
6394 EVT MemoryVT = MSC->getMemoryVT();
6395 unsigned Alignment = MSC->getOriginalAlignment();
6397 EVT LoMemVT, HiMemVT;
6398 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6400 SDValue DataLo, DataHi;
6401 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6403 SDValue BasePtr = MSC->getBasePtr();
6404 SDValue IndexLo, IndexHi;
6405 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6407 MachineMemOperand *MMO = DAG.getMachineFunction().
6408 getMachineMemOperand(MSC->getPointerInfo(),
6409 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6410 Alignment, MSC->getAAInfo(), MSC->getRanges());
6412 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6413 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6416 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6417 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6420 AddToWorklist(Lo.getNode());
6421 AddToWorklist(Hi.getNode());
6423 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6426 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6428 if (Level >= AfterLegalizeTypes)
6431 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6432 SDValue Mask = MST->getMask();
6433 SDValue Data = MST->getValue();
6434 EVT VT = Data.getValueType();
6437 // If the MSTORE data type requires splitting and the mask is provided by a
6438 // SETCC, then split both nodes and its operands before legalization. This
6439 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6440 // and enables future optimizations (e.g. min/max pattern matching on X86).
6441 if (Mask.getOpcode() == ISD::SETCC) {
6443 // Check if any splitting is required.
6444 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6445 TargetLowering::TypeSplitVector)
6448 SDValue MaskLo, MaskHi, Lo, Hi;
6449 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6451 SDValue Chain = MST->getChain();
6452 SDValue Ptr = MST->getBasePtr();
6454 EVT MemoryVT = MST->getMemoryVT();
6455 unsigned Alignment = MST->getOriginalAlignment();
6457 // if Alignment is equal to the vector size,
6458 // take the half of it for the second part
6459 unsigned SecondHalfAlignment =
6460 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6462 EVT LoMemVT, HiMemVT;
6463 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6465 SDValue DataLo, DataHi;
6466 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6468 MachineMemOperand *MMO = DAG.getMachineFunction().
6469 getMachineMemOperand(MST->getPointerInfo(),
6470 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6471 Alignment, MST->getAAInfo(), MST->getRanges());
6473 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6474 MST->isTruncatingStore(),
6475 MST->isCompressingStore());
6477 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6478 MST->isCompressingStore());
6480 MMO = DAG.getMachineFunction().
6481 getMachineMemOperand(MST->getPointerInfo(),
6482 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
6483 SecondHalfAlignment, MST->getAAInfo(),
6486 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6487 MST->isTruncatingStore(),
6488 MST->isCompressingStore());
6490 AddToWorklist(Lo.getNode());
6491 AddToWorklist(Hi.getNode());
6493 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6498 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6500 if (Level >= AfterLegalizeTypes)
6503 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6504 SDValue Mask = MGT->getMask();
6507 // If the MGATHER result requires splitting and the mask is provided by a
6508 // SETCC, then split both nodes and its operands before legalization. This
6509 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6510 // and enables future optimizations (e.g. min/max pattern matching on X86).
6512 if (Mask.getOpcode() != ISD::SETCC)
6515 EVT VT = N->getValueType(0);
6517 // Check if any splitting is required.
6518 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6519 TargetLowering::TypeSplitVector)
6522 SDValue MaskLo, MaskHi, Lo, Hi;
6523 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6525 SDValue Src0 = MGT->getValue();
6526 SDValue Src0Lo, Src0Hi;
6527 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6530 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6532 SDValue Chain = MGT->getChain();
6533 EVT MemoryVT = MGT->getMemoryVT();
6534 unsigned Alignment = MGT->getOriginalAlignment();
6536 EVT LoMemVT, HiMemVT;
6537 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6539 SDValue BasePtr = MGT->getBasePtr();
6540 SDValue Index = MGT->getIndex();
6541 SDValue IndexLo, IndexHi;
6542 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6544 MachineMemOperand *MMO = DAG.getMachineFunction().
6545 getMachineMemOperand(MGT->getPointerInfo(),
6546 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6547 Alignment, MGT->getAAInfo(), MGT->getRanges());
6549 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6550 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6553 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6554 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6557 AddToWorklist(Lo.getNode());
6558 AddToWorklist(Hi.getNode());
6560 // Build a factor node to remember that this load is independent of the
6562 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6565 // Legalized the chain result - switch anything that used the old chain to
6567 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6569 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6571 SDValue RetOps[] = { GatherRes, Chain };
6572 return DAG.getMergeValues(RetOps, DL);
6575 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6577 if (Level >= AfterLegalizeTypes)
6580 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6581 SDValue Mask = MLD->getMask();
6584 // If the MLOAD result requires splitting and the mask is provided by a
6585 // SETCC, then split both nodes and its operands before legalization. This
6586 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6587 // and enables future optimizations (e.g. min/max pattern matching on X86).
6589 if (Mask.getOpcode() == ISD::SETCC) {
6590 EVT VT = N->getValueType(0);
6592 // Check if any splitting is required.
6593 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6594 TargetLowering::TypeSplitVector)
6597 SDValue MaskLo, MaskHi, Lo, Hi;
6598 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6600 SDValue Src0 = MLD->getSrc0();
6601 SDValue Src0Lo, Src0Hi;
6602 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6605 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6607 SDValue Chain = MLD->getChain();
6608 SDValue Ptr = MLD->getBasePtr();
6609 EVT MemoryVT = MLD->getMemoryVT();
6610 unsigned Alignment = MLD->getOriginalAlignment();
6612 // if Alignment is equal to the vector size,
6613 // take the half of it for the second part
6614 unsigned SecondHalfAlignment =
6615 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6616 Alignment/2 : Alignment;
6618 EVT LoMemVT, HiMemVT;
6619 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6621 MachineMemOperand *MMO = DAG.getMachineFunction().
6622 getMachineMemOperand(MLD->getPointerInfo(),
6623 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6624 Alignment, MLD->getAAInfo(), MLD->getRanges());
6626 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6627 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6629 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6630 MLD->isExpandingLoad());
6632 MMO = DAG.getMachineFunction().
6633 getMachineMemOperand(MLD->getPointerInfo(),
6634 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
6635 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6637 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6638 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6640 AddToWorklist(Lo.getNode());
6641 AddToWorklist(Hi.getNode());
6643 // Build a factor node to remember that this load is independent of the
6645 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6648 // Legalized the chain result - switch anything that used the old chain to
6650 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6652 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6654 SDValue RetOps[] = { LoadRes, Chain };
6655 return DAG.getMergeValues(RetOps, DL);
6660 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6661 SDValue N0 = N->getOperand(0);
6662 SDValue N1 = N->getOperand(1);
6663 SDValue N2 = N->getOperand(2);
6666 // fold (vselect C, X, X) -> X
6670 // Canonicalize integer abs.
6671 // vselect (setg[te] X, 0), X, -X ->
6672 // vselect (setgt X, -1), X, -X ->
6673 // vselect (setl[te] X, 0), -X, X ->
6674 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6675 if (N0.getOpcode() == ISD::SETCC) {
6676 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6677 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6679 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6681 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6682 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6683 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6684 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6685 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6686 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6687 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6690 EVT VT = LHS.getValueType();
6691 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
6692 return DAG.getNode(ISD::ABS, DL, VT, LHS);
6694 SDValue Shift = DAG.getNode(
6695 ISD::SRA, DL, VT, LHS,
6696 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6697 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6698 AddToWorklist(Shift.getNode());
6699 AddToWorklist(Add.getNode());
6700 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6704 if (SimplifySelectOps(N, N1, N2))
6705 return SDValue(N, 0); // Don't revisit N.
6707 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6708 if (ISD::isBuildVectorAllOnes(N0.getNode()))
6710 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6711 if (ISD::isBuildVectorAllZeros(N0.getNode()))
6714 // The ConvertSelectToConcatVector function is assuming both the above
6715 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6717 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6718 N2.getOpcode() == ISD::CONCAT_VECTORS &&
6719 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6720 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6727 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6728 SDValue N0 = N->getOperand(0);
6729 SDValue N1 = N->getOperand(1);
6730 SDValue N2 = N->getOperand(2);
6731 SDValue N3 = N->getOperand(3);
6732 SDValue N4 = N->getOperand(4);
6733 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6735 // fold select_cc lhs, rhs, x, x, cc -> x
6739 // Determine if the condition we're dealing with is constant
6740 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6741 CC, SDLoc(N), false)) {
6742 AddToWorklist(SCC.getNode());
6744 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6745 if (!SCCC->isNullValue())
6746 return N2; // cond always true -> true val
6748 return N3; // cond always false -> false val
6749 } else if (SCC->isUndef()) {
6750 // When the condition is UNDEF, just return the first operand. This is
6751 // coherent the DAG creation, no setcc node is created in this case
6753 } else if (SCC.getOpcode() == ISD::SETCC) {
6754 // Fold to a simpler select_cc
6755 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6756 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6761 // If we can fold this based on the true/false value, do so.
6762 if (SimplifySelectOps(N, N2, N3))
6763 return SDValue(N, 0); // Don't revisit N.
6765 // fold select_cc into other things, such as min/max/abs
6766 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6769 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6770 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6771 cast<CondCodeSDNode>(N->getOperand(2))->get(),
6775 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6776 SDValue LHS = N->getOperand(0);
6777 SDValue RHS = N->getOperand(1);
6778 SDValue Carry = N->getOperand(2);
6779 SDValue Cond = N->getOperand(3);
6781 // If Carry is false, fold to a regular SETCC.
6782 if (Carry.getOpcode() == ISD::CARRY_FALSE)
6783 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6788 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6789 /// a build_vector of constants.
6790 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6791 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6792 /// Vector extends are not folded if operations are legal; this is to
6793 /// avoid introducing illegal build_vector dag nodes.
6794 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6795 SelectionDAG &DAG, bool LegalTypes,
6796 bool LegalOperations) {
6797 unsigned Opcode = N->getOpcode();
6798 SDValue N0 = N->getOperand(0);
6799 EVT VT = N->getValueType(0);
6801 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6802 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6803 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6804 && "Expected EXTEND dag node in input!");
6806 // fold (sext c1) -> c1
6807 // fold (zext c1) -> c1
6808 // fold (aext c1) -> c1
6809 if (isa<ConstantSDNode>(N0))
6810 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6812 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6813 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6814 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6815 EVT SVT = VT.getScalarType();
6816 if (!(VT.isVector() &&
6817 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6818 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6821 // We can fold this node into a build_vector.
6822 unsigned VTBits = SVT.getSizeInBits();
6823 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6824 SmallVector<SDValue, 8> Elts;
6825 unsigned NumElts = VT.getVectorNumElements();
6828 for (unsigned i=0; i != NumElts; ++i) {
6829 SDValue Op = N0->getOperand(i);
6830 if (Op->isUndef()) {
6831 Elts.push_back(DAG.getUNDEF(SVT));
6836 // Get the constant value and if needed trunc it to the size of the type.
6837 // Nodes like build_vector might have constants wider than the scalar type.
6838 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6839 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6840 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6842 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6845 return DAG.getBuildVector(VT, DL, Elts).getNode();
6848 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6849 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6850 // transformation. Returns true if extension are possible and the above
6851 // mentioned transformation is profitable.
6852 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6854 SmallVectorImpl<SDNode *> &ExtendNodes,
6855 const TargetLowering &TLI) {
6856 bool HasCopyToRegUses = false;
6857 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6858 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6859 UE = N0.getNode()->use_end();
6864 if (UI.getUse().getResNo() != N0.getResNo())
6866 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6867 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6868 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6869 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6870 // Sign bits will be lost after a zext.
6873 for (unsigned i = 0; i != 2; ++i) {
6874 SDValue UseOp = User->getOperand(i);
6877 if (!isa<ConstantSDNode>(UseOp))
6882 ExtendNodes.push_back(User);
6885 // If truncates aren't free and there are users we can't
6886 // extend, it isn't worthwhile.
6889 // Remember if this value is live-out.
6890 if (User->getOpcode() == ISD::CopyToReg)
6891 HasCopyToRegUses = true;
6894 if (HasCopyToRegUses) {
6895 bool BothLiveOut = false;
6896 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6898 SDUse &Use = UI.getUse();
6899 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6905 // Both unextended and extended values are live out. There had better be
6906 // a good reason for the transformation.
6907 return ExtendNodes.size();
6912 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6913 SDValue Trunc, SDValue ExtLoad,
6914 const SDLoc &DL, ISD::NodeType ExtType) {
6915 // Extend SetCC uses if necessary.
6916 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6917 SDNode *SetCC = SetCCs[i];
6918 SmallVector<SDValue, 4> Ops;
6920 for (unsigned j = 0; j != 2; ++j) {
6921 SDValue SOp = SetCC->getOperand(j);
6923 Ops.push_back(ExtLoad);
6925 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6928 Ops.push_back(SetCC->getOperand(2));
6929 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6933 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6934 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6935 SDValue N0 = N->getOperand(0);
6936 EVT DstVT = N->getValueType(0);
6937 EVT SrcVT = N0.getValueType();
6939 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6940 N->getOpcode() == ISD::ZERO_EXTEND) &&
6941 "Unexpected node type (not an extend)!");
6943 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6944 // For example, on a target with legal v4i32, but illegal v8i32, turn:
6945 // (v8i32 (sext (v8i16 (load x))))
6947 // (v8i32 (concat_vectors (v4i32 (sextload x)),
6948 // (v4i32 (sextload (x + 16)))))
6949 // Where uses of the original load, i.e.:
6951 // are replaced with:
6953 // (v8i32 (concat_vectors (v4i32 (sextload x)),
6954 // (v4i32 (sextload (x + 16)))))))
6956 // This combine is only applicable to illegal, but splittable, vectors.
6957 // All legal types, and illegal non-vector types, are handled elsewhere.
6958 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6960 if (N0->getOpcode() != ISD::LOAD)
6963 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6965 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6966 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6967 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6970 SmallVector<SDNode *, 4> SetCCs;
6971 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6974 ISD::LoadExtType ExtType =
6975 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6977 // Try to split the vector types to get down to legal types.
6978 EVT SplitSrcVT = SrcVT;
6979 EVT SplitDstVT = DstVT;
6980 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6981 SplitSrcVT.getVectorNumElements() > 1) {
6982 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6983 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6986 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6990 const unsigned NumSplits =
6991 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6992 const unsigned Stride = SplitSrcVT.getStoreSize();
6993 SmallVector<SDValue, 4> Loads;
6994 SmallVector<SDValue, 4> Chains;
6996 SDValue BasePtr = LN0->getBasePtr();
6997 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6998 const unsigned Offset = Idx * Stride;
6999 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7001 SDValue SplitLoad = DAG.getExtLoad(
7002 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7003 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7004 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7006 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7007 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7009 Loads.push_back(SplitLoad.getValue(0));
7010 Chains.push_back(SplitLoad.getValue(1));
7013 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7014 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7017 AddToWorklist(NewChain.getNode());
7019 CombineTo(N, NewValue);
7021 // Replace uses of the original load (before extension)
7022 // with a truncate of the concatenated sextloaded vectors.
7024 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7025 CombineTo(N0.getNode(), Trunc, NewChain);
7026 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7027 (ISD::NodeType)N->getOpcode());
7028 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7031 /// If we're narrowing or widening the result of a vector select and the final
7032 /// size is the same size as a setcc (compare) feeding the select, then try to
7033 /// apply the cast operation to the select's operands because matching vector
7034 /// sizes for a select condition and other operands should be more efficient.
7035 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7036 unsigned CastOpcode = Cast->getOpcode();
7037 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7038 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7039 CastOpcode == ISD::FP_ROUND) &&
7040 "Unexpected opcode for vector select narrowing/widening");
7042 // We only do this transform before legal ops because the pattern may be
7043 // obfuscated by target-specific operations after legalization. Do not create
7044 // an illegal select op, however, because that may be difficult to lower.
7045 EVT VT = Cast->getValueType(0);
7046 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7049 SDValue VSel = Cast->getOperand(0);
7050 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7051 VSel.getOperand(0).getOpcode() != ISD::SETCC)
7054 // Does the setcc have the same vector size as the casted select?
7055 SDValue SetCC = VSel.getOperand(0);
7056 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7057 if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7060 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7061 SDValue A = VSel.getOperand(1);
7062 SDValue B = VSel.getOperand(2);
7063 SDValue CastA, CastB;
7065 if (CastOpcode == ISD::FP_ROUND) {
7066 // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7067 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7068 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7070 CastA = DAG.getNode(CastOpcode, DL, VT, A);
7071 CastB = DAG.getNode(CastOpcode, DL, VT, B);
7073 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7076 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7077 SDValue N0 = N->getOperand(0);
7078 EVT VT = N->getValueType(0);
7081 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7083 return SDValue(Res, 0);
7085 // fold (sext (sext x)) -> (sext x)
7086 // fold (sext (aext x)) -> (sext x)
7087 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7088 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7090 if (N0.getOpcode() == ISD::TRUNCATE) {
7091 // fold (sext (truncate (load x))) -> (sext (smaller load x))
7092 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7093 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7094 SDNode *oye = N0.getOperand(0).getNode();
7095 if (NarrowLoad.getNode() != N0.getNode()) {
7096 CombineTo(N0.getNode(), NarrowLoad);
7097 // CombineTo deleted the truncate, if needed, but not what's under it.
7100 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7103 // See if the value being truncated is already sign extended. If so, just
7104 // eliminate the trunc/sext pair.
7105 SDValue Op = N0.getOperand(0);
7106 unsigned OpBits = Op.getScalarValueSizeInBits();
7107 unsigned MidBits = N0.getScalarValueSizeInBits();
7108 unsigned DestBits = VT.getScalarSizeInBits();
7109 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7111 if (OpBits == DestBits) {
7112 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7113 // bits, it is already ready.
7114 if (NumSignBits > DestBits-MidBits)
7116 } else if (OpBits < DestBits) {
7117 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7118 // bits, just sext from i32.
7119 if (NumSignBits > OpBits-MidBits)
7120 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7122 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7123 // bits, just truncate to i32.
7124 if (NumSignBits > OpBits-MidBits)
7125 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7128 // fold (sext (truncate x)) -> (sextinreg x).
7129 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7130 N0.getValueType())) {
7131 if (OpBits < DestBits)
7132 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7133 else if (OpBits > DestBits)
7134 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7135 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7136 DAG.getValueType(N0.getValueType()));
7140 // fold (sext (load x)) -> (sext (truncate (sextload x)))
7141 // Only generate vector extloads when 1) they're legal, and 2) they are
7142 // deemed desirable by the target.
7143 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7144 ((!LegalOperations && !VT.isVector() &&
7145 !cast<LoadSDNode>(N0)->isVolatile()) ||
7146 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7147 bool DoXform = true;
7148 SmallVector<SDNode*, 4> SetCCs;
7149 if (!N0.hasOneUse())
7150 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7152 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7154 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7155 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7156 LN0->getBasePtr(), N0.getValueType(),
7157 LN0->getMemOperand());
7158 CombineTo(N, ExtLoad);
7159 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7160 N0.getValueType(), ExtLoad);
7161 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7162 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7163 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7167 // fold (sext (load x)) to multiple smaller sextloads.
7168 // Only on illegal but splittable vectors.
7169 if (SDValue ExtLoad = CombineExtLoad(N))
7172 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7173 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7174 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7175 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7176 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7177 EVT MemVT = LN0->getMemoryVT();
7178 if ((!LegalOperations && !LN0->isVolatile()) ||
7179 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7180 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7181 LN0->getBasePtr(), MemVT,
7182 LN0->getMemOperand());
7183 CombineTo(N, ExtLoad);
7184 CombineTo(N0.getNode(),
7185 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7186 N0.getValueType(), ExtLoad),
7187 ExtLoad.getValue(1));
7188 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7192 // fold (sext (and/or/xor (load x), cst)) ->
7193 // (and/or/xor (sextload x), (sext cst))
7194 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7195 N0.getOpcode() == ISD::XOR) &&
7196 isa<LoadSDNode>(N0.getOperand(0)) &&
7197 N0.getOperand(1).getOpcode() == ISD::Constant &&
7198 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7199 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7200 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7201 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7202 bool DoXform = true;
7203 SmallVector<SDNode*, 4> SetCCs;
7204 if (!N0.hasOneUse())
7205 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7208 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7209 LN0->getChain(), LN0->getBasePtr(),
7211 LN0->getMemOperand());
7212 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7213 Mask = Mask.sext(VT.getSizeInBits());
7214 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7215 ExtLoad, DAG.getConstant(Mask, DL, VT));
7216 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7217 SDLoc(N0.getOperand(0)),
7218 N0.getOperand(0).getValueType(), ExtLoad);
7220 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7221 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7222 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7227 if (N0.getOpcode() == ISD::SETCC) {
7228 SDValue N00 = N0.getOperand(0);
7229 SDValue N01 = N0.getOperand(1);
7230 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7231 EVT N00VT = N0.getOperand(0).getValueType();
7233 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7234 // Only do this before legalize for now.
7235 if (VT.isVector() && !LegalOperations &&
7236 TLI.getBooleanContents(N00VT) ==
7237 TargetLowering::ZeroOrNegativeOneBooleanContent) {
7238 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7239 // of the same size as the compared operands. Only optimize sext(setcc())
7240 // if this is the case.
7241 EVT SVT = getSetCCResultType(N00VT);
7243 // We know that the # elements of the results is the same as the
7244 // # elements of the compare (and the # elements of the compare result
7245 // for that matter). Check to see that they are the same size. If so,
7246 // we know that the element size of the sext'd result matches the
7247 // element size of the compare operands.
7248 if (VT.getSizeInBits() == SVT.getSizeInBits())
7249 return DAG.getSetCC(DL, VT, N00, N01, CC);
7251 // If the desired elements are smaller or larger than the source
7252 // elements, we can use a matching integer vector type and then
7253 // truncate/sign extend.
7254 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7255 if (SVT == MatchingVecType) {
7256 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7257 return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7261 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7262 // Here, T can be 1 or -1, depending on the type of the setcc and
7263 // getBooleanContents().
7264 unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7266 // To determine the "true" side of the select, we need to know the high bit
7267 // of the value returned by the setcc if it evaluates to true.
7268 // If the type of the setcc is i1, then the true case of the select is just
7269 // sext(i1 1), that is, -1.
7270 // If the type of the setcc is larger (say, i8) then the value of the high
7271 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7272 // of the appropriate width.
7273 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7274 : TLI.getConstTrueVal(DAG, VT, DL);
7275 SDValue Zero = DAG.getConstant(0, DL, VT);
7277 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7280 if (!VT.isVector()) {
7281 EVT SetCCVT = getSetCCResultType(N00VT);
7282 // Don't do this transform for i1 because there's a select transform
7283 // that would reverse it.
7284 // TODO: We should not do this transform at all without a target hook
7285 // because a sext is likely cheaper than a select?
7286 if (SetCCVT.getScalarSizeInBits() != 1 &&
7287 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7288 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7289 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7294 // fold (sext x) -> (zext x) if the sign bit is known zero.
7295 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7296 DAG.SignBitIsZero(N0))
7297 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7299 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7305 // isTruncateOf - If N is a truncate of some other value, return true, record
7306 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7307 // This function computes KnownBits to avoid a duplicated call to
7308 // computeKnownBits in the caller.
7309 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7311 if (N->getOpcode() == ISD::TRUNCATE) {
7312 Op = N->getOperand(0);
7313 DAG.computeKnownBits(Op, Known);
7317 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7318 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7321 SDValue Op0 = N->getOperand(0);
7322 SDValue Op1 = N->getOperand(1);
7323 assert(Op0.getValueType() == Op1.getValueType());
7325 if (isNullConstant(Op0))
7327 else if (isNullConstant(Op1))
7332 DAG.computeKnownBits(Op, Known);
7334 if (!(Known.Zero | 1).isAllOnesValue())
7340 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7341 SDValue N0 = N->getOperand(0);
7342 EVT VT = N->getValueType(0);
7344 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7346 return SDValue(Res, 0);
7348 // fold (zext (zext x)) -> (zext x)
7349 // fold (zext (aext x)) -> (zext x)
7350 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7351 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7354 // fold (zext (truncate x)) -> (zext x) or
7355 // (zext (truncate x)) -> (truncate x)
7356 // This is valid when the truncated bits of x are already zero.
7357 // FIXME: We should extend this to work for vectors too.
7360 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7361 APInt TruncatedBits =
7362 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7363 APInt(Op.getValueSizeInBits(), 0) :
7364 APInt::getBitsSet(Op.getValueSizeInBits(),
7365 N0.getValueSizeInBits(),
7366 std::min(Op.getValueSizeInBits(),
7367 VT.getSizeInBits()));
7368 if (TruncatedBits.isSubsetOf(Known.Zero)) {
7369 if (VT.bitsGT(Op.getValueType()))
7370 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
7371 if (VT.bitsLT(Op.getValueType()))
7372 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
7378 // fold (zext (truncate (load x))) -> (zext (smaller load x))
7379 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7380 if (N0.getOpcode() == ISD::TRUNCATE) {
7381 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7382 SDNode *oye = N0.getOperand(0).getNode();
7383 if (NarrowLoad.getNode() != N0.getNode()) {
7384 CombineTo(N0.getNode(), NarrowLoad);
7385 // CombineTo deleted the truncate, if needed, but not what's under it.
7388 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7392 // fold (zext (truncate x)) -> (and x, mask)
7393 if (N0.getOpcode() == ISD::TRUNCATE) {
7394 // fold (zext (truncate (load x))) -> (zext (smaller load x))
7395 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7396 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7397 SDNode *oye = N0.getOperand(0).getNode();
7398 if (NarrowLoad.getNode() != N0.getNode()) {
7399 CombineTo(N0.getNode(), NarrowLoad);
7400 // CombineTo deleted the truncate, if needed, but not what's under it.
7403 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7406 EVT SrcVT = N0.getOperand(0).getValueType();
7407 EVT MinVT = N0.getValueType();
7409 // Try to mask before the extension to avoid having to generate a larger mask,
7410 // possibly over several sub-vectors.
7411 if (SrcVT.bitsLT(VT)) {
7412 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7413 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7414 SDValue Op = N0.getOperand(0);
7415 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7416 AddToWorklist(Op.getNode());
7417 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7421 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7422 SDValue Op = N0.getOperand(0);
7423 if (SrcVT.bitsLT(VT)) {
7424 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
7425 AddToWorklist(Op.getNode());
7426 } else if (SrcVT.bitsGT(VT)) {
7427 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
7428 AddToWorklist(Op.getNode());
7430 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7434 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7435 // if either of the casts is not free.
7436 if (N0.getOpcode() == ISD::AND &&
7437 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7438 N0.getOperand(1).getOpcode() == ISD::Constant &&
7439 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7440 N0.getValueType()) ||
7441 !TLI.isZExtFree(N0.getValueType(), VT))) {
7442 SDValue X = N0.getOperand(0).getOperand(0);
7443 if (X.getValueType().bitsLT(VT)) {
7444 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
7445 } else if (X.getValueType().bitsGT(VT)) {
7446 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7448 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7449 Mask = Mask.zext(VT.getSizeInBits());
7451 return DAG.getNode(ISD::AND, DL, VT,
7452 X, DAG.getConstant(Mask, DL, VT));
7455 // fold (zext (load x)) -> (zext (truncate (zextload x)))
7456 // Only generate vector extloads when 1) they're legal, and 2) they are
7457 // deemed desirable by the target.
7458 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7459 ((!LegalOperations && !VT.isVector() &&
7460 !cast<LoadSDNode>(N0)->isVolatile()) ||
7461 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7462 bool DoXform = true;
7463 SmallVector<SDNode*, 4> SetCCs;
7464 if (!N0.hasOneUse())
7465 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7467 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7469 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7470 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7472 LN0->getBasePtr(), N0.getValueType(),
7473 LN0->getMemOperand());
7475 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7476 N0.getValueType(), ExtLoad);
7477 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7479 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7481 CombineTo(N, ExtLoad);
7482 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7486 // fold (zext (load x)) to multiple smaller zextloads.
7487 // Only on illegal but splittable vectors.
7488 if (SDValue ExtLoad = CombineExtLoad(N))
7491 // fold (zext (and/or/xor (load x), cst)) ->
7492 // (and/or/xor (zextload x), (zext cst))
7493 // Unless (and (load x) cst) will match as a zextload already and has
7494 // additional users.
7495 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7496 N0.getOpcode() == ISD::XOR) &&
7497 isa<LoadSDNode>(N0.getOperand(0)) &&
7498 N0.getOperand(1).getOpcode() == ISD::Constant &&
7499 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7500 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7501 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7502 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7503 bool DoXform = true;
7504 SmallVector<SDNode*, 4> SetCCs;
7505 if (!N0.hasOneUse()) {
7506 if (N0.getOpcode() == ISD::AND) {
7507 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7508 auto NarrowLoad = false;
7509 EVT LoadResultTy = AndC->getValueType(0);
7510 EVT ExtVT, LoadedVT;
7511 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7516 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7517 ISD::ZERO_EXTEND, SetCCs, TLI);
7520 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7521 LN0->getChain(), LN0->getBasePtr(),
7523 LN0->getMemOperand());
7524 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7525 Mask = Mask.zext(VT.getSizeInBits());
7527 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7528 ExtLoad, DAG.getConstant(Mask, DL, VT));
7529 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7530 SDLoc(N0.getOperand(0)),
7531 N0.getOperand(0).getValueType(), ExtLoad);
7533 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7534 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
7536 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7541 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7542 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7543 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7544 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7545 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7546 EVT MemVT = LN0->getMemoryVT();
7547 if ((!LegalOperations && !LN0->isVolatile()) ||
7548 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7549 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7551 LN0->getBasePtr(), MemVT,
7552 LN0->getMemOperand());
7553 CombineTo(N, ExtLoad);
7554 CombineTo(N0.getNode(),
7555 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7557 ExtLoad.getValue(1));
7558 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7562 if (N0.getOpcode() == ISD::SETCC) {
7563 // Only do this before legalize for now.
7564 if (!LegalOperations && VT.isVector() &&
7565 N0.getValueType().getVectorElementType() == MVT::i1) {
7566 EVT N00VT = N0.getOperand(0).getValueType();
7567 if (getSetCCResultType(N00VT) == N0.getValueType())
7570 // We know that the # elements of the results is the same as the #
7571 // elements of the compare (and the # elements of the compare result for
7572 // that matter). Check to see that they are the same size. If so, we know
7573 // that the element size of the sext'd result matches the element size of
7574 // the compare operands.
7576 SDValue VecOnes = DAG.getConstant(1, DL, VT);
7577 if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7578 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7579 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7580 N0.getOperand(1), N0.getOperand(2));
7581 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7584 // If the desired elements are smaller or larger than the source
7585 // elements we can use a matching integer vector type and then
7586 // truncate/sign extend.
7587 EVT MatchingElementType = EVT::getIntegerVT(
7588 *DAG.getContext(), N00VT.getScalarSizeInBits());
7589 EVT MatchingVectorType = EVT::getVectorVT(
7590 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7592 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7593 N0.getOperand(1), N0.getOperand(2));
7594 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7598 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7600 if (SDValue SCC = SimplifySelectCC(
7601 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7602 DAG.getConstant(0, DL, VT),
7603 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7607 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7608 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7609 isa<ConstantSDNode>(N0.getOperand(1)) &&
7610 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7612 SDValue ShAmt = N0.getOperand(1);
7613 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7614 if (N0.getOpcode() == ISD::SHL) {
7615 SDValue InnerZExt = N0.getOperand(0);
7616 // If the original shl may be shifting out bits, do not perform this
7618 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7619 InnerZExt.getOperand(0).getValueSizeInBits();
7620 if (ShAmtVal > KnownZeroBits)
7626 // Ensure that the shift amount is wide enough for the shifted value.
7627 if (VT.getSizeInBits() >= 256)
7628 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7630 return DAG.getNode(N0.getOpcode(), DL, VT,
7631 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7635 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7641 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7642 SDValue N0 = N->getOperand(0);
7643 EVT VT = N->getValueType(0);
7645 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7647 return SDValue(Res, 0);
7649 // fold (aext (aext x)) -> (aext x)
7650 // fold (aext (zext x)) -> (zext x)
7651 // fold (aext (sext x)) -> (sext x)
7652 if (N0.getOpcode() == ISD::ANY_EXTEND ||
7653 N0.getOpcode() == ISD::ZERO_EXTEND ||
7654 N0.getOpcode() == ISD::SIGN_EXTEND)
7655 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7657 // fold (aext (truncate (load x))) -> (aext (smaller load x))
7658 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7659 if (N0.getOpcode() == ISD::TRUNCATE) {
7660 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7661 SDNode *oye = N0.getOperand(0).getNode();
7662 if (NarrowLoad.getNode() != N0.getNode()) {
7663 CombineTo(N0.getNode(), NarrowLoad);
7664 // CombineTo deleted the truncate, if needed, but not what's under it.
7667 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7671 // fold (aext (truncate x))
7672 if (N0.getOpcode() == ISD::TRUNCATE) {
7673 SDValue TruncOp = N0.getOperand(0);
7674 if (TruncOp.getValueType() == VT)
7675 return TruncOp; // x iff x size == zext size.
7676 if (TruncOp.getValueType().bitsGT(VT))
7677 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
7678 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
7681 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7682 // if the trunc is not free.
7683 if (N0.getOpcode() == ISD::AND &&
7684 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7685 N0.getOperand(1).getOpcode() == ISD::Constant &&
7686 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7687 N0.getValueType())) {
7689 SDValue X = N0.getOperand(0).getOperand(0);
7690 if (X.getValueType().bitsLT(VT)) {
7691 X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
7692 } else if (X.getValueType().bitsGT(VT)) {
7693 X = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
7695 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7696 Mask = Mask.zext(VT.getSizeInBits());
7697 return DAG.getNode(ISD::AND, DL, VT,
7698 X, DAG.getConstant(Mask, DL, VT));
7701 // fold (aext (load x)) -> (aext (truncate (extload x)))
7702 // None of the supported targets knows how to perform load and any_ext
7703 // on vectors in one instruction. We only perform this transformation on
7705 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7706 ISD::isUNINDEXEDLoad(N0.getNode()) &&
7707 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7708 bool DoXform = true;
7709 SmallVector<SDNode*, 4> SetCCs;
7710 if (!N0.hasOneUse())
7711 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7713 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7714 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7716 LN0->getBasePtr(), N0.getValueType(),
7717 LN0->getMemOperand());
7718 CombineTo(N, ExtLoad);
7719 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7720 N0.getValueType(), ExtLoad);
7721 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7722 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7724 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7728 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7729 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7730 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
7731 if (N0.getOpcode() == ISD::LOAD &&
7732 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7734 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7735 ISD::LoadExtType ExtType = LN0->getExtensionType();
7736 EVT MemVT = LN0->getMemoryVT();
7737 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7738 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7739 VT, LN0->getChain(), LN0->getBasePtr(),
7740 MemVT, LN0->getMemOperand());
7741 CombineTo(N, ExtLoad);
7742 CombineTo(N0.getNode(),
7743 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7744 N0.getValueType(), ExtLoad),
7745 ExtLoad.getValue(1));
7746 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7750 if (N0.getOpcode() == ISD::SETCC) {
7752 // aext(setcc) -> vsetcc
7753 // aext(setcc) -> truncate(vsetcc)
7754 // aext(setcc) -> aext(vsetcc)
7755 // Only do this before legalize for now.
7756 if (VT.isVector() && !LegalOperations) {
7757 EVT N0VT = N0.getOperand(0).getValueType();
7758 // We know that the # elements of the results is the same as the
7759 // # elements of the compare (and the # elements of the compare result
7760 // for that matter). Check to see that they are the same size. If so,
7761 // we know that the element size of the sext'd result matches the
7762 // element size of the compare operands.
7763 if (VT.getSizeInBits() == N0VT.getSizeInBits())
7764 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7766 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7767 // If the desired elements are smaller or larger than the source
7768 // elements we can use a matching integer vector type and then
7769 // truncate/any extend
7771 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7773 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7775 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7776 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7780 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7782 if (SDValue SCC = SimplifySelectCC(
7783 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7784 DAG.getConstant(0, DL, VT),
7785 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7792 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7793 SDValue N0 = N->getOperand(0);
7794 SDValue N1 = N->getOperand(1);
7795 EVT EVT = cast<VTSDNode>(N1)->getVT();
7797 // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7798 if (N0.getOpcode() == ISD::AssertZext &&
7799 EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7805 /// See if the specified operand can be simplified with the knowledge that only
7806 /// the bits specified by Mask are used. If so, return the simpler operand,
7807 /// otherwise return a null SDValue.
7809 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7810 /// simplify nodes with multiple uses more aggressively.)
7811 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7812 switch (V.getOpcode()) {
7814 case ISD::Constant: {
7815 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7816 assert(CV && "Const value should be ConstSDNode.");
7817 const APInt &CVal = CV->getAPIntValue();
7818 APInt NewVal = CVal & Mask;
7820 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7825 // If the LHS or RHS don't contribute bits to the or, drop them.
7826 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7827 return V.getOperand(1);
7828 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7829 return V.getOperand(0);
7832 // Only look at single-use SRLs.
7833 if (!V.getNode()->hasOneUse())
7835 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7836 // See if we can recursively simplify the LHS.
7837 unsigned Amt = RHSC->getZExtValue();
7839 // Watch out for shift count overflow though.
7840 if (Amt >= Mask.getBitWidth()) break;
7841 APInt NewMask = Mask << Amt;
7842 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7843 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7844 SimplifyLHS, V.getOperand(1));
7848 // X & -1 -> X (ignoring bits which aren't demanded).
7849 ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7850 if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7851 return V.getOperand(0);
7858 /// If the result of a wider load is shifted to right of N bits and then
7859 /// truncated to a narrower type and where N is a multiple of number of bits of
7860 /// the narrower type, transform it to a narrower load from address + N / num of
7861 /// bits of new type. If the result is to be extended, also fold the extension
7862 /// to form a extending load.
7863 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7864 unsigned Opc = N->getOpcode();
7866 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7867 SDValue N0 = N->getOperand(0);
7868 EVT VT = N->getValueType(0);
7871 // This transformation isn't valid for vector loads.
7875 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7877 if (Opc == ISD::SIGN_EXTEND_INREG) {
7878 ExtType = ISD::SEXTLOAD;
7879 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7880 } else if (Opc == ISD::SRL) {
7881 // Another special-case: SRL is basically zero-extending a narrower value.
7882 ExtType = ISD::ZEXTLOAD;
7884 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7885 if (!N01) return SDValue();
7886 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7887 VT.getSizeInBits() - N01->getZExtValue());
7889 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7892 unsigned EVTBits = ExtVT.getSizeInBits();
7894 // Do not generate loads of non-round integer types since these can
7895 // be expensive (and would be wrong if the type is not byte sized).
7896 if (!ExtVT.isRound())
7900 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7901 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7902 ShAmt = N01->getZExtValue();
7903 // Is the shift amount a multiple of size of VT?
7904 if ((ShAmt & (EVTBits-1)) == 0) {
7905 N0 = N0.getOperand(0);
7906 // Is the load width a multiple of size of VT?
7907 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7911 // At this point, we must have a load or else we can't do the transform.
7912 if (!isa<LoadSDNode>(N0)) return SDValue();
7914 // Because a SRL must be assumed to *need* to zero-extend the high bits
7915 // (as opposed to anyext the high bits), we can't combine the zextload
7916 // lowering of SRL and an sextload.
7917 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7920 // If the shift amount is larger than the input type then we're not
7921 // accessing any of the loaded bytes. If the load was a zextload/extload
7922 // then the result of the shift+trunc is zero/undef (handled elsewhere).
7923 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7928 // If the load is shifted left (and the result isn't shifted back right),
7929 // we can fold the truncate through the shift.
7930 unsigned ShLeftAmt = 0;
7931 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7932 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7933 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7934 ShLeftAmt = N01->getZExtValue();
7935 N0 = N0.getOperand(0);
7939 // If we haven't found a load, we can't narrow it. Don't transform one with
7940 // multiple uses, this would require adding a new load.
7941 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7944 // Don't change the width of a volatile load.
7945 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7946 if (LN0->isVolatile())
7949 // Verify that we are actually reducing a load width here.
7950 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7953 // For the transform to be legal, the load must produce only two values
7954 // (the value loaded and the chain). Don't transform a pre-increment
7955 // load, for example, which produces an extra value. Otherwise the
7956 // transformation is not equivalent, and the downstream logic to replace
7957 // uses gets things wrong.
7958 if (LN0->getNumValues() > 2)
7961 // If the load that we're shrinking is an extload and we're not just
7962 // discarding the extension we can't simply shrink the load. Bail.
7963 // TODO: It would be possible to merge the extensions in some cases.
7964 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7965 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7968 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7971 EVT PtrType = N0.getOperand(1).getValueType();
7973 if (PtrType == MVT::Untyped || PtrType.isExtended())
7974 // It's not possible to generate a constant of extended or untyped type.
7977 // For big endian targets, we need to adjust the offset to the pointer to
7978 // load the correct bytes.
7979 if (DAG.getDataLayout().isBigEndian()) {
7980 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7981 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7982 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7985 uint64_t PtrOff = ShAmt / 8;
7986 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7988 // The original load itself didn't wrap, so an offset within it doesn't.
7990 Flags.setNoUnsignedWrap(true);
7991 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7992 PtrType, LN0->getBasePtr(),
7993 DAG.getConstant(PtrOff, DL, PtrType),
7995 AddToWorklist(NewPtr.getNode());
7998 if (ExtType == ISD::NON_EXTLOAD)
7999 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8000 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8001 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8003 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8004 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8005 NewAlign, LN0->getMemOperand()->getFlags(),
8008 // Replace the old load's chain with the new load's chain.
8009 WorklistRemover DeadNodes(*this);
8010 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8012 // Shift the result left, if we've swallowed a left shift.
8013 SDValue Result = Load;
8014 if (ShLeftAmt != 0) {
8015 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8016 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8018 // If the shift amount is as large as the result size (but, presumably,
8019 // no larger than the source) then the useful bits of the result are
8020 // zero; we can't simply return the shortened shift, because the result
8021 // of that operation is undefined.
8023 if (ShLeftAmt >= VT.getSizeInBits())
8024 Result = DAG.getConstant(0, DL, VT);
8026 Result = DAG.getNode(ISD::SHL, DL, VT,
8027 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8030 // Return the new loaded value.
8034 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8035 SDValue N0 = N->getOperand(0);
8036 SDValue N1 = N->getOperand(1);
8037 EVT VT = N->getValueType(0);
8038 EVT EVT = cast<VTSDNode>(N1)->getVT();
8039 unsigned VTBits = VT.getScalarSizeInBits();
8040 unsigned EVTBits = EVT.getScalarSizeInBits();
8043 return DAG.getUNDEF(VT);
8045 // fold (sext_in_reg c1) -> c1
8046 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8047 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8049 // If the input is already sign extended, just drop the extension.
8050 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8053 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8054 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8055 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8056 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8057 N0.getOperand(0), N1);
8059 // fold (sext_in_reg (sext x)) -> (sext x)
8060 // fold (sext_in_reg (aext x)) -> (sext x)
8061 // if x is small enough.
8062 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8063 SDValue N00 = N0.getOperand(0);
8064 if (N00.getScalarValueSizeInBits() <= EVTBits &&
8065 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8066 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8069 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8070 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8071 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8072 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8073 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8074 if (!LegalOperations ||
8075 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8076 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8079 // fold (sext_in_reg (zext x)) -> (sext x)
8080 // iff we are extending the source sign bit.
8081 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8082 SDValue N00 = N0.getOperand(0);
8083 if (N00.getScalarValueSizeInBits() == EVTBits &&
8084 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8085 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8088 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8089 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8090 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8092 // fold operands of sext_in_reg based on knowledge that the top bits are not
8094 if (SimplifyDemandedBits(SDValue(N, 0)))
8095 return SDValue(N, 0);
8097 // fold (sext_in_reg (load x)) -> (smaller sextload x)
8098 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8099 if (SDValue NarrowLoad = ReduceLoadWidth(N))
8102 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8103 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8104 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8105 if (N0.getOpcode() == ISD::SRL) {
8106 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8107 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8108 // We can turn this into an SRA iff the input to the SRL is already sign
8110 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8111 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8112 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8113 N0.getOperand(0), N0.getOperand(1));
8117 // fold (sext_inreg (extload x)) -> (sextload x)
8118 if (ISD::isEXTLoad(N0.getNode()) &&
8119 ISD::isUNINDEXEDLoad(N0.getNode()) &&
8120 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8121 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8122 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8123 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8124 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8126 LN0->getBasePtr(), EVT,
8127 LN0->getMemOperand());
8128 CombineTo(N, ExtLoad);
8129 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8130 AddToWorklist(ExtLoad.getNode());
8131 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8133 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8134 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8136 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8137 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8138 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8139 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8140 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8142 LN0->getBasePtr(), EVT,
8143 LN0->getMemOperand());
8144 CombineTo(N, ExtLoad);
8145 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8146 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8149 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8150 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8151 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8152 N0.getOperand(1), false))
8153 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8160 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8161 SDValue N0 = N->getOperand(0);
8162 EVT VT = N->getValueType(0);
8165 return DAG.getUNDEF(VT);
8167 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8169 return SDValue(Res, 0);
8174 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8175 SDValue N0 = N->getOperand(0);
8176 EVT VT = N->getValueType(0);
8179 return DAG.getUNDEF(VT);
8181 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8183 return SDValue(Res, 0);
8188 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8189 SDValue N0 = N->getOperand(0);
8190 EVT VT = N->getValueType(0);
8191 bool isLE = DAG.getDataLayout().isLittleEndian();
8194 if (N0.getValueType() == N->getValueType(0))
8196 // fold (truncate c1) -> c1
8197 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8198 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8199 // fold (truncate (truncate x)) -> (truncate x)
8200 if (N0.getOpcode() == ISD::TRUNCATE)
8201 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8202 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8203 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8204 N0.getOpcode() == ISD::SIGN_EXTEND ||
8205 N0.getOpcode() == ISD::ANY_EXTEND) {
8206 // if the source is smaller than the dest, we still need an extend.
8207 if (N0.getOperand(0).getValueType().bitsLT(VT))
8208 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8209 // if the source is larger than the dest, than we just need the truncate.
8210 if (N0.getOperand(0).getValueType().bitsGT(VT))
8211 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8212 // if the source and dest are the same type, we can drop both the extend
8213 // and the truncate.
8214 return N0.getOperand(0);
8217 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8218 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8221 // Fold extract-and-trunc into a narrow extract. For example:
8222 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8223 // i32 y = TRUNCATE(i64 x)
8225 // v16i8 b = BITCAST (v2i64 val)
8226 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8228 // Note: We only run this optimization after type legalization (which often
8229 // creates this pattern) and before operation legalization after which
8230 // we need to be more careful about the vector instructions that we generate.
8231 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8232 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8234 EVT VecTy = N0.getOperand(0).getValueType();
8235 EVT ExTy = N0.getValueType();
8236 EVT TrTy = N->getValueType(0);
8238 unsigned NumElem = VecTy.getVectorNumElements();
8239 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8241 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8242 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8244 SDValue EltNo = N0->getOperand(1);
8245 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8246 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8247 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8248 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8251 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8252 DAG.getBitcast(NVT, N0.getOperand(0)),
8253 DAG.getConstant(Index, DL, IndexTy));
8257 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8258 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8259 EVT SrcVT = N0.getValueType();
8260 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8261 TLI.isTruncateFree(SrcVT, VT)) {
8263 SDValue Cond = N0.getOperand(0);
8264 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8265 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8266 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8270 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8271 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8272 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8273 TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8274 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
8275 uint64_t Amt = CAmt->getZExtValue();
8276 unsigned Size = VT.getScalarSizeInBits();
8280 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8282 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8283 return DAG.getNode(ISD::SHL, SL, VT, Trunc,
8284 DAG.getConstant(Amt, SL, AmtVT));
8289 // Fold a series of buildvector, bitcast, and truncate if possible.
8291 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8292 // (2xi32 (buildvector x, y)).
8293 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8294 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8295 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8296 N0.getOperand(0).hasOneUse()) {
8298 SDValue BuildVect = N0.getOperand(0);
8299 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8300 EVT TruncVecEltTy = VT.getVectorElementType();
8302 // Check that the element types match.
8303 if (BuildVectEltTy == TruncVecEltTy) {
8304 // Now we only need to compute the offset of the truncated elements.
8305 unsigned BuildVecNumElts = BuildVect.getNumOperands();
8306 unsigned TruncVecNumElts = VT.getVectorNumElements();
8307 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8309 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8310 "Invalid number of elements");
8312 SmallVector<SDValue, 8> Opnds;
8313 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8314 Opnds.push_back(BuildVect.getOperand(i));
8316 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8320 // See if we can simplify the input to this truncate through knowledge that
8321 // only the low bits are being used.
8322 // For example "trunc (or (shl x, 8), y)" // -> trunc y
8323 // Currently we only perform this optimization on scalars because vectors
8324 // may have different active low bits.
8325 if (!VT.isVector()) {
8326 if (SDValue Shorter =
8327 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8328 VT.getSizeInBits())))
8329 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8332 // fold (truncate (load x)) -> (smaller load x)
8333 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8334 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8335 if (SDValue Reduced = ReduceLoadWidth(N))
8338 // Handle the case where the load remains an extending load even
8339 // after truncation.
8340 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8341 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8342 if (!LN0->isVolatile() &&
8343 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8344 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8345 VT, LN0->getChain(), LN0->getBasePtr(),
8347 LN0->getMemOperand());
8348 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8354 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8355 // where ... are all 'undef'.
8356 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8357 SmallVector<EVT, 8> VTs;
8360 unsigned NumDefs = 0;
8362 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8363 SDValue X = N0.getOperand(i);
8369 // Stop if more than one members are non-undef.
8372 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8373 VT.getVectorElementType(),
8374 X.getValueType().getVectorNumElements()));
8378 return DAG.getUNDEF(VT);
8381 assert(V.getNode() && "The single defined operand is empty!");
8382 SmallVector<SDValue, 8> Opnds;
8383 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8385 Opnds.push_back(DAG.getUNDEF(VTs[i]));
8388 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8389 AddToWorklist(NV.getNode());
8390 Opnds.push_back(NV);
8392 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8396 // Fold truncate of a bitcast of a vector to an extract of the low vector
8399 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8400 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8401 SDValue VecSrc = N0.getOperand(0);
8402 EVT SrcVT = VecSrc.getValueType();
8403 if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8404 (!LegalOperations ||
8405 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8408 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8409 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8410 VecSrc, DAG.getConstant(0, SL, IdxVT));
8414 // Simplify the operands using demanded-bits information.
8415 if (!VT.isVector() &&
8416 SimplifyDemandedBits(SDValue(N, 0)))
8417 return SDValue(N, 0);
8419 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8420 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8421 // When the adde's carry is not used.
8422 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8423 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8424 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8426 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8427 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8428 auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8429 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8432 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8438 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8439 SDValue Elt = N->getOperand(i);
8440 if (Elt.getOpcode() != ISD::MERGE_VALUES)
8441 return Elt.getNode();
8442 return Elt.getOperand(Elt.getResNo()).getNode();
8445 /// build_pair (load, load) -> load
8446 /// if load locations are consecutive.
8447 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8448 assert(N->getOpcode() == ISD::BUILD_PAIR);
8450 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8451 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8452 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8453 LD1->getAddressSpace() != LD2->getAddressSpace())
8455 EVT LD1VT = LD1->getValueType(0);
8456 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8457 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8458 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8459 unsigned Align = LD1->getAlignment();
8460 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8461 VT.getTypeForEVT(*DAG.getContext()));
8463 if (NewAlign <= Align &&
8464 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8465 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8466 LD1->getPointerInfo(), Align);
8472 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8473 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8474 // and Lo parts; on big-endian machines it doesn't.
8475 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8478 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8479 const TargetLowering &TLI) {
8480 // If this is not a bitcast to an FP type or if the target doesn't have
8481 // IEEE754-compliant FP logic, we're done.
8482 EVT VT = N->getValueType(0);
8483 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8486 // TODO: Use splat values for the constant-checking below and remove this
8488 SDValue N0 = N->getOperand(0);
8489 EVT SourceVT = N0.getValueType();
8490 if (SourceVT.isVector())
8495 switch (N0.getOpcode()) {
8497 FPOpcode = ISD::FABS;
8498 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8501 FPOpcode = ISD::FNEG;
8502 SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8504 // TODO: ISD::OR --> ISD::FNABS?
8509 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8510 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8511 SDValue LogicOp0 = N0.getOperand(0);
8512 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8513 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8514 LogicOp0.getOpcode() == ISD::BITCAST &&
8515 LogicOp0->getOperand(0).getValueType() == VT)
8516 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8521 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8522 SDValue N0 = N->getOperand(0);
8523 EVT VT = N->getValueType(0);
8526 return DAG.getUNDEF(VT);
8528 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8529 // Only do this before legalize, since afterward the target may be depending
8530 // on the bitconvert.
8531 // First check to see if this is all constant.
8533 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8535 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8537 EVT DestEltVT = N->getValueType(0).getVectorElementType();
8538 assert(!DestEltVT.isVector() &&
8539 "Element type of vector ValueType must not be vector!");
8541 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8544 // If the input is a constant, let getNode fold it.
8545 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8546 // If we can't allow illegal operations, we need to check that this is just
8547 // a fp -> int or int -> conversion and that the resulting operation will
8549 if (!LegalOperations ||
8550 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8551 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8552 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8553 TLI.isOperationLegal(ISD::Constant, VT)))
8554 return DAG.getBitcast(VT, N0);
8557 // (conv (conv x, t1), t2) -> (conv x, t2)
8558 if (N0.getOpcode() == ISD::BITCAST)
8559 return DAG.getBitcast(VT, N0.getOperand(0));
8561 // fold (conv (load x)) -> (load (conv*)x)
8562 // If the resultant load doesn't need a higher alignment than the original!
8563 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8564 // Do not change the width of a volatile load.
8565 !cast<LoadSDNode>(N0)->isVolatile() &&
8566 // Do not remove the cast if the types differ in endian layout.
8567 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8568 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8569 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8570 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8571 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8572 unsigned OrigAlign = LN0->getAlignment();
8575 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8576 LN0->getAddressSpace(), OrigAlign, &Fast) &&
8579 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8580 LN0->getPointerInfo(), OrigAlign,
8581 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8582 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8587 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8590 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8591 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8594 // fold (bitcast (fneg x)) ->
8595 // flipbit = signbit
8596 // (xor (bitcast x) (build_pair flipbit, flipbit))
8598 // fold (bitcast (fabs x)) ->
8599 // flipbit = (and (extract_element (bitcast x), 0), signbit)
8600 // (xor (bitcast x) (build_pair flipbit, flipbit))
8601 // This often reduces constant pool loads.
8602 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8603 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8604 N0.getNode()->hasOneUse() && VT.isInteger() &&
8605 !VT.isVector() && !N0.getValueType().isVector()) {
8606 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8607 AddToWorklist(NewConv.getNode());
8610 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8611 assert(VT.getSizeInBits() == 128);
8612 SDValue SignBit = DAG.getConstant(
8613 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8615 if (N0.getOpcode() == ISD::FNEG) {
8617 AddToWorklist(FlipBit.getNode());
8619 assert(N0.getOpcode() == ISD::FABS);
8621 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8622 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8624 AddToWorklist(Hi.getNode());
8625 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8626 AddToWorklist(FlipBit.getNode());
8629 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8630 AddToWorklist(FlipBits.getNode());
8631 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8633 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8634 if (N0.getOpcode() == ISD::FNEG)
8635 return DAG.getNode(ISD::XOR, DL, VT,
8636 NewConv, DAG.getConstant(SignBit, DL, VT));
8637 assert(N0.getOpcode() == ISD::FABS);
8638 return DAG.getNode(ISD::AND, DL, VT,
8639 NewConv, DAG.getConstant(~SignBit, DL, VT));
8642 // fold (bitconvert (fcopysign cst, x)) ->
8643 // (or (and (bitconvert x), sign), (and cst, (not sign)))
8644 // Note that we don't handle (copysign x, cst) because this can always be
8645 // folded to an fneg or fabs.
8648 // fold (bitcast (fcopysign cst, x)) ->
8649 // flipbit = (and (extract_element
8650 // (xor (bitcast cst), (bitcast x)), 0),
8652 // (xor (bitcast cst) (build_pair flipbit, flipbit))
8653 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8654 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8655 VT.isInteger() && !VT.isVector()) {
8656 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8657 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8658 if (isTypeLegal(IntXVT)) {
8659 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8660 AddToWorklist(X.getNode());
8662 // If X has a different width than the result/lhs, sext it or truncate it.
8663 unsigned VTWidth = VT.getSizeInBits();
8664 if (OrigXWidth < VTWidth) {
8665 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8666 AddToWorklist(X.getNode());
8667 } else if (OrigXWidth > VTWidth) {
8668 // To get the sign bit in the right place, we have to shift it right
8669 // before truncating.
8671 X = DAG.getNode(ISD::SRL, DL,
8672 X.getValueType(), X,
8673 DAG.getConstant(OrigXWidth-VTWidth, DL,
8675 AddToWorklist(X.getNode());
8676 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8677 AddToWorklist(X.getNode());
8680 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8681 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8682 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8683 AddToWorklist(Cst.getNode());
8684 SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8685 AddToWorklist(X.getNode());
8686 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8687 AddToWorklist(XorResult.getNode());
8688 SDValue XorResult64 = DAG.getNode(
8689 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8690 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8692 AddToWorklist(XorResult64.getNode());
8694 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8695 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8696 AddToWorklist(FlipBit.getNode());
8698 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8699 AddToWorklist(FlipBits.getNode());
8700 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8702 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8703 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8704 X, DAG.getConstant(SignBit, SDLoc(X), VT));
8705 AddToWorklist(X.getNode());
8707 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8708 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8709 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8710 AddToWorklist(Cst.getNode());
8712 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8716 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8717 if (N0.getOpcode() == ISD::BUILD_PAIR)
8718 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8721 // Remove double bitcasts from shuffles - this is often a legacy of
8722 // XformToShuffleWithZero being used to combine bitmaskings (of
8723 // float vectors bitcast to integer vectors) into shuffles.
8724 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8725 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8726 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8727 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8728 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8729 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8731 // If operands are a bitcast, peek through if it casts the original VT.
8732 // If operands are a constant, just bitcast back to original VT.
8733 auto PeekThroughBitcast = [&](SDValue Op) {
8734 if (Op.getOpcode() == ISD::BITCAST &&
8735 Op.getOperand(0).getValueType() == VT)
8736 return SDValue(Op.getOperand(0));
8737 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8738 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8739 return DAG.getBitcast(VT, Op);
8743 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8744 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8749 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8750 SmallVector<int, 8> NewMask;
8751 for (int M : SVN->getMask())
8752 for (int i = 0; i != MaskScale; ++i)
8753 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8755 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8757 std::swap(SV0, SV1);
8758 ShuffleVectorSDNode::commuteMask(NewMask);
8759 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8763 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8769 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8770 EVT VT = N->getValueType(0);
8771 return CombineConsecutiveLoads(N, VT);
8774 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8775 /// operands. DstEltVT indicates the destination element value type.
8776 SDValue DAGCombiner::
8777 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8778 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8780 // If this is already the right type, we're done.
8781 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8783 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8784 unsigned DstBitSize = DstEltVT.getSizeInBits();
8786 // If this is a conversion of N elements of one type to N elements of another
8787 // type, convert each element. This handles FP<->INT cases.
8788 if (SrcBitSize == DstBitSize) {
8789 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8790 BV->getValueType(0).getVectorNumElements());
8792 // Due to the FP element handling below calling this routine recursively,
8793 // we can end up with a scalar-to-vector node here.
8794 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8795 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8796 DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8798 SmallVector<SDValue, 8> Ops;
8799 for (SDValue Op : BV->op_values()) {
8800 // If the vector element type is not legal, the BUILD_VECTOR operands
8801 // are promoted and implicitly truncated. Make that explicit here.
8802 if (Op.getValueType() != SrcEltVT)
8803 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8804 Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8805 AddToWorklist(Ops.back().getNode());
8807 return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8810 // Otherwise, we're growing or shrinking the elements. To avoid having to
8811 // handle annoying details of growing/shrinking FP values, we convert them to
8813 if (SrcEltVT.isFloatingPoint()) {
8814 // Convert the input float vector to a int vector where the elements are the
8816 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8817 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8821 // Now we know the input is an integer vector. If the output is a FP type,
8822 // convert to integer first, then to FP of the right size.
8823 if (DstEltVT.isFloatingPoint()) {
8824 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8825 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8827 // Next, convert to FP elements of the same size.
8828 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8833 // Okay, we know the src/dst types are both integers of differing types.
8834 // Handling growing first.
8835 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8836 if (SrcBitSize < DstBitSize) {
8837 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8839 SmallVector<SDValue, 8> Ops;
8840 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8841 i += NumInputsPerOutput) {
8842 bool isLE = DAG.getDataLayout().isLittleEndian();
8843 APInt NewBits = APInt(DstBitSize, 0);
8844 bool EltIsUndef = true;
8845 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8846 // Shift the previously computed bits over.
8847 NewBits <<= SrcBitSize;
8848 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8849 if (Op.isUndef()) continue;
8852 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8853 zextOrTrunc(SrcBitSize).zext(DstBitSize);
8857 Ops.push_back(DAG.getUNDEF(DstEltVT));
8859 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8862 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8863 return DAG.getBuildVector(VT, DL, Ops);
8866 // Finally, this must be the case where we are shrinking elements: each input
8867 // turns into multiple outputs.
8868 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8869 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8870 NumOutputsPerInput*BV->getNumOperands());
8871 SmallVector<SDValue, 8> Ops;
8873 for (const SDValue &Op : BV->op_values()) {
8875 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8879 APInt OpVal = cast<ConstantSDNode>(Op)->
8880 getAPIntValue().zextOrTrunc(SrcBitSize);
8882 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8883 APInt ThisVal = OpVal.trunc(DstBitSize);
8884 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8885 OpVal.lshrInPlace(DstBitSize);
8888 // For big endian targets, swap the order of the pieces of each element.
8889 if (DAG.getDataLayout().isBigEndian())
8890 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8893 return DAG.getBuildVector(VT, DL, Ops);
8896 static bool isContractable(SDNode *N) {
8897 SDNodeFlags F = N->getFlags();
8898 return F.hasAllowContract() || F.hasUnsafeAlgebra();
8901 /// Try to perform FMA combining on a given FADD node.
8902 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8903 SDValue N0 = N->getOperand(0);
8904 SDValue N1 = N->getOperand(1);
8905 EVT VT = N->getValueType(0);
8908 const TargetOptions &Options = DAG.getTarget().Options;
8910 // Floating-point multiply-add with intermediate rounding.
8911 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8913 // Floating-point multiply-add without intermediate rounding.
8915 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8916 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8918 // No valid opcode, do not combine.
8919 if (!HasFMAD && !HasFMA)
8922 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8923 Options.UnsafeFPMath || HasFMAD);
8924 // If the addition is not contractable, do not combine.
8925 if (!AllowFusionGlobally && !isContractable(N))
8928 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8929 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8932 // Always prefer FMAD to FMA for precision.
8933 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8934 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8935 bool LookThroughFPExt = TLI.isFPExtFree(VT);
8937 // Is the node an FMUL and contractable either due to global flags or
8939 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8940 if (N.getOpcode() != ISD::FMUL)
8942 return AllowFusionGlobally || isContractable(N.getNode());
8944 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8945 // prefer to fold the multiply with fewer uses.
8946 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8947 if (N0.getNode()->use_size() > N1.getNode()->use_size())
8951 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8952 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8953 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8954 N0.getOperand(0), N0.getOperand(1), N1);
8957 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8958 // Note: Commutes FADD operands.
8959 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8960 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8961 N1.getOperand(0), N1.getOperand(1), N0);
8964 // Look through FP_EXTEND nodes to do more combining.
8965 if (LookThroughFPExt) {
8966 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8967 if (N0.getOpcode() == ISD::FP_EXTEND) {
8968 SDValue N00 = N0.getOperand(0);
8969 if (isContractableFMUL(N00))
8970 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8971 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8973 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8974 N00.getOperand(1)), N1);
8977 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8978 // Note: Commutes FADD operands.
8979 if (N1.getOpcode() == ISD::FP_EXTEND) {
8980 SDValue N10 = N1.getOperand(0);
8981 if (isContractableFMUL(N10))
8982 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8983 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8985 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8986 N10.getOperand(1)), N0);
8990 // More folding opportunities when target permits.
8992 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8993 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8994 // are currently only supported on binary nodes.
8995 if (Options.UnsafeFPMath &&
8996 N0.getOpcode() == PreferredFusedOpcode &&
8997 N0.getOperand(2).getOpcode() == ISD::FMUL &&
8998 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
8999 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9000 N0.getOperand(0), N0.getOperand(1),
9001 DAG.getNode(PreferredFusedOpcode, SL, VT,
9002 N0.getOperand(2).getOperand(0),
9003 N0.getOperand(2).getOperand(1),
9007 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9008 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9009 // are currently only supported on binary nodes.
9010 if (Options.UnsafeFPMath &&
9011 N1->getOpcode() == PreferredFusedOpcode &&
9012 N1.getOperand(2).getOpcode() == ISD::FMUL &&
9013 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9014 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9015 N1.getOperand(0), N1.getOperand(1),
9016 DAG.getNode(PreferredFusedOpcode, SL, VT,
9017 N1.getOperand(2).getOperand(0),
9018 N1.getOperand(2).getOperand(1),
9022 if (LookThroughFPExt) {
9023 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9024 // -> (fma x, y, (fma (fpext u), (fpext v), z))
9025 auto FoldFAddFMAFPExtFMul = [&] (
9026 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9027 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9028 DAG.getNode(PreferredFusedOpcode, SL, VT,
9029 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9030 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9033 if (N0.getOpcode() == PreferredFusedOpcode) {
9034 SDValue N02 = N0.getOperand(2);
9035 if (N02.getOpcode() == ISD::FP_EXTEND) {
9036 SDValue N020 = N02.getOperand(0);
9037 if (isContractableFMUL(N020))
9038 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9039 N020.getOperand(0), N020.getOperand(1),
9044 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9045 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9046 // FIXME: This turns two single-precision and one double-precision
9047 // operation into two double-precision operations, which might not be
9048 // interesting for all targets, especially GPUs.
9049 auto FoldFAddFPExtFMAFMul = [&] (
9050 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9051 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9052 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9053 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9054 DAG.getNode(PreferredFusedOpcode, SL, VT,
9055 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9056 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9059 if (N0.getOpcode() == ISD::FP_EXTEND) {
9060 SDValue N00 = N0.getOperand(0);
9061 if (N00.getOpcode() == PreferredFusedOpcode) {
9062 SDValue N002 = N00.getOperand(2);
9063 if (isContractableFMUL(N002))
9064 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9065 N002.getOperand(0), N002.getOperand(1),
9070 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9071 // -> (fma y, z, (fma (fpext u), (fpext v), x))
9072 if (N1.getOpcode() == PreferredFusedOpcode) {
9073 SDValue N12 = N1.getOperand(2);
9074 if (N12.getOpcode() == ISD::FP_EXTEND) {
9075 SDValue N120 = N12.getOperand(0);
9076 if (isContractableFMUL(N120))
9077 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9078 N120.getOperand(0), N120.getOperand(1),
9083 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9084 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9085 // FIXME: This turns two single-precision and one double-precision
9086 // operation into two double-precision operations, which might not be
9087 // interesting for all targets, especially GPUs.
9088 if (N1.getOpcode() == ISD::FP_EXTEND) {
9089 SDValue N10 = N1.getOperand(0);
9090 if (N10.getOpcode() == PreferredFusedOpcode) {
9091 SDValue N102 = N10.getOperand(2);
9092 if (isContractableFMUL(N102))
9093 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9094 N102.getOperand(0), N102.getOperand(1),
9104 /// Try to perform FMA combining on a given FSUB node.
9105 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9106 SDValue N0 = N->getOperand(0);
9107 SDValue N1 = N->getOperand(1);
9108 EVT VT = N->getValueType(0);
9111 const TargetOptions &Options = DAG.getTarget().Options;
9112 // Floating-point multiply-add with intermediate rounding.
9113 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9115 // Floating-point multiply-add without intermediate rounding.
9117 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9118 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9120 // No valid opcode, do not combine.
9121 if (!HasFMAD && !HasFMA)
9124 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9125 Options.UnsafeFPMath || HasFMAD);
9126 // If the subtraction is not contractable, do not combine.
9127 if (!AllowFusionGlobally && !isContractable(N))
9130 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9131 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9134 // Always prefer FMAD to FMA for precision.
9135 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9136 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9137 bool LookThroughFPExt = TLI.isFPExtFree(VT);
9139 // Is the node an FMUL and contractable either due to global flags or
9141 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9142 if (N.getOpcode() != ISD::FMUL)
9144 return AllowFusionGlobally || isContractable(N.getNode());
9147 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9148 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9149 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9150 N0.getOperand(0), N0.getOperand(1),
9151 DAG.getNode(ISD::FNEG, SL, VT, N1));
9154 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9155 // Note: Commutes FSUB operands.
9156 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9157 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9158 DAG.getNode(ISD::FNEG, SL, VT,
9160 N1.getOperand(1), N0);
9162 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9163 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9164 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9165 SDValue N00 = N0.getOperand(0).getOperand(0);
9166 SDValue N01 = N0.getOperand(0).getOperand(1);
9167 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9168 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9169 DAG.getNode(ISD::FNEG, SL, VT, N1));
9172 // Look through FP_EXTEND nodes to do more combining.
9173 if (LookThroughFPExt) {
9174 // fold (fsub (fpext (fmul x, y)), z)
9175 // -> (fma (fpext x), (fpext y), (fneg z))
9176 if (N0.getOpcode() == ISD::FP_EXTEND) {
9177 SDValue N00 = N0.getOperand(0);
9178 if (isContractableFMUL(N00))
9179 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9180 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9182 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9184 DAG.getNode(ISD::FNEG, SL, VT, N1));
9187 // fold (fsub x, (fpext (fmul y, z)))
9188 // -> (fma (fneg (fpext y)), (fpext z), x)
9189 // Note: Commutes FSUB operands.
9190 if (N1.getOpcode() == ISD::FP_EXTEND) {
9191 SDValue N10 = N1.getOperand(0);
9192 if (isContractableFMUL(N10))
9193 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9194 DAG.getNode(ISD::FNEG, SL, VT,
9195 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9196 N10.getOperand(0))),
9197 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9202 // fold (fsub (fpext (fneg (fmul, x, y))), z)
9203 // -> (fneg (fma (fpext x), (fpext y), z))
9204 // Note: This could be removed with appropriate canonicalization of the
9205 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9206 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9207 // from implementing the canonicalization in visitFSUB.
9208 if (N0.getOpcode() == ISD::FP_EXTEND) {
9209 SDValue N00 = N0.getOperand(0);
9210 if (N00.getOpcode() == ISD::FNEG) {
9211 SDValue N000 = N00.getOperand(0);
9212 if (isContractableFMUL(N000)) {
9213 return DAG.getNode(ISD::FNEG, SL, VT,
9214 DAG.getNode(PreferredFusedOpcode, SL, VT,
9215 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9216 N000.getOperand(0)),
9217 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9218 N000.getOperand(1)),
9224 // fold (fsub (fneg (fpext (fmul, x, y))), z)
9225 // -> (fneg (fma (fpext x)), (fpext y), z)
9226 // Note: This could be removed with appropriate canonicalization of the
9227 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9228 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9229 // from implementing the canonicalization in visitFSUB.
9230 if (N0.getOpcode() == ISD::FNEG) {
9231 SDValue N00 = N0.getOperand(0);
9232 if (N00.getOpcode() == ISD::FP_EXTEND) {
9233 SDValue N000 = N00.getOperand(0);
9234 if (isContractableFMUL(N000)) {
9235 return DAG.getNode(ISD::FNEG, SL, VT,
9236 DAG.getNode(PreferredFusedOpcode, SL, VT,
9237 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9238 N000.getOperand(0)),
9239 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9240 N000.getOperand(1)),
9248 // More folding opportunities when target permits.
9250 // fold (fsub (fma x, y, (fmul u, v)), z)
9251 // -> (fma x, y (fma u, v, (fneg z)))
9252 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9253 // are currently only supported on binary nodes.
9254 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9255 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9256 N0.getOperand(2)->hasOneUse()) {
9257 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9258 N0.getOperand(0), N0.getOperand(1),
9259 DAG.getNode(PreferredFusedOpcode, SL, VT,
9260 N0.getOperand(2).getOperand(0),
9261 N0.getOperand(2).getOperand(1),
9262 DAG.getNode(ISD::FNEG, SL, VT,
9266 // fold (fsub x, (fma y, z, (fmul u, v)))
9267 // -> (fma (fneg y), z, (fma (fneg u), v, x))
9268 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9269 // are currently only supported on binary nodes.
9270 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9271 isContractableFMUL(N1.getOperand(2))) {
9272 SDValue N20 = N1.getOperand(2).getOperand(0);
9273 SDValue N21 = N1.getOperand(2).getOperand(1);
9274 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9275 DAG.getNode(ISD::FNEG, SL, VT,
9278 DAG.getNode(PreferredFusedOpcode, SL, VT,
9279 DAG.getNode(ISD::FNEG, SL, VT, N20),
9284 if (LookThroughFPExt) {
9285 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9286 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9287 if (N0.getOpcode() == PreferredFusedOpcode) {
9288 SDValue N02 = N0.getOperand(2);
9289 if (N02.getOpcode() == ISD::FP_EXTEND) {
9290 SDValue N020 = N02.getOperand(0);
9291 if (isContractableFMUL(N020))
9292 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9293 N0.getOperand(0), N0.getOperand(1),
9294 DAG.getNode(PreferredFusedOpcode, SL, VT,
9295 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9296 N020.getOperand(0)),
9297 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9298 N020.getOperand(1)),
9299 DAG.getNode(ISD::FNEG, SL, VT,
9304 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9305 // -> (fma (fpext x), (fpext y),
9306 // (fma (fpext u), (fpext v), (fneg z)))
9307 // FIXME: This turns two single-precision and one double-precision
9308 // operation into two double-precision operations, which might not be
9309 // interesting for all targets, especially GPUs.
9310 if (N0.getOpcode() == ISD::FP_EXTEND) {
9311 SDValue N00 = N0.getOperand(0);
9312 if (N00.getOpcode() == PreferredFusedOpcode) {
9313 SDValue N002 = N00.getOperand(2);
9314 if (isContractableFMUL(N002))
9315 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9316 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9318 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9320 DAG.getNode(PreferredFusedOpcode, SL, VT,
9321 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9322 N002.getOperand(0)),
9323 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9324 N002.getOperand(1)),
9325 DAG.getNode(ISD::FNEG, SL, VT,
9330 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9331 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9332 if (N1.getOpcode() == PreferredFusedOpcode &&
9333 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9334 SDValue N120 = N1.getOperand(2).getOperand(0);
9335 if (isContractableFMUL(N120)) {
9336 SDValue N1200 = N120.getOperand(0);
9337 SDValue N1201 = N120.getOperand(1);
9338 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9339 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9341 DAG.getNode(PreferredFusedOpcode, SL, VT,
9342 DAG.getNode(ISD::FNEG, SL, VT,
9343 DAG.getNode(ISD::FP_EXTEND, SL,
9345 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9351 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9352 // -> (fma (fneg (fpext y)), (fpext z),
9353 // (fma (fneg (fpext u)), (fpext v), x))
9354 // FIXME: This turns two single-precision and one double-precision
9355 // operation into two double-precision operations, which might not be
9356 // interesting for all targets, especially GPUs.
9357 if (N1.getOpcode() == ISD::FP_EXTEND &&
9358 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9359 SDValue N100 = N1.getOperand(0).getOperand(0);
9360 SDValue N101 = N1.getOperand(0).getOperand(1);
9361 SDValue N102 = N1.getOperand(0).getOperand(2);
9362 if (isContractableFMUL(N102)) {
9363 SDValue N1020 = N102.getOperand(0);
9364 SDValue N1021 = N102.getOperand(1);
9365 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9366 DAG.getNode(ISD::FNEG, SL, VT,
9367 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9369 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9370 DAG.getNode(PreferredFusedOpcode, SL, VT,
9371 DAG.getNode(ISD::FNEG, SL, VT,
9372 DAG.getNode(ISD::FP_EXTEND, SL,
9374 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9385 /// Try to perform FMA combining on a given FMUL node based on the distributive
9386 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9387 /// subtraction instead of addition).
9388 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9389 SDValue N0 = N->getOperand(0);
9390 SDValue N1 = N->getOperand(1);
9391 EVT VT = N->getValueType(0);
9394 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9396 const TargetOptions &Options = DAG.getTarget().Options;
9398 // The transforms below are incorrect when x == 0 and y == inf, because the
9399 // intermediate multiplication produces a nan.
9400 if (!Options.NoInfsFPMath)
9403 // Floating-point multiply-add without intermediate rounding.
9405 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9406 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9407 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9409 // Floating-point multiply-add with intermediate rounding. This can result
9410 // in a less precise result due to the changed rounding order.
9411 bool HasFMAD = Options.UnsafeFPMath &&
9412 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9414 // No valid opcode, do not combine.
9415 if (!HasFMAD && !HasFMA)
9418 // Always prefer FMAD to FMA for precision.
9419 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9420 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9422 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9423 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9424 auto FuseFADD = [&](SDValue X, SDValue Y) {
9425 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9426 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9427 if (XC1 && XC1->isExactlyValue(+1.0))
9428 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9429 if (XC1 && XC1->isExactlyValue(-1.0))
9430 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9431 DAG.getNode(ISD::FNEG, SL, VT, Y));
9436 if (SDValue FMA = FuseFADD(N0, N1))
9438 if (SDValue FMA = FuseFADD(N1, N0))
9441 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9442 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9443 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9444 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9445 auto FuseFSUB = [&](SDValue X, SDValue Y) {
9446 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9447 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9448 if (XC0 && XC0->isExactlyValue(+1.0))
9449 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9450 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9452 if (XC0 && XC0->isExactlyValue(-1.0))
9453 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9454 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9455 DAG.getNode(ISD::FNEG, SL, VT, Y));
9457 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9458 if (XC1 && XC1->isExactlyValue(+1.0))
9459 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9460 DAG.getNode(ISD::FNEG, SL, VT, Y));
9461 if (XC1 && XC1->isExactlyValue(-1.0))
9462 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9467 if (SDValue FMA = FuseFSUB(N0, N1))
9469 if (SDValue FMA = FuseFSUB(N1, N0))
9475 static bool isFMulNegTwo(SDValue &N) {
9476 if (N.getOpcode() != ISD::FMUL)
9478 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9479 return CFP->isExactlyValue(-2.0);
9483 SDValue DAGCombiner::visitFADD(SDNode *N) {
9484 SDValue N0 = N->getOperand(0);
9485 SDValue N1 = N->getOperand(1);
9486 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9487 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9488 EVT VT = N->getValueType(0);
9490 const TargetOptions &Options = DAG.getTarget().Options;
9491 const SDNodeFlags Flags = N->getFlags();
9495 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9498 // fold (fadd c1, c2) -> c1 + c2
9500 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9502 // canonicalize constant to RHS
9503 if (N0CFP && !N1CFP)
9504 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9506 if (SDValue NewSel = foldBinOpIntoSelect(N))
9509 // fold (fadd A, (fneg B)) -> (fsub A, B)
9510 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9511 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9512 return DAG.getNode(ISD::FSUB, DL, VT, N0,
9513 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9515 // fold (fadd (fneg A), B) -> (fsub B, A)
9516 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9517 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9518 return DAG.getNode(ISD::FSUB, DL, VT, N1,
9519 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9521 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9522 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9523 if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9524 (isFMulNegTwo(N1) && N1.hasOneUse())) {
9525 bool N1IsFMul = isFMulNegTwo(N1);
9526 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9527 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9528 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9531 // FIXME: Auto-upgrade the target/function-level option.
9532 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9533 // fold (fadd A, 0) -> A
9534 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9539 // If 'unsafe math' is enabled, fold lots of things.
9540 if (Options.UnsafeFPMath) {
9541 // No FP constant should be created after legalization as Instruction
9542 // Selection pass has a hard time dealing with FP constants.
9543 bool AllowNewConst = (Level < AfterLegalizeDAG);
9545 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9546 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9547 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9548 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9549 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9553 // If allowed, fold (fadd (fneg x), x) -> 0.0
9554 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9555 return DAG.getConstantFP(0.0, DL, VT);
9557 // If allowed, fold (fadd x, (fneg x)) -> 0.0
9558 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9559 return DAG.getConstantFP(0.0, DL, VT);
9561 // We can fold chains of FADD's of the same value into multiplications.
9562 // This transform is not safe in general because we are reducing the number
9563 // of rounding steps.
9564 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9565 if (N0.getOpcode() == ISD::FMUL) {
9566 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9567 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9569 // (fadd (fmul x, c), x) -> (fmul x, c+1)
9570 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9571 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9572 DAG.getConstantFP(1.0, DL, VT), Flags);
9573 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9576 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9577 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9578 N1.getOperand(0) == N1.getOperand(1) &&
9579 N0.getOperand(0) == N1.getOperand(0)) {
9580 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9581 DAG.getConstantFP(2.0, DL, VT), Flags);
9582 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9586 if (N1.getOpcode() == ISD::FMUL) {
9587 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9588 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9590 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9591 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9592 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9593 DAG.getConstantFP(1.0, DL, VT), Flags);
9594 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9597 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9598 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9599 N0.getOperand(0) == N0.getOperand(1) &&
9600 N1.getOperand(0) == N0.getOperand(0)) {
9601 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9602 DAG.getConstantFP(2.0, DL, VT), Flags);
9603 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9607 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9608 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9609 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9610 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9611 (N0.getOperand(0) == N1)) {
9612 return DAG.getNode(ISD::FMUL, DL, VT,
9613 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9617 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9618 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9619 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9620 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9621 N1.getOperand(0) == N0) {
9622 return DAG.getNode(ISD::FMUL, DL, VT,
9623 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9627 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9628 if (AllowNewConst &&
9629 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9630 N0.getOperand(0) == N0.getOperand(1) &&
9631 N1.getOperand(0) == N1.getOperand(1) &&
9632 N0.getOperand(0) == N1.getOperand(0)) {
9633 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9634 DAG.getConstantFP(4.0, DL, VT), Flags);
9637 } // enable-unsafe-fp-math
9639 // FADD -> FMA combines:
9640 if (SDValue Fused = visitFADDForFMACombine(N)) {
9641 AddToWorklist(Fused.getNode());
9647 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9648 SDValue N0 = N->getOperand(0);
9649 SDValue N1 = N->getOperand(1);
9650 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9651 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9652 EVT VT = N->getValueType(0);
9654 const TargetOptions &Options = DAG.getTarget().Options;
9655 const SDNodeFlags Flags = N->getFlags();
9659 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9662 // fold (fsub c1, c2) -> c1-c2
9664 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9666 if (SDValue NewSel = foldBinOpIntoSelect(N))
9669 // fold (fsub A, (fneg B)) -> (fadd A, B)
9670 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9671 return DAG.getNode(ISD::FADD, DL, VT, N0,
9672 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9674 // FIXME: Auto-upgrade the target/function-level option.
9675 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9676 // (fsub 0, B) -> -B
9677 if (N0CFP && N0CFP->isZero()) {
9678 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9679 return GetNegatedExpression(N1, DAG, LegalOperations);
9680 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9681 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9685 // If 'unsafe math' is enabled, fold lots of things.
9686 if (Options.UnsafeFPMath) {
9688 if (N1CFP && N1CFP->isZero())
9691 // (fsub x, x) -> 0.0
9693 return DAG.getConstantFP(0.0f, DL, VT);
9695 // (fsub x, (fadd x, y)) -> (fneg y)
9696 // (fsub x, (fadd y, x)) -> (fneg y)
9697 if (N1.getOpcode() == ISD::FADD) {
9698 SDValue N10 = N1->getOperand(0);
9699 SDValue N11 = N1->getOperand(1);
9701 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9702 return GetNegatedExpression(N11, DAG, LegalOperations);
9704 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9705 return GetNegatedExpression(N10, DAG, LegalOperations);
9709 // FSUB -> FMA combines:
9710 if (SDValue Fused = visitFSUBForFMACombine(N)) {
9711 AddToWorklist(Fused.getNode());
9718 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9719 SDValue N0 = N->getOperand(0);
9720 SDValue N1 = N->getOperand(1);
9721 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9722 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9723 EVT VT = N->getValueType(0);
9725 const TargetOptions &Options = DAG.getTarget().Options;
9726 const SDNodeFlags Flags = N->getFlags();
9729 if (VT.isVector()) {
9730 // This just handles C1 * C2 for vectors. Other vector folds are below.
9731 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9735 // fold (fmul c1, c2) -> c1*c2
9737 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9739 // canonicalize constant to RHS
9740 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9741 !isConstantFPBuildVectorOrConstantFP(N1))
9742 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9744 // fold (fmul A, 1.0) -> A
9745 if (N1CFP && N1CFP->isExactlyValue(1.0))
9748 if (SDValue NewSel = foldBinOpIntoSelect(N))
9751 if (Options.UnsafeFPMath) {
9752 // fold (fmul A, 0) -> 0
9753 if (N1CFP && N1CFP->isZero())
9756 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9757 if (N0.getOpcode() == ISD::FMUL) {
9758 // Fold scalars or any vector constants (not just splats).
9759 // This fold is done in general by InstCombine, but extra fmul insts
9760 // may have been generated during lowering.
9761 SDValue N00 = N0.getOperand(0);
9762 SDValue N01 = N0.getOperand(1);
9763 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9764 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9765 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9767 // Check 1: Make sure that the first operand of the inner multiply is NOT
9768 // a constant. Otherwise, we may induce infinite looping.
9769 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9770 // Check 2: Make sure that the second operand of the inner multiply and
9771 // the second operand of the outer multiply are constants.
9772 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9773 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9774 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9775 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9780 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9781 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9782 // during an early run of DAGCombiner can prevent folding with fmuls
9783 // inserted during lowering.
9784 if (N0.getOpcode() == ISD::FADD &&
9785 (N0.getOperand(0) == N0.getOperand(1)) &&
9787 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9788 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9789 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9793 // fold (fmul X, 2.0) -> (fadd X, X)
9794 if (N1CFP && N1CFP->isExactlyValue(+2.0))
9795 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9797 // fold (fmul X, -1.0) -> (fneg X)
9798 if (N1CFP && N1CFP->isExactlyValue(-1.0))
9799 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9800 return DAG.getNode(ISD::FNEG, DL, VT, N0);
9802 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9803 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9804 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9805 // Both can be negated for free, check to see if at least one is cheaper
9807 if (LHSNeg == 2 || RHSNeg == 2)
9808 return DAG.getNode(ISD::FMUL, DL, VT,
9809 GetNegatedExpression(N0, DAG, LegalOperations),
9810 GetNegatedExpression(N1, DAG, LegalOperations),
9815 // FMUL -> FMA combines:
9816 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9817 AddToWorklist(Fused.getNode());
9824 SDValue DAGCombiner::visitFMA(SDNode *N) {
9825 SDValue N0 = N->getOperand(0);
9826 SDValue N1 = N->getOperand(1);
9827 SDValue N2 = N->getOperand(2);
9828 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9829 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9830 EVT VT = N->getValueType(0);
9832 const TargetOptions &Options = DAG.getTarget().Options;
9834 // Constant fold FMA.
9835 if (isa<ConstantFPSDNode>(N0) &&
9836 isa<ConstantFPSDNode>(N1) &&
9837 isa<ConstantFPSDNode>(N2)) {
9838 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9841 if (Options.UnsafeFPMath) {
9842 if (N0CFP && N0CFP->isZero())
9844 if (N1CFP && N1CFP->isZero())
9847 // TODO: The FMA node should have flags that propagate to these nodes.
9848 if (N0CFP && N0CFP->isExactlyValue(1.0))
9849 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9850 if (N1CFP && N1CFP->isExactlyValue(1.0))
9851 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9853 // Canonicalize (fma c, x, y) -> (fma x, c, y)
9854 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9855 !isConstantFPBuildVectorOrConstantFP(N1))
9856 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9858 // TODO: FMA nodes should have flags that propagate to the created nodes.
9859 // For now, create a Flags object for use with all unsafe math transforms.
9861 Flags.setUnsafeAlgebra(true);
9863 if (Options.UnsafeFPMath) {
9864 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9865 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9866 isConstantFPBuildVectorOrConstantFP(N1) &&
9867 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9868 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9869 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9873 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9874 if (N0.getOpcode() == ISD::FMUL &&
9875 isConstantFPBuildVectorOrConstantFP(N1) &&
9876 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9877 return DAG.getNode(ISD::FMA, DL, VT,
9879 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9885 // (fma x, 1, y) -> (fadd x, y)
9886 // (fma x, -1, y) -> (fadd (fneg x), y)
9888 if (N1CFP->isExactlyValue(1.0))
9889 // TODO: The FMA node should have flags that propagate to this node.
9890 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9892 if (N1CFP->isExactlyValue(-1.0) &&
9893 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9894 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9895 AddToWorklist(RHSNeg.getNode());
9896 // TODO: The FMA node should have flags that propagate to this node.
9897 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9901 if (Options.UnsafeFPMath) {
9902 // (fma x, c, x) -> (fmul x, (c+1))
9903 if (N1CFP && N0 == N2) {
9904 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9905 DAG.getNode(ISD::FADD, DL, VT, N1,
9906 DAG.getConstantFP(1.0, DL, VT), Flags),
9910 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9911 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9912 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9913 DAG.getNode(ISD::FADD, DL, VT, N1,
9914 DAG.getConstantFP(-1.0, DL, VT), Flags),
9922 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9924 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9925 // Notice that this is not always beneficial. One reason is different targets
9926 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9927 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9928 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9929 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9930 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9931 const SDNodeFlags Flags = N->getFlags();
9932 if (!UnsafeMath && !Flags.hasAllowReciprocal())
9935 // Skip if current node is a reciprocal.
9936 SDValue N0 = N->getOperand(0);
9937 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9938 if (N0CFP && N0CFP->isExactlyValue(1.0))
9941 // Exit early if the target does not want this transform or if there can't
9942 // possibly be enough uses of the divisor to make the transform worthwhile.
9943 SDValue N1 = N->getOperand(1);
9944 unsigned MinUses = TLI.combineRepeatedFPDivisors();
9945 if (!MinUses || N1->use_size() < MinUses)
9948 // Find all FDIV users of the same divisor.
9949 // Use a set because duplicates may be present in the user list.
9950 SetVector<SDNode *> Users;
9951 for (auto *U : N1->uses()) {
9952 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
9953 // This division is eligible for optimization only if global unsafe math
9954 // is enabled or if this division allows reciprocal formation.
9955 if (UnsafeMath || U->getFlags().hasAllowReciprocal())
9960 // Now that we have the actual number of divisor uses, make sure it meets
9961 // the minimum threshold specified by the target.
9962 if (Users.size() < MinUses)
9965 EVT VT = N->getValueType(0);
9967 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
9968 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
9970 // Dividend / Divisor -> Dividend * Reciprocal
9971 for (auto *U : Users) {
9972 SDValue Dividend = U->getOperand(0);
9973 if (Dividend != FPOne) {
9974 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
9976 CombineTo(U, NewNode);
9977 } else if (U != Reciprocal.getNode()) {
9978 // In the absence of fast-math-flags, this user node is always the
9979 // same node as Reciprocal, but with FMF they may be different nodes.
9980 CombineTo(U, Reciprocal);
9983 return SDValue(N, 0); // N was replaced.
9986 SDValue DAGCombiner::visitFDIV(SDNode *N) {
9987 SDValue N0 = N->getOperand(0);
9988 SDValue N1 = N->getOperand(1);
9989 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9990 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9991 EVT VT = N->getValueType(0);
9993 const TargetOptions &Options = DAG.getTarget().Options;
9994 SDNodeFlags Flags = N->getFlags();
9998 if (SDValue FoldedVOp = SimplifyVBinOp(N))
10001 // fold (fdiv c1, c2) -> c1/c2
10002 if (N0CFP && N1CFP)
10003 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10005 if (SDValue NewSel = foldBinOpIntoSelect(N))
10008 if (Options.UnsafeFPMath) {
10009 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10011 // Compute the reciprocal 1.0 / c2.
10012 const APFloat &N1APF = N1CFP->getValueAPF();
10013 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10014 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10015 // Only do the transform if the reciprocal is a legal fp immediate that
10016 // isn't too nasty (eg NaN, denormal, ...).
10017 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10018 (!LegalOperations ||
10019 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10020 // backend)... we should handle this gracefully after Legalize.
10021 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
10022 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
10023 TLI.isFPImmLegal(Recip, VT)))
10024 return DAG.getNode(ISD::FMUL, DL, VT, N0,
10025 DAG.getConstantFP(Recip, DL, VT), Flags);
10028 // If this FDIV is part of a reciprocal square root, it may be folded
10029 // into a target-specific square root estimate instruction.
10030 if (N1.getOpcode() == ISD::FSQRT) {
10031 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10032 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10034 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10035 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10036 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10038 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10039 AddToWorklist(RV.getNode());
10040 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10042 } else if (N1.getOpcode() == ISD::FP_ROUND &&
10043 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10044 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10046 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10047 AddToWorklist(RV.getNode());
10048 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10050 } else if (N1.getOpcode() == ISD::FMUL) {
10051 // Look through an FMUL. Even though this won't remove the FDIV directly,
10052 // it's still worthwhile to get rid of the FSQRT if possible.
10055 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10056 SqrtOp = N1.getOperand(0);
10057 OtherOp = N1.getOperand(1);
10058 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10059 SqrtOp = N1.getOperand(1);
10060 OtherOp = N1.getOperand(0);
10062 if (SqrtOp.getNode()) {
10063 // We found a FSQRT, so try to make this fold:
10064 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10065 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10066 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10067 AddToWorklist(RV.getNode());
10068 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10073 // Fold into a reciprocal estimate and multiply instead of a real divide.
10074 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10075 AddToWorklist(RV.getNode());
10076 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10080 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10081 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10082 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10083 // Both can be negated for free, check to see if at least one is cheaper
10085 if (LHSNeg == 2 || RHSNeg == 2)
10086 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10087 GetNegatedExpression(N0, DAG, LegalOperations),
10088 GetNegatedExpression(N1, DAG, LegalOperations),
10093 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10094 return CombineRepeatedDivisors;
10099 SDValue DAGCombiner::visitFREM(SDNode *N) {
10100 SDValue N0 = N->getOperand(0);
10101 SDValue N1 = N->getOperand(1);
10102 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10103 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10104 EVT VT = N->getValueType(0);
10106 // fold (frem c1, c2) -> fmod(c1,c2)
10107 if (N0CFP && N1CFP)
10108 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10110 if (SDValue NewSel = foldBinOpIntoSelect(N))
10116 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10117 if (!DAG.getTarget().Options.UnsafeFPMath)
10120 SDValue N0 = N->getOperand(0);
10121 if (TLI.isFsqrtCheap(N0, DAG))
10124 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10125 // For now, create a Flags object for use with all unsafe math transforms.
10127 Flags.setUnsafeAlgebra(true);
10128 return buildSqrtEstimate(N0, Flags);
10131 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10132 /// copysign(x, fp_round(y)) -> copysign(x, y)
10133 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10134 SDValue N1 = N->getOperand(1);
10135 if ((N1.getOpcode() == ISD::FP_EXTEND ||
10136 N1.getOpcode() == ISD::FP_ROUND)) {
10137 // Do not optimize out type conversion of f128 type yet.
10138 // For some targets like x86_64, configuration is changed to keep one f128
10139 // value in one SSE register, but instruction selection cannot handle
10140 // FCOPYSIGN on SSE registers yet.
10141 EVT N1VT = N1->getValueType(0);
10142 EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10143 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10148 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10149 SDValue N0 = N->getOperand(0);
10150 SDValue N1 = N->getOperand(1);
10151 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10152 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10153 EVT VT = N->getValueType(0);
10155 if (N0CFP && N1CFP) // Constant fold
10156 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10159 const APFloat &V = N1CFP->getValueAPF();
10160 // copysign(x, c1) -> fabs(x) iff ispos(c1)
10161 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10162 if (!V.isNegative()) {
10163 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10164 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10166 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10167 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10168 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10172 // copysign(fabs(x), y) -> copysign(x, y)
10173 // copysign(fneg(x), y) -> copysign(x, y)
10174 // copysign(copysign(x,z), y) -> copysign(x, y)
10175 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10176 N0.getOpcode() == ISD::FCOPYSIGN)
10177 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10179 // copysign(x, abs(y)) -> abs(x)
10180 if (N1.getOpcode() == ISD::FABS)
10181 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10183 // copysign(x, copysign(y,z)) -> copysign(x, z)
10184 if (N1.getOpcode() == ISD::FCOPYSIGN)
10185 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10187 // copysign(x, fp_extend(y)) -> copysign(x, y)
10188 // copysign(x, fp_round(y)) -> copysign(x, y)
10189 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10190 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10195 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10196 SDValue N0 = N->getOperand(0);
10197 EVT VT = N->getValueType(0);
10198 EVT OpVT = N0.getValueType();
10200 // fold (sint_to_fp c1) -> c1fp
10201 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10202 // ...but only if the target supports immediate floating-point values
10203 (!LegalOperations ||
10204 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10205 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10207 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10208 // but UINT_TO_FP is legal on this target, try to convert.
10209 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10210 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10211 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10212 if (DAG.SignBitIsZero(N0))
10213 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10216 // The next optimizations are desirable only if SELECT_CC can be lowered.
10217 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10218 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10219 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10221 (!LegalOperations ||
10222 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10225 { N0.getOperand(0), N0.getOperand(1),
10226 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10227 N0.getOperand(2) };
10228 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10231 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10232 // (select_cc x, y, 1.0, 0.0,, cc)
10233 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10234 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10235 (!LegalOperations ||
10236 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10239 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10240 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10241 N0.getOperand(0).getOperand(2) };
10242 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10249 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10250 SDValue N0 = N->getOperand(0);
10251 EVT VT = N->getValueType(0);
10252 EVT OpVT = N0.getValueType();
10254 // fold (uint_to_fp c1) -> c1fp
10255 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10256 // ...but only if the target supports immediate floating-point values
10257 (!LegalOperations ||
10258 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10259 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10261 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10262 // but SINT_TO_FP is legal on this target, try to convert.
10263 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10264 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10265 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10266 if (DAG.SignBitIsZero(N0))
10267 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10270 // The next optimizations are desirable only if SELECT_CC can be lowered.
10271 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10272 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10274 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10275 (!LegalOperations ||
10276 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10279 { N0.getOperand(0), N0.getOperand(1),
10280 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10281 N0.getOperand(2) };
10282 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10289 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10290 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10291 SDValue N0 = N->getOperand(0);
10292 EVT VT = N->getValueType(0);
10294 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10297 SDValue Src = N0.getOperand(0);
10298 EVT SrcVT = Src.getValueType();
10299 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10300 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10302 // We can safely assume the conversion won't overflow the output range,
10303 // because (for example) (uint8_t)18293.f is undefined behavior.
10305 // Since we can assume the conversion won't overflow, our decision as to
10306 // whether the input will fit in the float should depend on the minimum
10307 // of the input range and output range.
10309 // This means this is also safe for a signed input and unsigned output, since
10310 // a negative input would lead to undefined behavior.
10311 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10312 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10313 unsigned ActualSize = std::min(InputSize, OutputSize);
10314 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10316 // We can only fold away the float conversion if the input range can be
10317 // represented exactly in the float range.
10318 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10319 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10320 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10321 : ISD::ZERO_EXTEND;
10322 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10324 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10325 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10326 return DAG.getBitcast(VT, Src);
10331 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10332 SDValue N0 = N->getOperand(0);
10333 EVT VT = N->getValueType(0);
10335 // fold (fp_to_sint c1fp) -> c1
10336 if (isConstantFPBuildVectorOrConstantFP(N0))
10337 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10339 return FoldIntToFPToInt(N, DAG);
10342 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10343 SDValue N0 = N->getOperand(0);
10344 EVT VT = N->getValueType(0);
10346 // fold (fp_to_uint c1fp) -> c1
10347 if (isConstantFPBuildVectorOrConstantFP(N0))
10348 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10350 return FoldIntToFPToInt(N, DAG);
10353 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10354 SDValue N0 = N->getOperand(0);
10355 SDValue N1 = N->getOperand(1);
10356 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10357 EVT VT = N->getValueType(0);
10359 // fold (fp_round c1fp) -> c1fp
10361 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10363 // fold (fp_round (fp_extend x)) -> x
10364 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10365 return N0.getOperand(0);
10367 // fold (fp_round (fp_round x)) -> (fp_round x)
10368 if (N0.getOpcode() == ISD::FP_ROUND) {
10369 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10370 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10372 // Skip this folding if it results in an fp_round from f80 to f16.
10374 // f80 to f16 always generates an expensive (and as yet, unimplemented)
10375 // libcall to __truncxfhf2 instead of selecting native f16 conversion
10376 // instructions from f32 or f64. Moreover, the first (value-preserving)
10377 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10379 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10382 // If the first fp_round isn't a value preserving truncation, it might
10383 // introduce a tie in the second fp_round, that wouldn't occur in the
10384 // single-step fp_round we want to fold to.
10385 // In other words, double rounding isn't the same as rounding.
10386 // Also, this is a value preserving truncation iff both fp_round's are.
10387 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10389 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10390 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10394 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10395 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10396 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10397 N0.getOperand(0), N1);
10398 AddToWorklist(Tmp.getNode());
10399 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10400 Tmp, N0.getOperand(1));
10403 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10409 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10410 SDValue N0 = N->getOperand(0);
10411 EVT VT = N->getValueType(0);
10412 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10413 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10415 // fold (fp_round_inreg c1fp) -> c1fp
10416 if (N0CFP && isTypeLegal(EVT)) {
10418 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10419 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10425 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10426 SDValue N0 = N->getOperand(0);
10427 EVT VT = N->getValueType(0);
10429 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10430 if (N->hasOneUse() &&
10431 N->use_begin()->getOpcode() == ISD::FP_ROUND)
10434 // fold (fp_extend c1fp) -> c1fp
10435 if (isConstantFPBuildVectorOrConstantFP(N0))
10436 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10438 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10439 if (N0.getOpcode() == ISD::FP16_TO_FP &&
10440 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10441 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10443 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10445 if (N0.getOpcode() == ISD::FP_ROUND
10446 && N0.getConstantOperandVal(1) == 1) {
10447 SDValue In = N0.getOperand(0);
10448 if (In.getValueType() == VT) return In;
10449 if (VT.bitsLT(In.getValueType()))
10450 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10451 In, N0.getOperand(1));
10452 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10455 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10456 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10457 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10458 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10459 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10461 LN0->getBasePtr(), N0.getValueType(),
10462 LN0->getMemOperand());
10463 CombineTo(N, ExtLoad);
10464 CombineTo(N0.getNode(),
10465 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10466 N0.getValueType(), ExtLoad,
10467 DAG.getIntPtrConstant(1, SDLoc(N0))),
10468 ExtLoad.getValue(1));
10469 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10472 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10478 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10479 SDValue N0 = N->getOperand(0);
10480 EVT VT = N->getValueType(0);
10482 // fold (fceil c1) -> fceil(c1)
10483 if (isConstantFPBuildVectorOrConstantFP(N0))
10484 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10489 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10490 SDValue N0 = N->getOperand(0);
10491 EVT VT = N->getValueType(0);
10493 // fold (ftrunc c1) -> ftrunc(c1)
10494 if (isConstantFPBuildVectorOrConstantFP(N0))
10495 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10500 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10501 SDValue N0 = N->getOperand(0);
10502 EVT VT = N->getValueType(0);
10504 // fold (ffloor c1) -> ffloor(c1)
10505 if (isConstantFPBuildVectorOrConstantFP(N0))
10506 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10511 // FIXME: FNEG and FABS have a lot in common; refactor.
10512 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10513 SDValue N0 = N->getOperand(0);
10514 EVT VT = N->getValueType(0);
10516 // Constant fold FNEG.
10517 if (isConstantFPBuildVectorOrConstantFP(N0))
10518 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10520 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10521 &DAG.getTarget().Options))
10522 return GetNegatedExpression(N0, DAG, LegalOperations);
10524 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10525 // constant pool values.
10526 if (!TLI.isFNegFree(VT) &&
10527 N0.getOpcode() == ISD::BITCAST &&
10528 N0.getNode()->hasOneUse()) {
10529 SDValue Int = N0.getOperand(0);
10530 EVT IntVT = Int.getValueType();
10531 if (IntVT.isInteger() && !IntVT.isVector()) {
10533 if (N0.getValueType().isVector()) {
10534 // For a vector, get a mask such as 0x80... per scalar element
10536 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10537 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10539 // For a scalar, just generate 0x80...
10540 SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10543 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10544 DAG.getConstant(SignMask, DL0, IntVT));
10545 AddToWorklist(Int.getNode());
10546 return DAG.getBitcast(VT, Int);
10550 // (fneg (fmul c, x)) -> (fmul -c, x)
10551 if (N0.getOpcode() == ISD::FMUL &&
10552 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10553 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10555 APFloat CVal = CFP1->getValueAPF();
10557 if (Level >= AfterLegalizeDAG &&
10558 (TLI.isFPImmLegal(CVal, VT) ||
10559 TLI.isOperationLegal(ISD::ConstantFP, VT)))
10560 return DAG.getNode(
10561 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10562 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10570 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10571 SDValue N0 = N->getOperand(0);
10572 SDValue N1 = N->getOperand(1);
10573 EVT VT = N->getValueType(0);
10574 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10575 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10577 if (N0CFP && N1CFP) {
10578 const APFloat &C0 = N0CFP->getValueAPF();
10579 const APFloat &C1 = N1CFP->getValueAPF();
10580 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10583 // Canonicalize to constant on RHS.
10584 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10585 !isConstantFPBuildVectorOrConstantFP(N1))
10586 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10591 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10592 SDValue N0 = N->getOperand(0);
10593 SDValue N1 = N->getOperand(1);
10594 EVT VT = N->getValueType(0);
10595 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10596 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10598 if (N0CFP && N1CFP) {
10599 const APFloat &C0 = N0CFP->getValueAPF();
10600 const APFloat &C1 = N1CFP->getValueAPF();
10601 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10604 // Canonicalize to constant on RHS.
10605 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10606 !isConstantFPBuildVectorOrConstantFP(N1))
10607 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10612 SDValue DAGCombiner::visitFABS(SDNode *N) {
10613 SDValue N0 = N->getOperand(0);
10614 EVT VT = N->getValueType(0);
10616 // fold (fabs c1) -> fabs(c1)
10617 if (isConstantFPBuildVectorOrConstantFP(N0))
10618 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10620 // fold (fabs (fabs x)) -> (fabs x)
10621 if (N0.getOpcode() == ISD::FABS)
10622 return N->getOperand(0);
10624 // fold (fabs (fneg x)) -> (fabs x)
10625 // fold (fabs (fcopysign x, y)) -> (fabs x)
10626 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10627 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10629 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10630 // constant pool values.
10631 if (!TLI.isFAbsFree(VT) &&
10632 N0.getOpcode() == ISD::BITCAST &&
10633 N0.getNode()->hasOneUse()) {
10634 SDValue Int = N0.getOperand(0);
10635 EVT IntVT = Int.getValueType();
10636 if (IntVT.isInteger() && !IntVT.isVector()) {
10638 if (N0.getValueType().isVector()) {
10639 // For a vector, get a mask such as 0x7f... per scalar element
10641 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10642 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10644 // For a scalar, just generate 0x7f...
10645 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10648 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10649 DAG.getConstant(SignMask, DL, IntVT));
10650 AddToWorklist(Int.getNode());
10651 return DAG.getBitcast(N->getValueType(0), Int);
10658 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10659 SDValue Chain = N->getOperand(0);
10660 SDValue N1 = N->getOperand(1);
10661 SDValue N2 = N->getOperand(2);
10663 // If N is a constant we could fold this into a fallthrough or unconditional
10664 // branch. However that doesn't happen very often in normal code, because
10665 // Instcombine/SimplifyCFG should have handled the available opportunities.
10666 // If we did this folding here, it would be necessary to update the
10667 // MachineBasicBlock CFG, which is awkward.
10669 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10671 if (N1.getOpcode() == ISD::SETCC &&
10672 TLI.isOperationLegalOrCustom(ISD::BR_CC,
10673 N1.getOperand(0).getValueType())) {
10674 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10675 Chain, N1.getOperand(2),
10676 N1.getOperand(0), N1.getOperand(1), N2);
10679 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10680 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10681 (N1.getOperand(0).hasOneUse() &&
10682 N1.getOperand(0).getOpcode() == ISD::SRL))) {
10683 SDNode *Trunc = nullptr;
10684 if (N1.getOpcode() == ISD::TRUNCATE) {
10685 // Look pass the truncate.
10686 Trunc = N1.getNode();
10687 N1 = N1.getOperand(0);
10690 // Match this pattern so that we can generate simpler code:
10693 // %b = and i32 %a, 2
10694 // %c = srl i32 %b, 1
10695 // brcond i32 %c ...
10700 // %b = and i32 %a, 2
10701 // %c = setcc eq %b, 0
10704 // This applies only when the AND constant value has one bit set and the
10705 // SRL constant is equal to the log2 of the AND constant. The back-end is
10706 // smart enough to convert the result into a TEST/JMP sequence.
10707 SDValue Op0 = N1.getOperand(0);
10708 SDValue Op1 = N1.getOperand(1);
10710 if (Op0.getOpcode() == ISD::AND &&
10711 Op1.getOpcode() == ISD::Constant) {
10712 SDValue AndOp1 = Op0.getOperand(1);
10714 if (AndOp1.getOpcode() == ISD::Constant) {
10715 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10717 if (AndConst.isPowerOf2() &&
10718 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10722 getSetCCResultType(Op0.getValueType()),
10723 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10726 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10727 MVT::Other, Chain, SetCC, N2);
10728 // Don't add the new BRCond into the worklist or else SimplifySelectCC
10729 // will convert it back to (X & C1) >> C2.
10730 CombineTo(N, NewBRCond, false);
10731 // Truncate is dead.
10733 deleteAndRecombine(Trunc);
10734 // Replace the uses of SRL with SETCC
10735 WorklistRemover DeadNodes(*this);
10736 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10737 deleteAndRecombine(N1.getNode());
10738 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10744 // Restore N1 if the above transformation doesn't match.
10745 N1 = N->getOperand(1);
10748 // Transform br(xor(x, y)) -> br(x != y)
10749 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10750 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10751 SDNode *TheXor = N1.getNode();
10752 SDValue Op0 = TheXor->getOperand(0);
10753 SDValue Op1 = TheXor->getOperand(1);
10754 if (Op0.getOpcode() == Op1.getOpcode()) {
10755 // Avoid missing important xor optimizations.
10756 if (SDValue Tmp = visitXOR(TheXor)) {
10757 if (Tmp.getNode() != TheXor) {
10758 DEBUG(dbgs() << "\nReplacing.8 ";
10759 TheXor->dump(&DAG);
10760 dbgs() << "\nWith: ";
10761 Tmp.getNode()->dump(&DAG);
10763 WorklistRemover DeadNodes(*this);
10764 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10765 deleteAndRecombine(TheXor);
10766 return DAG.getNode(ISD::BRCOND, SDLoc(N),
10767 MVT::Other, Chain, Tmp, N2);
10770 // visitXOR has changed XOR's operands or replaced the XOR completely,
10772 return SDValue(N, 0);
10776 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10777 bool Equal = false;
10778 if (isOneConstant(Op0) && Op0.hasOneUse() &&
10779 Op0.getOpcode() == ISD::XOR) {
10780 TheXor = Op0.getNode();
10784 EVT SetCCVT = N1.getValueType();
10786 SetCCVT = getSetCCResultType(SetCCVT);
10787 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10790 Equal ? ISD::SETEQ : ISD::SETNE);
10791 // Replace the uses of XOR with SETCC
10792 WorklistRemover DeadNodes(*this);
10793 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10794 deleteAndRecombine(N1.getNode());
10795 return DAG.getNode(ISD::BRCOND, SDLoc(N),
10796 MVT::Other, Chain, SetCC, N2);
10803 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10805 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10806 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10807 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10809 // If N is a constant we could fold this into a fallthrough or unconditional
10810 // branch. However that doesn't happen very often in normal code, because
10811 // Instcombine/SimplifyCFG should have handled the available opportunities.
10812 // If we did this folding here, it would be necessary to update the
10813 // MachineBasicBlock CFG, which is awkward.
10815 // Use SimplifySetCC to simplify SETCC's.
10816 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10817 CondLHS, CondRHS, CC->get(), SDLoc(N),
10819 if (Simp.getNode()) AddToWorklist(Simp.getNode());
10821 // fold to a simpler setcc
10822 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10823 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10824 N->getOperand(0), Simp.getOperand(2),
10825 Simp.getOperand(0), Simp.getOperand(1),
10831 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10832 /// and that N may be folded in the load / store addressing mode.
10833 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10835 const TargetLowering &TLI) {
10839 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
10840 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10842 VT = LD->getMemoryVT();
10843 AS = LD->getAddressSpace();
10844 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
10845 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10847 VT = ST->getMemoryVT();
10848 AS = ST->getAddressSpace();
10852 TargetLowering::AddrMode AM;
10853 if (N->getOpcode() == ISD::ADD) {
10854 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10857 AM.BaseOffs = Offset->getSExtValue();
10861 } else if (N->getOpcode() == ISD::SUB) {
10862 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10865 AM.BaseOffs = -Offset->getSExtValue();
10872 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10873 VT.getTypeForEVT(*DAG.getContext()), AS);
10876 /// Try turning a load/store into a pre-indexed load/store when the base
10877 /// pointer is an add or subtract and it has other uses besides the load/store.
10878 /// After the transformation, the new indexed load/store has effectively folded
10879 /// the add/subtract in and all of its other uses are redirected to the
10880 /// new load/store.
10881 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10882 if (Level < AfterLegalizeDAG)
10885 bool isLoad = true;
10888 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10889 if (LD->isIndexed())
10891 VT = LD->getMemoryVT();
10892 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10893 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10895 Ptr = LD->getBasePtr();
10896 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10897 if (ST->isIndexed())
10899 VT = ST->getMemoryVT();
10900 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10901 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10903 Ptr = ST->getBasePtr();
10909 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10910 // out. There is no reason to make this a preinc/predec.
10911 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10912 Ptr.getNode()->hasOneUse())
10915 // Ask the target to do addressing mode selection.
10918 ISD::MemIndexedMode AM = ISD::UNINDEXED;
10919 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10922 // Backends without true r+i pre-indexed forms may need to pass a
10923 // constant base with a variable offset so that constant coercion
10924 // will work with the patterns in canonical form.
10925 bool Swapped = false;
10926 if (isa<ConstantSDNode>(BasePtr)) {
10927 std::swap(BasePtr, Offset);
10931 // Don't create a indexed load / store with zero offset.
10932 if (isNullConstant(Offset))
10935 // Try turning it into a pre-indexed load / store except when:
10936 // 1) The new base ptr is a frame index.
10937 // 2) If N is a store and the new base ptr is either the same as or is a
10938 // predecessor of the value being stored.
10939 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10940 // that would create a cycle.
10941 // 4) All uses are load / store ops that use it as old base ptr.
10943 // Check #1. Preinc'ing a frame index would require copying the stack pointer
10944 // (plus the implicit offset) to a register to preinc anyway.
10945 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10950 SDValue Val = cast<StoreSDNode>(N)->getValue();
10951 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
10955 // Caches for hasPredecessorHelper.
10956 SmallPtrSet<const SDNode *, 32> Visited;
10957 SmallVector<const SDNode *, 16> Worklist;
10958 Worklist.push_back(N);
10960 // If the offset is a constant, there may be other adds of constants that
10961 // can be folded with this one. We should do this to avoid having to keep
10962 // a copy of the original base pointer.
10963 SmallVector<SDNode *, 16> OtherUses;
10964 if (isa<ConstantSDNode>(Offset))
10965 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
10966 UE = BasePtr.getNode()->use_end();
10968 SDUse &Use = UI.getUse();
10969 // Skip the use that is Ptr and uses of other results from BasePtr's
10970 // node (important for nodes that return multiple results).
10971 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
10974 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
10977 if (Use.getUser()->getOpcode() != ISD::ADD &&
10978 Use.getUser()->getOpcode() != ISD::SUB) {
10983 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
10984 if (!isa<ConstantSDNode>(Op1)) {
10989 // FIXME: In some cases, we can be smarter about this.
10990 if (Op1.getValueType() != Offset.getValueType()) {
10995 OtherUses.push_back(Use.getUser());
10999 std::swap(BasePtr, Offset);
11001 // Now check for #3 and #4.
11002 bool RealUse = false;
11004 for (SDNode *Use : Ptr.getNode()->uses()) {
11007 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11010 // If Ptr may be folded in addressing mode of other use, then it's
11011 // not profitable to do this transformation.
11012 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11021 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11022 BasePtr, Offset, AM);
11024 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11025 BasePtr, Offset, AM);
11028 DEBUG(dbgs() << "\nReplacing.4 ";
11030 dbgs() << "\nWith: ";
11031 Result.getNode()->dump(&DAG);
11033 WorklistRemover DeadNodes(*this);
11035 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11036 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11038 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11041 // Finally, since the node is now dead, remove it from the graph.
11042 deleteAndRecombine(N);
11045 std::swap(BasePtr, Offset);
11047 // Replace other uses of BasePtr that can be updated to use Ptr
11048 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11049 unsigned OffsetIdx = 1;
11050 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11052 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11053 BasePtr.getNode() && "Expected BasePtr operand");
11055 // We need to replace ptr0 in the following expression:
11056 // x0 * offset0 + y0 * ptr0 = t0
11058 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11060 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11061 // indexed load/store and the expresion that needs to be re-written.
11063 // Therefore, we have:
11064 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11066 ConstantSDNode *CN =
11067 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11068 int X0, X1, Y0, Y1;
11069 const APInt &Offset0 = CN->getAPIntValue();
11070 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11072 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11073 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11074 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11075 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11077 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11079 APInt CNV = Offset0;
11080 if (X0 < 0) CNV = -CNV;
11081 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11082 else CNV = CNV - Offset1;
11084 SDLoc DL(OtherUses[i]);
11086 // We can now generate the new expression.
11087 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11088 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11090 SDValue NewUse = DAG.getNode(Opcode,
11092 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11093 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11094 deleteAndRecombine(OtherUses[i]);
11097 // Replace the uses of Ptr with uses of the updated base value.
11098 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11099 deleteAndRecombine(Ptr.getNode());
11104 /// Try to combine a load/store with a add/sub of the base pointer node into a
11105 /// post-indexed load/store. The transformation folded the add/subtract into the
11106 /// new indexed load/store effectively and all of its uses are redirected to the
11107 /// new load/store.
11108 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11109 if (Level < AfterLegalizeDAG)
11112 bool isLoad = true;
11115 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11116 if (LD->isIndexed())
11118 VT = LD->getMemoryVT();
11119 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11120 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11122 Ptr = LD->getBasePtr();
11123 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11124 if (ST->isIndexed())
11126 VT = ST->getMemoryVT();
11127 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11128 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11130 Ptr = ST->getBasePtr();
11136 if (Ptr.getNode()->hasOneUse())
11139 for (SDNode *Op : Ptr.getNode()->uses()) {
11141 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11146 ISD::MemIndexedMode AM = ISD::UNINDEXED;
11147 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11148 // Don't create a indexed load / store with zero offset.
11149 if (isNullConstant(Offset))
11152 // Try turning it into a post-indexed load / store except when
11153 // 1) All uses are load / store ops that use it as base ptr (and
11154 // it may be folded as addressing mmode).
11155 // 2) Op must be independent of N, i.e. Op is neither a predecessor
11156 // nor a successor of N. Otherwise, if Op is folded that would
11159 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11163 bool TryNext = false;
11164 for (SDNode *Use : BasePtr.getNode()->uses()) {
11165 if (Use == Ptr.getNode())
11168 // If all the uses are load / store addresses, then don't do the
11170 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11171 bool RealUse = false;
11172 for (SDNode *UseUse : Use->uses()) {
11173 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11188 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11189 SDValue Result = isLoad
11190 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11191 BasePtr, Offset, AM)
11192 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11193 BasePtr, Offset, AM);
11194 ++PostIndexedNodes;
11196 DEBUG(dbgs() << "\nReplacing.5 ";
11198 dbgs() << "\nWith: ";
11199 Result.getNode()->dump(&DAG);
11201 WorklistRemover DeadNodes(*this);
11203 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11204 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11206 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11209 // Finally, since the node is now dead, remove it from the graph.
11210 deleteAndRecombine(N);
11212 // Replace the uses of Use with uses of the updated base value.
11213 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11214 Result.getValue(isLoad ? 1 : 0));
11215 deleteAndRecombine(Op);
11224 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11225 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11226 ISD::MemIndexedMode AM = LD->getAddressingMode();
11227 assert(AM != ISD::UNINDEXED);
11228 SDValue BP = LD->getOperand(1);
11229 SDValue Inc = LD->getOperand(2);
11231 // Some backends use TargetConstants for load offsets, but don't expect
11232 // TargetConstants in general ADD nodes. We can convert these constants into
11233 // regular Constants (if the constant is not opaque).
11234 assert((Inc.getOpcode() != ISD::TargetConstant ||
11235 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11236 "Cannot split out indexing using opaque target constants");
11237 if (Inc.getOpcode() == ISD::TargetConstant) {
11238 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11239 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11240 ConstInc->getValueType(0));
11244 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11245 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11248 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11249 LoadSDNode *LD = cast<LoadSDNode>(N);
11250 SDValue Chain = LD->getChain();
11251 SDValue Ptr = LD->getBasePtr();
11253 // If load is not volatile and there are no uses of the loaded value (and
11254 // the updated indexed value in case of indexed loads), change uses of the
11255 // chain value into uses of the chain input (i.e. delete the dead load).
11256 if (!LD->isVolatile()) {
11257 if (N->getValueType(1) == MVT::Other) {
11258 // Unindexed loads.
11259 if (!N->hasAnyUseOfValue(0)) {
11260 // It's not safe to use the two value CombineTo variant here. e.g.
11261 // v1, chain2 = load chain1, loc
11262 // v2, chain3 = load chain2, loc
11264 // Now we replace use of chain2 with chain1. This makes the second load
11265 // isomorphic to the one we are deleting, and thus makes this load live.
11266 DEBUG(dbgs() << "\nReplacing.6 ";
11268 dbgs() << "\nWith chain: ";
11269 Chain.getNode()->dump(&DAG);
11271 WorklistRemover DeadNodes(*this);
11272 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11273 AddUsersToWorklist(Chain.getNode());
11274 if (N->use_empty())
11275 deleteAndRecombine(N);
11277 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11281 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11283 // If this load has an opaque TargetConstant offset, then we cannot split
11284 // the indexing into an add/sub directly (that TargetConstant may not be
11285 // valid for a different type of node, and we cannot convert an opaque
11286 // target constant into a regular constant).
11287 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11288 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11290 if (!N->hasAnyUseOfValue(0) &&
11291 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11292 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11294 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11295 Index = SplitIndexingFromLoad(LD);
11296 // Try to fold the base pointer arithmetic into subsequent loads and
11298 AddUsersToWorklist(N);
11300 Index = DAG.getUNDEF(N->getValueType(1));
11301 DEBUG(dbgs() << "\nReplacing.7 ";
11303 dbgs() << "\nWith: ";
11304 Undef.getNode()->dump(&DAG);
11305 dbgs() << " and 2 other values\n");
11306 WorklistRemover DeadNodes(*this);
11307 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11308 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11309 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11310 deleteAndRecombine(N);
11311 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11316 // If this load is directly stored, replace the load value with the stored
11318 // TODO: Handle store large -> read small portion.
11319 // TODO: Handle TRUNCSTORE/LOADEXT
11320 if (OptLevel != CodeGenOpt::None &&
11321 ISD::isNormalLoad(N) && !LD->isVolatile()) {
11322 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11323 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11324 if (PrevST->getBasePtr() == Ptr &&
11325 PrevST->getValue().getValueType() == N->getValueType(0))
11326 return CombineTo(N, PrevST->getOperand(1), Chain);
11330 // Try to infer better alignment information than the load already has.
11331 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11332 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11333 if (Align > LD->getMemOperand()->getBaseAlignment()) {
11334 SDValue NewLoad = DAG.getExtLoad(
11335 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11336 LD->getPointerInfo(), LD->getMemoryVT(), Align,
11337 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11338 if (NewLoad.getNode() != N)
11339 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11344 if (LD->isUnindexed()) {
11345 // Walk up chain skipping non-aliasing memory nodes.
11346 SDValue BetterChain = FindBetterChain(N, Chain);
11348 // If there is a better chain.
11349 if (Chain != BetterChain) {
11352 // Replace the chain to void dependency.
11353 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11354 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11355 BetterChain, Ptr, LD->getMemOperand());
11357 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11358 LD->getValueType(0),
11359 BetterChain, Ptr, LD->getMemoryVT(),
11360 LD->getMemOperand());
11363 // Create token factor to keep old chain connected.
11364 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11365 MVT::Other, Chain, ReplLoad.getValue(1));
11367 // Make sure the new and old chains are cleaned up.
11368 AddToWorklist(Token.getNode());
11370 // Replace uses with load result and token factor. Don't add users
11372 return CombineTo(N, ReplLoad.getValue(0), Token, false);
11376 // Try transforming N to an indexed load.
11377 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11378 return SDValue(N, 0);
11380 // Try to slice up N to more direct loads if the slices are mapped to
11381 // different register banks or pairing can take place.
11382 if (SliceUpLoad(N))
11383 return SDValue(N, 0);
11389 /// \brief Helper structure used to slice a load in smaller loads.
11390 /// Basically a slice is obtained from the following sequence:
11391 /// Origin = load Ty1, Base
11392 /// Shift = srl Ty1 Origin, CstTy Amount
11393 /// Inst = trunc Shift to Ty2
11395 /// Then, it will be rewriten into:
11396 /// Slice = load SliceTy, Base + SliceOffset
11397 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11399 /// SliceTy is deduced from the number of bits that are actually used to
11401 struct LoadedSlice {
11402 /// \brief Helper structure used to compute the cost of a slice.
11404 /// Are we optimizing for code size.
11408 unsigned Truncates;
11409 unsigned CrossRegisterBanksCopies;
11413 Cost(bool ForCodeSize = false)
11414 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11415 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11417 /// \brief Get the cost of one isolated slice.
11418 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11419 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11420 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11421 EVT TruncType = LS.Inst->getValueType(0);
11422 EVT LoadedType = LS.getLoadedType();
11423 if (TruncType != LoadedType &&
11424 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11428 /// \brief Account for slicing gain in the current cost.
11429 /// Slicing provide a few gains like removing a shift or a
11430 /// truncate. This method allows to grow the cost of the original
11431 /// load with the gain from this slice.
11432 void addSliceGain(const LoadedSlice &LS) {
11433 // Each slice saves a truncate.
11434 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11435 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11436 LS.Inst->getValueType(0)))
11438 // If there is a shift amount, this slice gets rid of it.
11441 // If this slice can merge a cross register bank copy, account for it.
11442 if (LS.canMergeExpensiveCrossRegisterBankCopy())
11443 ++CrossRegisterBanksCopies;
11446 Cost &operator+=(const Cost &RHS) {
11447 Loads += RHS.Loads;
11448 Truncates += RHS.Truncates;
11449 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11450 ZExts += RHS.ZExts;
11451 Shift += RHS.Shift;
11455 bool operator==(const Cost &RHS) const {
11456 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11457 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11458 ZExts == RHS.ZExts && Shift == RHS.Shift;
11461 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11463 bool operator<(const Cost &RHS) const {
11464 // Assume cross register banks copies are as expensive as loads.
11465 // FIXME: Do we want some more target hooks?
11466 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11467 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11468 // Unless we are optimizing for code size, consider the
11469 // expensive operation first.
11470 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11471 return ExpensiveOpsLHS < ExpensiveOpsRHS;
11472 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11473 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11476 bool operator>(const Cost &RHS) const { return RHS < *this; }
11478 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11480 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11482 // The last instruction that represent the slice. This should be a
11483 // truncate instruction.
11485 // The original load instruction.
11486 LoadSDNode *Origin;
11487 // The right shift amount in bits from the original load.
11489 // The DAG from which Origin came from.
11490 // This is used to get some contextual information about legal types, etc.
11493 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11494 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11495 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11497 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11498 /// \return Result is \p BitWidth and has used bits set to 1 and
11499 /// not used bits set to 0.
11500 APInt getUsedBits() const {
11501 // Reproduce the trunc(lshr) sequence:
11502 // - Start from the truncated value.
11503 // - Zero extend to the desired bit width.
11505 assert(Origin && "No original load to compare against.");
11506 unsigned BitWidth = Origin->getValueSizeInBits(0);
11507 assert(Inst && "This slice is not bound to an instruction");
11508 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11509 "Extracted slice is bigger than the whole type!");
11510 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11511 UsedBits.setAllBits();
11512 UsedBits = UsedBits.zext(BitWidth);
11513 UsedBits <<= Shift;
11517 /// \brief Get the size of the slice to be loaded in bytes.
11518 unsigned getLoadedSize() const {
11519 unsigned SliceSize = getUsedBits().countPopulation();
11520 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11521 return SliceSize / 8;
11524 /// \brief Get the type that will be loaded for this slice.
11525 /// Note: This may not be the final type for the slice.
11526 EVT getLoadedType() const {
11527 assert(DAG && "Missing context");
11528 LLVMContext &Ctxt = *DAG->getContext();
11529 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11532 /// \brief Get the alignment of the load used for this slice.
11533 unsigned getAlignment() const {
11534 unsigned Alignment = Origin->getAlignment();
11535 unsigned Offset = getOffsetFromBase();
11537 Alignment = MinAlign(Alignment, Alignment + Offset);
11541 /// \brief Check if this slice can be rewritten with legal operations.
11542 bool isLegal() const {
11543 // An invalid slice is not legal.
11544 if (!Origin || !Inst || !DAG)
11547 // Offsets are for indexed load only, we do not handle that.
11548 if (!Origin->getOffset().isUndef())
11551 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11553 // Check that the type is legal.
11554 EVT SliceType = getLoadedType();
11555 if (!TLI.isTypeLegal(SliceType))
11558 // Check that the load is legal for this type.
11559 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11562 // Check that the offset can be computed.
11563 // 1. Check its type.
11564 EVT PtrType = Origin->getBasePtr().getValueType();
11565 if (PtrType == MVT::Untyped || PtrType.isExtended())
11568 // 2. Check that it fits in the immediate.
11569 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11572 // 3. Check that the computation is legal.
11573 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11576 // Check that the zext is legal if it needs one.
11577 EVT TruncateType = Inst->getValueType(0);
11578 if (TruncateType != SliceType &&
11579 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11585 /// \brief Get the offset in bytes of this slice in the original chunk of
11587 /// \pre DAG != nullptr.
11588 uint64_t getOffsetFromBase() const {
11589 assert(DAG && "Missing context.");
11590 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11591 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11592 uint64_t Offset = Shift / 8;
11593 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11594 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11595 "The size of the original loaded type is not a multiple of a"
11597 // If Offset is bigger than TySizeInBytes, it means we are loading all
11598 // zeros. This should have been optimized before in the process.
11599 assert(TySizeInBytes > Offset &&
11600 "Invalid shift amount for given loaded size");
11602 Offset = TySizeInBytes - Offset - getLoadedSize();
11606 /// \brief Generate the sequence of instructions to load the slice
11607 /// represented by this object and redirect the uses of this slice to
11608 /// this new sequence of instructions.
11609 /// \pre this->Inst && this->Origin are valid Instructions and this
11610 /// object passed the legal check: LoadedSlice::isLegal returned true.
11611 /// \return The last instruction of the sequence used to load the slice.
11612 SDValue loadSlice() const {
11613 assert(Inst && Origin && "Unable to replace a non-existing slice.");
11614 const SDValue &OldBaseAddr = Origin->getBasePtr();
11615 SDValue BaseAddr = OldBaseAddr;
11616 // Get the offset in that chunk of bytes w.r.t. the endianness.
11617 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11618 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11620 // BaseAddr = BaseAddr + Offset.
11621 EVT ArithType = BaseAddr.getValueType();
11623 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11624 DAG->getConstant(Offset, DL, ArithType));
11627 // Create the type of the loaded slice according to its size.
11628 EVT SliceType = getLoadedType();
11630 // Create the load for the slice.
11632 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11633 Origin->getPointerInfo().getWithOffset(Offset),
11634 getAlignment(), Origin->getMemOperand()->getFlags());
11635 // If the final type is not the same as the loaded type, this means that
11636 // we have to pad with zero. Create a zero extend for that.
11637 EVT FinalType = Inst->getValueType(0);
11638 if (SliceType != FinalType)
11640 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11644 /// \brief Check if this slice can be merged with an expensive cross register
11645 /// bank copy. E.g.,
11647 /// f = bitcast i32 i to float
11648 bool canMergeExpensiveCrossRegisterBankCopy() const {
11649 if (!Inst || !Inst->hasOneUse())
11651 SDNode *Use = *Inst->use_begin();
11652 if (Use->getOpcode() != ISD::BITCAST)
11654 assert(DAG && "Missing context");
11655 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11656 EVT ResVT = Use->getValueType(0);
11657 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11658 const TargetRegisterClass *ArgRC =
11659 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11660 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11663 // At this point, we know that we perform a cross-register-bank copy.
11664 // Check if it is expensive.
11665 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11666 // Assume bitcasts are cheap, unless both register classes do not
11667 // explicitly share a common sub class.
11668 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11671 // Check if it will be merged with the load.
11672 // 1. Check the alignment constraint.
11673 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11674 ResVT.getTypeForEVT(*DAG->getContext()));
11676 if (RequiredAlignment > getAlignment())
11679 // 2. Check that the load is a legal operation for that type.
11680 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11683 // 3. Check that we do not have a zext in the way.
11684 if (Inst->getValueType(0) != getLoadedType())
11692 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11693 /// \p UsedBits looks like 0..0 1..1 0..0.
11694 static bool areUsedBitsDense(const APInt &UsedBits) {
11695 // If all the bits are one, this is dense!
11696 if (UsedBits.isAllOnesValue())
11699 // Get rid of the unused bits on the right.
11700 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11701 // Get rid of the unused bits on the left.
11702 if (NarrowedUsedBits.countLeadingZeros())
11703 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11704 // Check that the chunk of bits is completely used.
11705 return NarrowedUsedBits.isAllOnesValue();
11708 /// \brief Check whether or not \p First and \p Second are next to each other
11709 /// in memory. This means that there is no hole between the bits loaded
11710 /// by \p First and the bits loaded by \p Second.
11711 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11712 const LoadedSlice &Second) {
11713 assert(First.Origin == Second.Origin && First.Origin &&
11714 "Unable to match different memory origins.");
11715 APInt UsedBits = First.getUsedBits();
11716 assert((UsedBits & Second.getUsedBits()) == 0 &&
11717 "Slices are not supposed to overlap.");
11718 UsedBits |= Second.getUsedBits();
11719 return areUsedBitsDense(UsedBits);
11722 /// \brief Adjust the \p GlobalLSCost according to the target
11723 /// paring capabilities and the layout of the slices.
11724 /// \pre \p GlobalLSCost should account for at least as many loads as
11725 /// there is in the slices in \p LoadedSlices.
11726 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11727 LoadedSlice::Cost &GlobalLSCost) {
11728 unsigned NumberOfSlices = LoadedSlices.size();
11729 // If there is less than 2 elements, no pairing is possible.
11730 if (NumberOfSlices < 2)
11733 // Sort the slices so that elements that are likely to be next to each
11734 // other in memory are next to each other in the list.
11735 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11736 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11737 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11738 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11740 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11741 // First (resp. Second) is the first (resp. Second) potentially candidate
11742 // to be placed in a paired load.
11743 const LoadedSlice *First = nullptr;
11744 const LoadedSlice *Second = nullptr;
11745 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11746 // Set the beginning of the pair.
11749 Second = &LoadedSlices[CurrSlice];
11751 // If First is NULL, it means we start a new pair.
11752 // Get to the next slice.
11756 EVT LoadedType = First->getLoadedType();
11758 // If the types of the slices are different, we cannot pair them.
11759 if (LoadedType != Second->getLoadedType())
11762 // Check if the target supplies paired loads for this type.
11763 unsigned RequiredAlignment = 0;
11764 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11765 // move to the next pair, this type is hopeless.
11769 // Check if we meet the alignment requirement.
11770 if (RequiredAlignment > First->getAlignment())
11773 // Check that both loads are next to each other in memory.
11774 if (!areSlicesNextToEachOther(*First, *Second))
11777 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11778 --GlobalLSCost.Loads;
11779 // Move to the next pair.
11784 /// \brief Check the profitability of all involved LoadedSlice.
11785 /// Currently, it is considered profitable if there is exactly two
11786 /// involved slices (1) which are (2) next to each other in memory, and
11787 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11789 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11790 /// the elements themselves.
11792 /// FIXME: When the cost model will be mature enough, we can relax
11793 /// constraints (1) and (2).
11794 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11795 const APInt &UsedBits, bool ForCodeSize) {
11796 unsigned NumberOfSlices = LoadedSlices.size();
11797 if (StressLoadSlicing)
11798 return NumberOfSlices > 1;
11801 if (NumberOfSlices != 2)
11805 if (!areUsedBitsDense(UsedBits))
11809 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11810 // The original code has one big load.
11811 OrigCost.Loads = 1;
11812 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11813 const LoadedSlice &LS = LoadedSlices[CurrSlice];
11814 // Accumulate the cost of all the slices.
11815 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11816 GlobalSlicingCost += SliceCost;
11818 // Account as cost in the original configuration the gain obtained
11819 // with the current slices.
11820 OrigCost.addSliceGain(LS);
11823 // If the target supports paired load, adjust the cost accordingly.
11824 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11825 return OrigCost > GlobalSlicingCost;
11828 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11829 /// operations, split it in the various pieces being extracted.
11831 /// This sort of thing is introduced by SROA.
11832 /// This slicing takes care not to insert overlapping loads.
11833 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11834 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11835 if (Level < AfterLegalizeDAG)
11838 LoadSDNode *LD = cast<LoadSDNode>(N);
11839 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11840 !LD->getValueType(0).isInteger())
11843 // Keep track of already used bits to detect overlapping values.
11844 // In that case, we will just abort the transformation.
11845 APInt UsedBits(LD->getValueSizeInBits(0), 0);
11847 SmallVector<LoadedSlice, 4> LoadedSlices;
11849 // Check if this load is used as several smaller chunks of bits.
11850 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11851 // of computation for each trunc.
11852 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11853 UI != UIEnd; ++UI) {
11854 // Skip the uses of the chain.
11855 if (UI.getUse().getResNo() != 0)
11858 SDNode *User = *UI;
11859 unsigned Shift = 0;
11861 // Check if this is a trunc(lshr).
11862 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11863 isa<ConstantSDNode>(User->getOperand(1))) {
11864 Shift = User->getConstantOperandVal(1);
11865 User = *User->use_begin();
11868 // At this point, User is a Truncate, iff we encountered, trunc or
11870 if (User->getOpcode() != ISD::TRUNCATE)
11873 // The width of the type must be a power of 2 and greater than 8-bits.
11874 // Otherwise the load cannot be represented in LLVM IR.
11875 // Moreover, if we shifted with a non-8-bits multiple, the slice
11876 // will be across several bytes. We do not support that.
11877 unsigned Width = User->getValueSizeInBits(0);
11878 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11881 // Build the slice for this chain of computations.
11882 LoadedSlice LS(User, LD, Shift, &DAG);
11883 APInt CurrentUsedBits = LS.getUsedBits();
11885 // Check if this slice overlaps with another.
11886 if ((CurrentUsedBits & UsedBits) != 0)
11888 // Update the bits used globally.
11889 UsedBits |= CurrentUsedBits;
11891 // Check if the new slice would be legal.
11895 // Record the slice.
11896 LoadedSlices.push_back(LS);
11899 // Abort slicing if it does not seem to be profitable.
11900 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11905 // Rewrite each chain to use an independent load.
11906 // By construction, each chain can be represented by a unique load.
11908 // Prepare the argument for the new token factor for all the slices.
11909 SmallVector<SDValue, 8> ArgChains;
11910 for (SmallVectorImpl<LoadedSlice>::const_iterator
11911 LSIt = LoadedSlices.begin(),
11912 LSItEnd = LoadedSlices.end();
11913 LSIt != LSItEnd; ++LSIt) {
11914 SDValue SliceInst = LSIt->loadSlice();
11915 CombineTo(LSIt->Inst, SliceInst, true);
11916 if (SliceInst.getOpcode() != ISD::LOAD)
11917 SliceInst = SliceInst.getOperand(0);
11918 assert(SliceInst->getOpcode() == ISD::LOAD &&
11919 "It takes more than a zext to get to the loaded slice!!");
11920 ArgChains.push_back(SliceInst.getValue(1));
11923 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11925 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11926 AddToWorklist(Chain.getNode());
11930 /// Check to see if V is (and load (ptr), imm), where the load is having
11931 /// specific bytes cleared out. If so, return the byte size being masked out
11932 /// and the shift amount.
11933 static std::pair<unsigned, unsigned>
11934 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11935 std::pair<unsigned, unsigned> Result(0, 0);
11937 // Check for the structure we're looking for.
11938 if (V->getOpcode() != ISD::AND ||
11939 !isa<ConstantSDNode>(V->getOperand(1)) ||
11940 !ISD::isNormalLoad(V->getOperand(0).getNode()))
11943 // Check the chain and pointer.
11944 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11945 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
11947 // The store should be chained directly to the load or be an operand of a
11949 if (LD == Chain.getNode())
11951 else if (Chain->getOpcode() != ISD::TokenFactor)
11952 return Result; // Fail.
11955 for (const SDValue &ChainOp : Chain->op_values())
11956 if (ChainOp.getNode() == LD) {
11960 if (!isOk) return Result;
11963 // This only handles simple types.
11964 if (V.getValueType() != MVT::i16 &&
11965 V.getValueType() != MVT::i32 &&
11966 V.getValueType() != MVT::i64)
11969 // Check the constant mask. Invert it so that the bits being masked out are
11970 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
11971 // follow the sign bit for uniformity.
11972 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
11973 unsigned NotMaskLZ = countLeadingZeros(NotMask);
11974 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
11975 unsigned NotMaskTZ = countTrailingZeros(NotMask);
11976 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
11977 if (NotMaskLZ == 64) return Result; // All zero mask.
11979 // See if we have a continuous run of bits. If so, we have 0*1+0*
11980 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
11983 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
11984 if (V.getValueType() != MVT::i64 && NotMaskLZ)
11985 NotMaskLZ -= 64-V.getValueSizeInBits();
11987 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
11988 switch (MaskedBytes) {
11992 default: return Result; // All one mask, or 5-byte mask.
11995 // Verify that the first bit starts at a multiple of mask so that the access
11996 // is aligned the same as the access width.
11997 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
11999 Result.first = MaskedBytes;
12000 Result.second = NotMaskTZ/8;
12005 /// Check to see if IVal is something that provides a value as specified by
12006 /// MaskInfo. If so, replace the specified store with a narrower store of
12007 /// truncated IVal.
12009 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12010 SDValue IVal, StoreSDNode *St,
12012 unsigned NumBytes = MaskInfo.first;
12013 unsigned ByteShift = MaskInfo.second;
12014 SelectionDAG &DAG = DC->getDAG();
12016 // Check to see if IVal is all zeros in the part being masked in by the 'or'
12017 // that uses this. If not, this is not a replacement.
12018 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12019 ByteShift*8, (ByteShift+NumBytes)*8);
12020 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12022 // Check that it is legal on the target to do this. It is legal if the new
12023 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12025 MVT VT = MVT::getIntegerVT(NumBytes*8);
12026 if (!DC->isTypeLegal(VT))
12029 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
12030 // shifted by ByteShift and truncated down to NumBytes.
12033 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12034 DAG.getConstant(ByteShift*8, DL,
12035 DC->getShiftAmountTy(IVal.getValueType())));
12038 // Figure out the offset for the store and the alignment of the access.
12040 unsigned NewAlign = St->getAlignment();
12042 if (DAG.getDataLayout().isLittleEndian())
12043 StOffset = ByteShift;
12045 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12047 SDValue Ptr = St->getBasePtr();
12050 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12051 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12052 NewAlign = MinAlign(NewAlign, StOffset);
12055 // Truncate down to the new size.
12056 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12060 .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12061 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12066 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12067 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12068 /// narrowing the load and store if it would end up being a win for performance
12070 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12071 StoreSDNode *ST = cast<StoreSDNode>(N);
12072 if (ST->isVolatile())
12075 SDValue Chain = ST->getChain();
12076 SDValue Value = ST->getValue();
12077 SDValue Ptr = ST->getBasePtr();
12078 EVT VT = Value.getValueType();
12080 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12083 unsigned Opc = Value.getOpcode();
12085 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12086 // is a byte mask indicating a consecutive number of bytes, check to see if
12087 // Y is known to provide just those bytes. If so, we try to replace the
12088 // load + replace + store sequence with a single (narrower) store, which makes
12090 if (Opc == ISD::OR) {
12091 std::pair<unsigned, unsigned> MaskedLoad;
12092 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12093 if (MaskedLoad.first)
12094 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12095 Value.getOperand(1), ST,this))
12096 return SDValue(NewST, 0);
12098 // Or is commutative, so try swapping X and Y.
12099 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12100 if (MaskedLoad.first)
12101 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12102 Value.getOperand(0), ST,this))
12103 return SDValue(NewST, 0);
12106 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12107 Value.getOperand(1).getOpcode() != ISD::Constant)
12110 SDValue N0 = Value.getOperand(0);
12111 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12112 Chain == SDValue(N0.getNode(), 1)) {
12113 LoadSDNode *LD = cast<LoadSDNode>(N0);
12114 if (LD->getBasePtr() != Ptr ||
12115 LD->getPointerInfo().getAddrSpace() !=
12116 ST->getPointerInfo().getAddrSpace())
12119 // Find the type to narrow it the load / op / store to.
12120 SDValue N1 = Value.getOperand(1);
12121 unsigned BitWidth = N1.getValueSizeInBits();
12122 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12123 if (Opc == ISD::AND)
12124 Imm ^= APInt::getAllOnesValue(BitWidth);
12125 if (Imm == 0 || Imm.isAllOnesValue())
12127 unsigned ShAmt = Imm.countTrailingZeros();
12128 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12129 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12130 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12131 // The narrowing should be profitable, the load/store operation should be
12132 // legal (or custom) and the store size should be equal to the NewVT width.
12133 while (NewBW < BitWidth &&
12134 (NewVT.getStoreSizeInBits() != NewBW ||
12135 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12136 !TLI.isNarrowingProfitable(VT, NewVT))) {
12137 NewBW = NextPowerOf2(NewBW);
12138 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12140 if (NewBW >= BitWidth)
12143 // If the lsb changed does not start at the type bitwidth boundary,
12144 // start at the previous one.
12146 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12147 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12148 std::min(BitWidth, ShAmt + NewBW));
12149 if ((Imm & Mask) == Imm) {
12150 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12151 if (Opc == ISD::AND)
12152 NewImm ^= APInt::getAllOnesValue(NewBW);
12153 uint64_t PtrOff = ShAmt / 8;
12154 // For big endian targets, we need to adjust the offset to the pointer to
12155 // load the correct bytes.
12156 if (DAG.getDataLayout().isBigEndian())
12157 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12159 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12160 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12161 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12164 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12165 Ptr.getValueType(), Ptr,
12166 DAG.getConstant(PtrOff, SDLoc(LD),
12167 Ptr.getValueType()));
12169 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12170 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12171 LD->getMemOperand()->getFlags(), LD->getAAInfo());
12172 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12173 DAG.getConstant(NewImm, SDLoc(Value),
12176 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12177 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12179 AddToWorklist(NewPtr.getNode());
12180 AddToWorklist(NewLD.getNode());
12181 AddToWorklist(NewVal.getNode());
12182 WorklistRemover DeadNodes(*this);
12183 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12192 /// For a given floating point load / store pair, if the load value isn't used
12193 /// by any other operations, then consider transforming the pair to integer
12194 /// load / store operations if the target deems the transformation profitable.
12195 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12196 StoreSDNode *ST = cast<StoreSDNode>(N);
12197 SDValue Chain = ST->getChain();
12198 SDValue Value = ST->getValue();
12199 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12200 Value.hasOneUse() &&
12201 Chain == SDValue(Value.getNode(), 1)) {
12202 LoadSDNode *LD = cast<LoadSDNode>(Value);
12203 EVT VT = LD->getMemoryVT();
12204 if (!VT.isFloatingPoint() ||
12205 VT != ST->getMemoryVT() ||
12206 LD->isNonTemporal() ||
12207 ST->isNonTemporal() ||
12208 LD->getPointerInfo().getAddrSpace() != 0 ||
12209 ST->getPointerInfo().getAddrSpace() != 0)
12212 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12213 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12214 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12215 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12216 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12219 unsigned LDAlign = LD->getAlignment();
12220 unsigned STAlign = ST->getAlignment();
12221 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12222 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12223 if (LDAlign < ABIAlign || STAlign < ABIAlign)
12227 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12228 LD->getPointerInfo(), LDAlign);
12231 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12232 ST->getPointerInfo(), STAlign);
12234 AddToWorklist(NewLD.getNode());
12235 AddToWorklist(NewST.getNode());
12236 WorklistRemover DeadNodes(*this);
12237 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12245 // This is a helper function for visitMUL to check the profitability
12246 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12247 // MulNode is the original multiply, AddNode is (add x, c1),
12248 // and ConstNode is c2.
12250 // If the (add x, c1) has multiple uses, we could increase
12251 // the number of adds if we make this transformation.
12252 // It would only be worth doing this if we can remove a
12253 // multiply in the process. Check for that here.
12257 // We're checking for cases where we have common "c3 * A" expressions.
12258 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12260 SDValue &ConstNode) {
12263 // If the add only has one use, this would be OK to do.
12264 if (AddNode.getNode()->hasOneUse())
12267 // Walk all the users of the constant with which we're multiplying.
12268 for (SDNode *Use : ConstNode->uses()) {
12270 if (Use == MulNode) // This use is the one we're on right now. Skip it.
12273 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12275 SDNode *MulVar = AddNode.getOperand(0).getNode();
12277 // OtherOp is what we're multiplying against the constant.
12278 if (Use->getOperand(0) == ConstNode)
12279 OtherOp = Use->getOperand(1).getNode();
12281 OtherOp = Use->getOperand(0).getNode();
12283 // Check to see if multiply is with the same operand of our "add".
12285 // ConstNode = CONST
12286 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
12288 // AddNode = (A + c1) <-- MulVar is A.
12289 // = AddNode * ConstNode <-- current visiting instruction.
12291 // If we make this transformation, we will have a common
12292 // multiply (ConstNode * A) that we can save.
12293 if (OtherOp == MulVar)
12296 // Now check to see if a future expansion will give us a common
12299 // ConstNode = CONST
12300 // AddNode = (A + c1)
12301 // ... = AddNode * ConstNode <-- current visiting instruction.
12303 // OtherOp = (A + c2)
12304 // Use = OtherOp * ConstNode <-- visiting Use.
12306 // If we make this transformation, we will have a common
12307 // multiply (CONST * A) after we also do the same transformation
12308 // to the "t2" instruction.
12309 if (OtherOp->getOpcode() == ISD::ADD &&
12310 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12311 OtherOp->getOperand(0).getNode() == MulVar)
12316 // Didn't find a case where this would be profitable.
12320 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12321 unsigned NumStores) {
12322 SmallVector<SDValue, 8> Chains;
12323 SmallPtrSet<const SDNode *, 8> Visited;
12324 SDLoc StoreDL(StoreNodes[0].MemNode);
12326 for (unsigned i = 0; i < NumStores; ++i) {
12327 Visited.insert(StoreNodes[i].MemNode);
12330 // don't include nodes that are children
12331 for (unsigned i = 0; i < NumStores; ++i) {
12332 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12333 Chains.push_back(StoreNodes[i].MemNode->getChain());
12336 assert(Chains.size() > 0 && "Chain should have generated a chain");
12337 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12340 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12341 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
12342 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
12343 // Make sure we have something to merge.
12347 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12349 // The latest Node in the DAG.
12350 SDLoc DL(StoreNodes[0].MemNode);
12354 bool IsVec = MemVT.isVector();
12355 unsigned Elts = NumStores;
12357 // When merging vector stores, get the total number of elements.
12358 Elts *= MemVT.getVectorNumElements();
12360 // Get the type for the merged vector store.
12361 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12362 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12364 if (IsConstantSrc) {
12365 SmallVector<SDValue, 8> BuildVector;
12366 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12367 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12368 SDValue Val = St->getValue();
12369 if (MemVT.getScalarType().isInteger())
12370 if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12371 Val = DAG.getConstant(
12372 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12373 SDLoc(CFP), MemVT);
12374 BuildVector.push_back(Val);
12376 StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12378 SmallVector<SDValue, 8> Ops;
12379 for (unsigned i = 0; i < NumStores; ++i) {
12380 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12381 SDValue Val = St->getValue();
12382 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12383 if (Val.getValueType() != MemVT)
12385 Ops.push_back(Val);
12388 // Build the extracted vector elements back into a vector.
12389 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12392 // We should always use a vector store when merging extracted vector
12393 // elements, so this path implies a store of constants.
12394 assert(IsConstantSrc && "Merged vector elements should use vector store");
12396 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12397 APInt StoreInt(SizeInBits, 0);
12399 // Construct a single integer constant which is made of the smaller
12400 // constant inputs.
12401 bool IsLE = DAG.getDataLayout().isLittleEndian();
12402 for (unsigned i = 0; i < NumStores; ++i) {
12403 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12404 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12406 SDValue Val = St->getValue();
12407 StoreInt <<= ElementSizeBytes * 8;
12408 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12409 StoreInt |= C->getAPIntValue().zext(SizeInBits);
12410 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12411 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
12413 llvm_unreachable("Invalid constant element type");
12417 // Create the new Load and Store operations.
12418 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12419 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12422 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12423 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12424 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
12425 FirstInChain->getBasePtr(),
12426 FirstInChain->getPointerInfo(),
12427 FirstInChain->getAlignment());
12429 // Replace all merged stores with the new store.
12430 for (unsigned i = 0; i < NumStores; ++i)
12431 CombineTo(StoreNodes[i].MemNode, NewStore);
12433 AddToWorklist(NewChain.getNode());
12437 void DAGCombiner::getStoreMergeCandidates(
12438 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12439 // This holds the base pointer, index, and the offset in bytes from the base
12441 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12442 EVT MemVT = St->getMemoryVT();
12444 // We must have a base and an offset.
12445 if (!BasePtr.Base.getNode())
12448 // Do not handle stores to undef base pointers.
12449 if (BasePtr.Base.isUndef())
12452 bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12453 bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12454 isa<ConstantFPSDNode>(St->getValue());
12455 bool IsExtractVecSrc =
12456 (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12457 St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12458 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr) -> bool {
12459 if (Other->isVolatile() || Other->isIndexed())
12461 // We can merge constant floats to equivalent integers
12462 if (Other->getMemoryVT() != MemVT)
12463 if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12464 isa<ConstantFPSDNode>(Other->getValue())))
12467 if (!isa<LoadSDNode>(Other->getValue()))
12470 if (!(isa<ConstantSDNode>(Other->getValue()) ||
12471 isa<ConstantFPSDNode>(Other->getValue())))
12473 if (IsExtractVecSrc)
12474 if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12475 Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12477 Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12478 return (Ptr.equalBaseIndex(BasePtr));
12480 // We looking for a root node which is an ancestor to all mergable
12481 // stores. We search up through a load, to our root and then down
12482 // through all children. For instance we will find Store{1,2,3} if
12483 // St is Store1, Store2. or Store3 where the root is not a load
12484 // which always true for nonvolatile ops. TODO: Expand
12485 // the search to find all valid candidates through multiple layers of loads.
12488 // |-------|-------|
12489 // Load Load Store3
12493 // FIXME: We should be able to climb and
12494 // descend TokenFactors to find candidates as well.
12496 SDNode *RootNode = (St->getChain()).getNode();
12498 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12499 RootNode = Ldn->getChain().getNode();
12500 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12501 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12502 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12503 if (I2.getOperandNo() == 0)
12504 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12505 BaseIndexOffset Ptr;
12506 if (CandidateMatch(OtherST, Ptr))
12507 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12510 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12511 if (I.getOperandNo() == 0)
12512 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12513 BaseIndexOffset Ptr;
12514 if (CandidateMatch(OtherST, Ptr))
12515 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12519 // We need to check that merging these stores does not cause a loop
12520 // in the DAG. Any store candidate may depend on another candidate
12521 // indirectly through its operand (we already consider dependencies
12522 // through the chain). Check in parallel by searching up from
12523 // non-chain operands of candidates.
12524 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12525 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12526 SmallPtrSet<const SDNode *, 16> Visited;
12527 SmallVector<const SDNode *, 8> Worklist;
12528 // search ops of store candidates
12529 for (unsigned i = 0; i < NumStores; ++i) {
12530 SDNode *n = StoreNodes[i].MemNode;
12531 // Potential loops may happen only through non-chain operands
12532 for (unsigned j = 1; j < n->getNumOperands(); ++j)
12533 Worklist.push_back(n->getOperand(j).getNode());
12535 // search through DAG. We can stop early if we find a storenode
12536 for (unsigned i = 0; i < NumStores; ++i) {
12537 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12543 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12544 if (OptLevel == CodeGenOpt::None)
12547 EVT MemVT = St->getMemoryVT();
12548 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12550 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12553 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12554 Attribute::NoImplicitFloat);
12556 // This function cannot currently deal with non-byte-sized memory sizes.
12557 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12560 if (!MemVT.isSimple())
12563 // Perform an early exit check. Do not bother looking at stored values that
12564 // are not constants, loads, or extracted vector elements.
12565 SDValue StoredVal = St->getValue();
12566 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12567 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12568 isa<ConstantFPSDNode>(StoredVal);
12569 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12570 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12572 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12575 // Don't merge vectors into wider vectors if the source data comes from loads.
12576 // TODO: This restriction can be lifted by using logic similar to the
12577 // ExtractVecSrc case.
12578 if (MemVT.isVector() && IsLoadSrc)
12581 SmallVector<MemOpLink, 8> StoreNodes;
12582 // Find potential store merge candidates by searching through chain sub-DAG
12583 getStoreMergeCandidates(St, StoreNodes);
12585 // Check if there is anything to merge.
12586 if (StoreNodes.size() < 2)
12589 // Sort the memory operands according to their distance from the
12591 std::sort(StoreNodes.begin(), StoreNodes.end(),
12592 [](MemOpLink LHS, MemOpLink RHS) {
12593 return LHS.OffsetFromBase < RHS.OffsetFromBase;
12596 // Store Merge attempts to merge the lowest stores. This generally
12597 // works out as if successful, as the remaining stores are checked
12598 // after the first collection of stores is merged. However, in the
12599 // case that a non-mergeable store is found first, e.g., {p[-2],
12600 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12601 // mergeable cases. To prevent this, we prune such stores from the
12602 // front of StoreNodes here.
12604 unsigned StartIdx = 0;
12605 while ((StartIdx + 1 < StoreNodes.size()) &&
12606 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12607 StoreNodes[StartIdx + 1].OffsetFromBase)
12610 // Bail if we don't have enough candidates to merge.
12611 if (StartIdx + 1 >= StoreNodes.size())
12615 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12617 // Scan the memory operations on the chain and find the first non-consecutive
12618 // store memory address.
12619 unsigned NumConsecutiveStores = 0;
12620 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12622 // Check that the addresses are consecutive starting from the second
12623 // element in the list of stores.
12624 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12625 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12626 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12628 NumConsecutiveStores = i + 1;
12631 if (NumConsecutiveStores < 2)
12634 // Check that we can merge these candidates without causing a cycle
12635 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumConsecutiveStores))
12639 // The node with the lowest store address.
12640 LLVMContext &Context = *DAG.getContext();
12641 const DataLayout &DL = DAG.getDataLayout();
12643 // Store the constants into memory as one consecutive store.
12644 if (IsConstantSrc) {
12646 while (NumConsecutiveStores > 1) {
12647 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12648 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12649 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12650 unsigned LastLegalType = 0;
12651 unsigned LastLegalVectorType = 0;
12652 bool NonZero = false;
12653 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12654 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12655 SDValue StoredVal = ST->getValue();
12657 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12658 NonZero |= !C->isNullValue();
12659 } else if (ConstantFPSDNode *C =
12660 dyn_cast<ConstantFPSDNode>(StoredVal)) {
12661 NonZero |= !C->getConstantFPValue()->isNullValue();
12667 // Find a legal type for the constant store.
12668 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12669 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12670 bool IsFast = false;
12671 if (TLI.isTypeLegal(StoreTy) &&
12672 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12673 FirstStoreAlign, &IsFast) &&
12675 LastLegalType = i + 1;
12676 // Or check whether a truncstore is legal.
12677 } else if (TLI.getTypeAction(Context, StoreTy) ==
12678 TargetLowering::TypePromoteInteger) {
12679 EVT LegalizedStoredValueTy =
12680 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12681 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12682 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12683 FirstStoreAS, FirstStoreAlign, &IsFast) &&
12685 LastLegalType = i + 1;
12689 // We only use vectors if the constant is known to be zero or the target
12690 // allows it and the function is not marked with the noimplicitfloat
12693 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12695 // Find a legal type for the vector store.
12696 EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1);
12697 if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(Ty) &&
12698 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12699 FirstStoreAlign, &IsFast) &&
12701 LastLegalVectorType = i + 1;
12705 // Check if we found a legal integer type that creates a meaningful merge.
12706 if (LastLegalType < 2 && LastLegalVectorType < 2)
12709 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12710 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12712 bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
12716 // Remove merged stores for next iteration.
12717 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12719 NumConsecutiveStores -= NumElem;
12724 // When extracting multiple vector elements, try to store them
12725 // in one vector store rather than a sequence of scalar stores.
12726 if (IsExtractVecSrc) {
12728 while (StoreNodes.size() >= 2) {
12729 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12730 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12731 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12732 unsigned NumStoresToMerge = 0;
12733 bool IsVec = MemVT.isVector();
12734 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12735 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12736 unsigned StoreValOpcode = St->getValue().getOpcode();
12737 // This restriction could be loosened.
12738 // Bail out if any stored values are not elements extracted from a
12739 // vector. It should be possible to handle mixed sources, but load
12740 // sources need more careful handling (see the block of code below that
12741 // handles consecutive loads).
12742 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12743 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12746 // Find a legal type for the vector store.
12747 unsigned Elts = i + 1;
12749 // When merging vector stores, get the total number of elements.
12750 Elts *= MemVT.getVectorNumElements();
12753 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12755 if (TLI.isTypeLegal(Ty) &&
12756 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12757 FirstStoreAlign, &IsFast) &&
12759 NumStoresToMerge = i + 1;
12762 bool Merged = MergeStoresOfConstantsOrVecElts(
12763 StoreNodes, MemVT, NumStoresToMerge, false, true);
12766 // Remove merged stores for next iteration.
12767 StoreNodes.erase(StoreNodes.begin(),
12768 StoreNodes.begin() + NumStoresToMerge);
12770 NumConsecutiveStores -= NumStoresToMerge;
12775 // Below we handle the case of multiple consecutive stores that
12776 // come from multiple consecutive loads. We merge them into a single
12777 // wide load and a single wide store.
12779 // Look for load nodes which are used by the stored values.
12780 SmallVector<MemOpLink, 8> LoadNodes;
12782 // Find acceptable loads. Loads need to have the same chain (token factor),
12783 // must not be zext, volatile, indexed, and they must be consecutive.
12784 BaseIndexOffset LdBasePtr;
12785 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12786 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12787 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12790 // Loads must only have one use.
12791 if (!Ld->hasNUsesOfValue(1, 0))
12794 // The memory operands must not be volatile.
12795 if (Ld->isVolatile() || Ld->isIndexed())
12798 // We do not accept ext loads.
12799 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12802 // The stored memory type must be the same.
12803 if (Ld->getMemoryVT() != MemVT)
12806 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12807 // If this is not the first ptr that we check.
12808 if (LdBasePtr.Base.getNode()) {
12809 // The base ptr must be the same.
12810 if (!LdPtr.equalBaseIndex(LdBasePtr))
12813 // Check that all other base pointers are the same as this one.
12817 // We found a potential memory operand to merge.
12818 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset));
12821 if (LoadNodes.size() < 2)
12824 // If we have load/store pair instructions and we only have two values,
12826 unsigned RequiredAlignment;
12827 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12828 St->getAlignment() >= RequiredAlignment)
12830 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12831 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12832 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12833 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12834 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12835 unsigned FirstLoadAlign = FirstLoad->getAlignment();
12837 // Scan the memory operations on the chain and find the first non-consecutive
12838 // load memory address. These variables hold the index in the store node
12840 unsigned LastConsecutiveLoad = 0;
12841 // This variable refers to the size and not index in the array.
12842 unsigned LastLegalVectorType = 0;
12843 unsigned LastLegalIntegerType = 0;
12844 StartAddress = LoadNodes[0].OffsetFromBase;
12845 SDValue FirstChain = FirstLoad->getChain();
12846 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12847 // All loads must share the same chain.
12848 if (LoadNodes[i].MemNode->getChain() != FirstChain)
12851 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12852 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12854 LastConsecutiveLoad = i;
12855 // Find a legal type for the vector store.
12856 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
12857 bool IsFastSt, IsFastLd;
12858 if (TLI.isTypeLegal(StoreTy) &&
12859 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12860 FirstStoreAlign, &IsFastSt) && IsFastSt &&
12861 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12862 FirstLoadAlign, &IsFastLd) && IsFastLd) {
12863 LastLegalVectorType = i + 1;
12866 // Find a legal type for the integer store.
12867 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
12868 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12869 if (TLI.isTypeLegal(StoreTy) &&
12870 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12871 FirstStoreAlign, &IsFastSt) && IsFastSt &&
12872 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12873 FirstLoadAlign, &IsFastLd) && IsFastLd)
12874 LastLegalIntegerType = i + 1;
12875 // Or check whether a truncstore and extload is legal.
12876 else if (TLI.getTypeAction(Context, StoreTy) ==
12877 TargetLowering::TypePromoteInteger) {
12878 EVT LegalizedStoredValueTy =
12879 TLI.getTypeToTransformTo(Context, StoreTy);
12880 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12881 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12882 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12883 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12884 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12885 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
12887 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12888 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
12890 LastLegalIntegerType = i+1;
12894 // Only use vector types if the vector type is larger than the integer type.
12895 // If they are the same, use integers.
12896 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
12897 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
12899 // We add +1 here because the LastXXX variables refer to location while
12900 // the NumElem refers to array/index size.
12901 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
12902 NumElem = std::min(LastLegalType, NumElem);
12907 // Find if it is better to use vectors or integers to load and store
12911 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12913 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12914 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12917 SDLoc LoadDL(LoadNodes[0].MemNode);
12918 SDLoc StoreDL(StoreNodes[0].MemNode);
12920 // The merged loads are required to have the same incoming chain, so
12921 // using the first's chain is acceptable.
12922 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12923 FirstLoad->getBasePtr(),
12924 FirstLoad->getPointerInfo(), FirstLoadAlign);
12926 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
12928 AddToWorklist(NewStoreChain.getNode());
12931 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12932 FirstInChain->getPointerInfo(), FirstStoreAlign);
12934 // Transfer chain users from old loads to the new load.
12935 for (unsigned i = 0; i < NumElem; ++i) {
12936 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12937 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12938 SDValue(NewLoad.getNode(), 1));
12941 // Replace the all stores with the new store.
12942 for (unsigned i = 0; i < NumElem; ++i)
12943 CombineTo(StoreNodes[i].MemNode, NewStore);
12947 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12951 // Replace the chain to avoid dependency.
12952 if (ST->isTruncatingStore()) {
12953 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12954 ST->getBasePtr(), ST->getMemoryVT(),
12955 ST->getMemOperand());
12957 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12958 ST->getMemOperand());
12961 // Create token to keep both nodes around.
12962 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12963 MVT::Other, ST->getChain(), ReplStore);
12965 // Make sure the new and old chains are cleaned up.
12966 AddToWorklist(Token.getNode());
12968 // Don't add users to work list.
12969 return CombineTo(ST, Token, false);
12972 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12973 SDValue Value = ST->getValue();
12974 if (Value.getOpcode() == ISD::TargetConstantFP)
12979 SDValue Chain = ST->getChain();
12980 SDValue Ptr = ST->getBasePtr();
12982 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12984 // NOTE: If the original store is volatile, this transform must not increase
12985 // the number of stores. For example, on x86-32 an f64 can be stored in one
12986 // processor operation but an i64 (which is not legal) requires two. So the
12987 // transform should not be done in this case.
12990 switch (CFP->getSimpleValueType(0).SimpleTy) {
12992 llvm_unreachable("Unknown FP type");
12993 case MVT::f16: // We don't do this for these yet.
12999 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13000 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13002 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13003 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13005 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13010 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13011 !ST->isVolatile()) ||
13012 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13014 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13015 getZExtValue(), SDLoc(CFP), MVT::i64);
13016 return DAG.getStore(Chain, DL, Tmp,
13017 Ptr, ST->getMemOperand());
13020 if (!ST->isVolatile() &&
13021 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13022 // Many FP stores are not made apparent until after legalize, e.g. for
13023 // argument passing. Since this is so common, custom legalize the
13024 // 64-bit integer store into two 32-bit stores.
13025 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13026 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13027 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13028 if (DAG.getDataLayout().isBigEndian())
13031 unsigned Alignment = ST->getAlignment();
13032 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13033 AAMDNodes AAInfo = ST->getAAInfo();
13035 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13036 ST->getAlignment(), MMOFlags, AAInfo);
13037 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13038 DAG.getConstant(4, DL, Ptr.getValueType()));
13039 Alignment = MinAlign(Alignment, 4U);
13040 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13041 ST->getPointerInfo().getWithOffset(4),
13042 Alignment, MMOFlags, AAInfo);
13043 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13051 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13052 StoreSDNode *ST = cast<StoreSDNode>(N);
13053 SDValue Chain = ST->getChain();
13054 SDValue Value = ST->getValue();
13055 SDValue Ptr = ST->getBasePtr();
13057 // If this is a store of a bit convert, store the input value if the
13058 // resultant store does not need a higher alignment than the original.
13059 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13060 ST->isUnindexed()) {
13061 EVT SVT = Value.getOperand(0).getValueType();
13062 if (((!LegalOperations && !ST->isVolatile()) ||
13063 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13064 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13065 unsigned OrigAlign = ST->getAlignment();
13067 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13068 ST->getAddressSpace(), OrigAlign, &Fast) &&
13070 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13071 ST->getPointerInfo(), OrigAlign,
13072 ST->getMemOperand()->getFlags(), ST->getAAInfo());
13077 // Turn 'store undef, Ptr' -> nothing.
13078 if (Value.isUndef() && ST->isUnindexed())
13081 // Try to infer better alignment information than the store already has.
13082 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13083 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13084 if (Align > ST->getAlignment()) {
13086 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13087 ST->getMemoryVT(), Align,
13088 ST->getMemOperand()->getFlags(), ST->getAAInfo());
13089 if (NewStore.getNode() != N)
13090 return CombineTo(ST, NewStore, true);
13095 // Try transforming a pair floating point load / store ops to integer
13096 // load / store ops.
13097 if (SDValue NewST = TransformFPLoadStorePair(N))
13100 if (ST->isUnindexed()) {
13101 // Walk up chain skipping non-aliasing memory nodes, on this store and any
13102 // adjacent stores.
13103 if (findBetterNeighborChains(ST)) {
13104 // replaceStoreChain uses CombineTo, which handled all of the worklist
13105 // manipulation. Return the original node to not do anything else.
13106 return SDValue(ST, 0);
13108 Chain = ST->getChain();
13111 // Try transforming N to an indexed store.
13112 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13113 return SDValue(N, 0);
13115 // FIXME: is there such a thing as a truncating indexed store?
13116 if (ST->isTruncatingStore() && ST->isUnindexed() &&
13117 Value.getValueType().isInteger()) {
13118 // See if we can simplify the input to this truncstore with knowledge that
13119 // only the low bits are being used. For example:
13120 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
13121 SDValue Shorter = GetDemandedBits(
13122 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13123 ST->getMemoryVT().getScalarSizeInBits()));
13124 AddToWorklist(Value.getNode());
13125 if (Shorter.getNode())
13126 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13127 Ptr, ST->getMemoryVT(), ST->getMemOperand());
13129 // Otherwise, see if we can simplify the operation with
13130 // SimplifyDemandedBits, which only works if the value has a single use.
13131 if (SimplifyDemandedBits(
13133 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13134 ST->getMemoryVT().getScalarSizeInBits()))) {
13135 // Re-visit the store if anything changed and the store hasn't been merged
13136 // with another node (N is deleted) SimplifyDemandedBits will add Value's
13137 // node back to the worklist if necessary, but we also need to re-visit
13138 // the Store node itself.
13139 if (N->getOpcode() != ISD::DELETED_NODE)
13141 return SDValue(N, 0);
13145 // If this is a load followed by a store to the same location, then the store
13147 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13148 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13149 ST->isUnindexed() && !ST->isVolatile() &&
13150 // There can't be any side effects between the load and store, such as
13151 // a call or store.
13152 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13153 // The store is dead, remove it.
13158 // If this is a store followed by a store with the same value to the same
13159 // location, then the store is dead/noop.
13160 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13161 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
13162 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
13163 ST1->isUnindexed() && !ST1->isVolatile()) {
13164 // The store is dead, remove it.
13169 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13170 // truncating store. We can do this even if this is already a truncstore.
13171 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13172 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13173 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13174 ST->getMemoryVT())) {
13175 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13176 Ptr, ST->getMemoryVT(), ST->getMemOperand());
13179 // Only perform this optimization before the types are legal, because we
13180 // don't want to perform this optimization on every DAGCombine invocation.
13183 // There can be multiple store sequences on the same chain.
13184 // Keep trying to merge store sequences until we are unable to do so
13185 // or until we merge the last store on the chain.
13186 bool Changed = MergeConsecutiveStores(ST);
13187 if (!Changed) break;
13188 // Return N as merge only uses CombineTo and no worklist clean
13189 // up is necessary.
13190 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13191 return SDValue(N, 0);
13195 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13197 // Make sure to do this only after attempting to merge stores in order to
13198 // avoid changing the types of some subset of stores due to visit order,
13199 // preventing their merging.
13200 if (isa<ConstantFPSDNode>(ST->getValue())) {
13201 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13205 if (SDValue NewSt = splitMergedValStore(ST))
13208 return ReduceLoadOpStoreWidth(N);
13211 /// For the instruction sequence of store below, F and I values
13212 /// are bundled together as an i64 value before being stored into memory.
13213 /// Sometimes it is more efficent to generate separate stores for F and I,
13214 /// which can remove the bitwise instructions or sink them to colder places.
13216 /// (store (or (zext (bitcast F to i32) to i64),
13217 /// (shl (zext I to i64), 32)), addr) -->
13218 /// (store F, addr) and (store I, addr+4)
13220 /// Similarly, splitting for other merged store can also be beneficial, like:
13221 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13222 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13223 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13224 /// For pair of {i16, i8}, i32 store --> two i16 stores.
13225 /// For pair of {i8, i8}, i16 store --> two i8 stores.
13227 /// We allow each target to determine specifically which kind of splitting is
13230 /// The store patterns are commonly seen from the simple code snippet below
13231 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13232 /// void goo(const std::pair<int, float> &);
13235 /// goo(std::make_pair(tmp, ftmp));
13239 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13240 if (OptLevel == CodeGenOpt::None)
13243 SDValue Val = ST->getValue();
13246 // Match OR operand.
13247 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13250 // Match SHL operand and get Lower and Higher parts of Val.
13251 SDValue Op1 = Val.getOperand(0);
13252 SDValue Op2 = Val.getOperand(1);
13254 if (Op1.getOpcode() != ISD::SHL) {
13255 std::swap(Op1, Op2);
13256 if (Op1.getOpcode() != ISD::SHL)
13260 Hi = Op1.getOperand(0);
13261 if (!Op1.hasOneUse())
13264 // Match shift amount to HalfValBitSize.
13265 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13266 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13267 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13270 // Lo and Hi are zero-extended from int with size less equal than 32
13272 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13273 !Lo.getOperand(0).getValueType().isScalarInteger() ||
13274 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13275 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13276 !Hi.getOperand(0).getValueType().isScalarInteger() ||
13277 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13280 // Use the EVT of low and high parts before bitcast as the input
13281 // of target query.
13282 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13283 ? Lo.getOperand(0).getValueType()
13284 : Lo.getValueType();
13285 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13286 ? Hi.getOperand(0).getValueType()
13287 : Hi.getValueType();
13288 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13291 // Start to split store.
13292 unsigned Alignment = ST->getAlignment();
13293 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13294 AAMDNodes AAInfo = ST->getAAInfo();
13296 // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13297 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13298 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13299 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13301 SDValue Chain = ST->getChain();
13302 SDValue Ptr = ST->getBasePtr();
13303 // Lower value store.
13304 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13305 ST->getAlignment(), MMOFlags, AAInfo);
13307 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13308 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13309 // Higher value store.
13311 DAG.getStore(St0, DL, Hi, Ptr,
13312 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13313 Alignment / 2, MMOFlags, AAInfo);
13317 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13318 SDValue InVec = N->getOperand(0);
13319 SDValue InVal = N->getOperand(1);
13320 SDValue EltNo = N->getOperand(2);
13323 // If the inserted element is an UNDEF, just use the input vector.
13324 if (InVal.isUndef())
13327 EVT VT = InVec.getValueType();
13329 // Check that we know which element is being inserted
13330 if (!isa<ConstantSDNode>(EltNo))
13332 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13334 // Canonicalize insert_vector_elt dag nodes.
13336 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13337 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13339 // Do this only if the child insert_vector node has one use; also
13340 // do this only if indices are both constants and Idx1 < Idx0.
13341 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13342 && isa<ConstantSDNode>(InVec.getOperand(2))) {
13343 unsigned OtherElt = InVec.getConstantOperandVal(2);
13344 if (Elt < OtherElt) {
13346 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13347 InVec.getOperand(0), InVal, EltNo);
13348 AddToWorklist(NewOp.getNode());
13349 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13350 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13354 // If we can't generate a legal BUILD_VECTOR, exit
13355 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13358 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13359 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
13360 // vector elements.
13361 SmallVector<SDValue, 8> Ops;
13362 // Do not combine these two vectors if the output vector will not replace
13363 // the input vector.
13364 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13365 Ops.append(InVec.getNode()->op_begin(),
13366 InVec.getNode()->op_end());
13367 } else if (InVec.isUndef()) {
13368 unsigned NElts = VT.getVectorNumElements();
13369 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13374 // Insert the element
13375 if (Elt < Ops.size()) {
13376 // All the operands of BUILD_VECTOR must have the same type;
13377 // we enforce that here.
13378 EVT OpVT = Ops[0].getValueType();
13379 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13382 // Return the new vector
13383 return DAG.getBuildVector(VT, DL, Ops);
13386 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13387 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13388 assert(!OriginalLoad->isVolatile());
13390 EVT ResultVT = EVE->getValueType(0);
13391 EVT VecEltVT = InVecVT.getVectorElementType();
13392 unsigned Align = OriginalLoad->getAlignment();
13393 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13394 VecEltVT.getTypeForEVT(*DAG.getContext()));
13396 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13399 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13400 ISD::NON_EXTLOAD : ISD::EXTLOAD;
13401 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13406 SDValue NewPtr = OriginalLoad->getBasePtr();
13408 EVT PtrType = NewPtr.getValueType();
13409 MachinePointerInfo MPI;
13411 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13412 int Elt = ConstEltNo->getZExtValue();
13413 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13414 Offset = DAG.getConstant(PtrOff, DL, PtrType);
13415 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13417 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13418 Offset = DAG.getNode(
13419 ISD::MUL, DL, PtrType, Offset,
13420 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13421 MPI = OriginalLoad->getPointerInfo();
13423 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13425 // The replacement we need to do here is a little tricky: we need to
13426 // replace an extractelement of a load with a load.
13427 // Use ReplaceAllUsesOfValuesWith to do the replacement.
13428 // Note that this replacement assumes that the extractvalue is the only
13429 // use of the load; that's okay because we don't want to perform this
13430 // transformation in other cases anyway.
13433 if (ResultVT.bitsGT(VecEltVT)) {
13434 // If the result type of vextract is wider than the load, then issue an
13435 // extending load instead.
13436 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13440 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13441 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13442 Align, OriginalLoad->getMemOperand()->getFlags(),
13443 OriginalLoad->getAAInfo());
13444 Chain = Load.getValue(1);
13446 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13447 MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13448 OriginalLoad->getAAInfo());
13449 Chain = Load.getValue(1);
13450 if (ResultVT.bitsLT(VecEltVT))
13451 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13453 Load = DAG.getBitcast(ResultVT, Load);
13455 WorklistRemover DeadNodes(*this);
13456 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13457 SDValue To[] = { Load, Chain };
13458 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13459 // Since we're explicitly calling ReplaceAllUses, add the new node to the
13460 // worklist explicitly as well.
13461 AddToWorklist(Load.getNode());
13462 AddUsersToWorklist(Load.getNode()); // Add users too
13463 // Make sure to revisit this node to clean it up; it will usually be dead.
13464 AddToWorklist(EVE);
13466 return SDValue(EVE, 0);
13469 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13470 // (vextract (scalar_to_vector val, 0) -> val
13471 SDValue InVec = N->getOperand(0);
13472 EVT VT = InVec.getValueType();
13473 EVT NVT = N->getValueType(0);
13475 if (InVec.isUndef())
13476 return DAG.getUNDEF(NVT);
13478 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13479 // Check if the result type doesn't match the inserted element type. A
13480 // SCALAR_TO_VECTOR may truncate the inserted element and the
13481 // EXTRACT_VECTOR_ELT may widen the extracted vector.
13482 SDValue InOp = InVec.getOperand(0);
13483 if (InOp.getValueType() != NVT) {
13484 assert(InOp.getValueType().isInteger() && NVT.isInteger());
13485 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13490 SDValue EltNo = N->getOperand(1);
13491 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13493 // extract_vector_elt (build_vector x, y), 1 -> y
13495 InVec.getOpcode() == ISD::BUILD_VECTOR &&
13496 TLI.isTypeLegal(VT) &&
13497 (InVec.hasOneUse() ||
13498 TLI.aggressivelyPreferBuildVectorSources(VT))) {
13499 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13500 EVT InEltVT = Elt.getValueType();
13502 // Sometimes build_vector's scalar input types do not match result type.
13503 if (NVT == InEltVT)
13506 // TODO: It may be useful to truncate if free if the build_vector implicitly
13510 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13511 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13512 ConstEltNo->isNullValue() && VT.isInteger()) {
13513 SDValue BCSrc = InVec.getOperand(0);
13514 if (BCSrc.getValueType().isScalarInteger())
13515 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13518 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13520 // This only really matters if the index is non-constant since other combines
13521 // on the constant elements already work.
13522 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13523 EltNo == InVec.getOperand(2)) {
13524 SDValue Elt = InVec.getOperand(1);
13525 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13528 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13529 // We only perform this optimization before the op legalization phase because
13530 // we may introduce new vector instructions which are not backed by TD
13531 // patterns. For example on AVX, extracting elements from a wide vector
13532 // without using extract_subvector. However, if we can find an underlying
13533 // scalar value, then we can always use that.
13534 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13535 int NumElem = VT.getVectorNumElements();
13536 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13537 // Find the new index to extract from.
13538 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13540 // Extracting an undef index is undef.
13542 return DAG.getUNDEF(NVT);
13544 // Select the right vector half to extract from.
13546 if (OrigElt < NumElem) {
13547 SVInVec = InVec->getOperand(0);
13549 SVInVec = InVec->getOperand(1);
13550 OrigElt -= NumElem;
13553 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13554 SDValue InOp = SVInVec.getOperand(OrigElt);
13555 if (InOp.getValueType() != NVT) {
13556 assert(InOp.getValueType().isInteger() && NVT.isInteger());
13557 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13563 // FIXME: We should handle recursing on other vector shuffles and
13564 // scalar_to_vector here as well.
13566 if (!LegalOperations) {
13567 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13568 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13569 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13573 bool BCNumEltsChanged = false;
13574 EVT ExtVT = VT.getVectorElementType();
13577 // If the result of load has to be truncated, then it's not necessarily
13579 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13582 if (InVec.getOpcode() == ISD::BITCAST) {
13583 // Don't duplicate a load with other uses.
13584 if (!InVec.hasOneUse())
13587 EVT BCVT = InVec.getOperand(0).getValueType();
13588 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13590 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13591 BCNumEltsChanged = true;
13592 InVec = InVec.getOperand(0);
13593 ExtVT = BCVT.getVectorElementType();
13596 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13597 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13598 ISD::isNormalLoad(InVec.getNode()) &&
13599 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13600 SDValue Index = N->getOperand(1);
13601 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13602 if (!OrigLoad->isVolatile()) {
13603 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13609 // Perform only after legalization to ensure build_vector / vector_shuffle
13610 // optimizations have already been done.
13611 if (!LegalOperations) return SDValue();
13613 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13614 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13615 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13618 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13620 LoadSDNode *LN0 = nullptr;
13621 const ShuffleVectorSDNode *SVN = nullptr;
13622 if (ISD::isNormalLoad(InVec.getNode())) {
13623 LN0 = cast<LoadSDNode>(InVec);
13624 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13625 InVec.getOperand(0).getValueType() == ExtVT &&
13626 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13627 // Don't duplicate a load with other uses.
13628 if (!InVec.hasOneUse())
13631 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13632 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13633 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13635 // (load $addr+1*size)
13637 // Don't duplicate a load with other uses.
13638 if (!InVec.hasOneUse())
13641 // If the bit convert changed the number of elements, it is unsafe
13642 // to examine the mask.
13643 if (BCNumEltsChanged)
13646 // Select the input vector, guarding against out of range extract vector.
13647 unsigned NumElems = VT.getVectorNumElements();
13648 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13649 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13651 if (InVec.getOpcode() == ISD::BITCAST) {
13652 // Don't duplicate a load with other uses.
13653 if (!InVec.hasOneUse())
13656 InVec = InVec.getOperand(0);
13658 if (ISD::isNormalLoad(InVec.getNode())) {
13659 LN0 = cast<LoadSDNode>(InVec);
13660 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13661 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13665 // Make sure we found a non-volatile load and the extractelement is
13667 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13670 // If Idx was -1 above, Elt is going to be -1, so just return undef.
13672 return DAG.getUNDEF(LVT);
13674 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13680 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13681 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13682 // We perform this optimization post type-legalization because
13683 // the type-legalizer often scalarizes integer-promoted vectors.
13684 // Performing this optimization before may create bit-casts which
13685 // will be type-legalized to complex code sequences.
13686 // We perform this optimization only before the operation legalizer because we
13687 // may introduce illegal operations.
13688 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13691 unsigned NumInScalars = N->getNumOperands();
13693 EVT VT = N->getValueType(0);
13695 // Check to see if this is a BUILD_VECTOR of a bunch of values
13696 // which come from any_extend or zero_extend nodes. If so, we can create
13697 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13698 // optimizations. We do not handle sign-extend because we can't fill the sign
13700 EVT SourceType = MVT::Other;
13701 bool AllAnyExt = true;
13703 for (unsigned i = 0; i != NumInScalars; ++i) {
13704 SDValue In = N->getOperand(i);
13705 // Ignore undef inputs.
13706 if (In.isUndef()) continue;
13708 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
13709 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13711 // Abort if the element is not an extension.
13712 if (!ZeroExt && !AnyExt) {
13713 SourceType = MVT::Other;
13717 // The input is a ZeroExt or AnyExt. Check the original type.
13718 EVT InTy = In.getOperand(0).getValueType();
13720 // Check that all of the widened source types are the same.
13721 if (SourceType == MVT::Other)
13724 else if (InTy != SourceType) {
13725 // Multiple income types. Abort.
13726 SourceType = MVT::Other;
13730 // Check if all of the extends are ANY_EXTENDs.
13731 AllAnyExt &= AnyExt;
13734 // In order to have valid types, all of the inputs must be extended from the
13735 // same source type and all of the inputs must be any or zero extend.
13736 // Scalar sizes must be a power of two.
13737 EVT OutScalarTy = VT.getScalarType();
13738 bool ValidTypes = SourceType != MVT::Other &&
13739 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13740 isPowerOf2_32(SourceType.getSizeInBits());
13742 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13743 // turn into a single shuffle instruction.
13747 bool isLE = DAG.getDataLayout().isLittleEndian();
13748 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13749 assert(ElemRatio > 1 && "Invalid element size ratio");
13750 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13751 DAG.getConstant(0, DL, SourceType);
13753 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13754 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13756 // Populate the new build_vector
13757 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13758 SDValue Cast = N->getOperand(i);
13759 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13760 Cast.getOpcode() == ISD::ZERO_EXTEND ||
13761 Cast.isUndef()) && "Invalid cast opcode");
13763 if (Cast.isUndef())
13764 In = DAG.getUNDEF(SourceType);
13766 In = Cast->getOperand(0);
13767 unsigned Index = isLE ? (i * ElemRatio) :
13768 (i * ElemRatio + (ElemRatio - 1));
13770 assert(Index < Ops.size() && "Invalid index");
13774 // The type of the new BUILD_VECTOR node.
13775 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13776 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13777 "Invalid vector size");
13778 // Check if the new vector type is legal.
13779 if (!isTypeLegal(VecVT)) return SDValue();
13781 // Make the new BUILD_VECTOR.
13782 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13784 // The new BUILD_VECTOR node has the potential to be further optimized.
13785 AddToWorklist(BV.getNode());
13786 // Bitcast to the desired type.
13787 return DAG.getBitcast(VT, BV);
13790 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13791 EVT VT = N->getValueType(0);
13793 unsigned NumInScalars = N->getNumOperands();
13796 EVT SrcVT = MVT::Other;
13797 unsigned Opcode = ISD::DELETED_NODE;
13798 unsigned NumDefs = 0;
13800 for (unsigned i = 0; i != NumInScalars; ++i) {
13801 SDValue In = N->getOperand(i);
13802 unsigned Opc = In.getOpcode();
13804 if (Opc == ISD::UNDEF)
13807 // If all scalar values are floats and converted from integers.
13808 if (Opcode == ISD::DELETED_NODE &&
13809 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13816 EVT InVT = In.getOperand(0).getValueType();
13818 // If all scalar values are typed differently, bail out. It's chosen to
13819 // simplify BUILD_VECTOR of integer types.
13820 if (SrcVT == MVT::Other)
13827 // If the vector has just one element defined, it's not worth to fold it into
13828 // a vectorized one.
13832 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13833 && "Should only handle conversion from integer to float.");
13834 assert(SrcVT != MVT::Other && "Cannot determine source type!");
13836 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
13838 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
13841 // Just because the floating-point vector type is legal does not necessarily
13842 // mean that the corresponding integer vector type is.
13843 if (!isTypeLegal(NVT))
13846 SmallVector<SDValue, 8> Opnds;
13847 for (unsigned i = 0; i != NumInScalars; ++i) {
13848 SDValue In = N->getOperand(i);
13851 Opnds.push_back(DAG.getUNDEF(SrcVT));
13853 Opnds.push_back(In.getOperand(0));
13855 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
13856 AddToWorklist(BV.getNode());
13858 return DAG.getNode(Opcode, DL, VT, BV);
13861 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
13862 ArrayRef<int> VectorMask,
13863 SDValue VecIn1, SDValue VecIn2,
13864 unsigned LeftIdx) {
13865 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13866 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
13868 EVT VT = N->getValueType(0);
13869 EVT InVT1 = VecIn1.getValueType();
13870 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13872 unsigned Vec2Offset = InVT1.getVectorNumElements();
13873 unsigned NumElems = VT.getVectorNumElements();
13874 unsigned ShuffleNumElems = NumElems;
13876 // We can't generate a shuffle node with mismatched input and output types.
13877 // Try to make the types match the type of the output.
13878 if (InVT1 != VT || InVT2 != VT) {
13879 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13880 // If the output vector length is a multiple of both input lengths,
13881 // we can concatenate them and pad the rest with undefs.
13882 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13883 assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13884 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13885 ConcatOps[0] = VecIn1;
13886 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13887 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13888 VecIn2 = SDValue();
13889 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13890 if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13893 if (!VecIn2.getNode()) {
13894 // If we only have one input vector, and it's twice the size of the
13895 // output, split it in two.
13896 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13897 DAG.getConstant(NumElems, DL, IdxTy));
13898 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13899 // Since we now have shorter input vectors, adjust the offset of the
13900 // second vector's start.
13901 Vec2Offset = NumElems;
13902 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13903 // VecIn1 is wider than the output, and we have another, possibly
13904 // smaller input. Pad the smaller input with undefs, shuffle at the
13905 // input vector width, and extract the output.
13906 // The shuffle type is different than VT, so check legality again.
13907 if (LegalOperations &&
13908 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13911 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
13912 // lower it back into a BUILD_VECTOR. So if the inserted type is
13913 // illegal, don't even try.
13914 if (InVT1 != InVT2) {
13915 if (!TLI.isTypeLegal(InVT2))
13917 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13918 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13920 ShuffleNumElems = NumElems * 2;
13922 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13923 // than VecIn1. We can't handle this for now - this case will disappear
13924 // when we start sorting the vectors by type.
13928 // TODO: Support cases where the length mismatch isn't exactly by a
13930 // TODO: Move this check upwards, so that if we have bad type
13931 // mismatches, we don't create any DAG nodes.
13936 // Initialize mask to undef.
13937 SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13939 // Only need to run up to the number of elements actually used, not the
13940 // total number of elements in the shuffle - if we are shuffling a wider
13941 // vector, the high lanes should be set to undef.
13942 for (unsigned i = 0; i != NumElems; ++i) {
13943 if (VectorMask[i] <= 0)
13946 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13947 if (VectorMask[i] == (int)LeftIdx) {
13948 Mask[i] = ExtIndex;
13949 } else if (VectorMask[i] == (int)LeftIdx + 1) {
13950 Mask[i] = Vec2Offset + ExtIndex;
13954 // The type the input vectors may have changed above.
13955 InVT1 = VecIn1.getValueType();
13957 // If we already have a VecIn2, it should have the same type as VecIn1.
13958 // If we don't, get an undef/zero vector of the appropriate type.
13959 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13960 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13962 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13963 if (ShuffleNumElems > NumElems)
13964 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13969 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13970 // operations. If the types of the vectors we're extracting from allow it,
13971 // turn this into a vector_shuffle node.
13972 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13974 EVT VT = N->getValueType(0);
13976 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13977 if (!isTypeLegal(VT))
13980 // May only combine to shuffle after legalize if shuffle is legal.
13981 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13984 bool UsesZeroVector = false;
13985 unsigned NumElems = N->getNumOperands();
13987 // Record, for each element of the newly built vector, which input vector
13988 // that element comes from. -1 stands for undef, 0 for the zero vector,
13989 // and positive values for the input vectors.
13990 // VectorMask maps each element to its vector number, and VecIn maps vector
13991 // numbers to their initial SDValues.
13993 SmallVector<int, 8> VectorMask(NumElems, -1);
13994 SmallVector<SDValue, 8> VecIn;
13995 VecIn.push_back(SDValue());
13997 for (unsigned i = 0; i != NumElems; ++i) {
13998 SDValue Op = N->getOperand(i);
14003 // See if we can use a blend with a zero vector.
14004 // TODO: Should we generalize this to a blend with an arbitrary constant
14006 if (isNullConstant(Op) || isNullFPConstant(Op)) {
14007 UsesZeroVector = true;
14012 // Not an undef or zero. If the input is something other than an
14013 // EXTRACT_VECTOR_ELT with a constant index, bail out.
14014 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14015 !isa<ConstantSDNode>(Op.getOperand(1)))
14018 SDValue ExtractedFromVec = Op.getOperand(0);
14020 // All inputs must have the same element type as the output.
14021 if (VT.getVectorElementType() !=
14022 ExtractedFromVec.getValueType().getVectorElementType())
14025 // Have we seen this input vector before?
14026 // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14027 // a map back from SDValues to numbers isn't worth it.
14028 unsigned Idx = std::distance(
14029 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14030 if (Idx == VecIn.size())
14031 VecIn.push_back(ExtractedFromVec);
14033 VectorMask[i] = Idx;
14036 // If we didn't find at least one input vector, bail out.
14037 if (VecIn.size() < 2)
14040 // TODO: We want to sort the vectors by descending length, so that adjacent
14041 // pairs have similar length, and the longer vector is always first in the
14044 // TODO: Should this fire if some of the input vectors has illegal type (like
14045 // it does now), or should we let legalization run its course first?
14048 // Take pairs of vectors, and shuffle them so that the result has elements
14049 // from these vectors in the correct places.
14050 // For example, given:
14051 // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14052 // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14053 // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14054 // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14055 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14056 // We will generate:
14057 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14058 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14059 SmallVector<SDValue, 4> Shuffles;
14060 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14061 unsigned LeftIdx = 2 * In + 1;
14062 SDValue VecLeft = VecIn[LeftIdx];
14064 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14066 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14067 VecRight, LeftIdx))
14068 Shuffles.push_back(Shuffle);
14073 // If we need the zero vector as an "ingredient" in the blend tree, add it
14074 // to the list of shuffles.
14075 if (UsesZeroVector)
14076 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14077 : DAG.getConstantFP(0.0, DL, VT));
14079 // If we only have one shuffle, we're done.
14080 if (Shuffles.size() == 1)
14081 return Shuffles[0];
14083 // Update the vector mask to point to the post-shuffle vectors.
14084 for (int &Vec : VectorMask)
14086 Vec = Shuffles.size() - 1;
14088 Vec = (Vec - 1) / 2;
14090 // More than one shuffle. Generate a binary tree of blends, e.g. if from
14091 // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14093 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14094 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14095 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14096 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14097 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14098 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14099 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14101 // Make sure the initial size of the shuffle list is even.
14102 if (Shuffles.size() % 2)
14103 Shuffles.push_back(DAG.getUNDEF(VT));
14105 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14107 Shuffles[CurSize] = DAG.getUNDEF(VT);
14110 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14112 int Right = 2 * In + 1;
14113 SmallVector<int, 8> Mask(NumElems, -1);
14114 for (unsigned i = 0; i != NumElems; ++i) {
14115 if (VectorMask[i] == Left) {
14117 VectorMask[i] = In;
14118 } else if (VectorMask[i] == Right) {
14119 Mask[i] = i + NumElems;
14120 VectorMask[i] = In;
14125 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14129 return Shuffles[0];
14132 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14133 EVT VT = N->getValueType(0);
14135 // A vector built entirely of undefs is undef.
14136 if (ISD::allOperandsUndef(N))
14137 return DAG.getUNDEF(VT);
14139 // Check if we can express BUILD VECTOR via subvector extract.
14140 if (!LegalTypes && (N->getNumOperands() > 1)) {
14141 SDValue Op0 = N->getOperand(0);
14142 auto checkElem = [&](SDValue Op) -> uint64_t {
14143 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14144 (Op0.getOperand(0) == Op.getOperand(0)))
14145 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14146 return CNode->getZExtValue();
14150 int Offset = checkElem(Op0);
14151 for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14152 if (Offset + i != checkElem(N->getOperand(i))) {
14158 if ((Offset == 0) &&
14159 (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14160 return Op0.getOperand(0);
14161 if ((Offset != -1) &&
14162 ((Offset % N->getValueType(0).getVectorNumElements()) ==
14163 0)) // IDX must be multiple of output size.
14164 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14165 Op0.getOperand(0), Op0.getOperand(1));
14168 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14171 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14174 if (SDValue V = reduceBuildVecToShuffle(N))
14180 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14181 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14182 EVT OpVT = N->getOperand(0).getValueType();
14184 // If the operands are legal vectors, leave them alone.
14185 if (TLI.isTypeLegal(OpVT))
14189 EVT VT = N->getValueType(0);
14190 SmallVector<SDValue, 8> Ops;
14192 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14193 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14195 // Keep track of what we encounter.
14196 bool AnyInteger = false;
14197 bool AnyFP = false;
14198 for (const SDValue &Op : N->ops()) {
14199 if (ISD::BITCAST == Op.getOpcode() &&
14200 !Op.getOperand(0).getValueType().isVector())
14201 Ops.push_back(Op.getOperand(0));
14202 else if (ISD::UNDEF == Op.getOpcode())
14203 Ops.push_back(ScalarUndef);
14207 // Note whether we encounter an integer or floating point scalar.
14208 // If it's neither, bail out, it could be something weird like x86mmx.
14209 EVT LastOpVT = Ops.back().getValueType();
14210 if (LastOpVT.isFloatingPoint())
14212 else if (LastOpVT.isInteger())
14218 // If any of the operands is a floating point scalar bitcast to a vector,
14219 // use floating point types throughout, and bitcast everything.
14220 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14222 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14223 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14225 for (SDValue &Op : Ops) {
14226 if (Op.getValueType() == SVT)
14231 Op = DAG.getBitcast(SVT, Op);
14236 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14237 VT.getSizeInBits() / SVT.getSizeInBits());
14238 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14241 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14242 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14243 // most two distinct vectors the same size as the result, attempt to turn this
14244 // into a legal shuffle.
14245 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14246 EVT VT = N->getValueType(0);
14247 EVT OpVT = N->getOperand(0).getValueType();
14248 int NumElts = VT.getVectorNumElements();
14249 int NumOpElts = OpVT.getVectorNumElements();
14251 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14252 SmallVector<int, 8> Mask;
14254 for (SDValue Op : N->ops()) {
14255 // Peek through any bitcast.
14256 while (Op.getOpcode() == ISD::BITCAST)
14257 Op = Op.getOperand(0);
14259 // UNDEF nodes convert to UNDEF shuffle mask values.
14260 if (Op.isUndef()) {
14261 Mask.append((unsigned)NumOpElts, -1);
14265 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14268 // What vector are we extracting the subvector from and at what index?
14269 SDValue ExtVec = Op.getOperand(0);
14271 // We want the EVT of the original extraction to correctly scale the
14272 // extraction index.
14273 EVT ExtVT = ExtVec.getValueType();
14275 // Peek through any bitcast.
14276 while (ExtVec.getOpcode() == ISD::BITCAST)
14277 ExtVec = ExtVec.getOperand(0);
14279 // UNDEF nodes convert to UNDEF shuffle mask values.
14280 if (ExtVec.isUndef()) {
14281 Mask.append((unsigned)NumOpElts, -1);
14285 if (!isa<ConstantSDNode>(Op.getOperand(1)))
14287 int ExtIdx = Op.getConstantOperandVal(1);
14289 // Ensure that we are extracting a subvector from a vector the same
14290 // size as the result.
14291 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14294 // Scale the subvector index to account for any bitcast.
14295 int NumExtElts = ExtVT.getVectorNumElements();
14296 if (0 == (NumExtElts % NumElts))
14297 ExtIdx /= (NumExtElts / NumElts);
14298 else if (0 == (NumElts % NumExtElts))
14299 ExtIdx *= (NumElts / NumExtElts);
14303 // At most we can reference 2 inputs in the final shuffle.
14304 if (SV0.isUndef() || SV0 == ExtVec) {
14306 for (int i = 0; i != NumOpElts; ++i)
14307 Mask.push_back(i + ExtIdx);
14308 } else if (SV1.isUndef() || SV1 == ExtVec) {
14310 for (int i = 0; i != NumOpElts; ++i)
14311 Mask.push_back(i + ExtIdx + NumElts);
14317 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14320 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14321 DAG.getBitcast(VT, SV1), Mask);
14324 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14325 // If we only have one input vector, we don't need to do any concatenation.
14326 if (N->getNumOperands() == 1)
14327 return N->getOperand(0);
14329 // Check if all of the operands are undefs.
14330 EVT VT = N->getValueType(0);
14331 if (ISD::allOperandsUndef(N))
14332 return DAG.getUNDEF(VT);
14334 // Optimize concat_vectors where all but the first of the vectors are undef.
14335 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14336 return Op.isUndef();
14338 SDValue In = N->getOperand(0);
14339 assert(In.getValueType().isVector() && "Must concat vectors");
14341 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14342 if (In->getOpcode() == ISD::BITCAST &&
14343 !In->getOperand(0)->getValueType(0).isVector()) {
14344 SDValue Scalar = In->getOperand(0);
14346 // If the bitcast type isn't legal, it might be a trunc of a legal type;
14347 // look through the trunc so we can still do the transform:
14348 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14349 if (Scalar->getOpcode() == ISD::TRUNCATE &&
14350 !TLI.isTypeLegal(Scalar.getValueType()) &&
14351 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14352 Scalar = Scalar->getOperand(0);
14354 EVT SclTy = Scalar->getValueType(0);
14356 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14359 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14360 if (VNTNumElms < 2)
14363 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14364 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14367 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14368 return DAG.getBitcast(VT, Res);
14372 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14373 // We have already tested above for an UNDEF only concatenation.
14374 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14375 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14376 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14377 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14379 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14380 SmallVector<SDValue, 8> Opnds;
14381 EVT SVT = VT.getScalarType();
14384 if (!SVT.isFloatingPoint()) {
14385 // If BUILD_VECTOR are from built from integer, they may have different
14386 // operand types. Get the smallest type and truncate all operands to it.
14387 bool FoundMinVT = false;
14388 for (const SDValue &Op : N->ops())
14389 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14390 EVT OpSVT = Op.getOperand(0)->getValueType(0);
14391 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14394 assert(FoundMinVT && "Concat vector type mismatch");
14397 for (const SDValue &Op : N->ops()) {
14398 EVT OpVT = Op.getValueType();
14399 unsigned NumElts = OpVT.getVectorNumElements();
14401 if (ISD::UNDEF == Op.getOpcode())
14402 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14404 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14405 if (SVT.isFloatingPoint()) {
14406 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14407 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14409 for (unsigned i = 0; i != NumElts; ++i)
14411 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14416 assert(VT.getVectorNumElements() == Opnds.size() &&
14417 "Concat vector type mismatch");
14418 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14421 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14422 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14425 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14426 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14427 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14430 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14431 // nodes often generate nop CONCAT_VECTOR nodes.
14432 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14433 // place the incoming vectors at the exact same location.
14434 SDValue SingleSource = SDValue();
14435 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14437 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14438 SDValue Op = N->getOperand(i);
14443 // Check if this is the identity extract:
14444 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14447 // Find the single incoming vector for the extract_subvector.
14448 if (SingleSource.getNode()) {
14449 if (Op.getOperand(0) != SingleSource)
14452 SingleSource = Op.getOperand(0);
14454 // Check the source type is the same as the type of the result.
14455 // If not, this concat may extend the vector, so we can not
14456 // optimize it away.
14457 if (SingleSource.getValueType() != N->getValueType(0))
14461 unsigned IdentityIndex = i * PartNumElem;
14462 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14463 // The extract index must be constant.
14467 // Check that we are reading from the identity index.
14468 if (CS->getZExtValue() != IdentityIndex)
14472 if (SingleSource.getNode())
14473 return SingleSource;
14478 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14479 EVT NVT = N->getValueType(0);
14480 SDValue V = N->getOperand(0);
14482 // Extract from UNDEF is UNDEF.
14484 return DAG.getUNDEF(NVT);
14487 // (extract_subvec (concat V1, V2, ...), i)
14490 // Only operand 0 is checked as 'concat' assumes all inputs of the same
14492 if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14493 isa<ConstantSDNode>(N->getOperand(1)) &&
14494 V->getOperand(0).getValueType() == NVT) {
14495 unsigned Idx = N->getConstantOperandVal(1);
14496 unsigned NumElems = NVT.getVectorNumElements();
14497 assert((Idx % NumElems) == 0 &&
14498 "IDX in concat is not a multiple of the result vector length.");
14499 return V->getOperand(Idx / NumElems);
14503 if (V->getOpcode() == ISD::BITCAST)
14504 V = V.getOperand(0);
14506 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14507 // Handle only simple case where vector being inserted and vector
14508 // being extracted are of same size.
14509 EVT SmallVT = V->getOperand(1).getValueType();
14510 if (!NVT.bitsEq(SmallVT))
14513 // Only handle cases where both indexes are constants.
14514 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14515 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14517 if (InsIdx && ExtIdx) {
14519 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14521 // indices are equal or bit offsets are equal => V1
14522 // otherwise => (extract_subvec V1, ExtIdx)
14523 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14524 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14525 return DAG.getBitcast(NVT, V->getOperand(1));
14526 return DAG.getNode(
14527 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14528 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14536 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14537 SDValue V, SelectionDAG &DAG) {
14539 EVT VT = V.getValueType();
14541 switch (V.getOpcode()) {
14545 case ISD::CONCAT_VECTORS: {
14546 EVT OpVT = V->getOperand(0).getValueType();
14547 int OpSize = OpVT.getVectorNumElements();
14548 SmallBitVector OpUsedElements(OpSize, false);
14549 bool FoundSimplification = false;
14550 SmallVector<SDValue, 4> NewOps;
14551 NewOps.reserve(V->getNumOperands());
14552 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14553 SDValue Op = V->getOperand(i);
14554 bool OpUsed = false;
14555 for (int j = 0; j < OpSize; ++j)
14556 if (UsedElements[i * OpSize + j]) {
14557 OpUsedElements[j] = true;
14561 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14562 : DAG.getUNDEF(OpVT));
14563 FoundSimplification |= Op == NewOps.back();
14564 OpUsedElements.reset();
14566 if (FoundSimplification)
14567 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14571 case ISD::INSERT_SUBVECTOR: {
14572 SDValue BaseV = V->getOperand(0);
14573 SDValue SubV = V->getOperand(1);
14574 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14578 int SubSize = SubV.getValueType().getVectorNumElements();
14579 int Idx = IdxN->getZExtValue();
14580 bool SubVectorUsed = false;
14581 SmallBitVector SubUsedElements(SubSize, false);
14582 for (int i = 0; i < SubSize; ++i)
14583 if (UsedElements[i + Idx]) {
14584 SubVectorUsed = true;
14585 SubUsedElements[i] = true;
14586 UsedElements[i + Idx] = false;
14589 // Now recurse on both the base and sub vectors.
14590 SDValue SimplifiedSubV =
14592 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14593 : DAG.getUNDEF(SubV.getValueType());
14594 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14595 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14596 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14597 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14603 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14604 SDValue N1, SelectionDAG &DAG) {
14605 EVT VT = SVN->getValueType(0);
14606 int NumElts = VT.getVectorNumElements();
14607 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14608 for (int M : SVN->getMask())
14609 if (M >= 0 && M < NumElts)
14610 N0UsedElements[M] = true;
14611 else if (M >= NumElts)
14612 N1UsedElements[M - NumElts] = true;
14614 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14615 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14616 if (S0 == N0 && S1 == N1)
14619 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14622 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14623 // or turn a shuffle of a single concat into simpler shuffle then concat.
14624 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14625 EVT VT = N->getValueType(0);
14626 unsigned NumElts = VT.getVectorNumElements();
14628 SDValue N0 = N->getOperand(0);
14629 SDValue N1 = N->getOperand(1);
14630 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14632 SmallVector<SDValue, 4> Ops;
14633 EVT ConcatVT = N0.getOperand(0).getValueType();
14634 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
14635 unsigned NumConcats = NumElts / NumElemsPerConcat;
14637 // Special case: shuffle(concat(A,B)) can be more efficiently represented
14638 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
14639 // half vector elements.
14640 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
14641 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
14642 SVN->getMask().end(), [](int i) { return i == -1; })) {
14643 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
14644 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
14645 N1 = DAG.getUNDEF(ConcatVT);
14646 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
14649 // Look at every vector that's inserted. We're looking for exact
14650 // subvector-sized copies from a concatenated vector
14651 for (unsigned I = 0; I != NumConcats; ++I) {
14652 // Make sure we're dealing with a copy.
14653 unsigned Begin = I * NumElemsPerConcat;
14654 bool AllUndef = true, NoUndef = true;
14655 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
14656 if (SVN->getMaskElt(J) >= 0)
14663 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
14666 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
14667 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
14670 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
14671 if (FirstElt < N0.getNumOperands())
14672 Ops.push_back(N0.getOperand(FirstElt));
14674 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
14676 } else if (AllUndef) {
14677 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
14678 } else { // Mixed with general masks and undefs, can't do optimization.
14683 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
14686 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14687 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14689 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
14690 // a simplification in some sense, but it isn't appropriate in general: some
14691 // BUILD_VECTORs are substantially cheaper than others. The general case
14692 // of a BUILD_VECTOR requires inserting each element individually (or
14693 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
14694 // all constants is a single constant pool load. A BUILD_VECTOR where each
14695 // element is identical is a splat. A BUILD_VECTOR where most of the operands
14696 // are undef lowers to a small number of element insertions.
14698 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
14699 // We don't fold shuffles where one side is a non-zero constant, and we don't
14700 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
14701 // non-constant operands. This seems to work out reasonably well in practice.
14702 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
14704 const TargetLowering &TLI) {
14705 EVT VT = SVN->getValueType(0);
14706 unsigned NumElts = VT.getVectorNumElements();
14707 SDValue N0 = SVN->getOperand(0);
14708 SDValue N1 = SVN->getOperand(1);
14710 if (!N0->hasOneUse() || !N1->hasOneUse())
14712 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
14713 // discussed above.
14714 if (!N1.isUndef()) {
14715 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
14716 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
14717 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
14719 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
14723 SmallVector<SDValue, 8> Ops;
14724 SmallSet<SDValue, 16> DuplicateOps;
14725 for (int M : SVN->getMask()) {
14726 SDValue Op = DAG.getUNDEF(VT.getScalarType());
14728 int Idx = M < (int)NumElts ? M : M - NumElts;
14729 SDValue &S = (M < (int)NumElts ? N0 : N1);
14730 if (S.getOpcode() == ISD::BUILD_VECTOR) {
14731 Op = S.getOperand(Idx);
14732 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14734 Op = S.getOperand(0);
14736 // Operand can't be combined - bail out.
14741 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
14742 // fine, but it's likely to generate low-quality code if the target can't
14743 // reconstruct an appropriate shuffle.
14744 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
14745 if (!DuplicateOps.insert(Op).second)
14750 // BUILD_VECTOR requires all inputs to be of the same type, find the
14751 // maximum type and extend them all.
14752 EVT SVT = VT.getScalarType();
14753 if (SVT.isInteger())
14754 for (SDValue &Op : Ops)
14755 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
14756 if (SVT != VT.getScalarType())
14757 for (SDValue &Op : Ops)
14758 Op = TLI.isZExtFree(Op.getValueType(), SVT)
14759 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
14760 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
14761 return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
14764 // Match shuffles that can be converted to any_vector_extend_in_reg.
14765 // This is often generated during legalization.
14766 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
14767 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
14768 SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
14770 const TargetLowering &TLI,
14771 bool LegalOperations) {
14772 EVT VT = SVN->getValueType(0);
14773 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14775 // TODO Add support for big-endian when we have a test case.
14776 if (!VT.isInteger() || IsBigEndian)
14779 unsigned NumElts = VT.getVectorNumElements();
14780 unsigned EltSizeInBits = VT.getScalarSizeInBits();
14781 ArrayRef<int> Mask = SVN->getMask();
14782 SDValue N0 = SVN->getOperand(0);
14784 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
14785 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
14786 for (unsigned i = 0; i != NumElts; ++i) {
14789 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
14796 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
14797 // power-of-2 extensions as they are the most likely.
14798 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
14799 if (!isAnyExtend(Scale))
14802 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
14803 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
14804 if (!LegalOperations ||
14805 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
14806 return DAG.getBitcast(VT,
14807 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
14813 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
14814 // each source element of a large type into the lowest elements of a smaller
14815 // destination type. This is often generated during legalization.
14816 // If the source node itself was a '*_extend_vector_inreg' node then we should
14817 // then be able to remove it.
14818 SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) {
14819 EVT VT = SVN->getValueType(0);
14820 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14822 // TODO Add support for big-endian when we have a test case.
14823 if (!VT.isInteger() || IsBigEndian)
14826 SDValue N0 = SVN->getOperand(0);
14827 while (N0.getOpcode() == ISD::BITCAST)
14828 N0 = N0.getOperand(0);
14830 unsigned Opcode = N0.getOpcode();
14831 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
14832 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
14833 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
14836 SDValue N00 = N0.getOperand(0);
14837 ArrayRef<int> Mask = SVN->getMask();
14838 unsigned NumElts = VT.getVectorNumElements();
14839 unsigned EltSizeInBits = VT.getScalarSizeInBits();
14840 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
14842 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
14843 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
14844 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
14845 auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
14846 for (unsigned i = 0; i != NumElts; ++i) {
14849 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
14856 // At the moment we just handle the case where we've truncated back to the
14857 // same size as before the extension.
14858 // TODO: handle more extension/truncation cases as cases arise.
14859 if (EltSizeInBits != ExtSrcSizeInBits)
14862 // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for
14863 // power-of-2 truncations as they are the most likely.
14864 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2)
14865 if (isTruncate(Scale))
14866 return DAG.getBitcast(VT, N00);
14871 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
14872 EVT VT = N->getValueType(0);
14873 unsigned NumElts = VT.getVectorNumElements();
14875 SDValue N0 = N->getOperand(0);
14876 SDValue N1 = N->getOperand(1);
14878 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
14880 // Canonicalize shuffle undef, undef -> undef
14881 if (N0.isUndef() && N1.isUndef())
14882 return DAG.getUNDEF(VT);
14884 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14886 // Canonicalize shuffle v, v -> v, undef
14888 SmallVector<int, 8> NewMask;
14889 for (unsigned i = 0; i != NumElts; ++i) {
14890 int Idx = SVN->getMaskElt(i);
14891 if (Idx >= (int)NumElts) Idx -= NumElts;
14892 NewMask.push_back(Idx);
14894 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
14897 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
14899 return DAG.getCommutedVectorShuffle(*SVN);
14901 // Remove references to rhs if it is undef
14902 if (N1.isUndef()) {
14903 bool Changed = false;
14904 SmallVector<int, 8> NewMask;
14905 for (unsigned i = 0; i != NumElts; ++i) {
14906 int Idx = SVN->getMaskElt(i);
14907 if (Idx >= (int)NumElts) {
14911 NewMask.push_back(Idx);
14914 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
14917 // If it is a splat, check if the argument vector is another splat or a
14919 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
14920 SDNode *V = N0.getNode();
14922 // If this is a bit convert that changes the element type of the vector but
14923 // not the number of vector elements, look through it. Be careful not to
14924 // look though conversions that change things like v4f32 to v2f64.
14925 if (V->getOpcode() == ISD::BITCAST) {
14926 SDValue ConvInput = V->getOperand(0);
14927 if (ConvInput.getValueType().isVector() &&
14928 ConvInput.getValueType().getVectorNumElements() == NumElts)
14929 V = ConvInput.getNode();
14932 if (V->getOpcode() == ISD::BUILD_VECTOR) {
14933 assert(V->getNumOperands() == NumElts &&
14934 "BUILD_VECTOR has wrong number of operands");
14936 bool AllSame = true;
14937 for (unsigned i = 0; i != NumElts; ++i) {
14938 if (!V->getOperand(i).isUndef()) {
14939 Base = V->getOperand(i);
14943 // Splat of <u, u, u, u>, return <u, u, u, u>
14944 if (!Base.getNode())
14946 for (unsigned i = 0; i != NumElts; ++i) {
14947 if (V->getOperand(i) != Base) {
14952 // Splat of <x, x, x, x>, return <x, x, x, x>
14956 // Canonicalize any other splat as a build_vector.
14957 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
14958 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
14959 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
14961 // We may have jumped through bitcasts, so the type of the
14962 // BUILD_VECTOR may not match the type of the shuffle.
14963 if (V->getValueType(0) != VT)
14964 NewBV = DAG.getBitcast(VT, NewBV);
14969 // There are various patterns used to build up a vector from smaller vectors,
14970 // subvectors, or elements. Scan chains of these and replace unused insertions
14971 // or components with undef.
14972 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
14975 // Match shuffles that can be converted to any_vector_extend_in_reg.
14976 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
14979 // Combine "truncate_vector_in_reg" style shuffles.
14980 if (SDValue V = combineTruncationShuffle(SVN, DAG))
14983 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
14984 Level < AfterLegalizeVectorOps &&
14986 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
14987 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
14988 if (SDValue V = partitionShuffleOfConcats(N, DAG))
14992 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14993 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14994 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14995 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
14998 // If this shuffle only has a single input that is a bitcasted shuffle,
14999 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
15000 // back to their original types.
15001 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
15002 N1.isUndef() && Level < AfterLegalizeVectorOps &&
15003 TLI.isTypeLegal(VT)) {
15005 // Peek through the bitcast only if there is one user.
15007 while (BC0.getOpcode() == ISD::BITCAST) {
15008 if (!BC0.hasOneUse())
15010 BC0 = BC0.getOperand(0);
15013 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
15015 return SmallVector<int, 8>(Mask.begin(), Mask.end());
15017 SmallVector<int, 8> NewMask;
15019 for (int s = 0; s != Scale; ++s)
15020 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15024 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15025 EVT SVT = VT.getScalarType();
15026 EVT InnerVT = BC0->getValueType(0);
15027 EVT InnerSVT = InnerVT.getScalarType();
15029 // Determine which shuffle works with the smaller scalar type.
15030 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15031 EVT ScaleSVT = ScaleVT.getScalarType();
15033 if (TLI.isTypeLegal(ScaleVT) &&
15034 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15035 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15037 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15038 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15040 // Scale the shuffle masks to the smaller scalar type.
15041 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15042 SmallVector<int, 8> InnerMask =
15043 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15044 SmallVector<int, 8> OuterMask =
15045 ScaleShuffleMask(SVN->getMask(), OuterScale);
15047 // Merge the shuffle masks.
15048 SmallVector<int, 8> NewMask;
15049 for (int M : OuterMask)
15050 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15052 // Test for shuffle mask legality over both commutations.
15053 SDValue SV0 = BC0->getOperand(0);
15054 SDValue SV1 = BC0->getOperand(1);
15055 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15057 std::swap(SV0, SV1);
15058 ShuffleVectorSDNode::commuteMask(NewMask);
15059 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15063 SV0 = DAG.getBitcast(ScaleVT, SV0);
15064 SV1 = DAG.getBitcast(ScaleVT, SV1);
15065 return DAG.getBitcast(
15066 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15072 // Canonicalize shuffles according to rules:
15073 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15074 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15075 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15076 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15077 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15078 TLI.isTypeLegal(VT)) {
15079 // The incoming shuffle must be of the same type as the result of the
15080 // current shuffle.
15081 assert(N1->getOperand(0).getValueType() == VT &&
15082 "Shuffle types don't match");
15084 SDValue SV0 = N1->getOperand(0);
15085 SDValue SV1 = N1->getOperand(1);
15086 bool HasSameOp0 = N0 == SV0;
15087 bool IsSV1Undef = SV1.isUndef();
15088 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15089 // Commute the operands of this shuffle so that next rule
15091 return DAG.getCommutedVectorShuffle(*SVN);
15094 // Try to fold according to rules:
15095 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15096 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15097 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15098 // Don't try to fold shuffles with illegal type.
15099 // Only fold if this shuffle is the only user of the other shuffle.
15100 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15101 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15102 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15104 // Don't try to fold splats; they're likely to simplify somehow, or they
15106 if (OtherSV->isSplat())
15109 // The incoming shuffle must be of the same type as the result of the
15110 // current shuffle.
15111 assert(OtherSV->getOperand(0).getValueType() == VT &&
15112 "Shuffle types don't match");
15115 SmallVector<int, 4> Mask;
15116 // Compute the combined shuffle mask for a shuffle with SV0 as the first
15117 // operand, and SV1 as the second operand.
15118 for (unsigned i = 0; i != NumElts; ++i) {
15119 int Idx = SVN->getMaskElt(i);
15121 // Propagate Undef.
15122 Mask.push_back(Idx);
15126 SDValue CurrentVec;
15127 if (Idx < (int)NumElts) {
15128 // This shuffle index refers to the inner shuffle N0. Lookup the inner
15129 // shuffle mask to identify which vector is actually referenced.
15130 Idx = OtherSV->getMaskElt(Idx);
15132 // Propagate Undef.
15133 Mask.push_back(Idx);
15137 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15138 : OtherSV->getOperand(1);
15140 // This shuffle index references an element within N1.
15144 // Simple case where 'CurrentVec' is UNDEF.
15145 if (CurrentVec.isUndef()) {
15146 Mask.push_back(-1);
15150 // Canonicalize the shuffle index. We don't know yet if CurrentVec
15151 // will be the first or second operand of the combined shuffle.
15152 Idx = Idx % NumElts;
15153 if (!SV0.getNode() || SV0 == CurrentVec) {
15154 // Ok. CurrentVec is the left hand side.
15155 // Update the mask accordingly.
15157 Mask.push_back(Idx);
15161 // Bail out if we cannot convert the shuffle pair into a single shuffle.
15162 if (SV1.getNode() && SV1 != CurrentVec)
15165 // Ok. CurrentVec is the right hand side.
15166 // Update the mask accordingly.
15168 Mask.push_back(Idx + NumElts);
15171 // Check if all indices in Mask are Undef. In case, propagate Undef.
15172 bool isUndefMask = true;
15173 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
15174 isUndefMask &= Mask[i] < 0;
15177 return DAG.getUNDEF(VT);
15179 if (!SV0.getNode())
15180 SV0 = DAG.getUNDEF(VT);
15181 if (!SV1.getNode())
15182 SV1 = DAG.getUNDEF(VT);
15184 // Avoid introducing shuffles with illegal mask.
15185 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
15186 ShuffleVectorSDNode::commuteMask(Mask);
15188 if (!TLI.isShuffleMaskLegal(Mask, VT))
15191 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
15192 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
15193 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
15194 std::swap(SV0, SV1);
15197 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15198 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15199 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15200 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
15206 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
15207 SDValue InVal = N->getOperand(0);
15208 EVT VT = N->getValueType(0);
15210 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
15211 // with a VECTOR_SHUFFLE.
15212 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15213 SDValue InVec = InVal->getOperand(0);
15214 SDValue EltNo = InVal->getOperand(1);
15216 // FIXME: We could support implicit truncation if the shuffle can be
15217 // scaled to a smaller vector scalar type.
15218 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15219 if (C0 && VT == InVec.getValueType() &&
15220 VT.getScalarType() == InVal.getValueType()) {
15221 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15222 int Elt = C0->getZExtValue();
15225 if (TLI.isShuffleMaskLegal(NewMask, VT))
15226 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15234 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15235 EVT VT = N->getValueType(0);
15236 SDValue N0 = N->getOperand(0);
15237 SDValue N1 = N->getOperand(1);
15238 SDValue N2 = N->getOperand(2);
15240 // If inserting an UNDEF, just return the original vector.
15244 // If this is an insert of an extracted vector into an undef vector, we can
15245 // just use the input to the extract.
15246 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15247 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15248 return N1.getOperand(0);
15250 // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15251 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15252 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15253 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15254 N0.getOperand(1).getValueType() == N1.getValueType() &&
15255 N0.getOperand(2) == N2)
15256 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15259 if (!isa<ConstantSDNode>(N2))
15262 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15264 // Canonicalize insert_subvector dag nodes.
15266 // (insert_subvector (insert_subvector A, Idx0), Idx1)
15267 // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15268 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15269 N1.getValueType() == N0.getOperand(1).getValueType() &&
15270 isa<ConstantSDNode>(N0.getOperand(2))) {
15271 unsigned OtherIdx = N0.getConstantOperandVal(2);
15272 if (InsIdx < OtherIdx) {
15274 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15275 N0.getOperand(0), N1, N2);
15276 AddToWorklist(NewOp.getNode());
15277 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15278 VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15282 // If the input vector is a concatenation, and the insert replaces
15283 // one of the pieces, we can optimize into a single concat_vectors.
15284 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15285 N0.getOperand(0).getValueType() == N1.getValueType()) {
15286 unsigned Factor = N1.getValueType().getVectorNumElements();
15288 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15289 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15291 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15297 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15298 SDValue N0 = N->getOperand(0);
15300 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15301 if (N0->getOpcode() == ISD::FP16_TO_FP)
15302 return N0->getOperand(0);
15307 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15308 SDValue N0 = N->getOperand(0);
15310 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15311 if (N0->getOpcode() == ISD::AND) {
15312 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15313 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15314 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15322 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15323 /// with the destination vector and a zero vector.
15324 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15325 /// vector_shuffle V, Zero, <0, 4, 2, 4>
15326 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15327 EVT VT = N->getValueType(0);
15328 SDValue LHS = N->getOperand(0);
15329 SDValue RHS = N->getOperand(1);
15332 // Make sure we're not running after operation legalization where it
15333 // may have custom lowered the vector shuffles.
15334 if (LegalOperations)
15337 if (N->getOpcode() != ISD::AND)
15340 if (RHS.getOpcode() == ISD::BITCAST)
15341 RHS = RHS.getOperand(0);
15343 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15346 EVT RVT = RHS.getValueType();
15347 unsigned NumElts = RHS.getNumOperands();
15349 // Attempt to create a valid clear mask, splitting the mask into
15350 // sub elements and checking to see if each is
15351 // all zeros or all ones - suitable for shuffle masking.
15352 auto BuildClearMask = [&](int Split) {
15353 int NumSubElts = NumElts * Split;
15354 int NumSubBits = RVT.getScalarSizeInBits() / Split;
15356 SmallVector<int, 8> Indices;
15357 for (int i = 0; i != NumSubElts; ++i) {
15358 int EltIdx = i / Split;
15359 int SubIdx = i % Split;
15360 SDValue Elt = RHS.getOperand(EltIdx);
15361 if (Elt.isUndef()) {
15362 Indices.push_back(-1);
15367 if (isa<ConstantSDNode>(Elt))
15368 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15369 else if (isa<ConstantFPSDNode>(Elt))
15370 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15374 // Extract the sub element from the constant bit mask.
15375 if (DAG.getDataLayout().isBigEndian()) {
15376 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15378 Bits.lshrInPlace(SubIdx * NumSubBits);
15382 Bits = Bits.trunc(NumSubBits);
15384 if (Bits.isAllOnesValue())
15385 Indices.push_back(i);
15386 else if (Bits == 0)
15387 Indices.push_back(i + NumSubElts);
15392 // Let's see if the target supports this vector_shuffle.
15393 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15394 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15395 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15398 SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15399 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15400 DAG.getBitcast(ClearVT, LHS),
15404 // Determine maximum split level (byte level masking).
15406 if (RVT.getScalarSizeInBits() % 8 == 0)
15407 MaxSplit = RVT.getScalarSizeInBits() / 8;
15409 for (int Split = 1; Split <= MaxSplit; ++Split)
15410 if (RVT.getScalarSizeInBits() % Split == 0)
15411 if (SDValue S = BuildClearMask(Split))
15417 /// Visit a binary vector operation, like ADD.
15418 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15419 assert(N->getValueType(0).isVector() &&
15420 "SimplifyVBinOp only works on vectors!");
15422 SDValue LHS = N->getOperand(0);
15423 SDValue RHS = N->getOperand(1);
15424 SDValue Ops[] = {LHS, RHS};
15426 // See if we can constant fold the vector operation.
15427 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15428 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15431 // Try to convert a constant mask AND into a shuffle clear mask.
15432 if (SDValue Shuffle = XformToShuffleWithZero(N))
15435 // Type legalization might introduce new shuffles in the DAG.
15436 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15437 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
15438 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15439 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15440 LHS.getOperand(1).isUndef() &&
15441 RHS.getOperand(1).isUndef()) {
15442 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15443 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15445 if (SVN0->getMask().equals(SVN1->getMask())) {
15446 EVT VT = N->getValueType(0);
15447 SDValue UndefVector = LHS.getOperand(1);
15448 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15449 LHS.getOperand(0), RHS.getOperand(0),
15451 AddUsersToWorklist(N);
15452 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15460 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15462 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15464 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15465 cast<CondCodeSDNode>(N0.getOperand(2))->get());
15467 // If we got a simplified select_cc node back from SimplifySelectCC, then
15468 // break it down into a new SETCC node, and a new SELECT node, and then return
15469 // the SELECT node, since we were called with a SELECT node.
15470 if (SCC.getNode()) {
15471 // Check to see if we got a select_cc back (to turn into setcc/select).
15472 // Otherwise, just return whatever node we got back, like fabs.
15473 if (SCC.getOpcode() == ISD::SELECT_CC) {
15474 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15476 SCC.getOperand(0), SCC.getOperand(1),
15477 SCC.getOperand(4));
15478 AddToWorklist(SETCC.getNode());
15479 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15480 SCC.getOperand(2), SCC.getOperand(3));
15488 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15489 /// being selected between, see if we can simplify the select. Callers of this
15490 /// should assume that TheSelect is deleted if this returns true. As such, they
15491 /// should return the appropriate thing (e.g. the node) back to the top-level of
15492 /// the DAG combiner loop to avoid it being looked at.
15493 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15496 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15497 // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15498 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15499 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15500 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15501 SDValue Sqrt = RHS;
15504 const ConstantFPSDNode *Zero = nullptr;
15506 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15507 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15508 CmpLHS = TheSelect->getOperand(0);
15509 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15511 // SELECT or VSELECT
15512 SDValue Cmp = TheSelect->getOperand(0);
15513 if (Cmp.getOpcode() == ISD::SETCC) {
15514 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15515 CmpLHS = Cmp.getOperand(0);
15516 Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15519 if (Zero && Zero->isZero() &&
15520 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15521 CC == ISD::SETULT || CC == ISD::SETLT)) {
15522 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15523 CombineTo(TheSelect, Sqrt);
15528 // Cannot simplify select with vector condition
15529 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15531 // If this is a select from two identical things, try to pull the operation
15532 // through the select.
15533 if (LHS.getOpcode() != RHS.getOpcode() ||
15534 !LHS.hasOneUse() || !RHS.hasOneUse())
15537 // If this is a load and the token chain is identical, replace the select
15538 // of two loads with a load through a select of the address to load from.
15539 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15540 // constants have been dropped into the constant pool.
15541 if (LHS.getOpcode() == ISD::LOAD) {
15542 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15543 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15545 // Token chains must be identical.
15546 if (LHS.getOperand(0) != RHS.getOperand(0) ||
15547 // Do not let this transformation reduce the number of volatile loads.
15548 LLD->isVolatile() || RLD->isVolatile() ||
15549 // FIXME: If either is a pre/post inc/dec load,
15550 // we'd need to split out the address adjustment.
15551 LLD->isIndexed() || RLD->isIndexed() ||
15552 // If this is an EXTLOAD, the VT's must match.
15553 LLD->getMemoryVT() != RLD->getMemoryVT() ||
15554 // If this is an EXTLOAD, the kind of extension must match.
15555 (LLD->getExtensionType() != RLD->getExtensionType() &&
15556 // The only exception is if one of the extensions is anyext.
15557 LLD->getExtensionType() != ISD::EXTLOAD &&
15558 RLD->getExtensionType() != ISD::EXTLOAD) ||
15559 // FIXME: this discards src value information. This is
15560 // over-conservative. It would be beneficial to be able to remember
15561 // both potential memory locations. Since we are discarding
15562 // src value info, don't do the transformation if the memory
15563 // locations are not in the default address space.
15564 LLD->getPointerInfo().getAddrSpace() != 0 ||
15565 RLD->getPointerInfo().getAddrSpace() != 0 ||
15566 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
15567 LLD->getBasePtr().getValueType()))
15570 // Check that the select condition doesn't reach either load. If so,
15571 // folding this will induce a cycle into the DAG. If not, this is safe to
15572 // xform, so create a select of the addresses.
15574 if (TheSelect->getOpcode() == ISD::SELECT) {
15575 SDNode *CondNode = TheSelect->getOperand(0).getNode();
15576 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
15577 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
15579 // The loads must not depend on one another.
15580 if (LLD->isPredecessorOf(RLD) ||
15581 RLD->isPredecessorOf(LLD))
15583 Addr = DAG.getSelect(SDLoc(TheSelect),
15584 LLD->getBasePtr().getValueType(),
15585 TheSelect->getOperand(0), LLD->getBasePtr(),
15586 RLD->getBasePtr());
15587 } else { // Otherwise SELECT_CC
15588 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
15589 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
15591 if ((LLD->hasAnyUseOfValue(1) &&
15592 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
15593 (RLD->hasAnyUseOfValue(1) &&
15594 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
15597 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
15598 LLD->getBasePtr().getValueType(),
15599 TheSelect->getOperand(0),
15600 TheSelect->getOperand(1),
15601 LLD->getBasePtr(), RLD->getBasePtr(),
15602 TheSelect->getOperand(4));
15606 // It is safe to replace the two loads if they have different alignments,
15607 // but the new load must be the minimum (most restrictive) alignment of the
15609 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
15610 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
15611 if (!RLD->isInvariant())
15612 MMOFlags &= ~MachineMemOperand::MOInvariant;
15613 if (!RLD->isDereferenceable())
15614 MMOFlags &= ~MachineMemOperand::MODereferenceable;
15615 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
15616 // FIXME: Discards pointer and AA info.
15617 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
15618 LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
15621 // FIXME: Discards pointer and AA info.
15622 Load = DAG.getExtLoad(
15623 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
15624 : LLD->getExtensionType(),
15625 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
15626 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
15629 // Users of the select now use the result of the load.
15630 CombineTo(TheSelect, Load);
15632 // Users of the old loads now use the new load's chain. We know the
15633 // old-load value is dead now.
15634 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
15635 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
15642 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
15644 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
15645 SDValue N1, SDValue N2, SDValue N3,
15646 ISD::CondCode CC) {
15647 // If this is a select where the false operand is zero and the compare is a
15648 // check of the sign bit, see if we can perform the "gzip trick":
15649 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
15650 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
15651 EVT XType = N0.getValueType();
15652 EVT AType = N2.getValueType();
15653 if (!isNullConstant(N3) || !XType.bitsGE(AType))
15656 // If the comparison is testing for a positive value, we have to invert
15657 // the sign bit mask, so only do that transform if the target has a bitwise
15658 // 'and not' instruction (the invert is free).
15659 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
15660 // (X > -1) ? A : 0
15661 // (X > 0) ? X : 0 <-- This is canonical signed max.
15662 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
15664 } else if (CC == ISD::SETLT) {
15666 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
15667 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
15673 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
15675 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
15676 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15677 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
15678 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
15679 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
15680 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
15681 AddToWorklist(Shift.getNode());
15683 if (XType.bitsGT(AType)) {
15684 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15685 AddToWorklist(Shift.getNode());
15688 if (CC == ISD::SETGT)
15689 Shift = DAG.getNOT(DL, Shift, AType);
15691 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15694 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
15695 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
15696 AddToWorklist(Shift.getNode());
15698 if (XType.bitsGT(AType)) {
15699 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15700 AddToWorklist(Shift.getNode());
15703 if (CC == ISD::SETGT)
15704 Shift = DAG.getNOT(DL, Shift, AType);
15706 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15709 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
15710 /// where 'cond' is the comparison specified by CC.
15711 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
15712 SDValue N2, SDValue N3, ISD::CondCode CC,
15713 bool NotExtCompare) {
15714 // (x ? y : y) -> y.
15715 if (N2 == N3) return N2;
15717 EVT VT = N2.getValueType();
15718 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
15719 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15721 // Determine if the condition we're dealing with is constant
15722 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
15723 N0, N1, CC, DL, false);
15724 if (SCC.getNode()) AddToWorklist(SCC.getNode());
15726 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
15727 // fold select_cc true, x, y -> x
15728 // fold select_cc false, x, y -> y
15729 return !SCCC->isNullValue() ? N2 : N3;
15732 // Check to see if we can simplify the select into an fabs node
15733 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
15734 // Allow either -0.0 or 0.0
15735 if (CFP->isZero()) {
15736 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
15737 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
15738 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
15739 N2 == N3.getOperand(0))
15740 return DAG.getNode(ISD::FABS, DL, VT, N0);
15742 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
15743 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
15744 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
15745 N2.getOperand(0) == N3)
15746 return DAG.getNode(ISD::FABS, DL, VT, N3);
15750 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
15751 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
15752 // in it. This is a win when the constant is not otherwise available because
15753 // it replaces two constant pool loads with one. We only do this if the FP
15754 // type is known to be legal, because if it isn't, then we are before legalize
15755 // types an we want the other legalization to happen first (e.g. to avoid
15756 // messing with soft float) and if the ConstantFP is not legal, because if
15757 // it is legal, we may not need to store the FP constant in a constant pool.
15758 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
15759 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
15760 if (TLI.isTypeLegal(N2.getValueType()) &&
15761 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
15762 TargetLowering::Legal &&
15763 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
15764 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
15765 // If both constants have multiple uses, then we won't need to do an
15766 // extra load, they are likely around in registers for other users.
15767 (TV->hasOneUse() || FV->hasOneUse())) {
15768 Constant *Elts[] = {
15769 const_cast<ConstantFP*>(FV->getConstantFPValue()),
15770 const_cast<ConstantFP*>(TV->getConstantFPValue())
15772 Type *FPTy = Elts[0]->getType();
15773 const DataLayout &TD = DAG.getDataLayout();
15775 // Create a ConstantArray of the two constants.
15776 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
15778 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
15779 TD.getPrefTypeAlignment(FPTy));
15780 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
15782 // Get the offsets to the 0 and 1 element of the array so that we can
15783 // select between them.
15784 SDValue Zero = DAG.getIntPtrConstant(0, DL);
15785 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
15786 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
15788 SDValue Cond = DAG.getSetCC(DL,
15789 getSetCCResultType(N0.getValueType()),
15791 AddToWorklist(Cond.getNode());
15792 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
15794 AddToWorklist(CstOffset.getNode());
15795 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
15797 AddToWorklist(CPIdx.getNode());
15798 return DAG.getLoad(
15799 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
15800 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
15805 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
15808 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
15809 // where y is has a single bit set.
15810 // A plaintext description would be, we can turn the SELECT_CC into an AND
15811 // when the condition can be materialized as an all-ones register. Any
15812 // single bit-test can be materialized as an all-ones register with
15813 // shift-left and shift-right-arith.
15814 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
15815 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
15816 SDValue AndLHS = N0->getOperand(0);
15817 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
15818 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
15819 // Shift the tested bit over the sign bit.
15820 const APInt &AndMask = ConstAndRHS->getAPIntValue();
15822 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
15823 getShiftAmountTy(AndLHS.getValueType()));
15824 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
15826 // Now arithmetic right shift it all the way over, so the result is either
15827 // all-ones, or zero.
15829 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
15830 getShiftAmountTy(Shl.getValueType()));
15831 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
15833 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
15837 // fold select C, 16, 0 -> shl C, 4
15838 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
15839 TLI.getBooleanContents(N0.getValueType()) ==
15840 TargetLowering::ZeroOrOneBooleanContent) {
15842 // If the caller doesn't want us to simplify this into a zext of a compare,
15844 if (NotExtCompare && N2C->isOne())
15847 // Get a SetCC of the condition
15848 // NOTE: Don't create a SETCC if it's not legal on this target.
15849 if (!LegalOperations ||
15850 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
15852 // cast from setcc result type to select result type
15854 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
15856 if (N2.getValueType().bitsLT(SCC.getValueType()))
15857 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
15858 N2.getValueType());
15860 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15861 N2.getValueType(), SCC);
15863 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
15864 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15865 N2.getValueType(), SCC);
15868 AddToWorklist(SCC.getNode());
15869 AddToWorklist(Temp.getNode());
15874 // shl setcc result by log2 n2c
15875 return DAG.getNode(
15876 ISD::SHL, DL, N2.getValueType(), Temp,
15877 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
15878 getShiftAmountTy(Temp.getValueType())));
15882 // Check to see if this is an integer abs.
15883 // select_cc setg[te] X, 0, X, -X ->
15884 // select_cc setgt X, -1, X, -X ->
15885 // select_cc setl[te] X, 0, -X, X ->
15886 // select_cc setlt X, 1, -X, X ->
15887 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
15889 ConstantSDNode *SubC = nullptr;
15890 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
15891 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
15892 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
15893 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
15894 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
15895 (N1C->isOne() && CC == ISD::SETLT)) &&
15896 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
15897 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
15899 EVT XType = N0.getValueType();
15900 if (SubC && SubC->isNullValue() && XType.isInteger()) {
15902 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
15904 DAG.getConstant(XType.getSizeInBits() - 1, DL,
15905 getShiftAmountTy(N0.getValueType())));
15906 SDValue Add = DAG.getNode(ISD::ADD, DL,
15908 AddToWorklist(Shift.getNode());
15909 AddToWorklist(Add.getNode());
15910 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
15914 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
15915 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
15916 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
15917 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
15918 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
15919 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
15920 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
15921 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
15922 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15923 SDValue ValueOnZero = N2;
15924 SDValue Count = N3;
15925 // If the condition is NE instead of E, swap the operands.
15926 if (CC == ISD::SETNE)
15927 std::swap(ValueOnZero, Count);
15928 // Check if the value on zero is a constant equal to the bits in the type.
15929 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
15930 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
15931 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
15932 // legal, combine to just cttz.
15933 if ((Count.getOpcode() == ISD::CTTZ ||
15934 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
15935 N0 == Count.getOperand(0) &&
15936 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
15937 return DAG.getNode(ISD::CTTZ, DL, VT, N0);
15938 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
15939 // legal, combine to just ctlz.
15940 if ((Count.getOpcode() == ISD::CTLZ ||
15941 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
15942 N0 == Count.getOperand(0) &&
15943 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
15944 return DAG.getNode(ISD::CTLZ, DL, VT, N0);
15952 /// This is a stub for TargetLowering::SimplifySetCC.
15953 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
15954 ISD::CondCode Cond, const SDLoc &DL,
15955 bool foldBooleans) {
15956 TargetLowering::DAGCombinerInfo
15957 DagCombineInfo(DAG, Level, false, this);
15958 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
15961 /// Given an ISD::SDIV node expressing a divide by constant, return
15962 /// a DAG expression to select that will generate the same value by multiplying
15963 /// by a magic number.
15964 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15965 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
15966 // when optimising for minimum size, we don't want to expand a div to a mul
15968 if (DAG.getMachineFunction().getFunction()->optForMinSize())
15971 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15975 // Avoid division by zero.
15976 if (C->isNullValue())
15979 std::vector<SDNode*> Built;
15981 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15983 for (SDNode *N : Built)
15988 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
15989 /// DAG expression that will generate the same value by right shifting.
15990 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
15991 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15995 // Avoid division by zero.
15996 if (C->isNullValue())
15999 std::vector<SDNode *> Built;
16000 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
16002 for (SDNode *N : Built)
16007 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
16008 /// expression that will generate the same value by multiplying by a magic
16010 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16011 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
16012 // when optimising for minimum size, we don't want to expand a div to a mul
16014 if (DAG.getMachineFunction().getFunction()->optForMinSize())
16017 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16021 // Avoid division by zero.
16022 if (C->isNullValue())
16025 std::vector<SDNode*> Built;
16027 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16029 for (SDNode *N : Built)
16034 /// Determines the LogBase2 value for a non-null input value using the
16035 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16036 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16037 EVT VT = V.getValueType();
16038 unsigned EltBits = VT.getScalarSizeInBits();
16039 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16040 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16041 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16045 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16046 /// For the reciprocal, we need to find the zero of the function:
16047 /// F(X) = A X - 1 [which has a zero at X = 1/A]
16049 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16050 /// does not require additional intermediate precision]
16051 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16052 if (Level >= AfterLegalizeDAG)
16055 // TODO: Handle half and/or extended types?
16056 EVT VT = Op.getValueType();
16057 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16060 // If estimates are explicitly disabled for this function, we're done.
16061 MachineFunction &MF = DAG.getMachineFunction();
16062 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16063 if (Enabled == TLI.ReciprocalEstimate::Disabled)
16066 // Estimates may be explicitly enabled for this type with a custom number of
16067 // refinement steps.
16068 int Iterations = TLI.getDivRefinementSteps(VT, MF);
16069 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16070 AddToWorklist(Est.getNode());
16073 EVT VT = Op.getValueType();
16075 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16077 // Newton iterations: Est = Est + Est (1 - Arg * Est)
16078 for (int i = 0; i < Iterations; ++i) {
16079 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16080 AddToWorklist(NewEst.getNode());
16082 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16083 AddToWorklist(NewEst.getNode());
16085 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16086 AddToWorklist(NewEst.getNode());
16088 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16089 AddToWorklist(Est.getNode());
16098 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16099 /// For the reciprocal sqrt, we need to find the zero of the function:
16100 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16102 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16103 /// As a result, we precompute A/2 prior to the iteration loop.
16104 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16105 unsigned Iterations,
16106 SDNodeFlags Flags, bool Reciprocal) {
16107 EVT VT = Arg.getValueType();
16109 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16111 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16112 // this entire sequence requires only one FP constant.
16113 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16114 AddToWorklist(HalfArg.getNode());
16116 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
16117 AddToWorklist(HalfArg.getNode());
16119 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
16120 for (unsigned i = 0; i < Iterations; ++i) {
16121 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
16122 AddToWorklist(NewEst.getNode());
16124 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
16125 AddToWorklist(NewEst.getNode());
16127 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
16128 AddToWorklist(NewEst.getNode());
16130 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16131 AddToWorklist(Est.getNode());
16134 // If non-reciprocal square root is requested, multiply the result by Arg.
16136 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
16137 AddToWorklist(Est.getNode());
16143 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16144 /// For the reciprocal sqrt, we need to find the zero of the function:
16145 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16147 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
16148 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
16149 unsigned Iterations,
16150 SDNodeFlags Flags, bool Reciprocal) {
16151 EVT VT = Arg.getValueType();
16153 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
16154 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
16156 // This routine must enter the loop below to work correctly
16157 // when (Reciprocal == false).
16158 assert(Iterations > 0);
16160 // Newton iterations for reciprocal square root:
16161 // E = (E * -0.5) * ((A * E) * E + -3.0)
16162 for (unsigned i = 0; i < Iterations; ++i) {
16163 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
16164 AddToWorklist(AE.getNode());
16166 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
16167 AddToWorklist(AEE.getNode());
16169 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
16170 AddToWorklist(RHS.getNode());
16172 // When calculating a square root at the last iteration build:
16173 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
16174 // (notice a common subexpression)
16176 if (Reciprocal || (i + 1) < Iterations) {
16177 // RSQRT: LHS = (E * -0.5)
16178 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
16180 // SQRT: LHS = (A * E) * -0.5
16181 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
16183 AddToWorklist(LHS.getNode());
16185 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
16186 AddToWorklist(Est.getNode());
16192 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
16193 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
16194 /// Op can be zero.
16195 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
16197 if (Level >= AfterLegalizeDAG)
16200 // TODO: Handle half and/or extended types?
16201 EVT VT = Op.getValueType();
16202 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16205 // If estimates are explicitly disabled for this function, we're done.
16206 MachineFunction &MF = DAG.getMachineFunction();
16207 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
16208 if (Enabled == TLI.ReciprocalEstimate::Disabled)
16211 // Estimates may be explicitly enabled for this type with a custom number of
16212 // refinement steps.
16213 int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
16215 bool UseOneConstNR = false;
16217 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16219 AddToWorklist(Est.getNode());
16222 Est = UseOneConstNR
16223 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16224 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16227 // Unfortunately, Est is now NaN if the input was exactly 0.0.
16228 // Select out this case and force the answer to 0.0.
16229 EVT VT = Op.getValueType();
16232 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16233 EVT CCVT = getSetCCResultType(VT);
16234 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16235 AddToWorklist(ZeroCmp.getNode());
16237 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16238 ZeroCmp, FPZero, Est);
16239 AddToWorklist(Est.getNode());
16248 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16249 return buildSqrtEstimateImpl(Op, Flags, true);
16252 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16253 return buildSqrtEstimateImpl(Op, Flags, false);
16256 /// Return true if base is a frame index, which is known not to alias with
16257 /// anything but itself. Provides base object and offset as results.
16258 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16259 const GlobalValue *&GV, const void *&CV) {
16260 // Assume it is a primitive operation.
16261 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16263 // If it's an adding a simple constant then integrate the offset.
16264 if (Base.getOpcode() == ISD::ADD) {
16265 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16266 Base = Base.getOperand(0);
16267 Offset += C->getSExtValue();
16271 // Return the underlying GlobalValue, and update the Offset. Return false
16272 // for GlobalAddressSDNode since the same GlobalAddress may be represented
16273 // by multiple nodes with different offsets.
16274 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16275 GV = G->getGlobal();
16276 Offset += G->getOffset();
16280 // Return the underlying Constant value, and update the Offset. Return false
16281 // for ConstantSDNodes since the same constant pool entry may be represented
16282 // by multiple nodes with different offsets.
16283 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16284 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16285 : (const void *)C->getConstVal();
16286 Offset += C->getOffset();
16289 // If it's any of the following then it can't alias with anything but itself.
16290 return isa<FrameIndexSDNode>(Base);
16293 /// Return true if there is any possibility that the two addresses overlap.
16294 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16295 // If they are the same then they must be aliases.
16296 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16298 // If they are both volatile then they cannot be reordered.
16299 if (Op0->isVolatile() && Op1->isVolatile()) return true;
16301 // If one operation reads from invariant memory, and the other may store, they
16302 // cannot alias. These should really be checking the equivalent of mayWrite,
16303 // but it only matters for memory nodes other than load /store.
16304 if (Op0->isInvariant() && Op1->writeMem())
16307 if (Op1->isInvariant() && Op0->writeMem())
16310 unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16311 unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16313 // Check for BaseIndexOffset matching.
16314 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
16315 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
16316 if (BasePtr0.equalBaseIndex(BasePtr1))
16317 return !((BasePtr0.Offset + NumBytes0 <= BasePtr1.Offset) ||
16318 (BasePtr1.Offset + NumBytes1 <= BasePtr0.Offset));
16320 // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
16321 // modified to use BaseIndexOffset.
16323 // Gather base node and offset information.
16324 SDValue Base0, Base1;
16325 int64_t Offset0, Offset1;
16326 const GlobalValue *GV0, *GV1;
16327 const void *CV0, *CV1;
16328 bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16329 Base0, Offset0, GV0, CV0);
16330 bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16331 Base1, Offset1, GV1, CV1);
16333 // If they have the same base address, then check to see if they overlap.
16334 if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16335 return !((Offset0 + NumBytes0) <= Offset1 ||
16336 (Offset1 + NumBytes1) <= Offset0);
16338 // It is possible for different frame indices to alias each other, mostly
16339 // when tail call optimization reuses return address slots for arguments.
16340 // To catch this case, look up the actual index of frame indices to compute
16341 // the real alias relationship.
16342 if (IsFrameIndex0 && IsFrameIndex1) {
16343 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16344 Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16345 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16346 return !((Offset0 + NumBytes0) <= Offset1 ||
16347 (Offset1 + NumBytes1) <= Offset0);
16350 // Otherwise, if we know what the bases are, and they aren't identical, then
16351 // we know they cannot alias.
16352 if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16355 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16356 // compared to the size and offset of the access, we may be able to prove they
16357 // do not alias. This check is conservative for now to catch cases created by
16358 // splitting vector types.
16359 int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16360 int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16361 unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16362 unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16363 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16364 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16365 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16366 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16368 // There is no overlap between these relatively aligned accesses of similar
16369 // size. Return no alias.
16370 if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16371 (OffAlign1 + NumBytes1) <= OffAlign0)
16375 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16377 : DAG.getSubtarget().useAA();
16379 if (CombinerAAOnlyFunc.getNumOccurrences() &&
16380 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16385 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16386 // Use alias analysis information.
16387 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16388 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16389 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16390 AliasResult AAResult =
16391 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16392 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16393 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16394 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
16395 if (AAResult == NoAlias)
16399 // Otherwise we have to assume they alias.
16403 /// Walk up chain skipping non-aliasing memory nodes,
16404 /// looking for aliasing nodes and adding them to the Aliases vector.
16405 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16406 SmallVectorImpl<SDValue> &Aliases) {
16407 SmallVector<SDValue, 8> Chains; // List of chains to visit.
16408 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
16410 // Get alias information for node.
16411 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16414 Chains.push_back(OriginalChain);
16415 unsigned Depth = 0;
16417 // Look at each chain and determine if it is an alias. If so, add it to the
16418 // aliases list. If not, then continue up the chain looking for the next
16420 while (!Chains.empty()) {
16421 SDValue Chain = Chains.pop_back_val();
16423 // For TokenFactor nodes, look at each operand and only continue up the
16424 // chain until we reach the depth limit.
16426 // FIXME: The depth check could be made to return the last non-aliasing
16427 // chain we found before we hit a tokenfactor rather than the original
16429 if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16431 Aliases.push_back(OriginalChain);
16435 // Don't bother if we've been before.
16436 if (!Visited.insert(Chain.getNode()).second)
16439 switch (Chain.getOpcode()) {
16440 case ISD::EntryToken:
16441 // Entry token is ideal chain operand, but handled in FindBetterChain.
16446 // Get alias information for Chain.
16447 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16448 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16450 // If chain is alias then stop here.
16451 if (!(IsLoad && IsOpLoad) &&
16452 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16453 Aliases.push_back(Chain);
16455 // Look further up the chain.
16456 Chains.push_back(Chain.getOperand(0));
16462 case ISD::TokenFactor:
16463 // We have to check each of the operands of the token factor for "small"
16464 // token factors, so we queue them up. Adding the operands to the queue
16465 // (stack) in reverse order maintains the original order and increases the
16466 // likelihood that getNode will find a matching token factor (CSE.)
16467 if (Chain.getNumOperands() > 16) {
16468 Aliases.push_back(Chain);
16471 for (unsigned n = Chain.getNumOperands(); n;)
16472 Chains.push_back(Chain.getOperand(--n));
16476 case ISD::CopyFromReg:
16477 // Forward past CopyFromReg.
16478 Chains.push_back(Chain.getOperand(0));
16483 // For all other instructions we will just have to take what we can get.
16484 Aliases.push_back(Chain);
16490 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16491 /// (aliasing node.)
16492 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16493 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
16495 // Accumulate all the aliases to this node.
16496 GatherAllAliases(N, OldChain, Aliases);
16498 // If no operands then chain to entry token.
16499 if (Aliases.size() == 0)
16500 return DAG.getEntryNode();
16502 // If a single operand then chain to it. We don't need to revisit it.
16503 if (Aliases.size() == 1)
16506 // Construct a custom tailored token factor.
16507 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16510 // This function tries to collect a bunch of potentially interesting
16511 // nodes to improve the chains of, all at once. This might seem
16512 // redundant, as this function gets called when visiting every store
16513 // node, so why not let the work be done on each store as it's visited?
16515 // I believe this is mainly important because MergeConsecutiveStores
16516 // is unable to deal with merging stores of different sizes, so unless
16517 // we improve the chains of all the potential candidates up-front
16518 // before running MergeConsecutiveStores, it might only see some of
16519 // the nodes that will eventually be candidates, and then not be able
16520 // to go from a partially-merged state to the desired final
16521 // fully-merged state.
16522 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16523 // This holds the base pointer, index, and the offset in bytes from the base
16525 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16527 // We must have a base and an offset.
16528 if (!BasePtr.Base.getNode())
16531 // Do not handle stores to undef base pointers.
16532 if (BasePtr.Base.isUndef())
16535 SmallVector<StoreSDNode *, 8> ChainedStores;
16536 ChainedStores.push_back(St);
16538 // Walk up the chain and look for nodes with offsets from the same
16539 // base pointer. Stop when reaching an instruction with a different kind
16540 // or instruction which has a different base pointer.
16541 StoreSDNode *Index = St;
16543 // If the chain has more than one use, then we can't reorder the mem ops.
16544 if (Index != St && !SDValue(Index, 0)->hasOneUse())
16547 if (Index->isVolatile() || Index->isIndexed())
16550 // Find the base pointer and offset for this memory node.
16551 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
16553 // Check that the base pointer is the same as the original one.
16554 if (!Ptr.equalBaseIndex(BasePtr))
16557 // Walk up the chain to find the next store node, ignoring any
16558 // intermediate loads. Any other kind of node will halt the loop.
16559 SDNode *NextInChain = Index->getChain().getNode();
16561 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
16562 // We found a store node. Use it for the next iteration.
16563 if (STn->isVolatile() || STn->isIndexed()) {
16567 ChainedStores.push_back(STn);
16570 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
16571 NextInChain = Ldn->getChain().getNode();
16580 // At this point, ChainedStores lists all of the Store nodes
16581 // reachable by iterating up through chain nodes matching the above
16582 // conditions. For each such store identified, try to find an
16583 // earlier chain to attach the store to which won't violate the
16584 // required ordering.
16585 bool MadeChangeToSt = false;
16586 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
16588 for (StoreSDNode *ChainedStore : ChainedStores) {
16589 SDValue Chain = ChainedStore->getChain();
16590 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
16592 if (Chain != BetterChain) {
16593 if (ChainedStore == St)
16594 MadeChangeToSt = true;
16595 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
16599 // Do all replacements after finding the replacements to make to avoid making
16600 // the chains more complicated by introducing new TokenFactors.
16601 for (auto Replacement : BetterChains)
16602 replaceStoreChain(Replacement.first, Replacement.second);
16604 return MadeChangeToSt;
16607 /// This is the entry point for the file.
16608 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
16609 CodeGenOpt::Level OptLevel) {
16610 /// This is the main entry point to this class.
16611 DAGCombiner(*this, AA, OptLevel).Run(Level);