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/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "dagcombine"
47 STATISTIC(NodesCombined , "Number of dag nodes combined");
48 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
49 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
50 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
51 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
52 STATISTIC(SlicedLoads, "Number of load sliced");
56 CombinerAA("combiner-alias-analysis", cl::Hidden,
57 cl::desc("Enable DAG combiner alias-analysis heuristics"));
60 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
61 cl::desc("Enable DAG combiner's use of IR alias analysis"));
64 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
65 cl::desc("Enable DAG combiner's use of TBAA"));
68 static cl::opt<std::string>
69 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
70 cl::desc("Only use DAG-combiner alias analysis in this"
74 /// Hidden option to stress test load slicing, i.e., when this option
75 /// is enabled, load slicing bypasses most of its profitability guards.
77 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
78 cl::desc("Bypass the profitability model of load "
83 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
84 cl::desc("DAG combiner may split indexing from loads"));
86 //------------------------------ DAGCombiner ---------------------------------//
90 const TargetLowering &TLI;
92 CodeGenOpt::Level OptLevel;
97 /// \brief Worklist of all of the nodes that need to be simplified.
99 /// This must behave as a stack -- new nodes to process are pushed onto the
100 /// back and when processing we pop off of the back.
102 /// The worklist will not contain duplicates but may contain null entries
103 /// due to nodes being deleted from the underlying DAG.
104 SmallVector<SDNode *, 64> Worklist;
106 /// \brief Mapping from an SDNode to its position on the worklist.
108 /// This is used to find and remove nodes from the worklist (by nulling
109 /// them) when they are deleted from the underlying DAG. It relies on
110 /// stable indices of nodes within the worklist.
111 DenseMap<SDNode *, unsigned> WorklistMap;
113 /// \brief Set of nodes which have been combined (at least once).
115 /// This is used to allow us to reliably add any operands of a DAG node
116 /// which have not yet been combined to the worklist.
117 SmallPtrSet<SDNode *, 32> CombinedNodes;
119 // AA - Used for DAG load/store alias analysis.
122 /// When an instruction is simplified, add all users of the instruction to
123 /// the work lists because they might get more simplified now.
124 void AddUsersToWorklist(SDNode *N) {
125 for (SDNode *Node : N->uses())
129 /// Call the node-specific routine that folds each particular type of node.
130 SDValue visit(SDNode *N);
133 /// Add to the worklist making sure its instance is at the back (next to be
135 void AddToWorklist(SDNode *N) {
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);
181 /// Check the specified integer node value to see if it can be simplified or
182 /// if things it uses can be simplified by bit propagation.
183 /// If so, return true.
184 bool SimplifyDemandedBits(SDValue Op) {
185 unsigned BitWidth = Op.getScalarValueSizeInBits();
186 APInt Demanded = APInt::getAllOnesValue(BitWidth);
187 return SimplifyDemandedBits(Op, Demanded);
190 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
192 bool CombineToPreIndexedLoadStore(SDNode *N);
193 bool CombineToPostIndexedLoadStore(SDNode *N);
194 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
195 bool SliceUpLoad(SDNode *N);
197 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
200 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
201 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
202 /// \param EltNo index of the vector element to load.
203 /// \param OriginalLoad load that EVE came from to be replaced.
204 /// \returns EVE on success SDValue() on failure.
205 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
206 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
207 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
208 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
209 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
210 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
211 SDValue PromoteIntBinOp(SDValue Op);
212 SDValue PromoteIntShiftOp(SDValue Op);
213 SDValue PromoteExtend(SDValue Op);
214 bool PromoteLoad(SDValue Op);
216 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
217 SDValue ExtLoad, const SDLoc &DL,
218 ISD::NodeType ExtType);
220 /// Call the node-specific routine that knows how to fold each
221 /// particular type of node. If that doesn't do anything, try the
222 /// target-specific DAG combines.
223 SDValue combine(SDNode *N);
225 // Visitation implementation - Implement dag node combining for different
226 // node types. The semantics are as follows:
228 // SDValue.getNode() == 0 - No change was made
229 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
230 // otherwise - N should be replaced by the returned Operand.
232 SDValue visitTokenFactor(SDNode *N);
233 SDValue visitMERGE_VALUES(SDNode *N);
234 SDValue visitADD(SDNode *N);
235 SDValue visitSUB(SDNode *N);
236 SDValue visitADDC(SDNode *N);
237 SDValue visitSUBC(SDNode *N);
238 SDValue visitADDE(SDNode *N);
239 SDValue visitSUBE(SDNode *N);
240 SDValue visitMUL(SDNode *N);
241 SDValue useDivRem(SDNode *N);
242 SDValue visitSDIV(SDNode *N);
243 SDValue visitUDIV(SDNode *N);
244 SDValue visitREM(SDNode *N);
245 SDValue visitMULHU(SDNode *N);
246 SDValue visitMULHS(SDNode *N);
247 SDValue visitSMUL_LOHI(SDNode *N);
248 SDValue visitUMUL_LOHI(SDNode *N);
249 SDValue visitSMULO(SDNode *N);
250 SDValue visitUMULO(SDNode *N);
251 SDValue visitIMINMAX(SDNode *N);
252 SDValue visitAND(SDNode *N);
253 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
254 SDValue visitOR(SDNode *N);
255 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
256 SDValue visitXOR(SDNode *N);
257 SDValue SimplifyVBinOp(SDNode *N);
258 SDValue visitSHL(SDNode *N);
259 SDValue visitSRA(SDNode *N);
260 SDValue visitSRL(SDNode *N);
261 SDValue visitRotate(SDNode *N);
262 SDValue visitBSWAP(SDNode *N);
263 SDValue visitBITREVERSE(SDNode *N);
264 SDValue visitCTLZ(SDNode *N);
265 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
266 SDValue visitCTTZ(SDNode *N);
267 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
268 SDValue visitCTPOP(SDNode *N);
269 SDValue visitSELECT(SDNode *N);
270 SDValue visitVSELECT(SDNode *N);
271 SDValue visitSELECT_CC(SDNode *N);
272 SDValue visitSETCC(SDNode *N);
273 SDValue visitSETCCE(SDNode *N);
274 SDValue visitSIGN_EXTEND(SDNode *N);
275 SDValue visitZERO_EXTEND(SDNode *N);
276 SDValue visitANY_EXTEND(SDNode *N);
277 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
278 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
279 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
280 SDValue visitTRUNCATE(SDNode *N);
281 SDValue visitBITCAST(SDNode *N);
282 SDValue visitBUILD_PAIR(SDNode *N);
283 SDValue visitFADD(SDNode *N);
284 SDValue visitFSUB(SDNode *N);
285 SDValue visitFMUL(SDNode *N);
286 SDValue visitFMA(SDNode *N);
287 SDValue visitFDIV(SDNode *N);
288 SDValue visitFREM(SDNode *N);
289 SDValue visitFSQRT(SDNode *N);
290 SDValue visitFCOPYSIGN(SDNode *N);
291 SDValue visitSINT_TO_FP(SDNode *N);
292 SDValue visitUINT_TO_FP(SDNode *N);
293 SDValue visitFP_TO_SINT(SDNode *N);
294 SDValue visitFP_TO_UINT(SDNode *N);
295 SDValue visitFP_ROUND(SDNode *N);
296 SDValue visitFP_ROUND_INREG(SDNode *N);
297 SDValue visitFP_EXTEND(SDNode *N);
298 SDValue visitFNEG(SDNode *N);
299 SDValue visitFABS(SDNode *N);
300 SDValue visitFCEIL(SDNode *N);
301 SDValue visitFTRUNC(SDNode *N);
302 SDValue visitFFLOOR(SDNode *N);
303 SDValue visitFMINNUM(SDNode *N);
304 SDValue visitFMAXNUM(SDNode *N);
305 SDValue visitBRCOND(SDNode *N);
306 SDValue visitBR_CC(SDNode *N);
307 SDValue visitLOAD(SDNode *N);
309 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
310 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
312 SDValue visitSTORE(SDNode *N);
313 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
314 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
315 SDValue visitBUILD_VECTOR(SDNode *N);
316 SDValue visitCONCAT_VECTORS(SDNode *N);
317 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
318 SDValue visitVECTOR_SHUFFLE(SDNode *N);
319 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
320 SDValue visitINSERT_SUBVECTOR(SDNode *N);
321 SDValue visitMLOAD(SDNode *N);
322 SDValue visitMSTORE(SDNode *N);
323 SDValue visitMGATHER(SDNode *N);
324 SDValue visitMSCATTER(SDNode *N);
325 SDValue visitFP_TO_FP16(SDNode *N);
326 SDValue visitFP16_TO_FP(SDNode *N);
328 SDValue visitFADDForFMACombine(SDNode *N);
329 SDValue visitFSUBForFMACombine(SDNode *N);
330 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
332 SDValue XformToShuffleWithZero(SDNode *N);
333 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
336 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
338 SDValue foldSelectOfConstants(SDNode *N);
339 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
340 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
341 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
342 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
343 SDValue N2, SDValue N3, ISD::CondCode CC,
344 bool NotExtCompare = false);
345 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
346 SDValue N2, SDValue N3, ISD::CondCode CC);
347 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
348 const SDLoc &DL, bool foldBooleans = true);
350 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
352 bool isOneUseSetCC(SDValue N) const;
354 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
356 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
357 SDValue CombineExtLoad(SDNode *N);
358 SDValue combineRepeatedFPDivisors(SDNode *N);
359 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
360 SDValue BuildSDIV(SDNode *N);
361 SDValue BuildSDIVPow2(SDNode *N);
362 SDValue BuildUDIV(SDNode *N);
363 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
364 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
365 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
366 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
367 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
368 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
369 SDNodeFlags *Flags, bool Reciprocal);
370 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
371 SDNodeFlags *Flags, bool Reciprocal);
372 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
373 bool DemandHighBits = true);
374 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
375 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
376 SDValue InnerPos, SDValue InnerNeg,
377 unsigned PosOpcode, unsigned NegOpcode,
379 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
380 SDValue ReduceLoadWidth(SDNode *N);
381 SDValue ReduceLoadOpStoreWidth(SDNode *N);
382 SDValue splitMergedValStore(StoreSDNode *ST);
383 SDValue TransformFPLoadStorePair(SDNode *N);
384 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
385 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
386 SDValue reduceBuildVecToShuffle(SDNode *N);
387 SDValue createBuildVecShuffle(SDLoc DL, SDNode *N, ArrayRef<int> VectorMask,
388 SDValue VecIn1, SDValue VecIn2,
391 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
393 /// Walk up chain skipping non-aliasing memory nodes,
394 /// looking for aliasing nodes and adding them to the Aliases vector.
395 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
396 SmallVectorImpl<SDValue> &Aliases);
398 /// Return true if there is any possibility that the two addresses overlap.
399 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
401 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
402 /// chain (aliasing node.)
403 SDValue FindBetterChain(SDNode *N, SDValue Chain);
405 /// Try to replace a store and any possibly adjacent stores on
406 /// consecutive chains with better chains. Return true only if St is
409 /// Notice that other chains may still be replaced even if the function
411 bool findBetterNeighborChains(StoreSDNode *St);
413 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
414 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
416 /// Holds a pointer to an LSBaseSDNode as well as information on where it
417 /// is located in a sequence of memory operations connected by a chain.
419 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
420 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
421 // Ptr to the mem node.
422 LSBaseSDNode *MemNode;
423 // Offset from the base ptr.
424 int64_t OffsetFromBase;
425 // What is the sequence number of this mem node.
426 // Lowest mem operand in the DAG starts at zero.
427 unsigned SequenceNum;
430 /// This is a helper function for visitMUL to check the profitability
431 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
432 /// MulNode is the original multiply, AddNode is (add x, c1),
433 /// and ConstNode is c2.
434 bool isMulAddWithConstProfitable(SDNode *MulNode,
438 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
439 /// constant build_vector of the stored constant values in Stores.
440 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL,
441 ArrayRef<MemOpLink> Stores,
442 SmallVectorImpl<SDValue> &Chains,
445 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
446 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
447 /// the type of the loaded value to be extended. LoadedVT returns the type
448 /// of the original loaded value. NarrowLoad returns whether the load would
449 /// need to be narrowed in order to match.
450 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
451 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
454 /// This is a helper function for MergeConsecutiveStores. When the source
455 /// elements of the consecutive stores are all constants or all extracted
456 /// vector elements, try to merge them into one larger store.
457 /// \return number of stores that were merged into a merged store (always
458 /// a prefix of \p StoreNode).
459 bool MergeStoresOfConstantsOrVecElts(
460 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
461 bool IsConstantSrc, bool UseVector);
463 /// This is a helper function for MergeConsecutiveStores.
464 /// Stores that may be merged are placed in StoreNodes.
465 /// Loads that may alias with those stores are placed in AliasLoadNodes.
466 void getStoreMergeAndAliasCandidates(
467 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
468 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
470 /// Helper function for MergeConsecutiveStores. Checks if
471 /// Candidate stores have indirect dependency through their
472 /// operands. \return True if safe to merge
473 bool checkMergeStoreCandidatesForDependencies(
474 SmallVectorImpl<MemOpLink> &StoreNodes);
476 /// Merge consecutive store operations into a wide store.
477 /// This optimization uses wide integers or vectors when possible.
478 /// \return number of stores that were merged into a merged store (the
479 /// affected nodes are stored as a prefix in \p StoreNodes).
480 bool MergeConsecutiveStores(StoreSDNode *N,
481 SmallVectorImpl<MemOpLink> &StoreNodes);
483 /// \brief Try to transform a truncation where C is a constant:
484 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
486 /// \p N needs to be a truncation and its first operand an AND. Other
487 /// requirements are checked by the function (e.g. that trunc is
488 /// single-use) and if missed an empty SDValue is returned.
489 SDValue distributeTruncateThroughAnd(SDNode *N);
492 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
493 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
494 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
495 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
498 /// Runs the dag combiner on all nodes in the work list
499 void Run(CombineLevel AtLevel);
501 SelectionDAG &getDAG() const { return DAG; }
503 /// Returns a type large enough to hold any valid shift amount - before type
504 /// legalization these can be huge.
505 EVT getShiftAmountTy(EVT LHSTy) {
506 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
507 if (LHSTy.isVector())
509 auto &DL = DAG.getDataLayout();
510 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
511 : TLI.getPointerTy(DL);
514 /// This method returns true if we are running before type legalization or
515 /// if the specified VT is legal.
516 bool isTypeLegal(const EVT &VT) {
517 if (!LegalTypes) return true;
518 return TLI.isTypeLegal(VT);
521 /// Convenience wrapper around TargetLowering::getSetCCResultType
522 EVT getSetCCResultType(EVT VT) const {
523 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
530 /// This class is a DAGUpdateListener that removes any deleted
531 /// nodes from the worklist.
532 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
535 explicit WorklistRemover(DAGCombiner &dc)
536 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
538 void NodeDeleted(SDNode *N, SDNode *E) override {
539 DC.removeFromWorklist(N);
544 //===----------------------------------------------------------------------===//
545 // TargetLowering::DAGCombinerInfo implementation
546 //===----------------------------------------------------------------------===//
548 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
549 ((DAGCombiner*)DC)->AddToWorklist(N);
552 SDValue TargetLowering::DAGCombinerInfo::
553 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
554 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
557 SDValue TargetLowering::DAGCombinerInfo::
558 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
559 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
563 SDValue TargetLowering::DAGCombinerInfo::
564 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
565 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
568 void TargetLowering::DAGCombinerInfo::
569 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
570 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
573 //===----------------------------------------------------------------------===//
575 //===----------------------------------------------------------------------===//
577 void DAGCombiner::deleteAndRecombine(SDNode *N) {
578 removeFromWorklist(N);
580 // If the operands of this node are only used by the node, they will now be
581 // dead. Make sure to re-visit them and recursively delete dead nodes.
582 for (const SDValue &Op : N->ops())
583 // For an operand generating multiple values, one of the values may
584 // become dead allowing further simplification (e.g. split index
585 // arithmetic from an indexed load).
586 if (Op->hasOneUse() || Op->getNumValues() > 1)
587 AddToWorklist(Op.getNode());
592 /// Return 1 if we can compute the negated form of the specified expression for
593 /// the same cost as the expression itself, or 2 if we can compute the negated
594 /// form more cheaply than the expression itself.
595 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
596 const TargetLowering &TLI,
597 const TargetOptions *Options,
598 unsigned Depth = 0) {
599 // fneg is removable even if it has multiple uses.
600 if (Op.getOpcode() == ISD::FNEG) return 2;
602 // Don't allow anything with multiple uses.
603 if (!Op.hasOneUse()) return 0;
605 // Don't recurse exponentially.
606 if (Depth > 6) return 0;
608 switch (Op.getOpcode()) {
609 default: return false;
610 case ISD::ConstantFP:
611 // Don't invert constant FP values after legalize. The negated constant
612 // isn't necessarily legal.
613 return LegalOperations ? 0 : 1;
615 // FIXME: determine better conditions for this xform.
616 if (!Options->UnsafeFPMath) return 0;
618 // After operation legalization, it might not be legal to create new FSUBs.
619 if (LegalOperations &&
620 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
623 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
624 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
627 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
628 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
631 // We can't turn -(A-B) into B-A when we honor signed zeros.
632 if (!Options->UnsafeFPMath && !Op.getNode()->getFlags()->hasNoSignedZeros())
635 // fold (fneg (fsub A, B)) -> (fsub B, A)
640 if (Options->HonorSignDependentRoundingFPMath()) return 0;
642 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
643 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
647 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
653 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
658 /// If isNegatibleForFree returns true, return the newly negated expression.
659 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
660 bool LegalOperations, unsigned Depth = 0) {
661 const TargetOptions &Options = DAG.getTarget().Options;
662 // fneg is removable even if it has multiple uses.
663 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
665 // Don't allow anything with multiple uses.
666 assert(Op.hasOneUse() && "Unknown reuse!");
668 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
670 const SDNodeFlags *Flags = Op.getNode()->getFlags();
672 switch (Op.getOpcode()) {
673 default: llvm_unreachable("Unknown code");
674 case ISD::ConstantFP: {
675 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
677 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
680 // FIXME: determine better conditions for this xform.
681 assert(Options.UnsafeFPMath);
683 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
684 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
685 DAG.getTargetLoweringInfo(), &Options, Depth+1))
686 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
687 GetNegatedExpression(Op.getOperand(0), DAG,
688 LegalOperations, Depth+1),
689 Op.getOperand(1), Flags);
690 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
691 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
692 GetNegatedExpression(Op.getOperand(1), DAG,
693 LegalOperations, Depth+1),
694 Op.getOperand(0), Flags);
696 // fold (fneg (fsub 0, B)) -> B
697 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
699 return Op.getOperand(1);
701 // fold (fneg (fsub A, B)) -> (fsub B, A)
702 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
703 Op.getOperand(1), Op.getOperand(0), Flags);
707 assert(!Options.HonorSignDependentRoundingFPMath());
709 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
710 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
711 DAG.getTargetLoweringInfo(), &Options, Depth+1))
712 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
713 GetNegatedExpression(Op.getOperand(0), DAG,
714 LegalOperations, Depth+1),
715 Op.getOperand(1), Flags);
717 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
718 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
720 GetNegatedExpression(Op.getOperand(1), DAG,
721 LegalOperations, Depth+1), Flags);
725 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
726 GetNegatedExpression(Op.getOperand(0), DAG,
727 LegalOperations, Depth+1));
729 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
730 GetNegatedExpression(Op.getOperand(0), DAG,
731 LegalOperations, Depth+1),
736 // APInts must be the same size for most operations, this helper
737 // function zero extends the shorter of the pair so that they match.
738 // We provide an Offset so that we can create bitwidths that won't overflow.
739 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
740 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
741 LHS = LHS.zextOrSelf(Bits);
742 RHS = RHS.zextOrSelf(Bits);
745 // Return true if this node is a setcc, or is a select_cc
746 // that selects between the target values used for true and false, making it
747 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
748 // the appropriate nodes based on the type of node we are checking. This
749 // simplifies life a bit for the callers.
750 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
752 if (N.getOpcode() == ISD::SETCC) {
753 LHS = N.getOperand(0);
754 RHS = N.getOperand(1);
755 CC = N.getOperand(2);
759 if (N.getOpcode() != ISD::SELECT_CC ||
760 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
761 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
764 if (TLI.getBooleanContents(N.getValueType()) ==
765 TargetLowering::UndefinedBooleanContent)
768 LHS = N.getOperand(0);
769 RHS = N.getOperand(1);
770 CC = N.getOperand(4);
774 /// Return true if this is a SetCC-equivalent operation with only one use.
775 /// If this is true, it allows the users to invert the operation for free when
776 /// it is profitable to do so.
777 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
779 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
784 // \brief Returns the SDNode if it is a constant float BuildVector
785 // or constant float.
786 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
787 if (isa<ConstantFPSDNode>(N))
789 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
794 // Determines if it is a constant integer or a build vector of constant
795 // integers (and undefs).
796 // Do not permit build vector implicit truncation.
797 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
798 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
799 return !(Const->isOpaque() && NoOpaques);
800 if (N.getOpcode() != ISD::BUILD_VECTOR)
802 unsigned BitWidth = N.getScalarValueSizeInBits();
803 for (const SDValue &Op : N->op_values()) {
806 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
807 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
808 (Const->isOpaque() && NoOpaques))
814 // Determines if it is a constant null integer or a splatted vector of a
815 // constant null integer (with no undefs).
816 // Build vector implicit truncation is not an issue for null values.
817 static bool isNullConstantOrNullSplatConstant(SDValue N) {
818 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
819 return Splat->isNullValue();
823 // Determines if it is a constant integer of one or a splatted vector of a
824 // constant integer of one (with no undefs).
825 // Do not permit build vector implicit truncation.
826 static bool isOneConstantOrOneSplatConstant(SDValue N) {
827 unsigned BitWidth = N.getScalarValueSizeInBits();
828 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
829 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
833 // Determines if it is a constant integer of all ones or a splatted vector of a
834 // constant integer of all ones (with no undefs).
835 // Do not permit build vector implicit truncation.
836 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
837 unsigned BitWidth = N.getScalarValueSizeInBits();
838 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
839 return Splat->isAllOnesValue() &&
840 Splat->getAPIntValue().getBitWidth() == BitWidth;
844 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
846 static bool isAnyConstantBuildVector(const SDNode *N) {
847 return ISD::isBuildVectorOfConstantSDNodes(N) ||
848 ISD::isBuildVectorOfConstantFPSDNodes(N);
851 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
853 EVT VT = N0.getValueType();
854 if (N0.getOpcode() == Opc) {
855 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
856 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
857 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
858 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
859 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
862 if (N0.hasOneUse()) {
863 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
865 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
866 if (!OpNode.getNode())
868 AddToWorklist(OpNode.getNode());
869 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
874 if (N1.getOpcode() == Opc) {
875 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
876 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
877 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
878 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
879 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
882 if (N1.hasOneUse()) {
883 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
885 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
886 if (!OpNode.getNode())
888 AddToWorklist(OpNode.getNode());
889 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
897 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
899 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
901 DEBUG(dbgs() << "\nReplacing.1 ";
903 dbgs() << "\nWith: ";
904 To[0].getNode()->dump(&DAG);
905 dbgs() << " and " << NumTo-1 << " other values\n");
906 for (unsigned i = 0, e = NumTo; i != e; ++i)
907 assert((!To[i].getNode() ||
908 N->getValueType(i) == To[i].getValueType()) &&
909 "Cannot combine value to value of different type!");
911 WorklistRemover DeadNodes(*this);
912 DAG.ReplaceAllUsesWith(N, To);
914 // Push the new nodes and any users onto the worklist
915 for (unsigned i = 0, e = NumTo; i != e; ++i) {
916 if (To[i].getNode()) {
917 AddToWorklist(To[i].getNode());
918 AddUsersToWorklist(To[i].getNode());
923 // Finally, if the node is now dead, remove it from the graph. The node
924 // may not be dead if the replacement process recursively simplified to
925 // something else needing this node.
927 deleteAndRecombine(N);
928 return SDValue(N, 0);
932 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
933 // Replace all uses. If any nodes become isomorphic to other nodes and
934 // are deleted, make sure to remove them from our worklist.
935 WorklistRemover DeadNodes(*this);
936 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
938 // Push the new node and any (possibly new) users onto the worklist.
939 AddToWorklist(TLO.New.getNode());
940 AddUsersToWorklist(TLO.New.getNode());
942 // Finally, if the node is now dead, remove it from the graph. The node
943 // may not be dead if the replacement process recursively simplified to
944 // something else needing this node.
945 if (TLO.Old.getNode()->use_empty())
946 deleteAndRecombine(TLO.Old.getNode());
949 /// Check the specified integer node value to see if it can be simplified or if
950 /// things it uses can be simplified by bit propagation. If so, return true.
951 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
952 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
953 APInt KnownZero, KnownOne;
954 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
958 AddToWorklist(Op.getNode());
960 // Replace the old value with the new one.
962 DEBUG(dbgs() << "\nReplacing.2 ";
963 TLO.Old.getNode()->dump(&DAG);
964 dbgs() << "\nWith: ";
965 TLO.New.getNode()->dump(&DAG);
968 CommitTargetLoweringOpt(TLO);
972 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
974 EVT VT = Load->getValueType(0);
975 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
977 DEBUG(dbgs() << "\nReplacing.9 ";
979 dbgs() << "\nWith: ";
980 Trunc.getNode()->dump(&DAG);
982 WorklistRemover DeadNodes(*this);
983 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
984 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
985 deleteAndRecombine(Load);
986 AddToWorklist(Trunc.getNode());
989 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
992 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
993 LoadSDNode *LD = cast<LoadSDNode>(Op);
994 EVT MemVT = LD->getMemoryVT();
995 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
996 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
998 : LD->getExtensionType();
1000 return DAG.getExtLoad(ExtType, DL, PVT,
1001 LD->getChain(), LD->getBasePtr(),
1002 MemVT, LD->getMemOperand());
1005 unsigned Opc = Op.getOpcode();
1008 case ISD::AssertSext:
1009 return DAG.getNode(ISD::AssertSext, DL, PVT,
1010 SExtPromoteOperand(Op.getOperand(0), PVT),
1012 case ISD::AssertZext:
1013 return DAG.getNode(ISD::AssertZext, DL, PVT,
1014 ZExtPromoteOperand(Op.getOperand(0), PVT),
1016 case ISD::Constant: {
1018 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1019 return DAG.getNode(ExtOpc, DL, PVT, Op);
1023 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1025 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1028 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1029 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1031 EVT OldVT = Op.getValueType();
1033 bool Replace = false;
1034 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1035 if (!NewOp.getNode())
1037 AddToWorklist(NewOp.getNode());
1040 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1041 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1042 DAG.getValueType(OldVT));
1045 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1046 EVT OldVT = Op.getValueType();
1048 bool Replace = false;
1049 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1050 if (!NewOp.getNode())
1052 AddToWorklist(NewOp.getNode());
1055 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1056 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1059 /// Promote the specified integer binary operation if the target indicates it is
1060 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1061 /// i32 since i16 instructions are longer.
1062 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1063 if (!LegalOperations)
1066 EVT VT = Op.getValueType();
1067 if (VT.isVector() || !VT.isInteger())
1070 // If operation type is 'undesirable', e.g. i16 on x86, consider
1072 unsigned Opc = Op.getOpcode();
1073 if (TLI.isTypeDesirableForOp(Opc, VT))
1077 // Consult target whether it is a good idea to promote this operation and
1078 // what's the right type to promote it to.
1079 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1080 assert(PVT != VT && "Don't know what type to promote to!");
1082 bool Replace0 = false;
1083 SDValue N0 = Op.getOperand(0);
1084 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1088 bool Replace1 = false;
1089 SDValue N1 = Op.getOperand(1);
1094 NN1 = PromoteOperand(N1, PVT, Replace1);
1099 AddToWorklist(NN0.getNode());
1101 AddToWorklist(NN1.getNode());
1104 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1106 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1108 DEBUG(dbgs() << "\nPromoting ";
1109 Op.getNode()->dump(&DAG));
1111 return DAG.getNode(ISD::TRUNCATE, DL, VT,
1112 DAG.getNode(Opc, DL, PVT, NN0, NN1));
1117 /// Promote the specified integer shift operation if the target indicates it is
1118 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1119 /// i32 since i16 instructions are longer.
1120 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1121 if (!LegalOperations)
1124 EVT VT = Op.getValueType();
1125 if (VT.isVector() || !VT.isInteger())
1128 // If operation type is 'undesirable', e.g. i16 on x86, consider
1130 unsigned Opc = Op.getOpcode();
1131 if (TLI.isTypeDesirableForOp(Opc, VT))
1135 // Consult target whether it is a good idea to promote this operation and
1136 // what's the right type to promote it to.
1137 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1138 assert(PVT != VT && "Don't know what type to promote to!");
1140 bool Replace = false;
1141 SDValue N0 = Op.getOperand(0);
1142 if (Opc == ISD::SRA)
1143 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1144 else if (Opc == ISD::SRL)
1145 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1147 N0 = PromoteOperand(N0, PVT, Replace);
1151 AddToWorklist(N0.getNode());
1153 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1155 DEBUG(dbgs() << "\nPromoting ";
1156 Op.getNode()->dump(&DAG));
1158 return DAG.getNode(ISD::TRUNCATE, DL, VT,
1159 DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1)));
1164 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1165 if (!LegalOperations)
1168 EVT VT = Op.getValueType();
1169 if (VT.isVector() || !VT.isInteger())
1172 // If operation type is 'undesirable', e.g. i16 on x86, consider
1174 unsigned Opc = Op.getOpcode();
1175 if (TLI.isTypeDesirableForOp(Opc, VT))
1179 // Consult target whether it is a good idea to promote this operation and
1180 // what's the right type to promote it to.
1181 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1182 assert(PVT != VT && "Don't know what type to promote to!");
1183 // fold (aext (aext x)) -> (aext x)
1184 // fold (aext (zext x)) -> (zext x)
1185 // fold (aext (sext x)) -> (sext x)
1186 DEBUG(dbgs() << "\nPromoting ";
1187 Op.getNode()->dump(&DAG));
1188 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1193 bool DAGCombiner::PromoteLoad(SDValue Op) {
1194 if (!LegalOperations)
1197 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1200 EVT VT = Op.getValueType();
1201 if (VT.isVector() || !VT.isInteger())
1204 // If operation type is 'undesirable', e.g. i16 on x86, consider
1206 unsigned Opc = Op.getOpcode();
1207 if (TLI.isTypeDesirableForOp(Opc, VT))
1211 // Consult target whether it is a good idea to promote this operation and
1212 // what's the right type to promote it to.
1213 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1214 assert(PVT != VT && "Don't know what type to promote to!");
1217 SDNode *N = Op.getNode();
1218 LoadSDNode *LD = cast<LoadSDNode>(N);
1219 EVT MemVT = LD->getMemoryVT();
1220 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1221 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1223 : LD->getExtensionType();
1224 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1225 LD->getChain(), LD->getBasePtr(),
1226 MemVT, LD->getMemOperand());
1227 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1229 DEBUG(dbgs() << "\nPromoting ";
1232 Result.getNode()->dump(&DAG);
1234 WorklistRemover DeadNodes(*this);
1235 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1236 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1237 deleteAndRecombine(N);
1238 AddToWorklist(Result.getNode());
1244 /// \brief Recursively delete a node which has no uses and any operands for
1245 /// which it is the only use.
1247 /// Note that this both deletes the nodes and removes them from the worklist.
1248 /// It also adds any nodes who have had a user deleted to the worklist as they
1249 /// may now have only one use and subject to other combines.
1250 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1251 if (!N->use_empty())
1254 SmallSetVector<SDNode *, 16> Nodes;
1257 N = Nodes.pop_back_val();
1261 if (N->use_empty()) {
1262 for (const SDValue &ChildN : N->op_values())
1263 Nodes.insert(ChildN.getNode());
1265 removeFromWorklist(N);
1270 } while (!Nodes.empty());
1274 //===----------------------------------------------------------------------===//
1275 // Main DAG Combiner implementation
1276 //===----------------------------------------------------------------------===//
1278 void DAGCombiner::Run(CombineLevel AtLevel) {
1279 // set the instance variables, so that the various visit routines may use it.
1281 LegalOperations = Level >= AfterLegalizeVectorOps;
1282 LegalTypes = Level >= AfterLegalizeTypes;
1284 // Add all the dag nodes to the worklist.
1285 for (SDNode &Node : DAG.allnodes())
1286 AddToWorklist(&Node);
1288 // Create a dummy node (which is not added to allnodes), that adds a reference
1289 // to the root node, preventing it from being deleted, and tracking any
1290 // changes of the root.
1291 HandleSDNode Dummy(DAG.getRoot());
1293 // While the worklist isn't empty, find a node and try to combine it.
1294 while (!WorklistMap.empty()) {
1296 // The Worklist holds the SDNodes in order, but it may contain null entries.
1298 N = Worklist.pop_back_val();
1301 bool GoodWorklistEntry = WorklistMap.erase(N);
1302 (void)GoodWorklistEntry;
1303 assert(GoodWorklistEntry &&
1304 "Found a worklist entry without a corresponding map entry!");
1306 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1307 // N is deleted from the DAG, since they too may now be dead or may have a
1308 // reduced number of uses, allowing other xforms.
1309 if (recursivelyDeleteUnusedNodes(N))
1312 WorklistRemover DeadNodes(*this);
1314 // If this combine is running after legalizing the DAG, re-legalize any
1315 // nodes pulled off the worklist.
1316 if (Level == AfterLegalizeDAG) {
1317 SmallSetVector<SDNode *, 16> UpdatedNodes;
1318 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1320 for (SDNode *LN : UpdatedNodes) {
1322 AddUsersToWorklist(LN);
1328 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1330 // Add any operands of the new node which have not yet been combined to the
1331 // worklist as well. Because the worklist uniques things already, this
1332 // won't repeatedly process the same operand.
1333 CombinedNodes.insert(N);
1334 for (const SDValue &ChildN : N->op_values())
1335 if (!CombinedNodes.count(ChildN.getNode()))
1336 AddToWorklist(ChildN.getNode());
1338 SDValue RV = combine(N);
1345 // If we get back the same node we passed in, rather than a new node or
1346 // zero, we know that the node must have defined multiple values and
1347 // CombineTo was used. Since CombineTo takes care of the worklist
1348 // mechanics for us, we have no work to do in this case.
1349 if (RV.getNode() == N)
1352 assert(N->getOpcode() != ISD::DELETED_NODE &&
1353 RV.getOpcode() != ISD::DELETED_NODE &&
1354 "Node was deleted but visit returned new node!");
1356 DEBUG(dbgs() << " ... into: ";
1357 RV.getNode()->dump(&DAG));
1359 if (N->getNumValues() == RV.getNode()->getNumValues())
1360 DAG.ReplaceAllUsesWith(N, RV.getNode());
1362 assert(N->getValueType(0) == RV.getValueType() &&
1363 N->getNumValues() == 1 && "Type mismatch");
1365 DAG.ReplaceAllUsesWith(N, &OpV);
1368 // Push the new node and any users onto the worklist
1369 AddToWorklist(RV.getNode());
1370 AddUsersToWorklist(RV.getNode());
1372 // Finally, if the node is now dead, remove it from the graph. The node
1373 // may not be dead if the replacement process recursively simplified to
1374 // something else needing this node. This will also take care of adding any
1375 // operands which have lost a user to the worklist.
1376 recursivelyDeleteUnusedNodes(N);
1379 // If the root changed (e.g. it was a dead load, update the root).
1380 DAG.setRoot(Dummy.getValue());
1381 DAG.RemoveDeadNodes();
1384 SDValue DAGCombiner::visit(SDNode *N) {
1385 switch (N->getOpcode()) {
1387 case ISD::TokenFactor: return visitTokenFactor(N);
1388 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1389 case ISD::ADD: return visitADD(N);
1390 case ISD::SUB: return visitSUB(N);
1391 case ISD::ADDC: return visitADDC(N);
1392 case ISD::SUBC: return visitSUBC(N);
1393 case ISD::ADDE: return visitADDE(N);
1394 case ISD::SUBE: return visitSUBE(N);
1395 case ISD::MUL: return visitMUL(N);
1396 case ISD::SDIV: return visitSDIV(N);
1397 case ISD::UDIV: return visitUDIV(N);
1399 case ISD::UREM: return visitREM(N);
1400 case ISD::MULHU: return visitMULHU(N);
1401 case ISD::MULHS: return visitMULHS(N);
1402 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1403 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1404 case ISD::SMULO: return visitSMULO(N);
1405 case ISD::UMULO: return visitUMULO(N);
1409 case ISD::UMAX: return visitIMINMAX(N);
1410 case ISD::AND: return visitAND(N);
1411 case ISD::OR: return visitOR(N);
1412 case ISD::XOR: return visitXOR(N);
1413 case ISD::SHL: return visitSHL(N);
1414 case ISD::SRA: return visitSRA(N);
1415 case ISD::SRL: return visitSRL(N);
1417 case ISD::ROTL: return visitRotate(N);
1418 case ISD::BSWAP: return visitBSWAP(N);
1419 case ISD::BITREVERSE: return visitBITREVERSE(N);
1420 case ISD::CTLZ: return visitCTLZ(N);
1421 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1422 case ISD::CTTZ: return visitCTTZ(N);
1423 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1424 case ISD::CTPOP: return visitCTPOP(N);
1425 case ISD::SELECT: return visitSELECT(N);
1426 case ISD::VSELECT: return visitVSELECT(N);
1427 case ISD::SELECT_CC: return visitSELECT_CC(N);
1428 case ISD::SETCC: return visitSETCC(N);
1429 case ISD::SETCCE: return visitSETCCE(N);
1430 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1431 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1432 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1433 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1434 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1435 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1436 case ISD::TRUNCATE: return visitTRUNCATE(N);
1437 case ISD::BITCAST: return visitBITCAST(N);
1438 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1439 case ISD::FADD: return visitFADD(N);
1440 case ISD::FSUB: return visitFSUB(N);
1441 case ISD::FMUL: return visitFMUL(N);
1442 case ISD::FMA: return visitFMA(N);
1443 case ISD::FDIV: return visitFDIV(N);
1444 case ISD::FREM: return visitFREM(N);
1445 case ISD::FSQRT: return visitFSQRT(N);
1446 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1447 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1448 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1449 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1450 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1451 case ISD::FP_ROUND: return visitFP_ROUND(N);
1452 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1453 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1454 case ISD::FNEG: return visitFNEG(N);
1455 case ISD::FABS: return visitFABS(N);
1456 case ISD::FFLOOR: return visitFFLOOR(N);
1457 case ISD::FMINNUM: return visitFMINNUM(N);
1458 case ISD::FMAXNUM: return visitFMAXNUM(N);
1459 case ISD::FCEIL: return visitFCEIL(N);
1460 case ISD::FTRUNC: return visitFTRUNC(N);
1461 case ISD::BRCOND: return visitBRCOND(N);
1462 case ISD::BR_CC: return visitBR_CC(N);
1463 case ISD::LOAD: return visitLOAD(N);
1464 case ISD::STORE: return visitSTORE(N);
1465 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1466 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1467 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1468 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1469 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1470 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1471 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1472 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1473 case ISD::MGATHER: return visitMGATHER(N);
1474 case ISD::MLOAD: return visitMLOAD(N);
1475 case ISD::MSCATTER: return visitMSCATTER(N);
1476 case ISD::MSTORE: return visitMSTORE(N);
1477 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1478 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1483 SDValue DAGCombiner::combine(SDNode *N) {
1484 SDValue RV = visit(N);
1486 // If nothing happened, try a target-specific DAG combine.
1487 if (!RV.getNode()) {
1488 assert(N->getOpcode() != ISD::DELETED_NODE &&
1489 "Node was deleted but visit returned NULL!");
1491 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1492 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1494 // Expose the DAG combiner to the target combiner impls.
1495 TargetLowering::DAGCombinerInfo
1496 DagCombineInfo(DAG, Level, false, this);
1498 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1502 // If nothing happened still, try promoting the operation.
1503 if (!RV.getNode()) {
1504 switch (N->getOpcode()) {
1512 RV = PromoteIntBinOp(SDValue(N, 0));
1517 RV = PromoteIntShiftOp(SDValue(N, 0));
1519 case ISD::SIGN_EXTEND:
1520 case ISD::ZERO_EXTEND:
1521 case ISD::ANY_EXTEND:
1522 RV = PromoteExtend(SDValue(N, 0));
1525 if (PromoteLoad(SDValue(N, 0)))
1531 // If N is a commutative binary node, try commuting it to enable more
1533 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1534 N->getNumValues() == 1) {
1535 SDValue N0 = N->getOperand(0);
1536 SDValue N1 = N->getOperand(1);
1538 // Constant operands are canonicalized to RHS.
1539 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1540 SDValue Ops[] = {N1, N0};
1541 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1544 return SDValue(CSENode, 0);
1551 /// Given a node, return its input chain if it has one, otherwise return a null
1553 static SDValue getInputChainForNode(SDNode *N) {
1554 if (unsigned NumOps = N->getNumOperands()) {
1555 if (N->getOperand(0).getValueType() == MVT::Other)
1556 return N->getOperand(0);
1557 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1558 return N->getOperand(NumOps-1);
1559 for (unsigned i = 1; i < NumOps-1; ++i)
1560 if (N->getOperand(i).getValueType() == MVT::Other)
1561 return N->getOperand(i);
1566 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1567 // If N has two operands, where one has an input chain equal to the other,
1568 // the 'other' chain is redundant.
1569 if (N->getNumOperands() == 2) {
1570 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1571 return N->getOperand(0);
1572 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1573 return N->getOperand(1);
1576 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1577 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1578 SmallPtrSet<SDNode*, 16> SeenOps;
1579 bool Changed = false; // If we should replace this token factor.
1581 // Start out with this token factor.
1584 // Iterate through token factors. The TFs grows when new token factors are
1586 for (unsigned i = 0; i < TFs.size(); ++i) {
1587 SDNode *TF = TFs[i];
1589 // Check each of the operands.
1590 for (const SDValue &Op : TF->op_values()) {
1592 switch (Op.getOpcode()) {
1593 case ISD::EntryToken:
1594 // Entry tokens don't need to be added to the list. They are
1599 case ISD::TokenFactor:
1600 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1601 // Queue up for processing.
1602 TFs.push_back(Op.getNode());
1603 // Clean up in case the token factor is removed.
1604 AddToWorklist(Op.getNode());
1611 // Only add if it isn't already in the list.
1612 if (SeenOps.insert(Op.getNode()).second)
1623 // If we've changed things around then replace token factor.
1626 // The entry token is the only possible outcome.
1627 Result = DAG.getEntryNode();
1629 // New and improved token factor.
1630 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1633 // Add users to worklist if AA is enabled, since it may introduce
1634 // a lot of new chained token factors while removing memory deps.
1635 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1636 : DAG.getSubtarget().useAA();
1637 return CombineTo(N, Result, UseAA /*add to worklist*/);
1643 /// MERGE_VALUES can always be eliminated.
1644 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1645 WorklistRemover DeadNodes(*this);
1646 // Replacing results may cause a different MERGE_VALUES to suddenly
1647 // be CSE'd with N, and carry its uses with it. Iterate until no
1648 // uses remain, to ensure that the node can be safely deleted.
1649 // First add the users of this node to the work list so that they
1650 // can be tried again once they have new operands.
1651 AddUsersToWorklist(N);
1653 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1654 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1655 } while (!N->use_empty());
1656 deleteAndRecombine(N);
1657 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1660 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1661 /// ConstantSDNode pointer else nullptr.
1662 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1663 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1664 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1667 SDValue DAGCombiner::visitADD(SDNode *N) {
1668 SDValue N0 = N->getOperand(0);
1669 SDValue N1 = N->getOperand(1);
1670 EVT VT = N0.getValueType();
1674 if (VT.isVector()) {
1675 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1678 // fold (add x, 0) -> x, vector edition
1679 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1681 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1685 // fold (add x, undef) -> undef
1692 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1693 // canonicalize constant to RHS
1694 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1695 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1696 // fold (add c1, c2) -> c1+c2
1697 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1701 // fold (add x, 0) -> x
1702 if (isNullConstant(N1))
1705 // fold ((c1-A)+c2) -> (c1+c2)-A
1706 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1707 if (N0.getOpcode() == ISD::SUB)
1708 if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1709 return DAG.getNode(ISD::SUB, DL, VT,
1710 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1716 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1719 // fold ((0-A) + B) -> B-A
1720 if (N0.getOpcode() == ISD::SUB &&
1721 isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1722 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1724 // fold (A + (0-B)) -> A-B
1725 if (N1.getOpcode() == ISD::SUB &&
1726 isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1727 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1729 // fold (A+(B-A)) -> B
1730 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1731 return N1.getOperand(0);
1733 // fold ((B-A)+A) -> B
1734 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1735 return N0.getOperand(0);
1737 // fold (A+(B-(A+C))) to (B-C)
1738 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1739 N0 == N1.getOperand(1).getOperand(0))
1740 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1741 N1.getOperand(1).getOperand(1));
1743 // fold (A+(B-(C+A))) to (B-C)
1744 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1745 N0 == N1.getOperand(1).getOperand(1))
1746 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1747 N1.getOperand(1).getOperand(0));
1749 // fold (A+((B-A)+or-C)) to (B+or-C)
1750 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1751 N1.getOperand(0).getOpcode() == ISD::SUB &&
1752 N0 == N1.getOperand(0).getOperand(1))
1753 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1756 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1757 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1758 SDValue N00 = N0.getOperand(0);
1759 SDValue N01 = N0.getOperand(1);
1760 SDValue N10 = N1.getOperand(0);
1761 SDValue N11 = N1.getOperand(1);
1763 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1764 return DAG.getNode(ISD::SUB, DL, VT,
1765 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1766 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1769 if (SimplifyDemandedBits(SDValue(N, 0)))
1770 return SDValue(N, 0);
1772 // fold (a+b) -> (a|b) iff a and b share no bits.
1773 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1774 VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1775 return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1777 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1778 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1779 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1780 return DAG.getNode(ISD::SUB, DL, VT, N0,
1781 DAG.getNode(ISD::SHL, DL, VT,
1782 N1.getOperand(0).getOperand(1),
1784 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1785 isNullConstantOrNullSplatConstant(N0.getOperand(0).getOperand(0)))
1786 return DAG.getNode(ISD::SUB, DL, VT, N1,
1787 DAG.getNode(ISD::SHL, DL, VT,
1788 N0.getOperand(0).getOperand(1),
1791 if (N1.getOpcode() == ISD::AND) {
1792 SDValue AndOp0 = N1.getOperand(0);
1793 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1794 unsigned DestBits = VT.getScalarSizeInBits();
1796 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1797 // and similar xforms where the inner op is either ~0 or 0.
1798 if (NumSignBits == DestBits &&
1799 isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1800 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1803 // add (sext i1), X -> sub X, (zext i1)
1804 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1805 N0.getOperand(0).getValueType() == MVT::i1 &&
1806 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1807 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1808 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1811 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1812 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1813 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1814 if (TN->getVT() == MVT::i1) {
1815 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1816 DAG.getConstant(1, DL, VT));
1817 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1824 SDValue DAGCombiner::visitADDC(SDNode *N) {
1825 SDValue N0 = N->getOperand(0);
1826 SDValue N1 = N->getOperand(1);
1827 EVT VT = N0.getValueType();
1829 // If the flag result is dead, turn this into an ADD.
1830 if (!N->hasAnyUseOfValue(1))
1831 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1832 DAG.getNode(ISD::CARRY_FALSE,
1833 SDLoc(N), MVT::Glue));
1835 // canonicalize constant to RHS.
1836 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1837 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1839 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1841 // fold (addc x, 0) -> x + no carry out
1842 if (isNullConstant(N1))
1843 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1844 SDLoc(N), MVT::Glue));
1846 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1847 APInt LHSZero, LHSOne;
1848 APInt RHSZero, RHSOne;
1849 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1851 if (LHSZero.getBoolValue()) {
1852 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1854 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1855 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1856 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1857 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1858 DAG.getNode(ISD::CARRY_FALSE,
1859 SDLoc(N), MVT::Glue));
1865 SDValue DAGCombiner::visitADDE(SDNode *N) {
1866 SDValue N0 = N->getOperand(0);
1867 SDValue N1 = N->getOperand(1);
1868 SDValue CarryIn = N->getOperand(2);
1870 // canonicalize constant to RHS
1871 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1872 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1874 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1877 // fold (adde x, y, false) -> (addc x, y)
1878 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1879 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1884 // Since it may not be valid to emit a fold to zero for vector initializers
1885 // check if we can before folding.
1886 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1887 SelectionDAG &DAG, bool LegalOperations,
1890 return DAG.getConstant(0, DL, VT);
1891 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1892 return DAG.getConstant(0, DL, VT);
1896 SDValue DAGCombiner::visitSUB(SDNode *N) {
1897 SDValue N0 = N->getOperand(0);
1898 SDValue N1 = N->getOperand(1);
1899 EVT VT = N0.getValueType();
1903 if (VT.isVector()) {
1904 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1907 // fold (sub x, 0) -> x, vector edition
1908 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1912 // fold (sub x, x) -> 0
1913 // FIXME: Refactor this and xor and other similar operations together.
1915 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
1916 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1917 DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1918 // fold (sub c1, c2) -> c1-c2
1919 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
1923 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1925 // fold (sub x, c) -> (add x, -c)
1927 return DAG.getNode(ISD::ADD, DL, VT, N0,
1928 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1931 if (isNullConstantOrNullSplatConstant(N0)) {
1932 unsigned BitWidth = VT.getScalarSizeInBits();
1933 // Right-shifting everything out but the sign bit followed by negation is
1934 // the same as flipping arithmetic/logical shift type without the negation:
1935 // -(X >>u 31) -> (X >>s 31)
1936 // -(X >>s 31) -> (X >>u 31)
1937 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
1938 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
1939 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
1940 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
1941 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
1942 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
1946 // 0 - X --> 0 if the sub is NUW.
1947 if (N->getFlags()->hasNoUnsignedWrap())
1950 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignBit(BitWidth))) {
1951 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
1952 // N1 must be 0 because negating the minimum signed value is undefined.
1953 if (N->getFlags()->hasNoSignedWrap())
1956 // 0 - X --> X if X is 0 or the minimum signed value.
1961 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1962 if (isAllOnesConstantOrAllOnesSplatConstant(N0))
1963 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
1965 // fold A-(A-B) -> B
1966 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1967 return N1.getOperand(1);
1969 // fold (A+B)-A -> B
1970 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1971 return N0.getOperand(1);
1973 // fold (A+B)-B -> A
1974 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1975 return N0.getOperand(0);
1977 // fold C2-(A+C1) -> (C2-C1)-A
1978 if (N1.getOpcode() == ISD::ADD) {
1979 SDValue N11 = N1.getOperand(1);
1980 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
1981 isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
1982 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
1983 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
1987 // fold ((A+(B+or-C))-B) -> A+or-C
1988 if (N0.getOpcode() == ISD::ADD &&
1989 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1990 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1991 N0.getOperand(1).getOperand(0) == N1)
1992 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
1993 N0.getOperand(1).getOperand(1));
1995 // fold ((A+(C+B))-B) -> A+C
1996 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
1997 N0.getOperand(1).getOperand(1) == N1)
1998 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
1999 N0.getOperand(1).getOperand(0));
2001 // fold ((A-(B-C))-C) -> A-B
2002 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2003 N0.getOperand(1).getOperand(1) == N1)
2004 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2005 N0.getOperand(1).getOperand(0));
2007 // If either operand of a sub is undef, the result is undef
2013 // If the relocation model supports it, consider symbol offsets.
2014 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2015 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2016 // fold (sub Sym, c) -> Sym-c
2017 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2018 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2020 (uint64_t)N1C->getSExtValue());
2021 // fold (sub Sym+c1, Sym+c2) -> c1-c2
2022 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2023 if (GA->getGlobal() == GB->getGlobal())
2024 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2028 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2029 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2030 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2031 if (TN->getVT() == MVT::i1) {
2032 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2033 DAG.getConstant(1, DL, VT));
2034 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2041 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2042 SDValue N0 = N->getOperand(0);
2043 SDValue N1 = N->getOperand(1);
2044 EVT VT = N0.getValueType();
2047 // If the flag result is dead, turn this into an SUB.
2048 if (!N->hasAnyUseOfValue(1))
2049 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2050 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2052 // fold (subc x, x) -> 0 + no borrow
2054 return CombineTo(N, DAG.getConstant(0, DL, VT),
2055 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2057 // fold (subc x, 0) -> x + no borrow
2058 if (isNullConstant(N1))
2059 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2061 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2062 if (isAllOnesConstant(N0))
2063 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2064 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2069 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2070 SDValue N0 = N->getOperand(0);
2071 SDValue N1 = N->getOperand(1);
2072 SDValue CarryIn = N->getOperand(2);
2074 // fold (sube x, y, false) -> (subc x, y)
2075 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2076 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2081 SDValue DAGCombiner::visitMUL(SDNode *N) {
2082 SDValue N0 = N->getOperand(0);
2083 SDValue N1 = N->getOperand(1);
2084 EVT VT = N0.getValueType();
2086 // fold (mul x, undef) -> 0
2087 if (N0.isUndef() || N1.isUndef())
2088 return DAG.getConstant(0, SDLoc(N), VT);
2090 bool N0IsConst = false;
2091 bool N1IsConst = false;
2092 bool N1IsOpaqueConst = false;
2093 bool N0IsOpaqueConst = false;
2094 APInt ConstValue0, ConstValue1;
2096 if (VT.isVector()) {
2097 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2100 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2101 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2103 N0IsConst = isa<ConstantSDNode>(N0);
2105 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2106 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2108 N1IsConst = isa<ConstantSDNode>(N1);
2110 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2111 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2115 // fold (mul c1, c2) -> c1*c2
2116 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2117 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2118 N0.getNode(), N1.getNode());
2120 // canonicalize constant to RHS (vector doesn't have to splat)
2121 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2122 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2123 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2124 // fold (mul x, 0) -> 0
2125 if (N1IsConst && ConstValue1 == 0)
2127 // We require a splat of the entire scalar bit width for non-contiguous
2130 ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2131 // fold (mul x, 1) -> x
2132 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2134 // fold (mul x, -1) -> 0-x
2135 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2137 return DAG.getNode(ISD::SUB, DL, VT,
2138 DAG.getConstant(0, DL, VT), N0);
2140 // fold (mul x, (1 << c)) -> x << c
2141 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2144 return DAG.getNode(ISD::SHL, DL, VT, N0,
2145 DAG.getConstant(ConstValue1.logBase2(), DL,
2146 getShiftAmountTy(N0.getValueType())));
2148 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2149 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2151 unsigned Log2Val = (-ConstValue1).logBase2();
2153 // FIXME: If the input is something that is easily negated (e.g. a
2154 // single-use add), we should put the negate there.
2155 return DAG.getNode(ISD::SUB, DL, VT,
2156 DAG.getConstant(0, DL, VT),
2157 DAG.getNode(ISD::SHL, DL, VT, N0,
2158 DAG.getConstant(Log2Val, DL,
2159 getShiftAmountTy(N0.getValueType()))));
2162 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2163 if (N0.getOpcode() == ISD::SHL &&
2164 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2165 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2166 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2167 if (isConstantOrConstantVector(C3))
2168 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2171 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2174 SDValue Sh(nullptr, 0), Y(nullptr, 0);
2176 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2177 if (N0.getOpcode() == ISD::SHL &&
2178 isConstantOrConstantVector(N0.getOperand(1)) &&
2179 N0.getNode()->hasOneUse()) {
2181 } else if (N1.getOpcode() == ISD::SHL &&
2182 isConstantOrConstantVector(N1.getOperand(1)) &&
2183 N1.getNode()->hasOneUse()) {
2188 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2189 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2193 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2194 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2195 N0.getOpcode() == ISD::ADD &&
2196 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2197 isMulAddWithConstProfitable(N, N0, N1))
2198 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2199 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2200 N0.getOperand(0), N1),
2201 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2202 N0.getOperand(1), N1));
2205 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2211 /// Return true if divmod libcall is available.
2212 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2213 const TargetLowering &TLI) {
2215 EVT NodeType = Node->getValueType(0);
2216 if (!NodeType.isSimple())
2218 switch (NodeType.getSimpleVT().SimpleTy) {
2219 default: return false; // No libcall for vector types.
2220 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2221 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2222 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2223 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2224 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2227 return TLI.getLibcallName(LC) != nullptr;
2230 /// Issue divrem if both quotient and remainder are needed.
2231 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2232 if (Node->use_empty())
2233 return SDValue(); // This is a dead node, leave it alone.
2235 unsigned Opcode = Node->getOpcode();
2236 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2237 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2239 // DivMod lib calls can still work on non-legal types if using lib-calls.
2240 EVT VT = Node->getValueType(0);
2241 if (VT.isVector() || !VT.isInteger())
2244 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2247 // If DIVREM is going to get expanded into a libcall,
2248 // but there is no libcall available, then don't combine.
2249 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2250 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2253 // If div is legal, it's better to do the normal expansion
2254 unsigned OtherOpcode = 0;
2255 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2256 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2257 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2260 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2261 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2265 SDValue Op0 = Node->getOperand(0);
2266 SDValue Op1 = Node->getOperand(1);
2268 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2269 UE = Op0.getNode()->use_end(); UI != UE;) {
2270 SDNode *User = *UI++;
2271 if (User == Node || User->use_empty())
2273 // Convert the other matching node(s), too;
2274 // otherwise, the DIVREM may get target-legalized into something
2275 // target-specific that we won't be able to recognize.
2276 unsigned UserOpc = User->getOpcode();
2277 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2278 User->getOperand(0) == Op0 &&
2279 User->getOperand(1) == Op1) {
2281 if (UserOpc == OtherOpcode) {
2282 SDVTList VTs = DAG.getVTList(VT, VT);
2283 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2284 } else if (UserOpc == DivRemOpc) {
2285 combined = SDValue(User, 0);
2287 assert(UserOpc == Opcode);
2291 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2292 CombineTo(User, combined);
2293 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2294 CombineTo(User, combined.getValue(1));
2300 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2301 SDValue N0 = N->getOperand(0);
2302 SDValue N1 = N->getOperand(1);
2303 EVT VT = N->getValueType(0);
2307 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2312 // fold (sdiv c1, c2) -> c1/c2
2313 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2314 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2315 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2316 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2317 // fold (sdiv X, 1) -> X
2318 if (N1C && N1C->isOne())
2320 // fold (sdiv X, -1) -> 0-X
2321 if (N1C && N1C->isAllOnesValue())
2322 return DAG.getNode(ISD::SUB, DL, VT,
2323 DAG.getConstant(0, DL, VT), N0);
2325 // If we know the sign bits of both operands are zero, strength reduce to a
2326 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2327 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2328 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2330 // fold (sdiv X, pow2) -> simple ops after legalize
2331 // FIXME: We check for the exact bit here because the generic lowering gives
2332 // better results in that case. The target-specific lowering should learn how
2333 // to handle exact sdivs efficiently.
2334 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2335 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2336 (N1C->getAPIntValue().isPowerOf2() ||
2337 (-N1C->getAPIntValue()).isPowerOf2())) {
2338 // Target-specific implementation of sdiv x, pow2.
2339 if (SDValue Res = BuildSDIVPow2(N))
2342 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2344 // Splat the sign bit into the register
2346 DAG.getNode(ISD::SRA, DL, VT, N0,
2347 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2348 getShiftAmountTy(N0.getValueType())));
2349 AddToWorklist(SGN.getNode());
2351 // Add (N0 < 0) ? abs2 - 1 : 0;
2353 DAG.getNode(ISD::SRL, DL, VT, SGN,
2354 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2355 getShiftAmountTy(SGN.getValueType())));
2356 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2357 AddToWorklist(SRL.getNode());
2358 AddToWorklist(ADD.getNode()); // Divide by pow2
2359 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2360 DAG.getConstant(lg2, DL,
2361 getShiftAmountTy(ADD.getValueType())));
2363 // If we're dividing by a positive value, we're done. Otherwise, we must
2364 // negate the result.
2365 if (N1C->getAPIntValue().isNonNegative())
2368 AddToWorklist(SRA.getNode());
2369 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2372 // If integer divide is expensive and we satisfy the requirements, emit an
2373 // alternate sequence. Targets may check function attributes for size/speed
2375 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2376 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2377 if (SDValue Op = BuildSDIV(N))
2380 // sdiv, srem -> sdivrem
2381 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2382 // true. Otherwise, we break the simplification logic in visitREM().
2383 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2384 if (SDValue DivRem = useDivRem(N))
2389 return DAG.getConstant(0, DL, VT);
2390 // X / undef -> undef
2397 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2398 SDValue N0 = N->getOperand(0);
2399 SDValue N1 = N->getOperand(1);
2400 EVT VT = N->getValueType(0);
2404 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2409 // fold (udiv c1, c2) -> c1/c2
2410 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2411 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2413 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2417 // fold (udiv x, (1 << c)) -> x >>u c
2418 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2419 DAG.isKnownToBeAPowerOfTwo(N1)) {
2420 SDValue LogBase2 = BuildLogBase2(N1, DL);
2421 AddToWorklist(LogBase2.getNode());
2423 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2424 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2425 AddToWorklist(Trunc.getNode());
2426 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2429 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2430 if (N1.getOpcode() == ISD::SHL) {
2431 SDValue N10 = N1.getOperand(0);
2432 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2433 DAG.isKnownToBeAPowerOfTwo(N10)) {
2434 SDValue LogBase2 = BuildLogBase2(N10, DL);
2435 AddToWorklist(LogBase2.getNode());
2437 EVT ADDVT = N1.getOperand(1).getValueType();
2438 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2439 AddToWorklist(Trunc.getNode());
2440 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2441 AddToWorklist(Add.getNode());
2442 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2446 // fold (udiv x, c) -> alternate
2447 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2448 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2449 if (SDValue Op = BuildUDIV(N))
2452 // sdiv, srem -> sdivrem
2453 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2454 // true. Otherwise, we break the simplification logic in visitREM().
2455 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2456 if (SDValue DivRem = useDivRem(N))
2461 return DAG.getConstant(0, DL, VT);
2462 // X / undef -> undef
2469 // handles ISD::SREM and ISD::UREM
2470 SDValue DAGCombiner::visitREM(SDNode *N) {
2471 unsigned Opcode = N->getOpcode();
2472 SDValue N0 = N->getOperand(0);
2473 SDValue N1 = N->getOperand(1);
2474 EVT VT = N->getValueType(0);
2475 bool isSigned = (Opcode == ISD::SREM);
2478 // fold (rem c1, c2) -> c1%c2
2479 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2480 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2482 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2486 // If we know the sign bits of both operands are zero, strength reduce to a
2487 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2488 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2489 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2491 // fold (urem x, pow2) -> (and x, pow2-1)
2492 if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2493 APInt NegOne = APInt::getAllOnesValue(VT.getScalarSizeInBits());
2495 DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2496 AddToWorklist(Add.getNode());
2497 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2499 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2500 if (N1.getOpcode() == ISD::SHL &&
2501 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2502 APInt NegOne = APInt::getAllOnesValue(VT.getScalarSizeInBits());
2504 DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2505 AddToWorklist(Add.getNode());
2506 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2510 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2512 // If X/C can be simplified by the division-by-constant logic, lower
2513 // X%C to the equivalent of X-X/C*C.
2514 // To avoid mangling nodes, this simplification requires that the combine()
2515 // call for the speculative DIV must not cause a DIVREM conversion. We guard
2516 // against this by skipping the simplification if isIntDivCheap(). When
2517 // div is not cheap, combine will not return a DIVREM. Regardless,
2518 // checking cheapness here makes sense since the simplification results in
2520 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2521 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2522 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2523 AddToWorklist(Div.getNode());
2524 SDValue OptimizedDiv = combine(Div.getNode());
2525 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2526 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2527 (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2528 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2529 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2530 AddToWorklist(Mul.getNode());
2535 // sdiv, srem -> sdivrem
2536 if (SDValue DivRem = useDivRem(N))
2537 return DivRem.getValue(1);
2541 return DAG.getConstant(0, DL, VT);
2542 // X % undef -> undef
2549 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2550 SDValue N0 = N->getOperand(0);
2551 SDValue N1 = N->getOperand(1);
2552 EVT VT = N->getValueType(0);
2555 // fold (mulhs x, 0) -> 0
2556 if (isNullConstant(N1))
2558 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2559 if (isOneConstant(N1)) {
2561 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2562 DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2563 getShiftAmountTy(N0.getValueType())));
2565 // fold (mulhs x, undef) -> 0
2566 if (N0.isUndef() || N1.isUndef())
2567 return DAG.getConstant(0, SDLoc(N), VT);
2569 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2571 if (VT.isSimple() && !VT.isVector()) {
2572 MVT Simple = VT.getSimpleVT();
2573 unsigned SimpleSize = Simple.getSizeInBits();
2574 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2575 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2576 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2577 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2578 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2579 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2580 DAG.getConstant(SimpleSize, DL,
2581 getShiftAmountTy(N1.getValueType())));
2582 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2589 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2590 SDValue N0 = N->getOperand(0);
2591 SDValue N1 = N->getOperand(1);
2592 EVT VT = N->getValueType(0);
2595 // fold (mulhu x, 0) -> 0
2596 if (isNullConstant(N1))
2598 // fold (mulhu x, 1) -> 0
2599 if (isOneConstant(N1))
2600 return DAG.getConstant(0, DL, N0.getValueType());
2601 // fold (mulhu x, undef) -> 0
2602 if (N0.isUndef() || N1.isUndef())
2603 return DAG.getConstant(0, DL, VT);
2605 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2607 if (VT.isSimple() && !VT.isVector()) {
2608 MVT Simple = VT.getSimpleVT();
2609 unsigned SimpleSize = Simple.getSizeInBits();
2610 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2611 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2612 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2613 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2614 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2615 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2616 DAG.getConstant(SimpleSize, DL,
2617 getShiftAmountTy(N1.getValueType())));
2618 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2625 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2626 /// give the opcodes for the two computations that are being performed. Return
2627 /// true if a simplification was made.
2628 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2630 // If the high half is not needed, just compute the low half.
2631 bool HiExists = N->hasAnyUseOfValue(1);
2633 (!LegalOperations ||
2634 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2635 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2636 return CombineTo(N, Res, Res);
2639 // If the low half is not needed, just compute the high half.
2640 bool LoExists = N->hasAnyUseOfValue(0);
2642 (!LegalOperations ||
2643 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2644 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2645 return CombineTo(N, Res, Res);
2648 // If both halves are used, return as it is.
2649 if (LoExists && HiExists)
2652 // If the two computed results can be simplified separately, separate them.
2654 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2655 AddToWorklist(Lo.getNode());
2656 SDValue LoOpt = combine(Lo.getNode());
2657 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2658 (!LegalOperations ||
2659 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2660 return CombineTo(N, LoOpt, LoOpt);
2664 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2665 AddToWorklist(Hi.getNode());
2666 SDValue HiOpt = combine(Hi.getNode());
2667 if (HiOpt.getNode() && HiOpt != Hi &&
2668 (!LegalOperations ||
2669 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2670 return CombineTo(N, HiOpt, HiOpt);
2676 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2677 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2680 EVT VT = N->getValueType(0);
2683 // If the type is twice as wide is legal, transform the mulhu to a wider
2684 // multiply plus a shift.
2685 if (VT.isSimple() && !VT.isVector()) {
2686 MVT Simple = VT.getSimpleVT();
2687 unsigned SimpleSize = Simple.getSizeInBits();
2688 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2689 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2690 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2691 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2692 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2693 // Compute the high part as N1.
2694 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2695 DAG.getConstant(SimpleSize, DL,
2696 getShiftAmountTy(Lo.getValueType())));
2697 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2698 // Compute the low part as N0.
2699 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2700 return CombineTo(N, Lo, Hi);
2707 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2708 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2711 EVT VT = N->getValueType(0);
2714 // If the type is twice as wide is legal, transform the mulhu to a wider
2715 // multiply plus a shift.
2716 if (VT.isSimple() && !VT.isVector()) {
2717 MVT Simple = VT.getSimpleVT();
2718 unsigned SimpleSize = Simple.getSizeInBits();
2719 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2720 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2721 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2722 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2723 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2724 // Compute the high part as N1.
2725 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2726 DAG.getConstant(SimpleSize, DL,
2727 getShiftAmountTy(Lo.getValueType())));
2728 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2729 // Compute the low part as N0.
2730 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2731 return CombineTo(N, Lo, Hi);
2738 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2739 // (smulo x, 2) -> (saddo x, x)
2740 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2741 if (C2->getAPIntValue() == 2)
2742 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2743 N->getOperand(0), N->getOperand(0));
2748 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2749 // (umulo x, 2) -> (uaddo x, x)
2750 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2751 if (C2->getAPIntValue() == 2)
2752 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2753 N->getOperand(0), N->getOperand(0));
2758 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2759 SDValue N0 = N->getOperand(0);
2760 SDValue N1 = N->getOperand(1);
2761 EVT VT = N0.getValueType();
2765 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2768 // fold (add c1, c2) -> c1+c2
2769 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2770 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2772 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2774 // canonicalize constant to RHS
2775 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2776 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2777 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2782 /// If this is a binary operator with two operands of the same opcode, try to
2784 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2785 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2786 EVT VT = N0.getValueType();
2787 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2789 // Bail early if none of these transforms apply.
2790 if (N0.getNumOperands() == 0) return SDValue();
2792 // For each of OP in AND/OR/XOR:
2793 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2794 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2795 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2796 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2797 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2799 // do not sink logical op inside of a vector extend, since it may combine
2801 EVT Op0VT = N0.getOperand(0).getValueType();
2802 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2803 N0.getOpcode() == ISD::SIGN_EXTEND ||
2804 N0.getOpcode() == ISD::BSWAP ||
2805 // Avoid infinite looping with PromoteIntBinOp.
2806 (N0.getOpcode() == ISD::ANY_EXTEND &&
2807 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2808 (N0.getOpcode() == ISD::TRUNCATE &&
2809 (!TLI.isZExtFree(VT, Op0VT) ||
2810 !TLI.isTruncateFree(Op0VT, VT)) &&
2811 TLI.isTypeLegal(Op0VT))) &&
2813 Op0VT == N1.getOperand(0).getValueType() &&
2814 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2815 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2816 N0.getOperand(0).getValueType(),
2817 N0.getOperand(0), N1.getOperand(0));
2818 AddToWorklist(ORNode.getNode());
2819 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2822 // For each of OP in SHL/SRL/SRA/AND...
2823 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2824 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2825 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2826 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2827 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2828 N0.getOperand(1) == N1.getOperand(1)) {
2829 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2830 N0.getOperand(0).getValueType(),
2831 N0.getOperand(0), N1.getOperand(0));
2832 AddToWorklist(ORNode.getNode());
2833 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2834 ORNode, N0.getOperand(1));
2837 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2838 // Only perform this optimization up until type legalization, before
2839 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2840 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2841 // we don't want to undo this promotion.
2842 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2844 if ((N0.getOpcode() == ISD::BITCAST ||
2845 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2846 Level <= AfterLegalizeTypes) {
2847 SDValue In0 = N0.getOperand(0);
2848 SDValue In1 = N1.getOperand(0);
2849 EVT In0Ty = In0.getValueType();
2850 EVT In1Ty = In1.getValueType();
2852 // If both incoming values are integers, and the original types are the
2854 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2855 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2856 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2857 AddToWorklist(Op.getNode());
2862 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2863 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2864 // If both shuffles use the same mask, and both shuffle within a single
2865 // vector, then it is worthwhile to move the swizzle after the operation.
2866 // The type-legalizer generates this pattern when loading illegal
2867 // vector types from memory. In many cases this allows additional shuffle
2869 // There are other cases where moving the shuffle after the xor/and/or
2870 // is profitable even if shuffles don't perform a swizzle.
2871 // If both shuffles use the same mask, and both shuffles have the same first
2872 // or second operand, then it might still be profitable to move the shuffle
2873 // after the xor/and/or operation.
2874 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2875 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2876 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2878 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2879 "Inputs to shuffles are not the same type");
2881 // Check that both shuffles use the same mask. The masks are known to be of
2882 // the same length because the result vector type is the same.
2883 // Check also that shuffles have only one use to avoid introducing extra
2885 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2886 SVN0->getMask().equals(SVN1->getMask())) {
2887 SDValue ShOp = N0->getOperand(1);
2889 // Don't try to fold this node if it requires introducing a
2890 // build vector of all zeros that might be illegal at this stage.
2891 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2893 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2898 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2899 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2900 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2901 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2902 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2903 N0->getOperand(0), N1->getOperand(0));
2904 AddToWorklist(NewNode.getNode());
2905 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2909 // Don't try to fold this node if it requires introducing a
2910 // build vector of all zeros that might be illegal at this stage.
2911 ShOp = N0->getOperand(0);
2912 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2914 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2919 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2920 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2921 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2922 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2923 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2924 N0->getOperand(1), N1->getOperand(1));
2925 AddToWorklist(NewNode.getNode());
2926 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2935 /// This contains all DAGCombine rules which reduce two values combined by
2936 /// an And operation to a single value. This makes them reusable in the context
2937 /// of visitSELECT(). Rules involving constants are not included as
2938 /// visitSELECT() already handles those cases.
2939 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2940 SDNode *LocReference) {
2941 EVT VT = N1.getValueType();
2943 // fold (and x, undef) -> 0
2944 if (N0.isUndef() || N1.isUndef())
2945 return DAG.getConstant(0, SDLoc(LocReference), VT);
2946 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2947 SDValue LL, LR, RL, RR, CC0, CC1;
2948 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2949 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2950 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2952 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2953 LL.getValueType().isInteger()) {
2954 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2955 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2956 EVT CCVT = getSetCCResultType(LR.getValueType());
2957 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2958 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2959 LR.getValueType(), LL, RL);
2960 AddToWorklist(ORNode.getNode());
2961 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2964 if (isAllOnesConstant(LR)) {
2965 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2966 if (Op1 == ISD::SETEQ) {
2967 EVT CCVT = getSetCCResultType(LR.getValueType());
2968 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2969 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2970 LR.getValueType(), LL, RL);
2971 AddToWorklist(ANDNode.getNode());
2972 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2975 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2976 if (Op1 == ISD::SETGT) {
2977 EVT CCVT = getSetCCResultType(LR.getValueType());
2978 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2979 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2980 LR.getValueType(), LL, RL);
2981 AddToWorklist(ORNode.getNode());
2982 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2987 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2988 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2989 Op0 == Op1 && LL.getValueType().isInteger() &&
2990 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2991 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2992 EVT CCVT = getSetCCResultType(LL.getValueType());
2993 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2995 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2996 LL, DAG.getConstant(1, DL,
2997 LL.getValueType()));
2998 AddToWorklist(ADDNode.getNode());
2999 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
3000 DAG.getConstant(2, DL, LL.getValueType()),
3004 // canonicalize equivalent to ll == rl
3005 if (LL == RR && LR == RL) {
3006 Op1 = ISD::getSetCCSwappedOperands(Op1);
3009 if (LL == RL && LR == RR) {
3010 bool isInteger = LL.getValueType().isInteger();
3011 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
3012 if (Result != ISD::SETCC_INVALID &&
3013 (!LegalOperations ||
3014 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3015 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3016 EVT CCVT = getSetCCResultType(LL.getValueType());
3017 if (N0.getValueType() == CCVT ||
3018 (!LegalOperations && N0.getValueType() == MVT::i1))
3019 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3025 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3026 VT.getSizeInBits() <= 64) {
3027 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3028 APInt ADDC = ADDI->getAPIntValue();
3029 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3030 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3031 // immediate for an add, but it is legal if its top c2 bits are set,
3032 // transform the ADD so the immediate doesn't need to be materialized
3034 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3035 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3036 SRLI->getZExtValue());
3037 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3039 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3042 DAG.getNode(ISD::ADD, DL, VT,
3043 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3044 CombineTo(N0.getNode(), NewAdd);
3045 // Return N so it doesn't get rechecked!
3046 return SDValue(LocReference, 0);
3054 // Reduce bit extract of low half of an integer to the narrower type.
3055 // (and (srl i64:x, K), KMask) ->
3056 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3057 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3058 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3059 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3060 unsigned Size = VT.getSizeInBits();
3061 const APInt &AndMask = CAnd->getAPIntValue();
3062 unsigned ShiftBits = CShift->getZExtValue();
3064 // Bail out, this node will probably disappear anyway.
3068 unsigned MaskBits = AndMask.countTrailingOnes();
3069 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3071 if (APIntOps::isMask(AndMask) &&
3072 // Required bits must not span the two halves of the integer and
3073 // must fit in the half size type.
3074 (ShiftBits + MaskBits <= Size / 2) &&
3075 TLI.isNarrowingProfitable(VT, HalfVT) &&
3076 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3077 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3078 TLI.isTruncateFree(VT, HalfVT) &&
3079 TLI.isZExtFree(HalfVT, VT)) {
3080 // The isNarrowingProfitable is to avoid regressions on PPC and
3081 // AArch64 which match a few 64-bit bit insert / bit extract patterns
3082 // on downstream users of this. Those patterns could probably be
3083 // extended to handle extensions mixed in.
3086 assert(MaskBits <= Size);
3088 // Extracting the highest bit of the low half.
3089 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3090 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3093 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3094 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3095 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3096 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3097 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3106 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3107 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3109 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3111 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3114 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3115 LoadedVT = LoadN->getMemoryVT();
3117 if (ExtVT == LoadedVT &&
3118 (!LegalOperations ||
3119 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3120 // ZEXTLOAD will match without needing to change the size of the value being
3126 // Do not change the width of a volatile load.
3127 if (LoadN->isVolatile())
3130 // Do not generate loads of non-round integer types since these can
3131 // be expensive (and would be wrong if the type is not byte sized).
3132 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3135 if (LegalOperations &&
3136 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3139 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3146 SDValue DAGCombiner::visitAND(SDNode *N) {
3147 SDValue N0 = N->getOperand(0);
3148 SDValue N1 = N->getOperand(1);
3149 EVT VT = N1.getValueType();
3156 if (VT.isVector()) {
3157 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3160 // fold (and x, 0) -> 0, vector edition
3161 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3162 // do not return N0, because undef node may exist in N0
3163 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3164 SDLoc(N), N0.getValueType());
3165 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3166 // do not return N1, because undef node may exist in N1
3167 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3168 SDLoc(N), N1.getValueType());
3170 // fold (and x, -1) -> x, vector edition
3171 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3173 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3177 // fold (and c1, c2) -> c1&c2
3178 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3179 ConstantSDNode *N1C = isConstOrConstSplat(N1);
3180 if (N0C && N1C && !N1C->isOpaque())
3181 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3182 // canonicalize constant to RHS
3183 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3184 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3185 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3186 // fold (and x, -1) -> x
3187 if (isAllOnesConstant(N1))
3189 // if (and x, c) is known to be zero, return 0
3190 unsigned BitWidth = VT.getScalarSizeInBits();
3191 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3192 APInt::getAllOnesValue(BitWidth)))
3193 return DAG.getConstant(0, SDLoc(N), VT);
3195 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3197 // fold (and (or x, C), D) -> D if (C & D) == D
3198 if (N1C && N0.getOpcode() == ISD::OR)
3199 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3200 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3202 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3203 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3204 SDValue N0Op0 = N0.getOperand(0);
3205 APInt Mask = ~N1C->getAPIntValue();
3206 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3207 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3208 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3209 N0.getValueType(), N0Op0);
3211 // Replace uses of the AND with uses of the Zero extend node.
3214 // We actually want to replace all uses of the any_extend with the
3215 // zero_extend, to avoid duplicating things. This will later cause this
3216 // AND to be folded.
3217 CombineTo(N0.getNode(), Zext);
3218 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3221 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3222 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3223 // already be zero by virtue of the width of the base type of the load.
3225 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3227 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3228 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3229 N0.getOperand(0).getOpcode() == ISD::LOAD &&
3230 N0.getOperand(0).getResNo() == 0) ||
3231 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3232 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3233 N0 : N0.getOperand(0) );
3235 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3236 // This can be a pure constant or a vector splat, in which case we treat the
3237 // vector as a scalar and use the splat value.
3238 APInt Constant = APInt::getNullValue(1);
3239 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3240 Constant = C->getAPIntValue();
3241 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3242 APInt SplatValue, SplatUndef;
3243 unsigned SplatBitSize;
3245 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3246 SplatBitSize, HasAnyUndefs);
3248 // Undef bits can contribute to a possible optimisation if set, so
3250 SplatValue |= SplatUndef;
3252 // The splat value may be something like "0x00FFFFFF", which means 0 for
3253 // the first vector value and FF for the rest, repeating. We need a mask
3254 // that will apply equally to all members of the vector, so AND all the
3255 // lanes of the constant together.
3256 EVT VT = Vector->getValueType(0);
3257 unsigned BitWidth = VT.getScalarSizeInBits();
3259 // If the splat value has been compressed to a bitlength lower
3260 // than the size of the vector lane, we need to re-expand it to
3262 if (BitWidth > SplatBitSize)
3263 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3264 SplatBitSize < BitWidth;
3265 SplatBitSize = SplatBitSize * 2)
3266 SplatValue |= SplatValue.shl(SplatBitSize);
3268 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3269 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3270 if (SplatBitSize % BitWidth == 0) {
3271 Constant = APInt::getAllOnesValue(BitWidth);
3272 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3273 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3278 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3279 // actually legal and isn't going to get expanded, else this is a false
3281 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3282 Load->getValueType(0),
3283 Load->getMemoryVT());
3285 // Resize the constant to the same size as the original memory access before
3286 // extension. If it is still the AllOnesValue then this AND is completely
3288 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3291 switch (Load->getExtensionType()) {
3292 default: B = false; break;
3293 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3295 case ISD::NON_EXTLOAD: B = true; break;
3298 if (B && Constant.isAllOnesValue()) {
3299 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3300 // preserve semantics once we get rid of the AND.
3301 SDValue NewLoad(Load, 0);
3302 if (Load->getExtensionType() == ISD::EXTLOAD) {
3303 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3304 Load->getValueType(0), SDLoc(Load),
3305 Load->getChain(), Load->getBasePtr(),
3306 Load->getOffset(), Load->getMemoryVT(),
3307 Load->getMemOperand());
3308 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3309 if (Load->getNumValues() == 3) {
3310 // PRE/POST_INC loads have 3 values.
3311 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3312 NewLoad.getValue(2) };
3313 CombineTo(Load, To, 3, true);
3315 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3319 // Fold the AND away, taking care not to fold to the old load node if we
3321 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3323 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3327 // fold (and (load x), 255) -> (zextload x, i8)
3328 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3329 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3330 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3331 (N0.getOpcode() == ISD::ANY_EXTEND &&
3332 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3333 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3334 LoadSDNode *LN0 = HasAnyExt
3335 ? cast<LoadSDNode>(N0.getOperand(0))
3336 : cast<LoadSDNode>(N0);
3337 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3338 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3339 auto NarrowLoad = false;
3340 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3341 EVT ExtVT, LoadedVT;
3342 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3346 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3347 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3348 LN0->getMemOperand());
3350 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3351 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3353 EVT PtrType = LN0->getOperand(1).getValueType();
3355 unsigned Alignment = LN0->getAlignment();
3356 SDValue NewPtr = LN0->getBasePtr();
3358 // For big endian targets, we need to add an offset to the pointer
3359 // to load the correct bytes. For little endian systems, we merely
3360 // need to read fewer bytes from the same pointer.
3361 if (DAG.getDataLayout().isBigEndian()) {
3362 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3363 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3364 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3366 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3367 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3368 Alignment = MinAlign(Alignment, PtrOff);
3371 AddToWorklist(NewPtr.getNode());
3373 SDValue Load = DAG.getExtLoad(
3374 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3375 LN0->getPointerInfo(), ExtVT, Alignment,
3376 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3378 CombineTo(LN0, Load, Load.getValue(1));
3379 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3385 if (SDValue Combined = visitANDLike(N0, N1, N))
3388 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3389 if (N0.getOpcode() == N1.getOpcode())
3390 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3393 // Masking the negated extension of a boolean is just the zero-extended
3395 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3396 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3398 // Note: the SimplifyDemandedBits fold below can make an information-losing
3399 // transform, and then we have no way to find this better fold.
3400 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3401 ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3402 SDValue SubRHS = N0.getOperand(1);
3403 if (SubLHS && SubLHS->isNullValue()) {
3404 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3405 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3407 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3408 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3409 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3413 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3414 // fold (and (sra)) -> (and (srl)) when possible.
3415 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
3416 return SDValue(N, 0);
3418 // fold (zext_inreg (extload x)) -> (zextload x)
3419 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3420 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3421 EVT MemVT = LN0->getMemoryVT();
3422 // If we zero all the possible extended bits, then we can turn this into
3423 // a zextload if we are running before legalize or the operation is legal.
3424 unsigned BitWidth = N1.getScalarValueSizeInBits();
3425 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3426 BitWidth - MemVT.getScalarSizeInBits())) &&
3427 ((!LegalOperations && !LN0->isVolatile()) ||
3428 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3429 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3430 LN0->getChain(), LN0->getBasePtr(),
3431 MemVT, LN0->getMemOperand());
3433 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3434 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3437 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3438 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3440 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3441 EVT MemVT = LN0->getMemoryVT();
3442 // If we zero all the possible extended bits, then we can turn this into
3443 // a zextload if we are running before legalize or the operation is legal.
3444 unsigned BitWidth = N1.getScalarValueSizeInBits();
3445 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3446 BitWidth - MemVT.getScalarSizeInBits())) &&
3447 ((!LegalOperations && !LN0->isVolatile()) ||
3448 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3449 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3450 LN0->getChain(), LN0->getBasePtr(),
3451 MemVT, LN0->getMemOperand());
3453 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3454 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3457 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3458 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3459 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3460 N0.getOperand(1), false))
3467 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3468 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3469 bool DemandHighBits) {
3470 if (!LegalOperations)
3473 EVT VT = N->getValueType(0);
3474 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3476 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3479 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3480 bool LookPassAnd0 = false;
3481 bool LookPassAnd1 = false;
3482 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3484 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3486 if (N0.getOpcode() == ISD::AND) {
3487 if (!N0.getNode()->hasOneUse())
3489 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3490 if (!N01C || N01C->getZExtValue() != 0xFF00)
3492 N0 = N0.getOperand(0);
3493 LookPassAnd0 = true;
3496 if (N1.getOpcode() == ISD::AND) {
3497 if (!N1.getNode()->hasOneUse())
3499 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3500 if (!N11C || N11C->getZExtValue() != 0xFF)
3502 N1 = N1.getOperand(0);
3503 LookPassAnd1 = true;
3506 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3508 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3510 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3513 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3514 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3517 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3520 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3521 SDValue N00 = N0->getOperand(0);
3522 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3523 if (!N00.getNode()->hasOneUse())
3525 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3526 if (!N001C || N001C->getZExtValue() != 0xFF)
3528 N00 = N00.getOperand(0);
3529 LookPassAnd0 = true;
3532 SDValue N10 = N1->getOperand(0);
3533 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3534 if (!N10.getNode()->hasOneUse())
3536 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3537 if (!N101C || N101C->getZExtValue() != 0xFF00)
3539 N10 = N10.getOperand(0);
3540 LookPassAnd1 = true;
3546 // Make sure everything beyond the low halfword gets set to zero since the SRL
3547 // 16 will clear the top bits.
3548 unsigned OpSizeInBits = VT.getSizeInBits();
3549 if (DemandHighBits && OpSizeInBits > 16) {
3550 // If the left-shift isn't masked out then the only way this is a bswap is
3551 // if all bits beyond the low 8 are 0. In that case the entire pattern
3552 // reduces to a left shift anyway: leave it for other parts of the combiner.
3556 // However, if the right shift isn't masked out then it might be because
3557 // it's not needed. See if we can spot that too.
3558 if (!LookPassAnd1 &&
3559 !DAG.MaskedValueIsZero(
3560 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3564 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3565 if (OpSizeInBits > 16) {
3567 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3568 DAG.getConstant(OpSizeInBits - 16, DL,
3569 getShiftAmountTy(VT)));
3574 /// Return true if the specified node is an element that makes up a 32-bit
3575 /// packed halfword byteswap.
3576 /// ((x & 0x000000ff) << 8) |
3577 /// ((x & 0x0000ff00) >> 8) |
3578 /// ((x & 0x00ff0000) << 8) |
3579 /// ((x & 0xff000000) >> 8)
3580 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3581 if (!N.getNode()->hasOneUse())
3584 unsigned Opc = N.getOpcode();
3585 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3588 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3593 switch (N1C->getZExtValue()) {
3596 case 0xFF: Num = 0; break;
3597 case 0xFF00: Num = 1; break;
3598 case 0xFF0000: Num = 2; break;
3599 case 0xFF000000: Num = 3; break;
3602 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3603 SDValue N0 = N.getOperand(0);
3604 if (Opc == ISD::AND) {
3605 if (Num == 0 || Num == 2) {
3607 // (x >> 8) & 0xff0000
3608 if (N0.getOpcode() != ISD::SRL)
3610 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3611 if (!C || C->getZExtValue() != 8)
3614 // (x << 8) & 0xff00
3615 // (x << 8) & 0xff000000
3616 if (N0.getOpcode() != ISD::SHL)
3618 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3619 if (!C || C->getZExtValue() != 8)
3622 } else if (Opc == ISD::SHL) {
3624 // (x & 0xff0000) << 8
3625 if (Num != 0 && Num != 2)
3627 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3628 if (!C || C->getZExtValue() != 8)
3630 } else { // Opc == ISD::SRL
3631 // (x & 0xff00) >> 8
3632 // (x & 0xff000000) >> 8
3633 if (Num != 1 && Num != 3)
3635 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3636 if (!C || C->getZExtValue() != 8)
3643 Parts[Num] = N0.getOperand(0).getNode();
3647 /// Match a 32-bit packed halfword bswap. That is
3648 /// ((x & 0x000000ff) << 8) |
3649 /// ((x & 0x0000ff00) >> 8) |
3650 /// ((x & 0x00ff0000) << 8) |
3651 /// ((x & 0xff000000) >> 8)
3652 /// => (rotl (bswap x), 16)
3653 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3654 if (!LegalOperations)
3657 EVT VT = N->getValueType(0);
3660 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3664 // (or (or (and), (and)), (or (and), (and)))
3665 // (or (or (or (and), (and)), (and)), (and))
3666 if (N0.getOpcode() != ISD::OR)
3668 SDValue N00 = N0.getOperand(0);
3669 SDValue N01 = N0.getOperand(1);
3670 SDNode *Parts[4] = {};
3672 if (N1.getOpcode() == ISD::OR &&
3673 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3674 // (or (or (and), (and)), (or (and), (and)))
3675 SDValue N000 = N00.getOperand(0);
3676 if (!isBSwapHWordElement(N000, Parts))
3679 SDValue N001 = N00.getOperand(1);
3680 if (!isBSwapHWordElement(N001, Parts))
3682 SDValue N010 = N01.getOperand(0);
3683 if (!isBSwapHWordElement(N010, Parts))
3685 SDValue N011 = N01.getOperand(1);
3686 if (!isBSwapHWordElement(N011, Parts))
3689 // (or (or (or (and), (and)), (and)), (and))
3690 if (!isBSwapHWordElement(N1, Parts))
3692 if (!isBSwapHWordElement(N01, Parts))
3694 if (N00.getOpcode() != ISD::OR)
3696 SDValue N000 = N00.getOperand(0);
3697 if (!isBSwapHWordElement(N000, Parts))
3699 SDValue N001 = N00.getOperand(1);
3700 if (!isBSwapHWordElement(N001, Parts))
3704 // Make sure the parts are all coming from the same node.
3705 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3709 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3710 SDValue(Parts[0], 0));
3712 // Result of the bswap should be rotated by 16. If it's not legal, then
3713 // do (x << 16) | (x >> 16).
3714 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3715 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3716 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3717 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3718 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3719 return DAG.getNode(ISD::OR, DL, VT,
3720 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3721 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3724 /// This contains all DAGCombine rules which reduce two values combined by
3725 /// an Or operation to a single value \see visitANDLike().
3726 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3727 EVT VT = N1.getValueType();
3728 // fold (or x, undef) -> -1
3729 if (!LegalOperations &&
3730 (N0.isUndef() || N1.isUndef())) {
3731 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3732 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3733 SDLoc(LocReference), VT);
3735 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3736 SDValue LL, LR, RL, RR, CC0, CC1;
3737 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3738 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3739 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3741 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3742 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3743 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3744 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3745 EVT CCVT = getSetCCResultType(LR.getValueType());
3746 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3747 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3748 LR.getValueType(), LL, RL);
3749 AddToWorklist(ORNode.getNode());
3750 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3753 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3754 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3755 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3756 EVT CCVT = getSetCCResultType(LR.getValueType());
3757 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3758 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3759 LR.getValueType(), LL, RL);
3760 AddToWorklist(ANDNode.getNode());
3761 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3765 // canonicalize equivalent to ll == rl
3766 if (LL == RR && LR == RL) {
3767 Op1 = ISD::getSetCCSwappedOperands(Op1);
3770 if (LL == RL && LR == RR) {
3771 bool isInteger = LL.getValueType().isInteger();
3772 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3773 if (Result != ISD::SETCC_INVALID &&
3774 (!LegalOperations ||
3775 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3776 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3777 EVT CCVT = getSetCCResultType(LL.getValueType());
3778 if (N0.getValueType() == CCVT ||
3779 (!LegalOperations && N0.getValueType() == MVT::i1))
3780 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3786 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3787 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3788 // Don't increase # computations.
3789 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3790 // We can only do this xform if we know that bits from X that are set in C2
3791 // but not in C1 are already zero. Likewise for Y.
3792 if (const ConstantSDNode *N0O1C =
3793 getAsNonOpaqueConstant(N0.getOperand(1))) {
3794 if (const ConstantSDNode *N1O1C =
3795 getAsNonOpaqueConstant(N1.getOperand(1))) {
3796 // We can only do this xform if we know that bits from X that are set in
3797 // C2 but not in C1 are already zero. Likewise for Y.
3798 const APInt &LHSMask = N0O1C->getAPIntValue();
3799 const APInt &RHSMask = N1O1C->getAPIntValue();
3801 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3802 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3803 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3804 N0.getOperand(0), N1.getOperand(0));
3805 SDLoc DL(LocReference);
3806 return DAG.getNode(ISD::AND, DL, VT, X,
3807 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3813 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3814 if (N0.getOpcode() == ISD::AND &&
3815 N1.getOpcode() == ISD::AND &&
3816 N0.getOperand(0) == N1.getOperand(0) &&
3817 // Don't increase # computations.
3818 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3819 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3820 N0.getOperand(1), N1.getOperand(1));
3821 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3827 SDValue DAGCombiner::visitOR(SDNode *N) {
3828 SDValue N0 = N->getOperand(0);
3829 SDValue N1 = N->getOperand(1);
3830 EVT VT = N1.getValueType();
3837 if (VT.isVector()) {
3838 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3841 // fold (or x, 0) -> x, vector edition
3842 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3844 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3847 // fold (or x, -1) -> -1, vector edition
3848 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3849 // do not return N0, because undef node may exist in N0
3850 return DAG.getConstant(
3851 APInt::getAllOnesValue(N0.getScalarValueSizeInBits()), SDLoc(N),
3853 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3854 // do not return N1, because undef node may exist in N1
3855 return DAG.getConstant(
3856 APInt::getAllOnesValue(N1.getScalarValueSizeInBits()), SDLoc(N),
3859 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3860 // Do this only if the resulting shuffle is legal.
3861 if (isa<ShuffleVectorSDNode>(N0) &&
3862 isa<ShuffleVectorSDNode>(N1) &&
3863 // Avoid folding a node with illegal type.
3864 TLI.isTypeLegal(VT)) {
3865 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3866 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3867 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3868 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3869 // Ensure both shuffles have a zero input.
3870 if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3871 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3872 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3873 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3874 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3875 bool CanFold = true;
3876 int NumElts = VT.getVectorNumElements();
3877 SmallVector<int, 4> Mask(NumElts);
3879 for (int i = 0; i != NumElts; ++i) {
3880 int M0 = SV0->getMaskElt(i);
3881 int M1 = SV1->getMaskElt(i);
3883 // Determine if either index is pointing to a zero vector.
3884 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
3885 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
3887 // If one element is zero and the otherside is undef, keep undef.
3888 // This also handles the case that both are undef.
3889 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
3894 // Make sure only one of the elements is zero.
3895 if (M0Zero == M1Zero) {
3900 assert((M0 >= 0 || M1 >= 0) && "Undef index!");
3902 // We have a zero and non-zero element. If the non-zero came from
3903 // SV0 make the index a LHS index. If it came from SV1, make it
3904 // a RHS index. We need to mod by NumElts because we don't care
3905 // which operand it came from in the original shuffles.
3906 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3910 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3911 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3913 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3915 std::swap(NewLHS, NewRHS);
3916 ShuffleVectorSDNode::commuteMask(Mask);
3917 LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3921 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
3927 // fold (or c1, c2) -> c1|c2
3928 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3929 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3930 if (N0C && N1C && !N1C->isOpaque())
3931 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3932 // canonicalize constant to RHS
3933 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3934 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3935 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3936 // fold (or x, 0) -> x
3937 if (isNullConstant(N1))
3939 // fold (or x, -1) -> -1
3940 if (isAllOnesConstant(N1))
3942 // fold (or x, c) -> c iff (x & ~c) == 0
3943 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3946 if (SDValue Combined = visitORLike(N0, N1, N))
3949 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3950 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3952 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3956 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3958 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3959 // iff (c1 & c2) == 0.
3960 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3961 isa<ConstantSDNode>(N0.getOperand(1))) {
3962 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3963 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3964 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3967 ISD::AND, SDLoc(N), VT,
3968 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3972 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3973 if (N0.getOpcode() == N1.getOpcode())
3974 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3977 // See if this is some rotate idiom.
3978 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3979 return SDValue(Rot, 0);
3981 // Simplify the operands using demanded-bits information.
3982 if (!VT.isVector() &&
3983 SimplifyDemandedBits(SDValue(N, 0)))
3984 return SDValue(N, 0);
3989 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3990 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3991 if (Op.getOpcode() == ISD::AND) {
3992 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3993 Mask = Op.getOperand(1);
3994 Op = Op.getOperand(0);
4000 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4008 // Return true if we can prove that, whenever Neg and Pos are both in the
4009 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
4010 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4012 // (or (shift1 X, Neg), (shift2 X, Pos))
4014 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4015 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
4016 // to consider shift amounts with defined behavior.
4017 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4018 // If EltSize is a power of 2 then:
4020 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4021 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4023 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4024 // for the stronger condition:
4026 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
4028 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4029 // we can just replace Neg with Neg' for the rest of the function.
4031 // In other cases we check for the even stronger condition:
4033 // Neg == EltSize - Pos [B]
4035 // for all Neg and Pos. Note that the (or ...) then invokes undefined
4036 // behavior if Pos == 0 (and consequently Neg == EltSize).
4038 // We could actually use [A] whenever EltSize is a power of 2, but the
4039 // only extra cases that it would match are those uninteresting ones
4040 // where Neg and Pos are never in range at the same time. E.g. for
4041 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4042 // as well as (sub 32, Pos), but:
4044 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4046 // always invokes undefined behavior for 32-bit X.
4048 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4049 unsigned MaskLoBits = 0;
4050 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4051 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4052 if (NegC->getAPIntValue() == EltSize - 1) {
4053 Neg = Neg.getOperand(0);
4054 MaskLoBits = Log2_64(EltSize);
4059 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4060 if (Neg.getOpcode() != ISD::SUB)
4062 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4065 SDValue NegOp1 = Neg.getOperand(1);
4067 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4068 // Pos'. The truncation is redundant for the purpose of the equality.
4069 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4070 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4071 if (PosC->getAPIntValue() == EltSize - 1)
4072 Pos = Pos.getOperand(0);
4074 // The condition we need is now:
4076 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4078 // If NegOp1 == Pos then we need:
4080 // EltSize & Mask == NegC & Mask
4082 // (because "x & Mask" is a truncation and distributes through subtraction).
4085 Width = NegC->getAPIntValue();
4087 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4088 // Then the condition we want to prove becomes:
4090 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4092 // which, again because "x & Mask" is a truncation, becomes:
4094 // NegC & Mask == (EltSize - PosC) & Mask
4095 // EltSize & Mask == (NegC + PosC) & Mask
4096 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4097 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4098 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4104 // Now we just need to check that EltSize & Mask == Width & Mask.
4106 // EltSize & Mask is 0 since Mask is EltSize - 1.
4107 return Width.getLoBits(MaskLoBits) == 0;
4108 return Width == EltSize;
4111 // A subroutine of MatchRotate used once we have found an OR of two opposite
4112 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
4113 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4114 // former being preferred if supported. InnerPos and InnerNeg are Pos and
4115 // Neg with outer conversions stripped away.
4116 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4117 SDValue Neg, SDValue InnerPos,
4118 SDValue InnerNeg, unsigned PosOpcode,
4119 unsigned NegOpcode, const SDLoc &DL) {
4120 // fold (or (shl x, (*ext y)),
4121 // (srl x, (*ext (sub 32, y)))) ->
4122 // (rotl x, y) or (rotr x, (sub 32, y))
4124 // fold (or (shl x, (*ext (sub 32, y))),
4125 // (srl x, (*ext y))) ->
4126 // (rotr x, y) or (rotl x, (sub 32, y))
4127 EVT VT = Shifted.getValueType();
4128 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4129 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4130 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4131 HasPos ? Pos : Neg).getNode();
4137 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
4138 // idioms for rotate, and if the target supports rotation instructions, generate
4140 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4141 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
4142 EVT VT = LHS.getValueType();
4143 if (!TLI.isTypeLegal(VT)) return nullptr;
4145 // The target must have at least one rotate flavor.
4146 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4147 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4148 if (!HasROTL && !HasROTR) return nullptr;
4150 // Match "(X shl/srl V1) & V2" where V2 may not be present.
4151 SDValue LHSShift; // The shift.
4152 SDValue LHSMask; // AND value if any.
4153 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4154 return nullptr; // Not part of a rotate.
4156 SDValue RHSShift; // The shift.
4157 SDValue RHSMask; // AND value if any.
4158 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4159 return nullptr; // Not part of a rotate.
4161 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4162 return nullptr; // Not shifting the same value.
4164 if (LHSShift.getOpcode() == RHSShift.getOpcode())
4165 return nullptr; // Shifts must disagree.
4167 // Canonicalize shl to left side in a shl/srl pair.
4168 if (RHSShift.getOpcode() == ISD::SHL) {
4169 std::swap(LHS, RHS);
4170 std::swap(LHSShift, RHSShift);
4171 std::swap(LHSMask, RHSMask);
4174 unsigned EltSizeInBits = VT.getScalarSizeInBits();
4175 SDValue LHSShiftArg = LHSShift.getOperand(0);
4176 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4177 SDValue RHSShiftArg = RHSShift.getOperand(0);
4178 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4180 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4181 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4182 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4183 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4184 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4185 if ((LShVal + RShVal) != EltSizeInBits)
4188 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4189 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4191 // If there is an AND of either shifted operand, apply it to the result.
4192 if (LHSMask.getNode() || RHSMask.getNode()) {
4193 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4194 SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4196 if (LHSMask.getNode()) {
4197 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4198 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4199 DAG.getNode(ISD::OR, DL, VT, LHSMask,
4200 DAG.getConstant(RHSBits, DL, VT)));
4202 if (RHSMask.getNode()) {
4203 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4204 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4205 DAG.getNode(ISD::OR, DL, VT, RHSMask,
4206 DAG.getConstant(LHSBits, DL, VT)));
4209 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4212 return Rot.getNode();
4215 // If there is a mask here, and we have a variable shift, we can't be sure
4216 // that we're masking out the right stuff.
4217 if (LHSMask.getNode() || RHSMask.getNode())
4220 // If the shift amount is sign/zext/any-extended just peel it off.
4221 SDValue LExtOp0 = LHSShiftAmt;
4222 SDValue RExtOp0 = RHSShiftAmt;
4223 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4224 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4225 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4226 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4227 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4228 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4229 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4230 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4231 LExtOp0 = LHSShiftAmt.getOperand(0);
4232 RExtOp0 = RHSShiftAmt.getOperand(0);
4235 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4236 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4240 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4241 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4249 /// Helper struct to parse and store a memory address as base + index + offset.
4250 /// We ignore sign extensions when it is safe to do so.
4251 /// The following two expressions are not equivalent. To differentiate we need
4252 /// to store whether there was a sign extension involved in the index
4254 /// (load (i64 add (i64 copyfromreg %c)
4255 /// (i64 signextend (add (i8 load %index)
4259 /// (load (i64 add (i64 copyfromreg %c)
4260 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
4262 struct BaseIndexOffset {
4266 bool IsIndexSignExt;
4268 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
4270 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
4271 bool IsIndexSignExt) :
4272 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
4274 bool equalBaseIndex(const BaseIndexOffset &Other) {
4275 return Other.Base == Base && Other.Index == Index &&
4276 Other.IsIndexSignExt == IsIndexSignExt;
4279 /// Parses tree in Ptr for base, index, offset addresses.
4280 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG,
4281 int64_t PartialOffset = 0) {
4282 bool IsIndexSignExt = false;
4284 // Split up a folded GlobalAddress+Offset into its component parts.
4285 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
4286 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
4287 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
4289 GA->getValueType(0),
4290 /*Offset=*/PartialOffset,
4291 /*isTargetGA=*/false,
4292 GA->getTargetFlags()),
4298 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
4299 // instruction, then it could be just the BASE or everything else we don't
4300 // know how to handle. Just use Ptr as BASE and give up.
4301 if (Ptr->getOpcode() != ISD::ADD)
4302 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4304 // We know that we have at least an ADD instruction. Try to pattern match
4305 // the simple case of BASE + OFFSET.
4306 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
4307 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
4308 return match(Ptr->getOperand(0), DAG, Offset + PartialOffset);
4311 // Inside a loop the current BASE pointer is calculated using an ADD and a
4312 // MUL instruction. In this case Ptr is the actual BASE pointer.
4313 // (i64 add (i64 %array_ptr)
4314 // (i64 mul (i64 %induction_var)
4315 // (i64 %element_size)))
4316 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
4317 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4319 // Look at Base + Index + Offset cases.
4320 SDValue Base = Ptr->getOperand(0);
4321 SDValue IndexOffset = Ptr->getOperand(1);
4323 // Skip signextends.
4324 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
4325 IndexOffset = IndexOffset->getOperand(0);
4326 IsIndexSignExt = true;
4329 // Either the case of Base + Index (no offset) or something else.
4330 if (IndexOffset->getOpcode() != ISD::ADD)
4331 return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt);
4333 // Now we have the case of Base + Index + offset.
4334 SDValue Index = IndexOffset->getOperand(0);
4335 SDValue Offset = IndexOffset->getOperand(1);
4337 if (!isa<ConstantSDNode>(Offset))
4338 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4340 // Ignore signextends.
4341 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
4342 Index = Index->getOperand(0);
4343 IsIndexSignExt = true;
4344 } else IsIndexSignExt = false;
4346 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
4347 return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt);
4352 SDValue DAGCombiner::visitXOR(SDNode *N) {
4353 SDValue N0 = N->getOperand(0);
4354 SDValue N1 = N->getOperand(1);
4355 EVT VT = N0.getValueType();
4358 if (VT.isVector()) {
4359 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4362 // fold (xor x, 0) -> x, vector edition
4363 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4365 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4369 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4370 if (N0.isUndef() && N1.isUndef())
4371 return DAG.getConstant(0, SDLoc(N), VT);
4372 // fold (xor x, undef) -> undef
4377 // fold (xor c1, c2) -> c1^c2
4378 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4379 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4381 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4382 // canonicalize constant to RHS
4383 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4384 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4385 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4386 // fold (xor x, 0) -> x
4387 if (isNullConstant(N1))
4390 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4393 // fold !(x cc y) -> (x !cc y)
4394 SDValue LHS, RHS, CC;
4395 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4396 bool isInt = LHS.getValueType().isInteger();
4397 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4400 if (!LegalOperations ||
4401 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4402 switch (N0.getOpcode()) {
4404 llvm_unreachable("Unhandled SetCC Equivalent!");
4406 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4407 case ISD::SELECT_CC:
4408 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4409 N0.getOperand(3), NotCC);
4414 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4415 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4416 N0.getNode()->hasOneUse() &&
4417 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4418 SDValue V = N0.getOperand(0);
4420 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4421 DAG.getConstant(1, DL, V.getValueType()));
4422 AddToWorklist(V.getNode());
4423 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4426 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4427 if (isOneConstant(N1) && VT == MVT::i1 &&
4428 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4429 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4430 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4431 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4432 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4433 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4434 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4435 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4438 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4439 if (isAllOnesConstant(N1) &&
4440 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4441 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4442 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4443 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4444 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4445 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4446 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4447 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4450 // fold (xor (and x, y), y) -> (and (not x), y)
4451 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4452 N0->getOperand(1) == N1) {
4453 SDValue X = N0->getOperand(0);
4454 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4455 AddToWorklist(NotX.getNode());
4456 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4458 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4459 if (N1C && N0.getOpcode() == ISD::XOR) {
4460 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4462 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4463 DAG.getConstant(N1C->getAPIntValue() ^
4464 N00C->getAPIntValue(), DL, VT));
4466 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4468 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4469 DAG.getConstant(N1C->getAPIntValue() ^
4470 N01C->getAPIntValue(), DL, VT));
4473 // fold (xor x, x) -> 0
4475 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4477 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4478 // Here is a concrete example of this equivalence:
4480 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4481 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4485 // i16 ~1 == 0b1111111111111110
4486 // i16 rol(~1, 14) == 0b1011111111111111
4488 // Some additional tips to help conceptualize this transform:
4489 // - Try to see the operation as placing a single zero in a value of all ones.
4490 // - There exists no value for x which would allow the result to contain zero.
4491 // - Values of x larger than the bitwidth are undefined and do not require a
4492 // consistent result.
4493 // - Pushing the zero left requires shifting one bits in from the right.
4494 // A rotate left of ~1 is a nice way of achieving the desired result.
4495 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4496 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4498 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4502 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4503 if (N0.getOpcode() == N1.getOpcode())
4504 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4507 // Simplify the expression using non-local knowledge.
4508 if (!VT.isVector() &&
4509 SimplifyDemandedBits(SDValue(N, 0)))
4510 return SDValue(N, 0);
4515 /// Handle transforms common to the three shifts, when the shift amount is a
4517 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4518 SDNode *LHS = N->getOperand(0).getNode();
4519 if (!LHS->hasOneUse()) return SDValue();
4521 // We want to pull some binops through shifts, so that we have (and (shift))
4522 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4523 // thing happens with address calculations, so it's important to canonicalize
4525 bool HighBitSet = false; // Can we transform this if the high bit is set?
4527 switch (LHS->getOpcode()) {
4528 default: return SDValue();
4531 HighBitSet = false; // We can only transform sra if the high bit is clear.
4534 HighBitSet = true; // We can only transform sra if the high bit is set.
4537 if (N->getOpcode() != ISD::SHL)
4538 return SDValue(); // only shl(add) not sr[al](add).
4539 HighBitSet = false; // We can only transform sra if the high bit is clear.
4543 // We require the RHS of the binop to be a constant and not opaque as well.
4544 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4545 if (!BinOpCst) return SDValue();
4547 // FIXME: disable this unless the input to the binop is a shift by a constant
4548 // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
4549 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4550 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
4551 BinOpLHSVal->getOpcode() == ISD::SRA ||
4552 BinOpLHSVal->getOpcode() == ISD::SRL;
4553 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
4554 BinOpLHSVal->getOpcode() == ISD::SELECT;
4556 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
4560 if (isCopyOrSelect && N->hasOneUse())
4563 EVT VT = N->getValueType(0);
4565 // If this is a signed shift right, and the high bit is modified by the
4566 // logical operation, do not perform the transformation. The highBitSet
4567 // boolean indicates the value of the high bit of the constant which would
4568 // cause it to be modified for this operation.
4569 if (N->getOpcode() == ISD::SRA) {
4570 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4571 if (BinOpRHSSignSet != HighBitSet)
4575 if (!TLI.isDesirableToCommuteWithShift(LHS))
4578 // Fold the constants, shifting the binop RHS by the shift amount.
4579 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4581 LHS->getOperand(1), N->getOperand(1));
4582 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4584 // Create the new shift.
4585 SDValue NewShift = DAG.getNode(N->getOpcode(),
4586 SDLoc(LHS->getOperand(0)),
4587 VT, LHS->getOperand(0), N->getOperand(1));
4589 // Create the new binop.
4590 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4593 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4594 assert(N->getOpcode() == ISD::TRUNCATE);
4595 assert(N->getOperand(0).getOpcode() == ISD::AND);
4597 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4598 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4599 SDValue N01 = N->getOperand(0).getOperand(1);
4600 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
4602 EVT TruncVT = N->getValueType(0);
4603 SDValue N00 = N->getOperand(0).getOperand(0);
4604 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
4605 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
4606 AddToWorklist(Trunc00.getNode());
4607 AddToWorklist(Trunc01.getNode());
4608 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
4615 SDValue DAGCombiner::visitRotate(SDNode *N) {
4616 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4617 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4618 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4619 if (SDValue NewOp1 =
4620 distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4621 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4622 N->getOperand(0), NewOp1);
4627 SDValue DAGCombiner::visitSHL(SDNode *N) {
4628 SDValue N0 = N->getOperand(0);
4629 SDValue N1 = N->getOperand(1);
4630 EVT VT = N0.getValueType();
4631 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4634 if (VT.isVector()) {
4635 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4638 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4639 // If setcc produces all-one true value then:
4640 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4641 if (N1CV && N1CV->isConstant()) {
4642 if (N0.getOpcode() == ISD::AND) {
4643 SDValue N00 = N0->getOperand(0);
4644 SDValue N01 = N0->getOperand(1);
4645 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4647 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4648 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4649 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4650 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4652 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4658 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4660 // fold (shl c1, c2) -> c1<<c2
4661 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4662 if (N0C && N1C && !N1C->isOpaque())
4663 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4664 // fold (shl 0, x) -> 0
4665 if (isNullConstant(N0))
4667 // fold (shl x, c >= size(x)) -> undef
4668 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4669 return DAG.getUNDEF(VT);
4670 // fold (shl x, 0) -> x
4671 if (N1C && N1C->isNullValue())
4673 // fold (shl undef, x) -> 0
4675 return DAG.getConstant(0, SDLoc(N), VT);
4676 // if (shl x, c) is known to be zero, return 0
4677 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4678 APInt::getAllOnesValue(OpSizeInBits)))
4679 return DAG.getConstant(0, SDLoc(N), VT);
4680 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4681 if (N1.getOpcode() == ISD::TRUNCATE &&
4682 N1.getOperand(0).getOpcode() == ISD::AND) {
4683 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4684 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4687 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4688 return SDValue(N, 0);
4690 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4691 if (N1C && N0.getOpcode() == ISD::SHL) {
4692 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4694 APInt c1 = N0C1->getAPIntValue();
4695 APInt c2 = N1C->getAPIntValue();
4696 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4698 APInt Sum = c1 + c2;
4699 if (Sum.uge(OpSizeInBits))
4700 return DAG.getConstant(0, DL, VT);
4703 ISD::SHL, DL, VT, N0.getOperand(0),
4704 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4708 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4709 // For this to be valid, the second form must not preserve any of the bits
4710 // that are shifted out by the inner shift in the first form. This means
4711 // the outer shift size must be >= the number of bits added by the ext.
4712 // As a corollary, we don't care what kind of ext it is.
4713 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4714 N0.getOpcode() == ISD::ANY_EXTEND ||
4715 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4716 N0.getOperand(0).getOpcode() == ISD::SHL) {
4717 SDValue N0Op0 = N0.getOperand(0);
4718 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4719 APInt c1 = N0Op0C1->getAPIntValue();
4720 APInt c2 = N1C->getAPIntValue();
4721 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4723 EVT InnerShiftVT = N0Op0.getValueType();
4724 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4725 if (c2.uge(OpSizeInBits - InnerShiftSize)) {
4727 APInt Sum = c1 + c2;
4728 if (Sum.uge(OpSizeInBits))
4729 return DAG.getConstant(0, DL, VT);
4733 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
4734 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4739 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4740 // Only fold this if the inner zext has no other uses to avoid increasing
4741 // the total number of instructions.
4742 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4743 N0.getOperand(0).getOpcode() == ISD::SRL) {
4744 SDValue N0Op0 = N0.getOperand(0);
4745 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4746 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
4747 uint64_t c1 = N0Op0C1->getZExtValue();
4748 uint64_t c2 = N1C->getZExtValue();
4750 SDValue NewOp0 = N0.getOperand(0);
4751 EVT CountVT = NewOp0.getOperand(1).getValueType();
4753 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4755 DAG.getConstant(c2, DL, CountVT));
4756 AddToWorklist(NewSHL.getNode());
4757 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4763 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4764 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4765 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4766 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4767 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4768 uint64_t C1 = N0C1->getZExtValue();
4769 uint64_t C2 = N1C->getZExtValue();
4772 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4773 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4774 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4775 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4779 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4780 // (and (srl x, (sub c1, c2), MASK)
4781 // Only fold this if the inner shift has no other uses -- if it does, folding
4782 // this will increase the total number of instructions.
4783 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4784 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4785 uint64_t c1 = N0C1->getZExtValue();
4786 if (c1 < OpSizeInBits) {
4787 uint64_t c2 = N1C->getZExtValue();
4788 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4791 Mask = Mask.shl(c2 - c1);
4793 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4794 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4796 Mask = Mask.lshr(c1 - c2);
4798 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4799 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4802 return DAG.getNode(ISD::AND, DL, VT, Shift,
4803 DAG.getConstant(Mask, DL, VT));
4808 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4809 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
4810 isConstantOrConstantVector(N1, /* No Opaques */ true)) {
4811 unsigned BitSize = VT.getScalarSizeInBits();
4813 SDValue AllBits = DAG.getConstant(APInt::getAllOnesValue(BitSize), DL, VT);
4814 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
4815 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
4818 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4819 // Variant of version done on multiply, except mul by a power of 2 is turned
4821 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4822 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
4823 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
4824 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4825 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4826 AddToWorklist(Shl0.getNode());
4827 AddToWorklist(Shl1.getNode());
4828 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4831 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4832 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
4833 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
4834 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
4835 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4836 if (isConstantOrConstantVector(Shl))
4837 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
4840 if (N1C && !N1C->isOpaque())
4841 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4847 SDValue DAGCombiner::visitSRA(SDNode *N) {
4848 SDValue N0 = N->getOperand(0);
4849 SDValue N1 = N->getOperand(1);
4850 EVT VT = N0.getValueType();
4851 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4853 // Arithmetic shifting an all-sign-bit value is a no-op.
4854 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
4859 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4862 ConstantSDNode *N1C = isConstOrConstSplat(N1);
4864 // fold (sra c1, c2) -> (sra c1, c2)
4865 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4866 if (N0C && N1C && !N1C->isOpaque())
4867 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4868 // fold (sra 0, x) -> 0
4869 if (isNullConstant(N0))
4871 // fold (sra -1, x) -> -1
4872 if (isAllOnesConstant(N0))
4874 // fold (sra x, c >= size(x)) -> undef
4875 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4876 return DAG.getUNDEF(VT);
4877 // fold (sra x, 0) -> x
4878 if (N1C && N1C->isNullValue())
4880 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4882 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4883 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4884 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4886 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4887 ExtVT, VT.getVectorNumElements());
4888 if ((!LegalOperations ||
4889 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4890 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4891 N0.getOperand(0), DAG.getValueType(ExtVT));
4894 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4895 if (N1C && N0.getOpcode() == ISD::SRA) {
4896 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4898 APInt c1 = N0C1->getAPIntValue();
4899 APInt c2 = N1C->getAPIntValue();
4900 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4902 APInt Sum = c1 + c2;
4903 if (Sum.uge(OpSizeInBits))
4904 Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
4907 ISD::SRA, DL, VT, N0.getOperand(0),
4908 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4912 // fold (sra (shl X, m), (sub result_size, n))
4913 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4914 // result_size - n != m.
4915 // If truncate is free for the target sext(shl) is likely to result in better
4917 if (N0.getOpcode() == ISD::SHL && N1C) {
4918 // Get the two constanst of the shifts, CN0 = m, CN = n.
4919 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4921 LLVMContext &Ctx = *DAG.getContext();
4922 // Determine what the truncate's result bitsize and type would be.
4923 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4926 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4928 // Determine the residual right-shift amount.
4929 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4931 // If the shift is not a no-op (in which case this should be just a sign
4932 // extend already), the truncated to type is legal, sign_extend is legal
4933 // on that type, and the truncate to that type is both legal and free,
4934 // perform the transform.
4935 if ((ShiftAmt > 0) &&
4936 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4937 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4938 TLI.isTruncateFree(VT, TruncVT)) {
4941 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4942 getShiftAmountTy(N0.getOperand(0).getValueType()));
4943 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4944 N0.getOperand(0), Amt);
4945 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4947 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4948 N->getValueType(0), Trunc);
4953 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4954 if (N1.getOpcode() == ISD::TRUNCATE &&
4955 N1.getOperand(0).getOpcode() == ISD::AND) {
4956 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4957 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4960 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4961 // if c1 is equal to the number of bits the trunc removes
4962 if (N0.getOpcode() == ISD::TRUNCATE &&
4963 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4964 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4965 N0.getOperand(0).hasOneUse() &&
4966 N0.getOperand(0).getOperand(1).hasOneUse() &&
4968 SDValue N0Op0 = N0.getOperand(0);
4969 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4970 unsigned LargeShiftVal = LargeShift->getZExtValue();
4971 EVT LargeVT = N0Op0.getValueType();
4973 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4976 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4977 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4978 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4979 N0Op0.getOperand(0), Amt);
4980 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4985 // Simplify, based on bits shifted out of the LHS.
4986 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4987 return SDValue(N, 0);
4990 // If the sign bit is known to be zero, switch this to a SRL.
4991 if (DAG.SignBitIsZero(N0))
4992 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4994 if (N1C && !N1C->isOpaque())
4995 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5001 SDValue DAGCombiner::visitSRL(SDNode *N) {
5002 SDValue N0 = N->getOperand(0);
5003 SDValue N1 = N->getOperand(1);
5004 EVT VT = N0.getValueType();
5005 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5009 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5012 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5014 // fold (srl c1, c2) -> c1 >>u c2
5015 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5016 if (N0C && N1C && !N1C->isOpaque())
5017 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5018 // fold (srl 0, x) -> 0
5019 if (isNullConstant(N0))
5021 // fold (srl x, c >= size(x)) -> undef
5022 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5023 return DAG.getUNDEF(VT);
5024 // fold (srl x, 0) -> x
5025 if (N1C && N1C->isNullValue())
5027 // if (srl x, c) is known to be zero, return 0
5028 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5029 APInt::getAllOnesValue(OpSizeInBits)))
5030 return DAG.getConstant(0, SDLoc(N), VT);
5032 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5033 if (N1C && N0.getOpcode() == ISD::SRL) {
5034 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5036 APInt c1 = N0C1->getAPIntValue();
5037 APInt c2 = N1C->getAPIntValue();
5038 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5040 APInt Sum = c1 + c2;
5041 if (Sum.uge(OpSizeInBits))
5042 return DAG.getConstant(0, DL, VT);
5045 ISD::SRL, DL, VT, N0.getOperand(0),
5046 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5050 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5051 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5052 N0.getOperand(0).getOpcode() == ISD::SRL &&
5053 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
5055 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
5056 uint64_t c2 = N1C->getZExtValue();
5057 EVT InnerShiftVT = N0.getOperand(0).getValueType();
5058 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
5059 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5060 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5061 if (c1 + OpSizeInBits == InnerShiftSize) {
5063 if (c1 + c2 >= InnerShiftSize)
5064 return DAG.getConstant(0, DL, VT);
5065 return DAG.getNode(ISD::TRUNCATE, DL, VT,
5066 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5067 N0.getOperand(0)->getOperand(0),
5068 DAG.getConstant(c1 + c2, DL,
5073 // fold (srl (shl x, c), c) -> (and x, cst2)
5074 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5075 isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5077 APInt AllBits = APInt::getAllOnesValue(N0.getScalarValueSizeInBits());
5079 DAG.getNode(ISD::SRL, DL, VT, DAG.getConstant(AllBits, DL, VT), N1);
5080 AddToWorklist(Mask.getNode());
5081 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5084 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5085 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5086 // Shifting in all undef bits?
5087 EVT SmallVT = N0.getOperand(0).getValueType();
5088 unsigned BitSize = SmallVT.getScalarSizeInBits();
5089 if (N1C->getZExtValue() >= BitSize)
5090 return DAG.getUNDEF(VT);
5092 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5093 uint64_t ShiftAmt = N1C->getZExtValue();
5095 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5097 DAG.getConstant(ShiftAmt, DL0,
5098 getShiftAmountTy(SmallVT)));
5099 AddToWorklist(SmallShift.getNode());
5100 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
5102 return DAG.getNode(ISD::AND, DL, VT,
5103 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5104 DAG.getConstant(Mask, DL, VT));
5108 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
5109 // bit, which is unmodified by sra.
5110 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5111 if (N0.getOpcode() == ISD::SRA)
5112 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5115 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
5116 if (N1C && N0.getOpcode() == ISD::CTLZ &&
5117 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5118 APInt KnownZero, KnownOne;
5119 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
5121 // If any of the input bits are KnownOne, then the input couldn't be all
5122 // zeros, thus the result of the srl will always be zero.
5123 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5125 // If all of the bits input the to ctlz node are known to be zero, then
5126 // the result of the ctlz is "32" and the result of the shift is one.
5127 APInt UnknownBits = ~KnownZero;
5128 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5130 // Otherwise, check to see if there is exactly one bit input to the ctlz.
5131 if ((UnknownBits & (UnknownBits - 1)) == 0) {
5132 // Okay, we know that only that the single bit specified by UnknownBits
5133 // could be set on input to the CTLZ node. If this bit is set, the SRL
5134 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5135 // to an SRL/XOR pair, which is likely to simplify more.
5136 unsigned ShAmt = UnknownBits.countTrailingZeros();
5137 SDValue Op = N0.getOperand(0);
5141 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5142 DAG.getConstant(ShAmt, DL,
5143 getShiftAmountTy(Op.getValueType())));
5144 AddToWorklist(Op.getNode());
5148 return DAG.getNode(ISD::XOR, DL, VT,
5149 Op, DAG.getConstant(1, DL, VT));
5153 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5154 if (N1.getOpcode() == ISD::TRUNCATE &&
5155 N1.getOperand(0).getOpcode() == ISD::AND) {
5156 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5157 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5160 // fold operands of srl based on knowledge that the low bits are not
5162 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5163 return SDValue(N, 0);
5165 if (N1C && !N1C->isOpaque())
5166 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5169 // Attempt to convert a srl of a load into a narrower zero-extending load.
5170 if (SDValue NarrowLoad = ReduceLoadWidth(N))
5173 // Here is a common situation. We want to optimize:
5176 // %b = and i32 %a, 2
5177 // %c = srl i32 %b, 1
5178 // brcond i32 %c ...
5184 // %c = setcc eq %b, 0
5187 // However when after the source operand of SRL is optimized into AND, the SRL
5188 // itself may not be optimized further. Look for it and add the BRCOND into
5190 if (N->hasOneUse()) {
5191 SDNode *Use = *N->use_begin();
5192 if (Use->getOpcode() == ISD::BRCOND)
5194 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5195 // Also look pass the truncate.
5196 Use = *Use->use_begin();
5197 if (Use->getOpcode() == ISD::BRCOND)
5205 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5206 SDValue N0 = N->getOperand(0);
5207 EVT VT = N->getValueType(0);
5209 // fold (bswap c1) -> c2
5210 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5211 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5212 // fold (bswap (bswap x)) -> x
5213 if (N0.getOpcode() == ISD::BSWAP)
5214 return N0->getOperand(0);
5218 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5219 SDValue N0 = N->getOperand(0);
5221 // fold (bitreverse (bitreverse x)) -> x
5222 if (N0.getOpcode() == ISD::BITREVERSE)
5223 return N0.getOperand(0);
5227 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5228 SDValue N0 = N->getOperand(0);
5229 EVT VT = N->getValueType(0);
5231 // fold (ctlz c1) -> c2
5232 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5233 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5237 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5238 SDValue N0 = N->getOperand(0);
5239 EVT VT = N->getValueType(0);
5241 // fold (ctlz_zero_undef c1) -> c2
5242 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5243 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5247 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5248 SDValue N0 = N->getOperand(0);
5249 EVT VT = N->getValueType(0);
5251 // fold (cttz c1) -> c2
5252 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5253 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5257 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5258 SDValue N0 = N->getOperand(0);
5259 EVT VT = N->getValueType(0);
5261 // fold (cttz_zero_undef c1) -> c2
5262 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5263 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5267 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5268 SDValue N0 = N->getOperand(0);
5269 EVT VT = N->getValueType(0);
5271 // fold (ctpop c1) -> c2
5272 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5273 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5278 /// \brief Generate Min/Max node
5279 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5280 SDValue RHS, SDValue True, SDValue False,
5281 ISD::CondCode CC, const TargetLowering &TLI,
5282 SelectionDAG &DAG) {
5283 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5293 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5294 if (TLI.isOperationLegal(Opcode, VT))
5295 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5304 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5305 if (TLI.isOperationLegal(Opcode, VT))
5306 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5314 // TODO: We should handle other cases of selecting between {-1,0,1} here.
5315 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5316 SDValue Cond = N->getOperand(0);
5317 SDValue N1 = N->getOperand(1);
5318 SDValue N2 = N->getOperand(2);
5319 EVT VT = N->getValueType(0);
5320 EVT CondVT = Cond.getValueType();
5323 // fold (select Cond, 0, 1) -> (xor Cond, 1)
5324 // We can't do this reliably if integer based booleans have different contents
5325 // to floating point based booleans. This is because we can't tell whether we
5326 // have an integer-based boolean or a floating-point-based boolean unless we
5327 // can find the SETCC that produced it and inspect its operands. This is
5328 // fairly easy if C is the SETCC node, but it can potentially be
5329 // undiscoverable (or not reasonably discoverable). For example, it could be
5330 // in another basic block or it could require searching a complicated
5332 if (VT.isInteger() &&
5333 (CondVT == MVT::i1 || (CondVT.isInteger() &&
5334 TLI.getBooleanContents(false, true) ==
5335 TargetLowering::ZeroOrOneBooleanContent &&
5336 TLI.getBooleanContents(false, false) ==
5337 TargetLowering::ZeroOrOneBooleanContent)) &&
5338 isNullConstant(N1) && isOneConstant(N2)) {
5339 SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
5340 DAG.getConstant(1, DL, CondVT));
5341 if (VT.bitsEq(CondVT))
5343 return DAG.getZExtOrTrunc(NotCond, DL, VT);
5349 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5350 SDValue N0 = N->getOperand(0);
5351 SDValue N1 = N->getOperand(1);
5352 SDValue N2 = N->getOperand(2);
5353 EVT VT = N->getValueType(0);
5354 EVT VT0 = N0.getValueType();
5356 // fold (select C, X, X) -> X
5359 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5360 // fold (select true, X, Y) -> X
5361 // fold (select false, X, Y) -> Y
5362 return !N0C->isNullValue() ? N1 : N2;
5364 // fold (select C, 1, X) -> (or C, X)
5365 if (VT == MVT::i1 && isOneConstant(N1))
5366 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5368 if (SDValue V = foldSelectOfConstants(N))
5371 // fold (select C, 0, X) -> (and (not C), X)
5372 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5373 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5374 AddToWorklist(NOTNode.getNode());
5375 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5377 // fold (select C, X, 1) -> (or (not C), X)
5378 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5379 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5380 AddToWorklist(NOTNode.getNode());
5381 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5383 // fold (select C, X, 0) -> (and C, X)
5384 if (VT == MVT::i1 && isNullConstant(N2))
5385 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5386 // fold (select X, X, Y) -> (or X, Y)
5387 // fold (select X, 1, Y) -> (or X, Y)
5388 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5389 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5390 // fold (select X, Y, X) -> (and X, Y)
5391 // fold (select X, Y, 0) -> (and X, Y)
5392 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5393 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5395 // If we can fold this based on the true/false value, do so.
5396 if (SimplifySelectOps(N, N1, N2))
5397 return SDValue(N, 0); // Don't revisit N.
5399 if (VT0 == MVT::i1) {
5400 // The code in this block deals with the following 2 equivalences:
5401 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5402 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5403 // The target can specify its preferred form with the
5404 // shouldNormalizeToSelectSequence() callback. However we always transform
5405 // to the right anyway if we find the inner select exists in the DAG anyway
5406 // and we always transform to the left side if we know that we can further
5407 // optimize the combination of the conditions.
5408 bool normalizeToSequence
5409 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5410 // select (and Cond0, Cond1), X, Y
5411 // -> select Cond0, (select Cond1, X, Y), Y
5412 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5413 SDValue Cond0 = N0->getOperand(0);
5414 SDValue Cond1 = N0->getOperand(1);
5415 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5416 N1.getValueType(), Cond1, N1, N2);
5417 if (normalizeToSequence || !InnerSelect.use_empty())
5418 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5421 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5422 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5423 SDValue Cond0 = N0->getOperand(0);
5424 SDValue Cond1 = N0->getOperand(1);
5425 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5426 N1.getValueType(), Cond1, N1, N2);
5427 if (normalizeToSequence || !InnerSelect.use_empty())
5428 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5432 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5433 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5434 SDValue N1_0 = N1->getOperand(0);
5435 SDValue N1_1 = N1->getOperand(1);
5436 SDValue N1_2 = N1->getOperand(2);
5437 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5438 // Create the actual and node if we can generate good code for it.
5439 if (!normalizeToSequence) {
5440 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5442 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5445 // Otherwise see if we can optimize the "and" to a better pattern.
5446 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5447 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5451 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5452 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5453 SDValue N2_0 = N2->getOperand(0);
5454 SDValue N2_1 = N2->getOperand(1);
5455 SDValue N2_2 = N2->getOperand(2);
5456 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5457 // Create the actual or node if we can generate good code for it.
5458 if (!normalizeToSequence) {
5459 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5461 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5464 // Otherwise see if we can optimize to a better pattern.
5465 if (SDValue Combined = visitORLike(N0, N2_0, N))
5466 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5472 // select (xor Cond, 1), X, Y -> select Cond, Y, X
5473 // select (xor Cond, 0), X, Y -> selext Cond, X, Y
5474 if (VT0 == MVT::i1) {
5475 if (N0->getOpcode() == ISD::XOR) {
5476 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
5477 SDValue Cond0 = N0->getOperand(0);
5479 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5482 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5488 // fold selects based on a setcc into other things, such as min/max/abs
5489 if (N0.getOpcode() == ISD::SETCC) {
5490 // select x, y (fcmp lt x, y) -> fminnum x, y
5491 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5493 // This is OK if we don't care about what happens if either operand is a
5497 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5498 // no signed zeros as well as no nans.
5499 const TargetOptions &Options = DAG.getTarget().Options;
5500 if (Options.UnsafeFPMath &&
5501 VT.isFloatingPoint() && N0.hasOneUse() &&
5502 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5503 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5505 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5506 N0.getOperand(1), N1, N2, CC,
5511 if ((!LegalOperations &&
5512 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5513 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5514 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5515 N0.getOperand(0), N0.getOperand(1),
5516 N1, N2, N0.getOperand(2));
5517 return SimplifySelect(SDLoc(N), N0, N1, N2);
5524 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5527 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5529 // Split the inputs.
5530 SDValue Lo, Hi, LL, LH, RL, RH;
5531 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5532 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5534 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5535 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5537 return std::make_pair(Lo, Hi);
5540 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5541 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5542 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5544 SDValue Cond = N->getOperand(0);
5545 SDValue LHS = N->getOperand(1);
5546 SDValue RHS = N->getOperand(2);
5547 EVT VT = N->getValueType(0);
5548 int NumElems = VT.getVectorNumElements();
5549 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5550 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5551 Cond.getOpcode() == ISD::BUILD_VECTOR);
5553 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5554 // binary ones here.
5555 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5558 // We're sure we have an even number of elements due to the
5559 // concat_vectors we have as arguments to vselect.
5560 // Skip BV elements until we find one that's not an UNDEF
5561 // After we find an UNDEF element, keep looping until we get to half the
5562 // length of the BV and see if all the non-undef nodes are the same.
5563 ConstantSDNode *BottomHalf = nullptr;
5564 for (int i = 0; i < NumElems / 2; ++i) {
5565 if (Cond->getOperand(i)->isUndef())
5568 if (BottomHalf == nullptr)
5569 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5570 else if (Cond->getOperand(i).getNode() != BottomHalf)
5574 // Do the same for the second half of the BuildVector
5575 ConstantSDNode *TopHalf = nullptr;
5576 for (int i = NumElems / 2; i < NumElems; ++i) {
5577 if (Cond->getOperand(i)->isUndef())
5580 if (TopHalf == nullptr)
5581 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5582 else if (Cond->getOperand(i).getNode() != TopHalf)
5586 assert(TopHalf && BottomHalf &&
5587 "One half of the selector was all UNDEFs and the other was all the "
5588 "same value. This should have been addressed before this function.");
5590 ISD::CONCAT_VECTORS, DL, VT,
5591 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5592 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5595 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5597 if (Level >= AfterLegalizeTypes)
5600 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5601 SDValue Mask = MSC->getMask();
5602 SDValue Data = MSC->getValue();
5605 // If the MSCATTER data type requires splitting and the mask is provided by a
5606 // SETCC, then split both nodes and its operands before legalization. This
5607 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5608 // and enables future optimizations (e.g. min/max pattern matching on X86).
5609 if (Mask.getOpcode() != ISD::SETCC)
5612 // Check if any splitting is required.
5613 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5614 TargetLowering::TypeSplitVector)
5616 SDValue MaskLo, MaskHi, Lo, Hi;
5617 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5620 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5622 SDValue Chain = MSC->getChain();
5624 EVT MemoryVT = MSC->getMemoryVT();
5625 unsigned Alignment = MSC->getOriginalAlignment();
5627 EVT LoMemVT, HiMemVT;
5628 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5630 SDValue DataLo, DataHi;
5631 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5633 SDValue BasePtr = MSC->getBasePtr();
5634 SDValue IndexLo, IndexHi;
5635 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5637 MachineMemOperand *MMO = DAG.getMachineFunction().
5638 getMachineMemOperand(MSC->getPointerInfo(),
5639 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5640 Alignment, MSC->getAAInfo(), MSC->getRanges());
5642 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5643 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5646 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5647 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5650 AddToWorklist(Lo.getNode());
5651 AddToWorklist(Hi.getNode());
5653 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5656 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5658 if (Level >= AfterLegalizeTypes)
5661 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5662 SDValue Mask = MST->getMask();
5663 SDValue Data = MST->getValue();
5664 EVT VT = Data.getValueType();
5667 // If the MSTORE data type requires splitting and the mask is provided by a
5668 // SETCC, then split both nodes and its operands before legalization. This
5669 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5670 // and enables future optimizations (e.g. min/max pattern matching on X86).
5671 if (Mask.getOpcode() == ISD::SETCC) {
5673 // Check if any splitting is required.
5674 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5675 TargetLowering::TypeSplitVector)
5678 SDValue MaskLo, MaskHi, Lo, Hi;
5679 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5681 SDValue Chain = MST->getChain();
5682 SDValue Ptr = MST->getBasePtr();
5684 EVT MemoryVT = MST->getMemoryVT();
5685 unsigned Alignment = MST->getOriginalAlignment();
5687 // if Alignment is equal to the vector size,
5688 // take the half of it for the second part
5689 unsigned SecondHalfAlignment =
5690 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
5692 EVT LoMemVT, HiMemVT;
5693 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5695 SDValue DataLo, DataHi;
5696 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5698 MachineMemOperand *MMO = DAG.getMachineFunction().
5699 getMachineMemOperand(MST->getPointerInfo(),
5700 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5701 Alignment, MST->getAAInfo(), MST->getRanges());
5703 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5704 MST->isTruncatingStore(),
5705 MST->isCompressingStore());
5707 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
5708 MST->isCompressingStore());
5710 MMO = DAG.getMachineFunction().
5711 getMachineMemOperand(MST->getPointerInfo(),
5712 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5713 SecondHalfAlignment, MST->getAAInfo(),
5716 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5717 MST->isTruncatingStore(),
5718 MST->isCompressingStore());
5720 AddToWorklist(Lo.getNode());
5721 AddToWorklist(Hi.getNode());
5723 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5728 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5730 if (Level >= AfterLegalizeTypes)
5733 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5734 SDValue Mask = MGT->getMask();
5737 // If the MGATHER result requires splitting and the mask is provided by a
5738 // SETCC, then split both nodes and its operands before legalization. This
5739 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5740 // and enables future optimizations (e.g. min/max pattern matching on X86).
5742 if (Mask.getOpcode() != ISD::SETCC)
5745 EVT VT = N->getValueType(0);
5747 // Check if any splitting is required.
5748 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5749 TargetLowering::TypeSplitVector)
5752 SDValue MaskLo, MaskHi, Lo, Hi;
5753 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5755 SDValue Src0 = MGT->getValue();
5756 SDValue Src0Lo, Src0Hi;
5757 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5760 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5762 SDValue Chain = MGT->getChain();
5763 EVT MemoryVT = MGT->getMemoryVT();
5764 unsigned Alignment = MGT->getOriginalAlignment();
5766 EVT LoMemVT, HiMemVT;
5767 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5769 SDValue BasePtr = MGT->getBasePtr();
5770 SDValue Index = MGT->getIndex();
5771 SDValue IndexLo, IndexHi;
5772 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5774 MachineMemOperand *MMO = DAG.getMachineFunction().
5775 getMachineMemOperand(MGT->getPointerInfo(),
5776 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5777 Alignment, MGT->getAAInfo(), MGT->getRanges());
5779 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5780 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5783 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5784 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5787 AddToWorklist(Lo.getNode());
5788 AddToWorklist(Hi.getNode());
5790 // Build a factor node to remember that this load is independent of the
5792 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5795 // Legalized the chain result - switch anything that used the old chain to
5797 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5799 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5801 SDValue RetOps[] = { GatherRes, Chain };
5802 return DAG.getMergeValues(RetOps, DL);
5805 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5807 if (Level >= AfterLegalizeTypes)
5810 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5811 SDValue Mask = MLD->getMask();
5814 // If the MLOAD result requires splitting and the mask is provided by a
5815 // SETCC, then split both nodes and its operands before legalization. This
5816 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5817 // and enables future optimizations (e.g. min/max pattern matching on X86).
5819 if (Mask.getOpcode() == ISD::SETCC) {
5820 EVT VT = N->getValueType(0);
5822 // Check if any splitting is required.
5823 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5824 TargetLowering::TypeSplitVector)
5827 SDValue MaskLo, MaskHi, Lo, Hi;
5828 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5830 SDValue Src0 = MLD->getSrc0();
5831 SDValue Src0Lo, Src0Hi;
5832 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5835 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5837 SDValue Chain = MLD->getChain();
5838 SDValue Ptr = MLD->getBasePtr();
5839 EVT MemoryVT = MLD->getMemoryVT();
5840 unsigned Alignment = MLD->getOriginalAlignment();
5842 // if Alignment is equal to the vector size,
5843 // take the half of it for the second part
5844 unsigned SecondHalfAlignment =
5845 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5846 Alignment/2 : Alignment;
5848 EVT LoMemVT, HiMemVT;
5849 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5851 MachineMemOperand *MMO = DAG.getMachineFunction().
5852 getMachineMemOperand(MLD->getPointerInfo(),
5853 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5854 Alignment, MLD->getAAInfo(), MLD->getRanges());
5856 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5857 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
5859 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
5860 MLD->isExpandingLoad());
5862 MMO = DAG.getMachineFunction().
5863 getMachineMemOperand(MLD->getPointerInfo(),
5864 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5865 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5867 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5868 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
5870 AddToWorklist(Lo.getNode());
5871 AddToWorklist(Hi.getNode());
5873 // Build a factor node to remember that this load is independent of the
5875 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5878 // Legalized the chain result - switch anything that used the old chain to
5880 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5882 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5884 SDValue RetOps[] = { LoadRes, Chain };
5885 return DAG.getMergeValues(RetOps, DL);
5890 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5891 SDValue N0 = N->getOperand(0);
5892 SDValue N1 = N->getOperand(1);
5893 SDValue N2 = N->getOperand(2);
5896 // fold (vselect C, X, X) -> X
5900 // Canonicalize integer abs.
5901 // vselect (setg[te] X, 0), X, -X ->
5902 // vselect (setgt X, -1), X, -X ->
5903 // vselect (setl[te] X, 0), -X, X ->
5904 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5905 if (N0.getOpcode() == ISD::SETCC) {
5906 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5907 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5909 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5911 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5912 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5913 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5914 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5915 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5916 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5917 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5920 EVT VT = LHS.getValueType();
5921 SDValue Shift = DAG.getNode(
5922 ISD::SRA, DL, VT, LHS,
5923 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
5924 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5925 AddToWorklist(Shift.getNode());
5926 AddToWorklist(Add.getNode());
5927 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5931 if (SimplifySelectOps(N, N1, N2))
5932 return SDValue(N, 0); // Don't revisit N.
5934 // If the VSELECT result requires splitting and the mask is provided by a
5935 // SETCC, then split both nodes and its operands before legalization. This
5936 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5937 // and enables future optimizations (e.g. min/max pattern matching on X86).
5938 if (N0.getOpcode() == ISD::SETCC) {
5939 EVT VT = N->getValueType(0);
5941 // Check if any splitting is required.
5942 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5943 TargetLowering::TypeSplitVector)
5946 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5947 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5948 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5949 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5951 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5952 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5954 // Add the new VSELECT nodes to the work list in case they need to be split
5956 AddToWorklist(Lo.getNode());
5957 AddToWorklist(Hi.getNode());
5959 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5962 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5963 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5965 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5966 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5969 // The ConvertSelectToConcatVector function is assuming both the above
5970 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5972 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5973 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5974 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5975 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5982 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5983 SDValue N0 = N->getOperand(0);
5984 SDValue N1 = N->getOperand(1);
5985 SDValue N2 = N->getOperand(2);
5986 SDValue N3 = N->getOperand(3);
5987 SDValue N4 = N->getOperand(4);
5988 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5990 // fold select_cc lhs, rhs, x, x, cc -> x
5994 // Determine if the condition we're dealing with is constant
5995 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5996 CC, SDLoc(N), false)) {
5997 AddToWorklist(SCC.getNode());
5999 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6000 if (!SCCC->isNullValue())
6001 return N2; // cond always true -> true val
6003 return N3; // cond always false -> false val
6004 } else if (SCC->isUndef()) {
6005 // When the condition is UNDEF, just return the first operand. This is
6006 // coherent the DAG creation, no setcc node is created in this case
6008 } else if (SCC.getOpcode() == ISD::SETCC) {
6009 // Fold to a simpler select_cc
6010 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6011 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6016 // If we can fold this based on the true/false value, do so.
6017 if (SimplifySelectOps(N, N2, N3))
6018 return SDValue(N, 0); // Don't revisit N.
6020 // fold select_cc into other things, such as min/max/abs
6021 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6024 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6025 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6026 cast<CondCodeSDNode>(N->getOperand(2))->get(),
6030 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6031 SDValue LHS = N->getOperand(0);
6032 SDValue RHS = N->getOperand(1);
6033 SDValue Carry = N->getOperand(2);
6034 SDValue Cond = N->getOperand(3);
6036 // If Carry is false, fold to a regular SETCC.
6037 if (Carry.getOpcode() == ISD::CARRY_FALSE)
6038 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6043 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6044 /// a build_vector of constants.
6045 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6046 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6047 /// Vector extends are not folded if operations are legal; this is to
6048 /// avoid introducing illegal build_vector dag nodes.
6049 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6050 SelectionDAG &DAG, bool LegalTypes,
6051 bool LegalOperations) {
6052 unsigned Opcode = N->getOpcode();
6053 SDValue N0 = N->getOperand(0);
6054 EVT VT = N->getValueType(0);
6056 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6057 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6058 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6059 && "Expected EXTEND dag node in input!");
6061 // fold (sext c1) -> c1
6062 // fold (zext c1) -> c1
6063 // fold (aext c1) -> c1
6064 if (isa<ConstantSDNode>(N0))
6065 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6067 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6068 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6069 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6070 EVT SVT = VT.getScalarType();
6071 if (!(VT.isVector() &&
6072 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6073 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6076 // We can fold this node into a build_vector.
6077 unsigned VTBits = SVT.getSizeInBits();
6078 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6079 SmallVector<SDValue, 8> Elts;
6080 unsigned NumElts = VT.getVectorNumElements();
6083 for (unsigned i=0; i != NumElts; ++i) {
6084 SDValue Op = N0->getOperand(i);
6085 if (Op->isUndef()) {
6086 Elts.push_back(DAG.getUNDEF(SVT));
6091 // Get the constant value and if needed trunc it to the size of the type.
6092 // Nodes like build_vector might have constants wider than the scalar type.
6093 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6094 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6095 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6097 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6100 return DAG.getBuildVector(VT, DL, Elts).getNode();
6103 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6104 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6105 // transformation. Returns true if extension are possible and the above
6106 // mentioned transformation is profitable.
6107 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6109 SmallVectorImpl<SDNode *> &ExtendNodes,
6110 const TargetLowering &TLI) {
6111 bool HasCopyToRegUses = false;
6112 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6113 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6114 UE = N0.getNode()->use_end();
6119 if (UI.getUse().getResNo() != N0.getResNo())
6121 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6122 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6123 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6124 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6125 // Sign bits will be lost after a zext.
6128 for (unsigned i = 0; i != 2; ++i) {
6129 SDValue UseOp = User->getOperand(i);
6132 if (!isa<ConstantSDNode>(UseOp))
6137 ExtendNodes.push_back(User);
6140 // If truncates aren't free and there are users we can't
6141 // extend, it isn't worthwhile.
6144 // Remember if this value is live-out.
6145 if (User->getOpcode() == ISD::CopyToReg)
6146 HasCopyToRegUses = true;
6149 if (HasCopyToRegUses) {
6150 bool BothLiveOut = false;
6151 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6153 SDUse &Use = UI.getUse();
6154 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6160 // Both unextended and extended values are live out. There had better be
6161 // a good reason for the transformation.
6162 return ExtendNodes.size();
6167 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6168 SDValue Trunc, SDValue ExtLoad,
6169 const SDLoc &DL, ISD::NodeType ExtType) {
6170 // Extend SetCC uses if necessary.
6171 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6172 SDNode *SetCC = SetCCs[i];
6173 SmallVector<SDValue, 4> Ops;
6175 for (unsigned j = 0; j != 2; ++j) {
6176 SDValue SOp = SetCC->getOperand(j);
6178 Ops.push_back(ExtLoad);
6180 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6183 Ops.push_back(SetCC->getOperand(2));
6184 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6188 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6189 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6190 SDValue N0 = N->getOperand(0);
6191 EVT DstVT = N->getValueType(0);
6192 EVT SrcVT = N0.getValueType();
6194 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6195 N->getOpcode() == ISD::ZERO_EXTEND) &&
6196 "Unexpected node type (not an extend)!");
6198 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6199 // For example, on a target with legal v4i32, but illegal v8i32, turn:
6200 // (v8i32 (sext (v8i16 (load x))))
6202 // (v8i32 (concat_vectors (v4i32 (sextload x)),
6203 // (v4i32 (sextload (x + 16)))))
6204 // Where uses of the original load, i.e.:
6206 // are replaced with:
6208 // (v8i32 (concat_vectors (v4i32 (sextload x)),
6209 // (v4i32 (sextload (x + 16)))))))
6211 // This combine is only applicable to illegal, but splittable, vectors.
6212 // All legal types, and illegal non-vector types, are handled elsewhere.
6213 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6215 if (N0->getOpcode() != ISD::LOAD)
6218 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6220 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6221 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6222 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6225 SmallVector<SDNode *, 4> SetCCs;
6226 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6229 ISD::LoadExtType ExtType =
6230 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6232 // Try to split the vector types to get down to legal types.
6233 EVT SplitSrcVT = SrcVT;
6234 EVT SplitDstVT = DstVT;
6235 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6236 SplitSrcVT.getVectorNumElements() > 1) {
6237 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6238 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6241 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6245 const unsigned NumSplits =
6246 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6247 const unsigned Stride = SplitSrcVT.getStoreSize();
6248 SmallVector<SDValue, 4> Loads;
6249 SmallVector<SDValue, 4> Chains;
6251 SDValue BasePtr = LN0->getBasePtr();
6252 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6253 const unsigned Offset = Idx * Stride;
6254 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6256 SDValue SplitLoad = DAG.getExtLoad(
6257 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6258 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6259 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6261 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6262 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6264 Loads.push_back(SplitLoad.getValue(0));
6265 Chains.push_back(SplitLoad.getValue(1));
6268 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6269 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6271 CombineTo(N, NewValue);
6273 // Replace uses of the original load (before extension)
6274 // with a truncate of the concatenated sextloaded vectors.
6276 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6277 CombineTo(N0.getNode(), Trunc, NewChain);
6278 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6279 (ISD::NodeType)N->getOpcode());
6280 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6283 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6284 SDValue N0 = N->getOperand(0);
6285 EVT VT = N->getValueType(0);
6287 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6289 return SDValue(Res, 0);
6291 // fold (sext (sext x)) -> (sext x)
6292 // fold (sext (aext x)) -> (sext x)
6293 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6294 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6297 if (N0.getOpcode() == ISD::TRUNCATE) {
6298 // fold (sext (truncate (load x))) -> (sext (smaller load x))
6299 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6300 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6301 SDNode *oye = N0.getOperand(0).getNode();
6302 if (NarrowLoad.getNode() != N0.getNode()) {
6303 CombineTo(N0.getNode(), NarrowLoad);
6304 // CombineTo deleted the truncate, if needed, but not what's under it.
6307 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6310 // See if the value being truncated is already sign extended. If so, just
6311 // eliminate the trunc/sext pair.
6312 SDValue Op = N0.getOperand(0);
6313 unsigned OpBits = Op.getScalarValueSizeInBits();
6314 unsigned MidBits = N0.getScalarValueSizeInBits();
6315 unsigned DestBits = VT.getScalarSizeInBits();
6316 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6318 if (OpBits == DestBits) {
6319 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
6320 // bits, it is already ready.
6321 if (NumSignBits > DestBits-MidBits)
6323 } else if (OpBits < DestBits) {
6324 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
6325 // bits, just sext from i32.
6326 if (NumSignBits > OpBits-MidBits)
6327 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6329 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
6330 // bits, just truncate to i32.
6331 if (NumSignBits > OpBits-MidBits)
6332 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6335 // fold (sext (truncate x)) -> (sextinreg x).
6336 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6337 N0.getValueType())) {
6338 if (OpBits < DestBits)
6339 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6340 else if (OpBits > DestBits)
6341 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6342 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6343 DAG.getValueType(N0.getValueType()));
6347 // fold (sext (load x)) -> (sext (truncate (sextload x)))
6348 // Only generate vector extloads when 1) they're legal, and 2) they are
6349 // deemed desirable by the target.
6350 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6351 ((!LegalOperations && !VT.isVector() &&
6352 !cast<LoadSDNode>(N0)->isVolatile()) ||
6353 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6354 bool DoXform = true;
6355 SmallVector<SDNode*, 4> SetCCs;
6356 if (!N0.hasOneUse())
6357 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6359 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6361 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6362 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6364 LN0->getBasePtr(), N0.getValueType(),
6365 LN0->getMemOperand());
6366 CombineTo(N, ExtLoad);
6367 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6368 N0.getValueType(), ExtLoad);
6369 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6370 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6372 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6376 // fold (sext (load x)) to multiple smaller sextloads.
6377 // Only on illegal but splittable vectors.
6378 if (SDValue ExtLoad = CombineExtLoad(N))
6381 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6382 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6383 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6384 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6385 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6386 EVT MemVT = LN0->getMemoryVT();
6387 if ((!LegalOperations && !LN0->isVolatile()) ||
6388 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6389 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6391 LN0->getBasePtr(), MemVT,
6392 LN0->getMemOperand());
6393 CombineTo(N, ExtLoad);
6394 CombineTo(N0.getNode(),
6395 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6396 N0.getValueType(), ExtLoad),
6397 ExtLoad.getValue(1));
6398 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6402 // fold (sext (and/or/xor (load x), cst)) ->
6403 // (and/or/xor (sextload x), (sext cst))
6404 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6405 N0.getOpcode() == ISD::XOR) &&
6406 isa<LoadSDNode>(N0.getOperand(0)) &&
6407 N0.getOperand(1).getOpcode() == ISD::Constant &&
6408 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6409 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6410 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6411 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6412 bool DoXform = true;
6413 SmallVector<SDNode*, 4> SetCCs;
6414 if (!N0.hasOneUse())
6415 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6418 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6419 LN0->getChain(), LN0->getBasePtr(),
6421 LN0->getMemOperand());
6422 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6423 Mask = Mask.sext(VT.getSizeInBits());
6425 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6426 ExtLoad, DAG.getConstant(Mask, DL, VT));
6427 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6428 SDLoc(N0.getOperand(0)),
6429 N0.getOperand(0).getValueType(), ExtLoad);
6431 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6432 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6434 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6439 if (N0.getOpcode() == ISD::SETCC) {
6440 EVT N0VT = N0.getOperand(0).getValueType();
6441 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6442 // Only do this before legalize for now.
6443 if (VT.isVector() && !LegalOperations &&
6444 TLI.getBooleanContents(N0VT) ==
6445 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6446 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6447 // of the same size as the compared operands. Only optimize sext(setcc())
6448 // if this is the case.
6449 EVT SVT = getSetCCResultType(N0VT);
6451 // We know that the # elements of the results is the same as the
6452 // # elements of the compare (and the # elements of the compare result
6453 // for that matter). Check to see that they are the same size. If so,
6454 // we know that the element size of the sext'd result matches the
6455 // element size of the compare operands.
6456 if (VT.getSizeInBits() == SVT.getSizeInBits())
6457 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6459 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6461 // If the desired elements are smaller or larger than the source
6462 // elements we can use a matching integer vector type and then
6463 // truncate/sign extend
6464 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6465 if (SVT == MatchingVectorType) {
6466 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6467 N0.getOperand(0), N0.getOperand(1),
6468 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6469 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6473 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6474 // Here, T can be 1 or -1, depending on the type of the setcc and
6475 // getBooleanContents().
6476 unsigned SetCCWidth = N0.getScalarValueSizeInBits();
6479 // To determine the "true" side of the select, we need to know the high bit
6480 // of the value returned by the setcc if it evaluates to true.
6481 // If the type of the setcc is i1, then the true case of the select is just
6482 // sext(i1 1), that is, -1.
6483 // If the type of the setcc is larger (say, i8) then the value of the high
6484 // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6485 // of the appropriate width.
6486 SDValue ExtTrueVal =
6488 ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6490 : TLI.getConstTrueVal(DAG, VT, DL);
6492 if (SDValue SCC = SimplifySelectCC(
6493 DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6494 DAG.getConstant(0, DL, VT),
6495 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6498 if (!VT.isVector()) {
6499 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6500 if (!LegalOperations ||
6501 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6503 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6505 DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6506 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6507 DAG.getConstant(0, DL, VT));
6512 // fold (sext x) -> (zext x) if the sign bit is known zero.
6513 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6514 DAG.SignBitIsZero(N0))
6515 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6520 // isTruncateOf - If N is a truncate of some other value, return true, record
6521 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6522 // This function computes KnownZero to avoid a duplicated call to
6523 // computeKnownBits in the caller.
6524 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6527 if (N->getOpcode() == ISD::TRUNCATE) {
6528 Op = N->getOperand(0);
6529 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6533 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6534 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6537 SDValue Op0 = N->getOperand(0);
6538 SDValue Op1 = N->getOperand(1);
6539 assert(Op0.getValueType() == Op1.getValueType());
6541 if (isNullConstant(Op0))
6543 else if (isNullConstant(Op1))
6548 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6550 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6556 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6557 SDValue N0 = N->getOperand(0);
6558 EVT VT = N->getValueType(0);
6560 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6562 return SDValue(Res, 0);
6564 // fold (zext (zext x)) -> (zext x)
6565 // fold (zext (aext x)) -> (zext x)
6566 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6567 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6570 // fold (zext (truncate x)) -> (zext x) or
6571 // (zext (truncate x)) -> (truncate x)
6572 // This is valid when the truncated bits of x are already zero.
6573 // FIXME: We should extend this to work for vectors too.
6576 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6577 APInt TruncatedBits =
6578 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6579 APInt(Op.getValueSizeInBits(), 0) :
6580 APInt::getBitsSet(Op.getValueSizeInBits(),
6581 N0.getValueSizeInBits(),
6582 std::min(Op.getValueSizeInBits(),
6583 VT.getSizeInBits()));
6584 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6585 if (VT.bitsGT(Op.getValueType()))
6586 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6587 if (VT.bitsLT(Op.getValueType()))
6588 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6594 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6595 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6596 if (N0.getOpcode() == ISD::TRUNCATE) {
6597 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6598 SDNode *oye = N0.getOperand(0).getNode();
6599 if (NarrowLoad.getNode() != N0.getNode()) {
6600 CombineTo(N0.getNode(), NarrowLoad);
6601 // CombineTo deleted the truncate, if needed, but not what's under it.
6604 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6608 // fold (zext (truncate x)) -> (and x, mask)
6609 if (N0.getOpcode() == ISD::TRUNCATE) {
6610 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6611 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6612 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6613 SDNode *oye = N0.getOperand(0).getNode();
6614 if (NarrowLoad.getNode() != N0.getNode()) {
6615 CombineTo(N0.getNode(), NarrowLoad);
6616 // CombineTo deleted the truncate, if needed, but not what's under it.
6619 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6622 EVT SrcVT = N0.getOperand(0).getValueType();
6623 EVT MinVT = N0.getValueType();
6625 // Try to mask before the extension to avoid having to generate a larger mask,
6626 // possibly over several sub-vectors.
6627 if (SrcVT.bitsLT(VT)) {
6628 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6629 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6630 SDValue Op = N0.getOperand(0);
6631 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6632 AddToWorklist(Op.getNode());
6633 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6637 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6638 SDValue Op = N0.getOperand(0);
6639 if (SrcVT.bitsLT(VT)) {
6640 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6641 AddToWorklist(Op.getNode());
6642 } else if (SrcVT.bitsGT(VT)) {
6643 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6644 AddToWorklist(Op.getNode());
6646 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6650 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6651 // if either of the casts is not free.
6652 if (N0.getOpcode() == ISD::AND &&
6653 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6654 N0.getOperand(1).getOpcode() == ISD::Constant &&
6655 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6656 N0.getValueType()) ||
6657 !TLI.isZExtFree(N0.getValueType(), VT))) {
6658 SDValue X = N0.getOperand(0).getOperand(0);
6659 if (X.getValueType().bitsLT(VT)) {
6660 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6661 } else if (X.getValueType().bitsGT(VT)) {
6662 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6664 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6665 Mask = Mask.zext(VT.getSizeInBits());
6667 return DAG.getNode(ISD::AND, DL, VT,
6668 X, DAG.getConstant(Mask, DL, VT));
6671 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6672 // Only generate vector extloads when 1) they're legal, and 2) they are
6673 // deemed desirable by the target.
6674 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6675 ((!LegalOperations && !VT.isVector() &&
6676 !cast<LoadSDNode>(N0)->isVolatile()) ||
6677 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6678 bool DoXform = true;
6679 SmallVector<SDNode*, 4> SetCCs;
6680 if (!N0.hasOneUse())
6681 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6683 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6685 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6686 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6688 LN0->getBasePtr(), N0.getValueType(),
6689 LN0->getMemOperand());
6690 CombineTo(N, ExtLoad);
6691 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6692 N0.getValueType(), ExtLoad);
6693 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6695 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6697 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6701 // fold (zext (load x)) to multiple smaller zextloads.
6702 // Only on illegal but splittable vectors.
6703 if (SDValue ExtLoad = CombineExtLoad(N))
6706 // fold (zext (and/or/xor (load x), cst)) ->
6707 // (and/or/xor (zextload x), (zext cst))
6708 // Unless (and (load x) cst) will match as a zextload already and has
6709 // additional users.
6710 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6711 N0.getOpcode() == ISD::XOR) &&
6712 isa<LoadSDNode>(N0.getOperand(0)) &&
6713 N0.getOperand(1).getOpcode() == ISD::Constant &&
6714 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6715 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6716 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6717 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6718 bool DoXform = true;
6719 SmallVector<SDNode*, 4> SetCCs;
6720 if (!N0.hasOneUse()) {
6721 if (N0.getOpcode() == ISD::AND) {
6722 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6723 auto NarrowLoad = false;
6724 EVT LoadResultTy = AndC->getValueType(0);
6725 EVT ExtVT, LoadedVT;
6726 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6731 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6732 ISD::ZERO_EXTEND, SetCCs, TLI);
6735 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6736 LN0->getChain(), LN0->getBasePtr(),
6738 LN0->getMemOperand());
6739 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6740 Mask = Mask.zext(VT.getSizeInBits());
6742 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6743 ExtLoad, DAG.getConstant(Mask, DL, VT));
6744 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6745 SDLoc(N0.getOperand(0)),
6746 N0.getOperand(0).getValueType(), ExtLoad);
6748 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6749 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6751 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6756 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6757 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6758 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6759 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6760 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6761 EVT MemVT = LN0->getMemoryVT();
6762 if ((!LegalOperations && !LN0->isVolatile()) ||
6763 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6764 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6766 LN0->getBasePtr(), MemVT,
6767 LN0->getMemOperand());
6768 CombineTo(N, ExtLoad);
6769 CombineTo(N0.getNode(),
6770 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6772 ExtLoad.getValue(1));
6773 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6777 if (N0.getOpcode() == ISD::SETCC) {
6778 // Only do this before legalize for now.
6779 if (!LegalOperations && VT.isVector() &&
6780 N0.getValueType().getVectorElementType() == MVT::i1) {
6781 EVT N00VT = N0.getOperand(0).getValueType();
6782 if (getSetCCResultType(N00VT) == N0.getValueType())
6785 // We know that the # elements of the results is the same as the #
6786 // elements of the compare (and the # elements of the compare result for
6787 // that matter). Check to see that they are the same size. If so, we know
6788 // that the element size of the sext'd result matches the element size of
6789 // the compare operands.
6791 SDValue VecOnes = DAG.getConstant(1, DL, VT);
6792 if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
6793 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6794 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
6795 N0.getOperand(1), N0.getOperand(2));
6796 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
6799 // If the desired elements are smaller or larger than the source
6800 // elements we can use a matching integer vector type and then
6801 // truncate/sign extend.
6802 EVT MatchingElementType = EVT::getIntegerVT(
6803 *DAG.getContext(), N00VT.getScalarSizeInBits());
6804 EVT MatchingVectorType = EVT::getVectorVT(
6805 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
6807 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
6808 N0.getOperand(1), N0.getOperand(2));
6809 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
6813 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6815 if (SDValue SCC = SimplifySelectCC(
6816 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6817 DAG.getConstant(0, DL, VT),
6818 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6822 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6823 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6824 isa<ConstantSDNode>(N0.getOperand(1)) &&
6825 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6827 SDValue ShAmt = N0.getOperand(1);
6828 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6829 if (N0.getOpcode() == ISD::SHL) {
6830 SDValue InnerZExt = N0.getOperand(0);
6831 // If the original shl may be shifting out bits, do not perform this
6833 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
6834 InnerZExt.getOperand(0).getValueSizeInBits();
6835 if (ShAmtVal > KnownZeroBits)
6841 // Ensure that the shift amount is wide enough for the shifted value.
6842 if (VT.getSizeInBits() >= 256)
6843 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6845 return DAG.getNode(N0.getOpcode(), DL, VT,
6846 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6853 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6854 SDValue N0 = N->getOperand(0);
6855 EVT VT = N->getValueType(0);
6857 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6859 return SDValue(Res, 0);
6861 // fold (aext (aext x)) -> (aext x)
6862 // fold (aext (zext x)) -> (zext x)
6863 // fold (aext (sext x)) -> (sext x)
6864 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6865 N0.getOpcode() == ISD::ZERO_EXTEND ||
6866 N0.getOpcode() == ISD::SIGN_EXTEND)
6867 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6869 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6870 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6871 if (N0.getOpcode() == ISD::TRUNCATE) {
6872 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6873 SDNode *oye = N0.getOperand(0).getNode();
6874 if (NarrowLoad.getNode() != N0.getNode()) {
6875 CombineTo(N0.getNode(), NarrowLoad);
6876 // CombineTo deleted the truncate, if needed, but not what's under it.
6879 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6883 // fold (aext (truncate x))
6884 if (N0.getOpcode() == ISD::TRUNCATE) {
6885 SDValue TruncOp = N0.getOperand(0);
6886 if (TruncOp.getValueType() == VT)
6887 return TruncOp; // x iff x size == zext size.
6888 if (TruncOp.getValueType().bitsGT(VT))
6889 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6890 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6893 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6894 // if the trunc is not free.
6895 if (N0.getOpcode() == ISD::AND &&
6896 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6897 N0.getOperand(1).getOpcode() == ISD::Constant &&
6898 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6899 N0.getValueType())) {
6901 SDValue X = N0.getOperand(0).getOperand(0);
6902 if (X.getValueType().bitsLT(VT)) {
6903 X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
6904 } else if (X.getValueType().bitsGT(VT)) {
6905 X = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
6907 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6908 Mask = Mask.zext(VT.getSizeInBits());
6909 return DAG.getNode(ISD::AND, DL, VT,
6910 X, DAG.getConstant(Mask, DL, VT));
6913 // fold (aext (load x)) -> (aext (truncate (extload x)))
6914 // None of the supported targets knows how to perform load and any_ext
6915 // on vectors in one instruction. We only perform this transformation on
6917 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6918 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6919 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6920 bool DoXform = true;
6921 SmallVector<SDNode*, 4> SetCCs;
6922 if (!N0.hasOneUse())
6923 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6925 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6926 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6928 LN0->getBasePtr(), N0.getValueType(),
6929 LN0->getMemOperand());
6930 CombineTo(N, ExtLoad);
6931 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6932 N0.getValueType(), ExtLoad);
6933 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6934 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6936 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6940 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6941 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6942 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6943 if (N0.getOpcode() == ISD::LOAD &&
6944 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6946 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6947 ISD::LoadExtType ExtType = LN0->getExtensionType();
6948 EVT MemVT = LN0->getMemoryVT();
6949 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6950 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6951 VT, LN0->getChain(), LN0->getBasePtr(),
6952 MemVT, LN0->getMemOperand());
6953 CombineTo(N, ExtLoad);
6954 CombineTo(N0.getNode(),
6955 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6956 N0.getValueType(), ExtLoad),
6957 ExtLoad.getValue(1));
6958 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6962 if (N0.getOpcode() == ISD::SETCC) {
6964 // aext(setcc) -> vsetcc
6965 // aext(setcc) -> truncate(vsetcc)
6966 // aext(setcc) -> aext(vsetcc)
6967 // Only do this before legalize for now.
6968 if (VT.isVector() && !LegalOperations) {
6969 EVT N0VT = N0.getOperand(0).getValueType();
6970 // We know that the # elements of the results is the same as the
6971 // # elements of the compare (and the # elements of the compare result
6972 // for that matter). Check to see that they are the same size. If so,
6973 // we know that the element size of the sext'd result matches the
6974 // element size of the compare operands.
6975 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6976 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6978 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6979 // If the desired elements are smaller or larger than the source
6980 // elements we can use a matching integer vector type and then
6981 // truncate/any extend
6983 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6985 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6987 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6988 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6992 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6994 if (SDValue SCC = SimplifySelectCC(
6995 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6996 DAG.getConstant(0, DL, VT),
6997 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7004 /// See if the specified operand can be simplified with the knowledge that only
7005 /// the bits specified by Mask are used. If so, return the simpler operand,
7006 /// otherwise return a null SDValue.
7007 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7008 switch (V.getOpcode()) {
7010 case ISD::Constant: {
7011 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7012 assert(CV && "Const value should be ConstSDNode.");
7013 const APInt &CVal = CV->getAPIntValue();
7014 APInt NewVal = CVal & Mask;
7016 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7021 // If the LHS or RHS don't contribute bits to the or, drop them.
7022 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7023 return V.getOperand(1);
7024 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7025 return V.getOperand(0);
7028 // Only look at single-use SRLs.
7029 if (!V.getNode()->hasOneUse())
7031 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7032 // See if we can recursively simplify the LHS.
7033 unsigned Amt = RHSC->getZExtValue();
7035 // Watch out for shift count overflow though.
7036 if (Amt >= Mask.getBitWidth()) break;
7037 APInt NewMask = Mask << Amt;
7038 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7039 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7040 SimplifyLHS, V.getOperand(1));
7046 /// If the result of a wider load is shifted to right of N bits and then
7047 /// truncated to a narrower type and where N is a multiple of number of bits of
7048 /// the narrower type, transform it to a narrower load from address + N / num of
7049 /// bits of new type. If the result is to be extended, also fold the extension
7050 /// to form a extending load.
7051 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7052 unsigned Opc = N->getOpcode();
7054 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7055 SDValue N0 = N->getOperand(0);
7056 EVT VT = N->getValueType(0);
7059 // This transformation isn't valid for vector loads.
7063 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7065 if (Opc == ISD::SIGN_EXTEND_INREG) {
7066 ExtType = ISD::SEXTLOAD;
7067 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7068 } else if (Opc == ISD::SRL) {
7069 // Another special-case: SRL is basically zero-extending a narrower value.
7070 ExtType = ISD::ZEXTLOAD;
7072 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7073 if (!N01) return SDValue();
7074 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7075 VT.getSizeInBits() - N01->getZExtValue());
7077 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7080 unsigned EVTBits = ExtVT.getSizeInBits();
7082 // Do not generate loads of non-round integer types since these can
7083 // be expensive (and would be wrong if the type is not byte sized).
7084 if (!ExtVT.isRound())
7088 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7089 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7090 ShAmt = N01->getZExtValue();
7091 // Is the shift amount a multiple of size of VT?
7092 if ((ShAmt & (EVTBits-1)) == 0) {
7093 N0 = N0.getOperand(0);
7094 // Is the load width a multiple of size of VT?
7095 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7099 // At this point, we must have a load or else we can't do the transform.
7100 if (!isa<LoadSDNode>(N0)) return SDValue();
7102 // Because a SRL must be assumed to *need* to zero-extend the high bits
7103 // (as opposed to anyext the high bits), we can't combine the zextload
7104 // lowering of SRL and an sextload.
7105 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7108 // If the shift amount is larger than the input type then we're not
7109 // accessing any of the loaded bytes. If the load was a zextload/extload
7110 // then the result of the shift+trunc is zero/undef (handled elsewhere).
7111 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7116 // If the load is shifted left (and the result isn't shifted back right),
7117 // we can fold the truncate through the shift.
7118 unsigned ShLeftAmt = 0;
7119 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7120 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7121 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7122 ShLeftAmt = N01->getZExtValue();
7123 N0 = N0.getOperand(0);
7127 // If we haven't found a load, we can't narrow it. Don't transform one with
7128 // multiple uses, this would require adding a new load.
7129 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7132 // Don't change the width of a volatile load.
7133 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7134 if (LN0->isVolatile())
7137 // Verify that we are actually reducing a load width here.
7138 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7141 // For the transform to be legal, the load must produce only two values
7142 // (the value loaded and the chain). Don't transform a pre-increment
7143 // load, for example, which produces an extra value. Otherwise the
7144 // transformation is not equivalent, and the downstream logic to replace
7145 // uses gets things wrong.
7146 if (LN0->getNumValues() > 2)
7149 // If the load that we're shrinking is an extload and we're not just
7150 // discarding the extension we can't simply shrink the load. Bail.
7151 // TODO: It would be possible to merge the extensions in some cases.
7152 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7153 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7156 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7159 EVT PtrType = N0.getOperand(1).getValueType();
7161 if (PtrType == MVT::Untyped || PtrType.isExtended())
7162 // It's not possible to generate a constant of extended or untyped type.
7165 // For big endian targets, we need to adjust the offset to the pointer to
7166 // load the correct bytes.
7167 if (DAG.getDataLayout().isBigEndian()) {
7168 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7169 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7170 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7173 uint64_t PtrOff = ShAmt / 8;
7174 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7176 // The original load itself didn't wrap, so an offset within it doesn't.
7178 Flags.setNoUnsignedWrap(true);
7179 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7180 PtrType, LN0->getBasePtr(),
7181 DAG.getConstant(PtrOff, DL, PtrType),
7183 AddToWorklist(NewPtr.getNode());
7186 if (ExtType == ISD::NON_EXTLOAD)
7187 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7188 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7189 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7191 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7192 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7193 NewAlign, LN0->getMemOperand()->getFlags(),
7196 // Replace the old load's chain with the new load's chain.
7197 WorklistRemover DeadNodes(*this);
7198 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7200 // Shift the result left, if we've swallowed a left shift.
7201 SDValue Result = Load;
7202 if (ShLeftAmt != 0) {
7203 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7204 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7206 // If the shift amount is as large as the result size (but, presumably,
7207 // no larger than the source) then the useful bits of the result are
7208 // zero; we can't simply return the shortened shift, because the result
7209 // of that operation is undefined.
7211 if (ShLeftAmt >= VT.getSizeInBits())
7212 Result = DAG.getConstant(0, DL, VT);
7214 Result = DAG.getNode(ISD::SHL, DL, VT,
7215 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7218 // Return the new loaded value.
7222 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7223 SDValue N0 = N->getOperand(0);
7224 SDValue N1 = N->getOperand(1);
7225 EVT VT = N->getValueType(0);
7226 EVT EVT = cast<VTSDNode>(N1)->getVT();
7227 unsigned VTBits = VT.getScalarSizeInBits();
7228 unsigned EVTBits = EVT.getScalarSizeInBits();
7231 return DAG.getUNDEF(VT);
7233 // fold (sext_in_reg c1) -> c1
7234 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7235 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7237 // If the input is already sign extended, just drop the extension.
7238 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7241 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7242 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7243 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7244 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7245 N0.getOperand(0), N1);
7247 // fold (sext_in_reg (sext x)) -> (sext x)
7248 // fold (sext_in_reg (aext x)) -> (sext x)
7249 // if x is small enough.
7250 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7251 SDValue N00 = N0.getOperand(0);
7252 if (N00.getScalarValueSizeInBits() <= EVTBits &&
7253 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7254 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7257 // fold (sext_in_reg (zext x)) -> (sext x)
7258 // iff we are extending the source sign bit.
7259 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
7260 SDValue N00 = N0.getOperand(0);
7261 if (N00.getScalarValueSizeInBits() == EVTBits &&
7262 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7263 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7266 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7267 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7268 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7270 // fold operands of sext_in_reg based on knowledge that the top bits are not
7272 if (SimplifyDemandedBits(SDValue(N, 0)))
7273 return SDValue(N, 0);
7275 // fold (sext_in_reg (load x)) -> (smaller sextload x)
7276 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7277 if (SDValue NarrowLoad = ReduceLoadWidth(N))
7280 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7281 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7282 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7283 if (N0.getOpcode() == ISD::SRL) {
7284 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7285 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7286 // We can turn this into an SRA iff the input to the SRL is already sign
7288 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7289 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7290 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7291 N0.getOperand(0), N0.getOperand(1));
7295 // fold (sext_inreg (extload x)) -> (sextload x)
7296 if (ISD::isEXTLoad(N0.getNode()) &&
7297 ISD::isUNINDEXEDLoad(N0.getNode()) &&
7298 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7299 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7300 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7301 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7302 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7304 LN0->getBasePtr(), EVT,
7305 LN0->getMemOperand());
7306 CombineTo(N, ExtLoad);
7307 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7308 AddToWorklist(ExtLoad.getNode());
7309 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7311 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7312 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7314 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7315 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7316 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7317 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7318 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7320 LN0->getBasePtr(), EVT,
7321 LN0->getMemOperand());
7322 CombineTo(N, ExtLoad);
7323 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7324 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7327 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7328 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7329 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7330 N0.getOperand(1), false))
7331 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7338 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7339 SDValue N0 = N->getOperand(0);
7340 EVT VT = N->getValueType(0);
7343 return DAG.getUNDEF(VT);
7345 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7347 return SDValue(Res, 0);
7352 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7353 SDValue N0 = N->getOperand(0);
7354 EVT VT = N->getValueType(0);
7357 return DAG.getUNDEF(VT);
7359 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7361 return SDValue(Res, 0);
7366 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7367 SDValue N0 = N->getOperand(0);
7368 EVT VT = N->getValueType(0);
7369 bool isLE = DAG.getDataLayout().isLittleEndian();
7372 if (N0.getValueType() == N->getValueType(0))
7374 // fold (truncate c1) -> c1
7375 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7376 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7377 // fold (truncate (truncate x)) -> (truncate x)
7378 if (N0.getOpcode() == ISD::TRUNCATE)
7379 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7380 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7381 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7382 N0.getOpcode() == ISD::SIGN_EXTEND ||
7383 N0.getOpcode() == ISD::ANY_EXTEND) {
7384 // if the source is smaller than the dest, we still need an extend.
7385 if (N0.getOperand(0).getValueType().bitsLT(VT))
7386 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7387 // if the source is larger than the dest, than we just need the truncate.
7388 if (N0.getOperand(0).getValueType().bitsGT(VT))
7389 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7390 // if the source and dest are the same type, we can drop both the extend
7391 // and the truncate.
7392 return N0.getOperand(0);
7395 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
7396 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
7399 // Fold extract-and-trunc into a narrow extract. For example:
7400 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7401 // i32 y = TRUNCATE(i64 x)
7403 // v16i8 b = BITCAST (v2i64 val)
7404 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7406 // Note: We only run this optimization after type legalization (which often
7407 // creates this pattern) and before operation legalization after which
7408 // we need to be more careful about the vector instructions that we generate.
7409 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7410 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7412 EVT VecTy = N0.getOperand(0).getValueType();
7413 EVT ExTy = N0.getValueType();
7414 EVT TrTy = N->getValueType(0);
7416 unsigned NumElem = VecTy.getVectorNumElements();
7417 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7419 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7420 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7422 SDValue EltNo = N0->getOperand(1);
7423 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7424 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7425 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7426 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7429 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7430 DAG.getBitcast(NVT, N0.getOperand(0)),
7431 DAG.getConstant(Index, DL, IndexTy));
7435 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7436 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
7437 EVT SrcVT = N0.getValueType();
7438 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7439 TLI.isTruncateFree(SrcVT, VT)) {
7441 SDValue Cond = N0.getOperand(0);
7442 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7443 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7444 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7448 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
7449 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7450 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7451 TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7452 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7453 uint64_t Amt = CAmt->getZExtValue();
7454 unsigned Size = VT.getScalarSizeInBits();
7458 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7460 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7461 return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7462 DAG.getConstant(Amt, SL, AmtVT));
7467 // Fold a series of buildvector, bitcast, and truncate if possible.
7469 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7470 // (2xi32 (buildvector x, y)).
7471 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7472 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7473 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7474 N0.getOperand(0).hasOneUse()) {
7476 SDValue BuildVect = N0.getOperand(0);
7477 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7478 EVT TruncVecEltTy = VT.getVectorElementType();
7480 // Check that the element types match.
7481 if (BuildVectEltTy == TruncVecEltTy) {
7482 // Now we only need to compute the offset of the truncated elements.
7483 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7484 unsigned TruncVecNumElts = VT.getVectorNumElements();
7485 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7487 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7488 "Invalid number of elements");
7490 SmallVector<SDValue, 8> Opnds;
7491 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7492 Opnds.push_back(BuildVect.getOperand(i));
7494 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7498 // See if we can simplify the input to this truncate through knowledge that
7499 // only the low bits are being used.
7500 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7501 // Currently we only perform this optimization on scalars because vectors
7502 // may have different active low bits.
7503 if (!VT.isVector()) {
7504 if (SDValue Shorter =
7505 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7506 VT.getSizeInBits())))
7507 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7509 // fold (truncate (load x)) -> (smaller load x)
7510 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7511 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7512 if (SDValue Reduced = ReduceLoadWidth(N))
7515 // Handle the case where the load remains an extending load even
7516 // after truncation.
7517 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7518 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7519 if (!LN0->isVolatile() &&
7520 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7521 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7522 VT, LN0->getChain(), LN0->getBasePtr(),
7524 LN0->getMemOperand());
7525 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7530 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7531 // where ... are all 'undef'.
7532 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7533 SmallVector<EVT, 8> VTs;
7536 unsigned NumDefs = 0;
7538 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7539 SDValue X = N0.getOperand(i);
7545 // Stop if more than one members are non-undef.
7548 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7549 VT.getVectorElementType(),
7550 X.getValueType().getVectorNumElements()));
7554 return DAG.getUNDEF(VT);
7557 assert(V.getNode() && "The single defined operand is empty!");
7558 SmallVector<SDValue, 8> Opnds;
7559 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7561 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7564 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7565 AddToWorklist(NV.getNode());
7566 Opnds.push_back(NV);
7568 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7572 // Fold truncate of a bitcast of a vector to an extract of the low vector
7575 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7576 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7577 SDValue VecSrc = N0.getOperand(0);
7578 EVT SrcVT = VecSrc.getValueType();
7579 if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7580 (!LegalOperations ||
7581 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7584 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7585 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7586 VecSrc, DAG.getConstant(0, SL, IdxVT));
7590 // Simplify the operands using demanded-bits information.
7591 if (!VT.isVector() &&
7592 SimplifyDemandedBits(SDValue(N, 0)))
7593 return SDValue(N, 0);
7598 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7599 SDValue Elt = N->getOperand(i);
7600 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7601 return Elt.getNode();
7602 return Elt.getOperand(Elt.getResNo()).getNode();
7605 /// build_pair (load, load) -> load
7606 /// if load locations are consecutive.
7607 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7608 assert(N->getOpcode() == ISD::BUILD_PAIR);
7610 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7611 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7612 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7613 LD1->getAddressSpace() != LD2->getAddressSpace())
7615 EVT LD1VT = LD1->getValueType(0);
7616 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7617 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7618 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7619 unsigned Align = LD1->getAlignment();
7620 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7621 VT.getTypeForEVT(*DAG.getContext()));
7623 if (NewAlign <= Align &&
7624 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7625 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
7626 LD1->getPointerInfo(), Align);
7632 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7633 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7634 // and Lo parts; on big-endian machines it doesn't.
7635 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7638 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7639 const TargetLowering &TLI) {
7640 // If this is not a bitcast to an FP type or if the target doesn't have
7641 // IEEE754-compliant FP logic, we're done.
7642 EVT VT = N->getValueType(0);
7643 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7646 // TODO: Use splat values for the constant-checking below and remove this
7648 SDValue N0 = N->getOperand(0);
7649 EVT SourceVT = N0.getValueType();
7650 if (SourceVT.isVector())
7655 switch (N0.getOpcode()) {
7657 FPOpcode = ISD::FABS;
7658 SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7661 FPOpcode = ISD::FNEG;
7662 SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7664 // TODO: ISD::OR --> ISD::FNABS?
7669 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7670 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7671 SDValue LogicOp0 = N0.getOperand(0);
7672 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7673 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7674 LogicOp0.getOpcode() == ISD::BITCAST &&
7675 LogicOp0->getOperand(0).getValueType() == VT)
7676 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7681 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7682 SDValue N0 = N->getOperand(0);
7683 EVT VT = N->getValueType(0);
7685 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7686 // Only do this before legalize, since afterward the target may be depending
7687 // on the bitconvert.
7688 // First check to see if this is all constant.
7690 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7692 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7694 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7695 assert(!DestEltVT.isVector() &&
7696 "Element type of vector ValueType must not be vector!");
7698 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7701 // If the input is a constant, let getNode fold it.
7702 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7703 // If we can't allow illegal operations, we need to check that this is just
7704 // a fp -> int or int -> conversion and that the resulting operation will
7706 if (!LegalOperations ||
7707 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7708 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7709 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7710 TLI.isOperationLegal(ISD::Constant, VT)))
7711 return DAG.getBitcast(VT, N0);
7714 // (conv (conv x, t1), t2) -> (conv x, t2)
7715 if (N0.getOpcode() == ISD::BITCAST)
7716 return DAG.getBitcast(VT, N0.getOperand(0));
7718 // fold (conv (load x)) -> (load (conv*)x)
7719 // If the resultant load doesn't need a higher alignment than the original!
7720 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7721 // Do not change the width of a volatile load.
7722 !cast<LoadSDNode>(N0)->isVolatile() &&
7723 // Do not remove the cast if the types differ in endian layout.
7724 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7725 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7726 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7727 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7728 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7729 unsigned OrigAlign = LN0->getAlignment();
7732 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7733 LN0->getAddressSpace(), OrigAlign, &Fast) &&
7736 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7737 LN0->getPointerInfo(), OrigAlign,
7738 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7739 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7744 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7747 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7748 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7751 // fold (bitcast (fneg x)) ->
7752 // flipbit = signbit
7753 // (xor (bitcast x) (build_pair flipbit, flipbit))
7755 // fold (bitcast (fabs x)) ->
7756 // flipbit = (and (extract_element (bitcast x), 0), signbit)
7757 // (xor (bitcast x) (build_pair flipbit, flipbit))
7758 // This often reduces constant pool loads.
7759 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7760 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7761 N0.getNode()->hasOneUse() && VT.isInteger() &&
7762 !VT.isVector() && !N0.getValueType().isVector()) {
7763 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7764 AddToWorklist(NewConv.getNode());
7767 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7768 assert(VT.getSizeInBits() == 128);
7769 SDValue SignBit = DAG.getConstant(
7770 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7772 if (N0.getOpcode() == ISD::FNEG) {
7774 AddToWorklist(FlipBit.getNode());
7776 assert(N0.getOpcode() == ISD::FABS);
7778 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7779 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7781 AddToWorklist(Hi.getNode());
7782 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7783 AddToWorklist(FlipBit.getNode());
7786 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7787 AddToWorklist(FlipBits.getNode());
7788 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7790 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7791 if (N0.getOpcode() == ISD::FNEG)
7792 return DAG.getNode(ISD::XOR, DL, VT,
7793 NewConv, DAG.getConstant(SignBit, DL, VT));
7794 assert(N0.getOpcode() == ISD::FABS);
7795 return DAG.getNode(ISD::AND, DL, VT,
7796 NewConv, DAG.getConstant(~SignBit, DL, VT));
7799 // fold (bitconvert (fcopysign cst, x)) ->
7800 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7801 // Note that we don't handle (copysign x, cst) because this can always be
7802 // folded to an fneg or fabs.
7805 // fold (bitcast (fcopysign cst, x)) ->
7806 // flipbit = (and (extract_element
7807 // (xor (bitcast cst), (bitcast x)), 0),
7809 // (xor (bitcast cst) (build_pair flipbit, flipbit))
7810 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7811 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7812 VT.isInteger() && !VT.isVector()) {
7813 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
7814 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7815 if (isTypeLegal(IntXVT)) {
7816 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7817 AddToWorklist(X.getNode());
7819 // If X has a different width than the result/lhs, sext it or truncate it.
7820 unsigned VTWidth = VT.getSizeInBits();
7821 if (OrigXWidth < VTWidth) {
7822 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7823 AddToWorklist(X.getNode());
7824 } else if (OrigXWidth > VTWidth) {
7825 // To get the sign bit in the right place, we have to shift it right
7826 // before truncating.
7828 X = DAG.getNode(ISD::SRL, DL,
7829 X.getValueType(), X,
7830 DAG.getConstant(OrigXWidth-VTWidth, DL,
7832 AddToWorklist(X.getNode());
7833 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7834 AddToWorklist(X.getNode());
7837 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7838 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7839 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7840 AddToWorklist(Cst.getNode());
7841 SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7842 AddToWorklist(X.getNode());
7843 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7844 AddToWorklist(XorResult.getNode());
7845 SDValue XorResult64 = DAG.getNode(
7846 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7847 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7849 AddToWorklist(XorResult64.getNode());
7851 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7852 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7853 AddToWorklist(FlipBit.getNode());
7855 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7856 AddToWorklist(FlipBits.getNode());
7857 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7859 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7860 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7861 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7862 AddToWorklist(X.getNode());
7864 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7865 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7866 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7867 AddToWorklist(Cst.getNode());
7869 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7873 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7874 if (N0.getOpcode() == ISD::BUILD_PAIR)
7875 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7878 // Remove double bitcasts from shuffles - this is often a legacy of
7879 // XformToShuffleWithZero being used to combine bitmaskings (of
7880 // float vectors bitcast to integer vectors) into shuffles.
7881 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7882 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7883 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7884 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7885 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7886 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7888 // If operands are a bitcast, peek through if it casts the original VT.
7889 // If operands are a constant, just bitcast back to original VT.
7890 auto PeekThroughBitcast = [&](SDValue Op) {
7891 if (Op.getOpcode() == ISD::BITCAST &&
7892 Op.getOperand(0).getValueType() == VT)
7893 return SDValue(Op.getOperand(0));
7894 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7895 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7896 return DAG.getBitcast(VT, Op);
7900 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7901 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7906 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7907 SmallVector<int, 8> NewMask;
7908 for (int M : SVN->getMask())
7909 for (int i = 0; i != MaskScale; ++i)
7910 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7912 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7914 std::swap(SV0, SV1);
7915 ShuffleVectorSDNode::commuteMask(NewMask);
7916 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7920 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7926 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7927 EVT VT = N->getValueType(0);
7928 return CombineConsecutiveLoads(N, VT);
7931 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7932 /// operands. DstEltVT indicates the destination element value type.
7933 SDValue DAGCombiner::
7934 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7935 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7937 // If this is already the right type, we're done.
7938 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7940 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7941 unsigned DstBitSize = DstEltVT.getSizeInBits();
7943 // If this is a conversion of N elements of one type to N elements of another
7944 // type, convert each element. This handles FP<->INT cases.
7945 if (SrcBitSize == DstBitSize) {
7946 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7947 BV->getValueType(0).getVectorNumElements());
7949 // Due to the FP element handling below calling this routine recursively,
7950 // we can end up with a scalar-to-vector node here.
7951 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7952 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7953 DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7955 SmallVector<SDValue, 8> Ops;
7956 for (SDValue Op : BV->op_values()) {
7957 // If the vector element type is not legal, the BUILD_VECTOR operands
7958 // are promoted and implicitly truncated. Make that explicit here.
7959 if (Op.getValueType() != SrcEltVT)
7960 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7961 Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7962 AddToWorklist(Ops.back().getNode());
7964 return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7967 // Otherwise, we're growing or shrinking the elements. To avoid having to
7968 // handle annoying details of growing/shrinking FP values, we convert them to
7970 if (SrcEltVT.isFloatingPoint()) {
7971 // Convert the input float vector to a int vector where the elements are the
7973 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7974 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7978 // Now we know the input is an integer vector. If the output is a FP type,
7979 // convert to integer first, then to FP of the right size.
7980 if (DstEltVT.isFloatingPoint()) {
7981 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7982 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7984 // Next, convert to FP elements of the same size.
7985 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7990 // Okay, we know the src/dst types are both integers of differing types.
7991 // Handling growing first.
7992 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7993 if (SrcBitSize < DstBitSize) {
7994 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7996 SmallVector<SDValue, 8> Ops;
7997 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7998 i += NumInputsPerOutput) {
7999 bool isLE = DAG.getDataLayout().isLittleEndian();
8000 APInt NewBits = APInt(DstBitSize, 0);
8001 bool EltIsUndef = true;
8002 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8003 // Shift the previously computed bits over.
8004 NewBits <<= SrcBitSize;
8005 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8006 if (Op.isUndef()) continue;
8009 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8010 zextOrTrunc(SrcBitSize).zext(DstBitSize);
8014 Ops.push_back(DAG.getUNDEF(DstEltVT));
8016 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8019 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8020 return DAG.getBuildVector(VT, DL, Ops);
8023 // Finally, this must be the case where we are shrinking elements: each input
8024 // turns into multiple outputs.
8025 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8026 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8027 NumOutputsPerInput*BV->getNumOperands());
8028 SmallVector<SDValue, 8> Ops;
8030 for (const SDValue &Op : BV->op_values()) {
8032 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8036 APInt OpVal = cast<ConstantSDNode>(Op)->
8037 getAPIntValue().zextOrTrunc(SrcBitSize);
8039 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8040 APInt ThisVal = OpVal.trunc(DstBitSize);
8041 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8042 OpVal = OpVal.lshr(DstBitSize);
8045 // For big endian targets, swap the order of the pieces of each element.
8046 if (DAG.getDataLayout().isBigEndian())
8047 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8050 return DAG.getBuildVector(VT, DL, Ops);
8053 /// Try to perform FMA combining on a given FADD node.
8054 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8055 SDValue N0 = N->getOperand(0);
8056 SDValue N1 = N->getOperand(1);
8057 EVT VT = N->getValueType(0);
8060 const TargetOptions &Options = DAG.getTarget().Options;
8062 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8064 // Floating-point multiply-add with intermediate rounding.
8065 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8067 // Floating-point multiply-add without intermediate rounding.
8069 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8070 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8072 // No valid opcode, do not combine.
8073 if (!HasFMAD && !HasFMA)
8076 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8078 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8081 // Always prefer FMAD to FMA for precision.
8082 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8083 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8084 bool LookThroughFPExt = TLI.isFPExtFree(VT);
8086 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8087 // prefer to fold the multiply with fewer uses.
8088 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
8089 N1.getOpcode() == ISD::FMUL) {
8090 if (N0.getNode()->use_size() > N1.getNode()->use_size())
8094 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8095 if (N0.getOpcode() == ISD::FMUL &&
8096 (Aggressive || N0->hasOneUse())) {
8097 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8098 N0.getOperand(0), N0.getOperand(1), N1);
8101 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8102 // Note: Commutes FADD operands.
8103 if (N1.getOpcode() == ISD::FMUL &&
8104 (Aggressive || N1->hasOneUse())) {
8105 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8106 N1.getOperand(0), N1.getOperand(1), N0);
8109 // Look through FP_EXTEND nodes to do more combining.
8110 if (AllowFusion && LookThroughFPExt) {
8111 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8112 if (N0.getOpcode() == ISD::FP_EXTEND) {
8113 SDValue N00 = N0.getOperand(0);
8114 if (N00.getOpcode() == ISD::FMUL)
8115 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8116 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8118 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8119 N00.getOperand(1)), N1);
8122 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8123 // Note: Commutes FADD operands.
8124 if (N1.getOpcode() == ISD::FP_EXTEND) {
8125 SDValue N10 = N1.getOperand(0);
8126 if (N10.getOpcode() == ISD::FMUL)
8127 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8128 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8130 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8131 N10.getOperand(1)), N0);
8135 // More folding opportunities when target permits.
8136 if ((AllowFusion || HasFMAD) && Aggressive) {
8137 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8138 if (N0.getOpcode() == PreferredFusedOpcode &&
8139 N0.getOperand(2).getOpcode() == ISD::FMUL) {
8140 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8141 N0.getOperand(0), N0.getOperand(1),
8142 DAG.getNode(PreferredFusedOpcode, SL, VT,
8143 N0.getOperand(2).getOperand(0),
8144 N0.getOperand(2).getOperand(1),
8148 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8149 if (N1->getOpcode() == PreferredFusedOpcode &&
8150 N1.getOperand(2).getOpcode() == ISD::FMUL) {
8151 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8152 N1.getOperand(0), N1.getOperand(1),
8153 DAG.getNode(PreferredFusedOpcode, SL, VT,
8154 N1.getOperand(2).getOperand(0),
8155 N1.getOperand(2).getOperand(1),
8159 if (AllowFusion && LookThroughFPExt) {
8160 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8161 // -> (fma x, y, (fma (fpext u), (fpext v), z))
8162 auto FoldFAddFMAFPExtFMul = [&] (
8163 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8164 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8165 DAG.getNode(PreferredFusedOpcode, SL, VT,
8166 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8167 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8170 if (N0.getOpcode() == PreferredFusedOpcode) {
8171 SDValue N02 = N0.getOperand(2);
8172 if (N02.getOpcode() == ISD::FP_EXTEND) {
8173 SDValue N020 = N02.getOperand(0);
8174 if (N020.getOpcode() == ISD::FMUL)
8175 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8176 N020.getOperand(0), N020.getOperand(1),
8181 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8182 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8183 // FIXME: This turns two single-precision and one double-precision
8184 // operation into two double-precision operations, which might not be
8185 // interesting for all targets, especially GPUs.
8186 auto FoldFAddFPExtFMAFMul = [&] (
8187 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8188 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8189 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8190 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8191 DAG.getNode(PreferredFusedOpcode, SL, VT,
8192 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8193 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8196 if (N0.getOpcode() == ISD::FP_EXTEND) {
8197 SDValue N00 = N0.getOperand(0);
8198 if (N00.getOpcode() == PreferredFusedOpcode) {
8199 SDValue N002 = N00.getOperand(2);
8200 if (N002.getOpcode() == ISD::FMUL)
8201 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8202 N002.getOperand(0), N002.getOperand(1),
8207 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8208 // -> (fma y, z, (fma (fpext u), (fpext v), x))
8209 if (N1.getOpcode() == PreferredFusedOpcode) {
8210 SDValue N12 = N1.getOperand(2);
8211 if (N12.getOpcode() == ISD::FP_EXTEND) {
8212 SDValue N120 = N12.getOperand(0);
8213 if (N120.getOpcode() == ISD::FMUL)
8214 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8215 N120.getOperand(0), N120.getOperand(1),
8220 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8221 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8222 // FIXME: This turns two single-precision and one double-precision
8223 // operation into two double-precision operations, which might not be
8224 // interesting for all targets, especially GPUs.
8225 if (N1.getOpcode() == ISD::FP_EXTEND) {
8226 SDValue N10 = N1.getOperand(0);
8227 if (N10.getOpcode() == PreferredFusedOpcode) {
8228 SDValue N102 = N10.getOperand(2);
8229 if (N102.getOpcode() == ISD::FMUL)
8230 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8231 N102.getOperand(0), N102.getOperand(1),
8241 /// Try to perform FMA combining on a given FSUB node.
8242 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8243 SDValue N0 = N->getOperand(0);
8244 SDValue N1 = N->getOperand(1);
8245 EVT VT = N->getValueType(0);
8248 const TargetOptions &Options = DAG.getTarget().Options;
8250 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8252 // Floating-point multiply-add with intermediate rounding.
8253 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8255 // Floating-point multiply-add without intermediate rounding.
8257 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8258 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8260 // No valid opcode, do not combine.
8261 if (!HasFMAD && !HasFMA)
8264 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8265 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8268 // Always prefer FMAD to FMA for precision.
8269 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8270 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8271 bool LookThroughFPExt = TLI.isFPExtFree(VT);
8273 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8274 if (N0.getOpcode() == ISD::FMUL &&
8275 (Aggressive || N0->hasOneUse())) {
8276 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8277 N0.getOperand(0), N0.getOperand(1),
8278 DAG.getNode(ISD::FNEG, SL, VT, N1));
8281 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8282 // Note: Commutes FSUB operands.
8283 if (N1.getOpcode() == ISD::FMUL &&
8284 (Aggressive || N1->hasOneUse()))
8285 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8286 DAG.getNode(ISD::FNEG, SL, VT,
8288 N1.getOperand(1), N0);
8290 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8291 if (N0.getOpcode() == ISD::FNEG &&
8292 N0.getOperand(0).getOpcode() == ISD::FMUL &&
8293 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8294 SDValue N00 = N0.getOperand(0).getOperand(0);
8295 SDValue N01 = N0.getOperand(0).getOperand(1);
8296 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8297 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8298 DAG.getNode(ISD::FNEG, SL, VT, N1));
8301 // Look through FP_EXTEND nodes to do more combining.
8302 if (AllowFusion && LookThroughFPExt) {
8303 // fold (fsub (fpext (fmul x, y)), z)
8304 // -> (fma (fpext x), (fpext y), (fneg z))
8305 if (N0.getOpcode() == ISD::FP_EXTEND) {
8306 SDValue N00 = N0.getOperand(0);
8307 if (N00.getOpcode() == ISD::FMUL)
8308 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8309 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8311 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8313 DAG.getNode(ISD::FNEG, SL, VT, N1));
8316 // fold (fsub x, (fpext (fmul y, z)))
8317 // -> (fma (fneg (fpext y)), (fpext z), x)
8318 // Note: Commutes FSUB operands.
8319 if (N1.getOpcode() == ISD::FP_EXTEND) {
8320 SDValue N10 = N1.getOperand(0);
8321 if (N10.getOpcode() == ISD::FMUL)
8322 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8323 DAG.getNode(ISD::FNEG, SL, VT,
8324 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8325 N10.getOperand(0))),
8326 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8331 // fold (fsub (fpext (fneg (fmul, x, y))), z)
8332 // -> (fneg (fma (fpext x), (fpext y), z))
8333 // Note: This could be removed with appropriate canonicalization of the
8334 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8335 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8336 // from implementing the canonicalization in visitFSUB.
8337 if (N0.getOpcode() == ISD::FP_EXTEND) {
8338 SDValue N00 = N0.getOperand(0);
8339 if (N00.getOpcode() == ISD::FNEG) {
8340 SDValue N000 = N00.getOperand(0);
8341 if (N000.getOpcode() == ISD::FMUL) {
8342 return DAG.getNode(ISD::FNEG, SL, VT,
8343 DAG.getNode(PreferredFusedOpcode, SL, VT,
8344 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8345 N000.getOperand(0)),
8346 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8347 N000.getOperand(1)),
8353 // fold (fsub (fneg (fpext (fmul, x, y))), z)
8354 // -> (fneg (fma (fpext x)), (fpext y), z)
8355 // Note: This could be removed with appropriate canonicalization of the
8356 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8357 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8358 // from implementing the canonicalization in visitFSUB.
8359 if (N0.getOpcode() == ISD::FNEG) {
8360 SDValue N00 = N0.getOperand(0);
8361 if (N00.getOpcode() == ISD::FP_EXTEND) {
8362 SDValue N000 = N00.getOperand(0);
8363 if (N000.getOpcode() == ISD::FMUL) {
8364 return DAG.getNode(ISD::FNEG, SL, VT,
8365 DAG.getNode(PreferredFusedOpcode, SL, VT,
8366 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8367 N000.getOperand(0)),
8368 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8369 N000.getOperand(1)),
8377 // More folding opportunities when target permits.
8378 if ((AllowFusion || HasFMAD) && Aggressive) {
8379 // fold (fsub (fma x, y, (fmul u, v)), z)
8380 // -> (fma x, y (fma u, v, (fneg z)))
8381 if (N0.getOpcode() == PreferredFusedOpcode &&
8382 N0.getOperand(2).getOpcode() == ISD::FMUL) {
8383 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8384 N0.getOperand(0), N0.getOperand(1),
8385 DAG.getNode(PreferredFusedOpcode, SL, VT,
8386 N0.getOperand(2).getOperand(0),
8387 N0.getOperand(2).getOperand(1),
8388 DAG.getNode(ISD::FNEG, SL, VT,
8392 // fold (fsub x, (fma y, z, (fmul u, v)))
8393 // -> (fma (fneg y), z, (fma (fneg u), v, x))
8394 if (N1.getOpcode() == PreferredFusedOpcode &&
8395 N1.getOperand(2).getOpcode() == ISD::FMUL) {
8396 SDValue N20 = N1.getOperand(2).getOperand(0);
8397 SDValue N21 = N1.getOperand(2).getOperand(1);
8398 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8399 DAG.getNode(ISD::FNEG, SL, VT,
8402 DAG.getNode(PreferredFusedOpcode, SL, VT,
8403 DAG.getNode(ISD::FNEG, SL, VT, N20),
8408 if (AllowFusion && LookThroughFPExt) {
8409 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8410 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8411 if (N0.getOpcode() == PreferredFusedOpcode) {
8412 SDValue N02 = N0.getOperand(2);
8413 if (N02.getOpcode() == ISD::FP_EXTEND) {
8414 SDValue N020 = N02.getOperand(0);
8415 if (N020.getOpcode() == ISD::FMUL)
8416 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8417 N0.getOperand(0), N0.getOperand(1),
8418 DAG.getNode(PreferredFusedOpcode, SL, VT,
8419 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8420 N020.getOperand(0)),
8421 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8422 N020.getOperand(1)),
8423 DAG.getNode(ISD::FNEG, SL, VT,
8428 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8429 // -> (fma (fpext x), (fpext y),
8430 // (fma (fpext u), (fpext v), (fneg z)))
8431 // FIXME: This turns two single-precision and one double-precision
8432 // operation into two double-precision operations, which might not be
8433 // interesting for all targets, especially GPUs.
8434 if (N0.getOpcode() == ISD::FP_EXTEND) {
8435 SDValue N00 = N0.getOperand(0);
8436 if (N00.getOpcode() == PreferredFusedOpcode) {
8437 SDValue N002 = N00.getOperand(2);
8438 if (N002.getOpcode() == ISD::FMUL)
8439 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8440 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8442 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8444 DAG.getNode(PreferredFusedOpcode, SL, VT,
8445 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8446 N002.getOperand(0)),
8447 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8448 N002.getOperand(1)),
8449 DAG.getNode(ISD::FNEG, SL, VT,
8454 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8455 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8456 if (N1.getOpcode() == PreferredFusedOpcode &&
8457 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8458 SDValue N120 = N1.getOperand(2).getOperand(0);
8459 if (N120.getOpcode() == ISD::FMUL) {
8460 SDValue N1200 = N120.getOperand(0);
8461 SDValue N1201 = N120.getOperand(1);
8462 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8463 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8465 DAG.getNode(PreferredFusedOpcode, SL, VT,
8466 DAG.getNode(ISD::FNEG, SL, VT,
8467 DAG.getNode(ISD::FP_EXTEND, SL,
8469 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8475 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8476 // -> (fma (fneg (fpext y)), (fpext z),
8477 // (fma (fneg (fpext u)), (fpext v), x))
8478 // FIXME: This turns two single-precision and one double-precision
8479 // operation into two double-precision operations, which might not be
8480 // interesting for all targets, especially GPUs.
8481 if (N1.getOpcode() == ISD::FP_EXTEND &&
8482 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8483 SDValue N100 = N1.getOperand(0).getOperand(0);
8484 SDValue N101 = N1.getOperand(0).getOperand(1);
8485 SDValue N102 = N1.getOperand(0).getOperand(2);
8486 if (N102.getOpcode() == ISD::FMUL) {
8487 SDValue N1020 = N102.getOperand(0);
8488 SDValue N1021 = N102.getOperand(1);
8489 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8490 DAG.getNode(ISD::FNEG, SL, VT,
8491 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8493 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8494 DAG.getNode(PreferredFusedOpcode, SL, VT,
8495 DAG.getNode(ISD::FNEG, SL, VT,
8496 DAG.getNode(ISD::FP_EXTEND, SL,
8498 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8509 /// Try to perform FMA combining on a given FMUL node based on the distributive
8510 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
8511 /// subtraction instead of addition).
8512 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
8513 SDValue N0 = N->getOperand(0);
8514 SDValue N1 = N->getOperand(1);
8515 EVT VT = N->getValueType(0);
8518 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8520 const TargetOptions &Options = DAG.getTarget().Options;
8522 // The transforms below are incorrect when x == 0 and y == inf, because the
8523 // intermediate multiplication produces a nan.
8524 if (!Options.NoInfsFPMath)
8527 // Floating-point multiply-add without intermediate rounding.
8529 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
8530 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8531 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8533 // Floating-point multiply-add with intermediate rounding. This can result
8534 // in a less precise result due to the changed rounding order.
8535 bool HasFMAD = Options.UnsafeFPMath &&
8536 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8538 // No valid opcode, do not combine.
8539 if (!HasFMAD && !HasFMA)
8542 // Always prefer FMAD to FMA for precision.
8543 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8544 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8546 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8547 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8548 auto FuseFADD = [&](SDValue X, SDValue Y) {
8549 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8550 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8551 if (XC1 && XC1->isExactlyValue(+1.0))
8552 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8553 if (XC1 && XC1->isExactlyValue(-1.0))
8554 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8555 DAG.getNode(ISD::FNEG, SL, VT, Y));
8560 if (SDValue FMA = FuseFADD(N0, N1))
8562 if (SDValue FMA = FuseFADD(N1, N0))
8565 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8566 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8567 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8568 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8569 auto FuseFSUB = [&](SDValue X, SDValue Y) {
8570 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8571 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8572 if (XC0 && XC0->isExactlyValue(+1.0))
8573 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8574 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8576 if (XC0 && XC0->isExactlyValue(-1.0))
8577 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8578 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8579 DAG.getNode(ISD::FNEG, SL, VT, Y));
8581 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8582 if (XC1 && XC1->isExactlyValue(+1.0))
8583 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8584 DAG.getNode(ISD::FNEG, SL, VT, Y));
8585 if (XC1 && XC1->isExactlyValue(-1.0))
8586 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8591 if (SDValue FMA = FuseFSUB(N0, N1))
8593 if (SDValue FMA = FuseFSUB(N1, N0))
8599 SDValue DAGCombiner::visitFADD(SDNode *N) {
8600 SDValue N0 = N->getOperand(0);
8601 SDValue N1 = N->getOperand(1);
8602 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8603 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8604 EVT VT = N->getValueType(0);
8606 const TargetOptions &Options = DAG.getTarget().Options;
8607 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8611 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8614 // fold (fadd c1, c2) -> c1 + c2
8616 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8618 // canonicalize constant to RHS
8619 if (N0CFP && !N1CFP)
8620 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8622 // fold (fadd A, (fneg B)) -> (fsub A, B)
8623 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8624 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8625 return DAG.getNode(ISD::FSUB, DL, VT, N0,
8626 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8628 // fold (fadd (fneg A), B) -> (fsub B, A)
8629 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8630 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8631 return DAG.getNode(ISD::FSUB, DL, VT, N1,
8632 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8634 // FIXME: Auto-upgrade the target/function-level option.
8635 if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8636 // fold (fadd A, 0) -> A
8637 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8642 // If 'unsafe math' is enabled, fold lots of things.
8643 if (Options.UnsafeFPMath) {
8644 // No FP constant should be created after legalization as Instruction
8645 // Selection pass has a hard time dealing with FP constants.
8646 bool AllowNewConst = (Level < AfterLegalizeDAG);
8648 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8649 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8650 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8651 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8652 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8656 // If allowed, fold (fadd (fneg x), x) -> 0.0
8657 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8658 return DAG.getConstantFP(0.0, DL, VT);
8660 // If allowed, fold (fadd x, (fneg x)) -> 0.0
8661 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8662 return DAG.getConstantFP(0.0, DL, VT);
8664 // We can fold chains of FADD's of the same value into multiplications.
8665 // This transform is not safe in general because we are reducing the number
8666 // of rounding steps.
8667 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8668 if (N0.getOpcode() == ISD::FMUL) {
8669 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8670 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8672 // (fadd (fmul x, c), x) -> (fmul x, c+1)
8673 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8674 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8675 DAG.getConstantFP(1.0, DL, VT), Flags);
8676 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8679 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8680 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8681 N1.getOperand(0) == N1.getOperand(1) &&
8682 N0.getOperand(0) == N1.getOperand(0)) {
8683 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8684 DAG.getConstantFP(2.0, DL, VT), Flags);
8685 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8689 if (N1.getOpcode() == ISD::FMUL) {
8690 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8691 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8693 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8694 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8695 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8696 DAG.getConstantFP(1.0, DL, VT), Flags);
8697 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8700 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8701 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8702 N0.getOperand(0) == N0.getOperand(1) &&
8703 N1.getOperand(0) == N0.getOperand(0)) {
8704 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8705 DAG.getConstantFP(2.0, DL, VT), Flags);
8706 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8710 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8711 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8712 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8713 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8714 (N0.getOperand(0) == N1)) {
8715 return DAG.getNode(ISD::FMUL, DL, VT,
8716 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8720 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8721 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8722 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8723 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8724 N1.getOperand(0) == N0) {
8725 return DAG.getNode(ISD::FMUL, DL, VT,
8726 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8730 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8731 if (AllowNewConst &&
8732 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8733 N0.getOperand(0) == N0.getOperand(1) &&
8734 N1.getOperand(0) == N1.getOperand(1) &&
8735 N0.getOperand(0) == N1.getOperand(0)) {
8736 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8737 DAG.getConstantFP(4.0, DL, VT), Flags);
8740 } // enable-unsafe-fp-math
8742 // FADD -> FMA combines:
8743 if (SDValue Fused = visitFADDForFMACombine(N)) {
8744 AddToWorklist(Fused.getNode());
8750 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8751 SDValue N0 = N->getOperand(0);
8752 SDValue N1 = N->getOperand(1);
8753 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8754 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8755 EVT VT = N->getValueType(0);
8757 const TargetOptions &Options = DAG.getTarget().Options;
8758 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8762 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8765 // fold (fsub c1, c2) -> c1-c2
8767 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
8769 // fold (fsub A, (fneg B)) -> (fadd A, B)
8770 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8771 return DAG.getNode(ISD::FADD, DL, VT, N0,
8772 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8774 // FIXME: Auto-upgrade the target/function-level option.
8775 if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8776 // (fsub 0, B) -> -B
8777 if (N0CFP && N0CFP->isZero()) {
8778 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8779 return GetNegatedExpression(N1, DAG, LegalOperations);
8780 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8781 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
8785 // If 'unsafe math' is enabled, fold lots of things.
8786 if (Options.UnsafeFPMath) {
8788 if (N1CFP && N1CFP->isZero())
8791 // (fsub x, x) -> 0.0
8793 return DAG.getConstantFP(0.0f, DL, VT);
8795 // (fsub x, (fadd x, y)) -> (fneg y)
8796 // (fsub x, (fadd y, x)) -> (fneg y)
8797 if (N1.getOpcode() == ISD::FADD) {
8798 SDValue N10 = N1->getOperand(0);
8799 SDValue N11 = N1->getOperand(1);
8801 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8802 return GetNegatedExpression(N11, DAG, LegalOperations);
8804 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8805 return GetNegatedExpression(N10, DAG, LegalOperations);
8809 // FSUB -> FMA combines:
8810 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8811 AddToWorklist(Fused.getNode());
8818 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8819 SDValue N0 = N->getOperand(0);
8820 SDValue N1 = N->getOperand(1);
8821 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8822 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8823 EVT VT = N->getValueType(0);
8825 const TargetOptions &Options = DAG.getTarget().Options;
8826 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8829 if (VT.isVector()) {
8830 // This just handles C1 * C2 for vectors. Other vector folds are below.
8831 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8835 // fold (fmul c1, c2) -> c1*c2
8837 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8839 // canonicalize constant to RHS
8840 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8841 !isConstantFPBuildVectorOrConstantFP(N1))
8842 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8844 // fold (fmul A, 1.0) -> A
8845 if (N1CFP && N1CFP->isExactlyValue(1.0))
8848 if (Options.UnsafeFPMath) {
8849 // fold (fmul A, 0) -> 0
8850 if (N1CFP && N1CFP->isZero())
8853 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8854 if (N0.getOpcode() == ISD::FMUL) {
8855 // Fold scalars or any vector constants (not just splats).
8856 // This fold is done in general by InstCombine, but extra fmul insts
8857 // may have been generated during lowering.
8858 SDValue N00 = N0.getOperand(0);
8859 SDValue N01 = N0.getOperand(1);
8860 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8861 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8862 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8864 // Check 1: Make sure that the first operand of the inner multiply is NOT
8865 // a constant. Otherwise, we may induce infinite looping.
8866 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8867 // Check 2: Make sure that the second operand of the inner multiply and
8868 // the second operand of the outer multiply are constants.
8869 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8870 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8871 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8872 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8877 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8878 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8879 // during an early run of DAGCombiner can prevent folding with fmuls
8880 // inserted during lowering.
8881 if (N0.getOpcode() == ISD::FADD &&
8882 (N0.getOperand(0) == N0.getOperand(1)) &&
8884 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8885 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8886 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8890 // fold (fmul X, 2.0) -> (fadd X, X)
8891 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8892 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8894 // fold (fmul X, -1.0) -> (fneg X)
8895 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8896 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8897 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8899 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8900 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8901 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8902 // Both can be negated for free, check to see if at least one is cheaper
8904 if (LHSNeg == 2 || RHSNeg == 2)
8905 return DAG.getNode(ISD::FMUL, DL, VT,
8906 GetNegatedExpression(N0, DAG, LegalOperations),
8907 GetNegatedExpression(N1, DAG, LegalOperations),
8912 // FMUL -> FMA combines:
8913 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
8914 AddToWorklist(Fused.getNode());
8921 SDValue DAGCombiner::visitFMA(SDNode *N) {
8922 SDValue N0 = N->getOperand(0);
8923 SDValue N1 = N->getOperand(1);
8924 SDValue N2 = N->getOperand(2);
8925 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8926 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8927 EVT VT = N->getValueType(0);
8929 const TargetOptions &Options = DAG.getTarget().Options;
8931 // Constant fold FMA.
8932 if (isa<ConstantFPSDNode>(N0) &&
8933 isa<ConstantFPSDNode>(N1) &&
8934 isa<ConstantFPSDNode>(N2)) {
8935 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
8938 if (Options.UnsafeFPMath) {
8939 if (N0CFP && N0CFP->isZero())
8941 if (N1CFP && N1CFP->isZero())
8944 // TODO: The FMA node should have flags that propagate to these nodes.
8945 if (N0CFP && N0CFP->isExactlyValue(1.0))
8946 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8947 if (N1CFP && N1CFP->isExactlyValue(1.0))
8948 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8950 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8951 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8952 !isConstantFPBuildVectorOrConstantFP(N1))
8953 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8955 // TODO: FMA nodes should have flags that propagate to the created nodes.
8956 // For now, create a Flags object for use with all unsafe math transforms.
8958 Flags.setUnsafeAlgebra(true);
8960 if (Options.UnsafeFPMath) {
8961 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8962 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8963 isConstantFPBuildVectorOrConstantFP(N1) &&
8964 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8965 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8966 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
8970 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8971 if (N0.getOpcode() == ISD::FMUL &&
8972 isConstantFPBuildVectorOrConstantFP(N1) &&
8973 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8974 return DAG.getNode(ISD::FMA, DL, VT,
8976 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
8982 // (fma x, 1, y) -> (fadd x, y)
8983 // (fma x, -1, y) -> (fadd (fneg x), y)
8985 if (N1CFP->isExactlyValue(1.0))
8986 // TODO: The FMA node should have flags that propagate to this node.
8987 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
8989 if (N1CFP->isExactlyValue(-1.0) &&
8990 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8991 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
8992 AddToWorklist(RHSNeg.getNode());
8993 // TODO: The FMA node should have flags that propagate to this node.
8994 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
8998 if (Options.UnsafeFPMath) {
8999 // (fma x, c, x) -> (fmul x, (c+1))
9000 if (N1CFP && N0 == N2) {
9001 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9002 DAG.getNode(ISD::FADD, DL, VT, N1,
9003 DAG.getConstantFP(1.0, DL, VT), &Flags),
9007 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9008 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9009 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9010 DAG.getNode(ISD::FADD, DL, VT, N1,
9011 DAG.getConstantFP(-1.0, DL, VT), &Flags),
9019 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9021 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9022 // Notice that this is not always beneficial. One reason is different targets
9023 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9024 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9025 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9026 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9027 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9028 const SDNodeFlags *Flags = N->getFlags();
9029 if (!UnsafeMath && !Flags->hasAllowReciprocal())
9032 // Skip if current node is a reciprocal.
9033 SDValue N0 = N->getOperand(0);
9034 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9035 if (N0CFP && N0CFP->isExactlyValue(1.0))
9038 // Exit early if the target does not want this transform or if there can't
9039 // possibly be enough uses of the divisor to make the transform worthwhile.
9040 SDValue N1 = N->getOperand(1);
9041 unsigned MinUses = TLI.combineRepeatedFPDivisors();
9042 if (!MinUses || N1->use_size() < MinUses)
9045 // Find all FDIV users of the same divisor.
9046 // Use a set because duplicates may be present in the user list.
9047 SetVector<SDNode *> Users;
9048 for (auto *U : N1->uses()) {
9049 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
9050 // This division is eligible for optimization only if global unsafe math
9051 // is enabled or if this division allows reciprocal formation.
9052 if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
9057 // Now that we have the actual number of divisor uses, make sure it meets
9058 // the minimum threshold specified by the target.
9059 if (Users.size() < MinUses)
9062 EVT VT = N->getValueType(0);
9064 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
9065 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
9067 // Dividend / Divisor -> Dividend * Reciprocal
9068 for (auto *U : Users) {
9069 SDValue Dividend = U->getOperand(0);
9070 if (Dividend != FPOne) {
9071 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
9073 CombineTo(U, NewNode);
9074 } else if (U != Reciprocal.getNode()) {
9075 // In the absence of fast-math-flags, this user node is always the
9076 // same node as Reciprocal, but with FMF they may be different nodes.
9077 CombineTo(U, Reciprocal);
9080 return SDValue(N, 0); // N was replaced.
9083 SDValue DAGCombiner::visitFDIV(SDNode *N) {
9084 SDValue N0 = N->getOperand(0);
9085 SDValue N1 = N->getOperand(1);
9086 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9087 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9088 EVT VT = N->getValueType(0);
9090 const TargetOptions &Options = DAG.getTarget().Options;
9091 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9095 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9098 // fold (fdiv c1, c2) -> c1/c2
9100 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
9102 if (Options.UnsafeFPMath) {
9103 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
9105 // Compute the reciprocal 1.0 / c2.
9106 const APFloat &N1APF = N1CFP->getValueAPF();
9107 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
9108 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
9109 // Only do the transform if the reciprocal is a legal fp immediate that
9110 // isn't too nasty (eg NaN, denormal, ...).
9111 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
9112 (!LegalOperations ||
9113 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
9114 // backend)... we should handle this gracefully after Legalize.
9115 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
9116 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
9117 TLI.isFPImmLegal(Recip, VT)))
9118 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9119 DAG.getConstantFP(Recip, DL, VT), Flags);
9122 // If this FDIV is part of a reciprocal square root, it may be folded
9123 // into a target-specific square root estimate instruction.
9124 if (N1.getOpcode() == ISD::FSQRT) {
9125 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
9126 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9128 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
9129 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9130 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9132 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
9133 AddToWorklist(RV.getNode());
9134 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9136 } else if (N1.getOpcode() == ISD::FP_ROUND &&
9137 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9138 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9140 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9141 AddToWorklist(RV.getNode());
9142 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9144 } else if (N1.getOpcode() == ISD::FMUL) {
9145 // Look through an FMUL. Even though this won't remove the FDIV directly,
9146 // it's still worthwhile to get rid of the FSQRT if possible.
9149 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9150 SqrtOp = N1.getOperand(0);
9151 OtherOp = N1.getOperand(1);
9152 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9153 SqrtOp = N1.getOperand(1);
9154 OtherOp = N1.getOperand(0);
9156 if (SqrtOp.getNode()) {
9157 // We found a FSQRT, so try to make this fold:
9158 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9159 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9160 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9161 AddToWorklist(RV.getNode());
9162 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9167 // Fold into a reciprocal estimate and multiply instead of a real divide.
9168 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9169 AddToWorklist(RV.getNode());
9170 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9174 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9175 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9176 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9177 // Both can be negated for free, check to see if at least one is cheaper
9179 if (LHSNeg == 2 || RHSNeg == 2)
9180 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9181 GetNegatedExpression(N0, DAG, LegalOperations),
9182 GetNegatedExpression(N1, DAG, LegalOperations),
9187 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9188 return CombineRepeatedDivisors;
9193 SDValue DAGCombiner::visitFREM(SDNode *N) {
9194 SDValue N0 = N->getOperand(0);
9195 SDValue N1 = N->getOperand(1);
9196 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9197 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9198 EVT VT = N->getValueType(0);
9200 // fold (frem c1, c2) -> fmod(c1,c2)
9202 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9203 &cast<BinaryWithFlagsSDNode>(N)->Flags);
9208 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9209 if (!DAG.getTarget().Options.UnsafeFPMath)
9212 SDValue N0 = N->getOperand(0);
9213 if (TLI.isFsqrtCheap(N0, DAG))
9216 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9217 // For now, create a Flags object for use with all unsafe math transforms.
9219 Flags.setUnsafeAlgebra(true);
9220 return buildSqrtEstimate(N0, &Flags);
9223 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9224 /// copysign(x, fp_round(y)) -> copysign(x, y)
9225 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9226 SDValue N1 = N->getOperand(1);
9227 if ((N1.getOpcode() == ISD::FP_EXTEND ||
9228 N1.getOpcode() == ISD::FP_ROUND)) {
9229 // Do not optimize out type conversion of f128 type yet.
9230 // For some targets like x86_64, configuration is changed to keep one f128
9231 // value in one SSE register, but instruction selection cannot handle
9232 // FCOPYSIGN on SSE registers yet.
9233 EVT N1VT = N1->getValueType(0);
9234 EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9235 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9240 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9241 SDValue N0 = N->getOperand(0);
9242 SDValue N1 = N->getOperand(1);
9243 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9244 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9245 EVT VT = N->getValueType(0);
9247 if (N0CFP && N1CFP) // Constant fold
9248 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9251 const APFloat &V = N1CFP->getValueAPF();
9252 // copysign(x, c1) -> fabs(x) iff ispos(c1)
9253 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9254 if (!V.isNegative()) {
9255 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9256 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9258 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9259 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9260 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9264 // copysign(fabs(x), y) -> copysign(x, y)
9265 // copysign(fneg(x), y) -> copysign(x, y)
9266 // copysign(copysign(x,z), y) -> copysign(x, y)
9267 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9268 N0.getOpcode() == ISD::FCOPYSIGN)
9269 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9271 // copysign(x, abs(y)) -> abs(x)
9272 if (N1.getOpcode() == ISD::FABS)
9273 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9275 // copysign(x, copysign(y,z)) -> copysign(x, z)
9276 if (N1.getOpcode() == ISD::FCOPYSIGN)
9277 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9279 // copysign(x, fp_extend(y)) -> copysign(x, y)
9280 // copysign(x, fp_round(y)) -> copysign(x, y)
9281 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9282 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9287 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9288 SDValue N0 = N->getOperand(0);
9289 EVT VT = N->getValueType(0);
9290 EVT OpVT = N0.getValueType();
9292 // fold (sint_to_fp c1) -> c1fp
9293 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9294 // ...but only if the target supports immediate floating-point values
9295 (!LegalOperations ||
9296 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9297 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9299 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9300 // but UINT_TO_FP is legal on this target, try to convert.
9301 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9302 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9303 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9304 if (DAG.SignBitIsZero(N0))
9305 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9308 // The next optimizations are desirable only if SELECT_CC can be lowered.
9309 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9310 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9311 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9313 (!LegalOperations ||
9314 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9317 { N0.getOperand(0), N0.getOperand(1),
9318 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9320 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9323 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9324 // (select_cc x, y, 1.0, 0.0,, cc)
9325 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9326 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9327 (!LegalOperations ||
9328 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9331 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9332 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9333 N0.getOperand(0).getOperand(2) };
9334 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9341 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9342 SDValue N0 = N->getOperand(0);
9343 EVT VT = N->getValueType(0);
9344 EVT OpVT = N0.getValueType();
9346 // fold (uint_to_fp c1) -> c1fp
9347 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9348 // ...but only if the target supports immediate floating-point values
9349 (!LegalOperations ||
9350 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9351 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9353 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9354 // but SINT_TO_FP is legal on this target, try to convert.
9355 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9356 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9357 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9358 if (DAG.SignBitIsZero(N0))
9359 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9362 // The next optimizations are desirable only if SELECT_CC can be lowered.
9363 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9364 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9366 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9367 (!LegalOperations ||
9368 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9371 { N0.getOperand(0), N0.getOperand(1),
9372 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9374 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9381 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9382 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9383 SDValue N0 = N->getOperand(0);
9384 EVT VT = N->getValueType(0);
9386 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9389 SDValue Src = N0.getOperand(0);
9390 EVT SrcVT = Src.getValueType();
9391 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9392 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9394 // We can safely assume the conversion won't overflow the output range,
9395 // because (for example) (uint8_t)18293.f is undefined behavior.
9397 // Since we can assume the conversion won't overflow, our decision as to
9398 // whether the input will fit in the float should depend on the minimum
9399 // of the input range and output range.
9401 // This means this is also safe for a signed input and unsigned output, since
9402 // a negative input would lead to undefined behavior.
9403 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9404 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9405 unsigned ActualSize = std::min(InputSize, OutputSize);
9406 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9408 // We can only fold away the float conversion if the input range can be
9409 // represented exactly in the float range.
9410 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9411 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9412 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9414 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9416 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9417 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9418 return DAG.getBitcast(VT, Src);
9423 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9424 SDValue N0 = N->getOperand(0);
9425 EVT VT = N->getValueType(0);
9427 // fold (fp_to_sint c1fp) -> c1
9428 if (isConstantFPBuildVectorOrConstantFP(N0))
9429 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9431 return FoldIntToFPToInt(N, DAG);
9434 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9435 SDValue N0 = N->getOperand(0);
9436 EVT VT = N->getValueType(0);
9438 // fold (fp_to_uint c1fp) -> c1
9439 if (isConstantFPBuildVectorOrConstantFP(N0))
9440 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9442 return FoldIntToFPToInt(N, DAG);
9445 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9446 SDValue N0 = N->getOperand(0);
9447 SDValue N1 = N->getOperand(1);
9448 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9449 EVT VT = N->getValueType(0);
9451 // fold (fp_round c1fp) -> c1fp
9453 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9455 // fold (fp_round (fp_extend x)) -> x
9456 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9457 return N0.getOperand(0);
9459 // fold (fp_round (fp_round x)) -> (fp_round x)
9460 if (N0.getOpcode() == ISD::FP_ROUND) {
9461 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9462 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
9464 // Skip this folding if it results in an fp_round from f80 to f16.
9466 // f80 to f16 always generates an expensive (and as yet, unimplemented)
9467 // libcall to __truncxfhf2 instead of selecting native f16 conversion
9468 // instructions from f32 or f64. Moreover, the first (value-preserving)
9469 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9471 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9474 // If the first fp_round isn't a value preserving truncation, it might
9475 // introduce a tie in the second fp_round, that wouldn't occur in the
9476 // single-step fp_round we want to fold to.
9477 // In other words, double rounding isn't the same as rounding.
9478 // Also, this is a value preserving truncation iff both fp_round's are.
9479 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9481 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9482 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9486 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9487 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9488 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9489 N0.getOperand(0), N1);
9490 AddToWorklist(Tmp.getNode());
9491 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9492 Tmp, N0.getOperand(1));
9498 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9499 SDValue N0 = N->getOperand(0);
9500 EVT VT = N->getValueType(0);
9501 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9502 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9504 // fold (fp_round_inreg c1fp) -> c1fp
9505 if (N0CFP && isTypeLegal(EVT)) {
9507 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9508 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9514 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9515 SDValue N0 = N->getOperand(0);
9516 EVT VT = N->getValueType(0);
9518 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9519 if (N->hasOneUse() &&
9520 N->use_begin()->getOpcode() == ISD::FP_ROUND)
9523 // fold (fp_extend c1fp) -> c1fp
9524 if (isConstantFPBuildVectorOrConstantFP(N0))
9525 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9527 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9528 if (N0.getOpcode() == ISD::FP16_TO_FP &&
9529 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9530 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9532 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9534 if (N0.getOpcode() == ISD::FP_ROUND
9535 && N0.getConstantOperandVal(1) == 1) {
9536 SDValue In = N0.getOperand(0);
9537 if (In.getValueType() == VT) return In;
9538 if (VT.bitsLT(In.getValueType()))
9539 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9540 In, N0.getOperand(1));
9541 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9544 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9545 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9546 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9547 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9548 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9550 LN0->getBasePtr(), N0.getValueType(),
9551 LN0->getMemOperand());
9552 CombineTo(N, ExtLoad);
9553 CombineTo(N0.getNode(),
9554 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9555 N0.getValueType(), ExtLoad,
9556 DAG.getIntPtrConstant(1, SDLoc(N0))),
9557 ExtLoad.getValue(1));
9558 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9564 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9565 SDValue N0 = N->getOperand(0);
9566 EVT VT = N->getValueType(0);
9568 // fold (fceil c1) -> fceil(c1)
9569 if (isConstantFPBuildVectorOrConstantFP(N0))
9570 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9575 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9576 SDValue N0 = N->getOperand(0);
9577 EVT VT = N->getValueType(0);
9579 // fold (ftrunc c1) -> ftrunc(c1)
9580 if (isConstantFPBuildVectorOrConstantFP(N0))
9581 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9586 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9587 SDValue N0 = N->getOperand(0);
9588 EVT VT = N->getValueType(0);
9590 // fold (ffloor c1) -> ffloor(c1)
9591 if (isConstantFPBuildVectorOrConstantFP(N0))
9592 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9597 // FIXME: FNEG and FABS have a lot in common; refactor.
9598 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9599 SDValue N0 = N->getOperand(0);
9600 EVT VT = N->getValueType(0);
9602 // Constant fold FNEG.
9603 if (isConstantFPBuildVectorOrConstantFP(N0))
9604 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9606 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9607 &DAG.getTarget().Options))
9608 return GetNegatedExpression(N0, DAG, LegalOperations);
9610 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9611 // constant pool values.
9612 if (!TLI.isFNegFree(VT) &&
9613 N0.getOpcode() == ISD::BITCAST &&
9614 N0.getNode()->hasOneUse()) {
9615 SDValue Int = N0.getOperand(0);
9616 EVT IntVT = Int.getValueType();
9617 if (IntVT.isInteger() && !IntVT.isVector()) {
9619 if (N0.getValueType().isVector()) {
9620 // For a vector, get a mask such as 0x80... per scalar element
9622 SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits());
9623 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9625 // For a scalar, just generate 0x80...
9626 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9629 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9630 DAG.getConstant(SignMask, DL0, IntVT));
9631 AddToWorklist(Int.getNode());
9632 return DAG.getBitcast(VT, Int);
9636 // (fneg (fmul c, x)) -> (fmul -c, x)
9637 if (N0.getOpcode() == ISD::FMUL &&
9638 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9639 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9641 APFloat CVal = CFP1->getValueAPF();
9643 if (Level >= AfterLegalizeDAG &&
9644 (TLI.isFPImmLegal(CVal, VT) ||
9645 TLI.isOperationLegal(ISD::ConstantFP, VT)))
9646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9647 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9649 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9656 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9657 SDValue N0 = N->getOperand(0);
9658 SDValue N1 = N->getOperand(1);
9659 EVT VT = N->getValueType(0);
9660 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9661 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9663 if (N0CFP && N1CFP) {
9664 const APFloat &C0 = N0CFP->getValueAPF();
9665 const APFloat &C1 = N1CFP->getValueAPF();
9666 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9669 // Canonicalize to constant on RHS.
9670 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9671 !isConstantFPBuildVectorOrConstantFP(N1))
9672 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9677 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9678 SDValue N0 = N->getOperand(0);
9679 SDValue N1 = N->getOperand(1);
9680 EVT VT = N->getValueType(0);
9681 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9682 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9684 if (N0CFP && N1CFP) {
9685 const APFloat &C0 = N0CFP->getValueAPF();
9686 const APFloat &C1 = N1CFP->getValueAPF();
9687 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9690 // Canonicalize to constant on RHS.
9691 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9692 !isConstantFPBuildVectorOrConstantFP(N1))
9693 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9698 SDValue DAGCombiner::visitFABS(SDNode *N) {
9699 SDValue N0 = N->getOperand(0);
9700 EVT VT = N->getValueType(0);
9702 // fold (fabs c1) -> fabs(c1)
9703 if (isConstantFPBuildVectorOrConstantFP(N0))
9704 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9706 // fold (fabs (fabs x)) -> (fabs x)
9707 if (N0.getOpcode() == ISD::FABS)
9708 return N->getOperand(0);
9710 // fold (fabs (fneg x)) -> (fabs x)
9711 // fold (fabs (fcopysign x, y)) -> (fabs x)
9712 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9713 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9715 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9716 // constant pool values.
9717 if (!TLI.isFAbsFree(VT) &&
9718 N0.getOpcode() == ISD::BITCAST &&
9719 N0.getNode()->hasOneUse()) {
9720 SDValue Int = N0.getOperand(0);
9721 EVT IntVT = Int.getValueType();
9722 if (IntVT.isInteger() && !IntVT.isVector()) {
9724 if (N0.getValueType().isVector()) {
9725 // For a vector, get a mask such as 0x7f... per scalar element
9727 SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits());
9728 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9730 // For a scalar, just generate 0x7f...
9731 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9734 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9735 DAG.getConstant(SignMask, DL, IntVT));
9736 AddToWorklist(Int.getNode());
9737 return DAG.getBitcast(N->getValueType(0), Int);
9744 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9745 SDValue Chain = N->getOperand(0);
9746 SDValue N1 = N->getOperand(1);
9747 SDValue N2 = N->getOperand(2);
9749 // If N is a constant we could fold this into a fallthrough or unconditional
9750 // branch. However that doesn't happen very often in normal code, because
9751 // Instcombine/SimplifyCFG should have handled the available opportunities.
9752 // If we did this folding here, it would be necessary to update the
9753 // MachineBasicBlock CFG, which is awkward.
9755 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9757 if (N1.getOpcode() == ISD::SETCC &&
9758 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9759 N1.getOperand(0).getValueType())) {
9760 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9761 Chain, N1.getOperand(2),
9762 N1.getOperand(0), N1.getOperand(1), N2);
9765 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9766 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9767 (N1.getOperand(0).hasOneUse() &&
9768 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9769 SDNode *Trunc = nullptr;
9770 if (N1.getOpcode() == ISD::TRUNCATE) {
9771 // Look pass the truncate.
9772 Trunc = N1.getNode();
9773 N1 = N1.getOperand(0);
9776 // Match this pattern so that we can generate simpler code:
9779 // %b = and i32 %a, 2
9780 // %c = srl i32 %b, 1
9781 // brcond i32 %c ...
9786 // %b = and i32 %a, 2
9787 // %c = setcc eq %b, 0
9790 // This applies only when the AND constant value has one bit set and the
9791 // SRL constant is equal to the log2 of the AND constant. The back-end is
9792 // smart enough to convert the result into a TEST/JMP sequence.
9793 SDValue Op0 = N1.getOperand(0);
9794 SDValue Op1 = N1.getOperand(1);
9796 if (Op0.getOpcode() == ISD::AND &&
9797 Op1.getOpcode() == ISD::Constant) {
9798 SDValue AndOp1 = Op0.getOperand(1);
9800 if (AndOp1.getOpcode() == ISD::Constant) {
9801 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9803 if (AndConst.isPowerOf2() &&
9804 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9808 getSetCCResultType(Op0.getValueType()),
9809 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9812 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9813 MVT::Other, Chain, SetCC, N2);
9814 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9815 // will convert it back to (X & C1) >> C2.
9816 CombineTo(N, NewBRCond, false);
9817 // Truncate is dead.
9819 deleteAndRecombine(Trunc);
9820 // Replace the uses of SRL with SETCC
9821 WorklistRemover DeadNodes(*this);
9822 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9823 deleteAndRecombine(N1.getNode());
9824 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9830 // Restore N1 if the above transformation doesn't match.
9831 N1 = N->getOperand(1);
9834 // Transform br(xor(x, y)) -> br(x != y)
9835 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9836 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9837 SDNode *TheXor = N1.getNode();
9838 SDValue Op0 = TheXor->getOperand(0);
9839 SDValue Op1 = TheXor->getOperand(1);
9840 if (Op0.getOpcode() == Op1.getOpcode()) {
9841 // Avoid missing important xor optimizations.
9842 if (SDValue Tmp = visitXOR(TheXor)) {
9843 if (Tmp.getNode() != TheXor) {
9844 DEBUG(dbgs() << "\nReplacing.8 ";
9846 dbgs() << "\nWith: ";
9847 Tmp.getNode()->dump(&DAG);
9849 WorklistRemover DeadNodes(*this);
9850 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9851 deleteAndRecombine(TheXor);
9852 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9853 MVT::Other, Chain, Tmp, N2);
9856 // visitXOR has changed XOR's operands or replaced the XOR completely,
9858 return SDValue(N, 0);
9862 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9864 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9865 Op0.getOpcode() == ISD::XOR) {
9866 TheXor = Op0.getNode();
9870 EVT SetCCVT = N1.getValueType();
9872 SetCCVT = getSetCCResultType(SetCCVT);
9873 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9876 Equal ? ISD::SETEQ : ISD::SETNE);
9877 // Replace the uses of XOR with SETCC
9878 WorklistRemover DeadNodes(*this);
9879 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9880 deleteAndRecombine(N1.getNode());
9881 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9882 MVT::Other, Chain, SetCC, N2);
9889 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9891 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9892 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9893 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9895 // If N is a constant we could fold this into a fallthrough or unconditional
9896 // branch. However that doesn't happen very often in normal code, because
9897 // Instcombine/SimplifyCFG should have handled the available opportunities.
9898 // If we did this folding here, it would be necessary to update the
9899 // MachineBasicBlock CFG, which is awkward.
9901 // Use SimplifySetCC to simplify SETCC's.
9902 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9903 CondLHS, CondRHS, CC->get(), SDLoc(N),
9905 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9907 // fold to a simpler setcc
9908 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9909 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9910 N->getOperand(0), Simp.getOperand(2),
9911 Simp.getOperand(0), Simp.getOperand(1),
9917 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9918 /// and that N may be folded in the load / store addressing mode.
9919 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9921 const TargetLowering &TLI) {
9925 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9926 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9928 VT = LD->getMemoryVT();
9929 AS = LD->getAddressSpace();
9930 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9931 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9933 VT = ST->getMemoryVT();
9934 AS = ST->getAddressSpace();
9938 TargetLowering::AddrMode AM;
9939 if (N->getOpcode() == ISD::ADD) {
9940 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9943 AM.BaseOffs = Offset->getSExtValue();
9947 } else if (N->getOpcode() == ISD::SUB) {
9948 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9951 AM.BaseOffs = -Offset->getSExtValue();
9958 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9959 VT.getTypeForEVT(*DAG.getContext()), AS);
9962 /// Try turning a load/store into a pre-indexed load/store when the base
9963 /// pointer is an add or subtract and it has other uses besides the load/store.
9964 /// After the transformation, the new indexed load/store has effectively folded
9965 /// the add/subtract in and all of its other uses are redirected to the
9967 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9968 if (Level < AfterLegalizeDAG)
9974 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9975 if (LD->isIndexed())
9977 VT = LD->getMemoryVT();
9978 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9979 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9981 Ptr = LD->getBasePtr();
9982 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9983 if (ST->isIndexed())
9985 VT = ST->getMemoryVT();
9986 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9987 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9989 Ptr = ST->getBasePtr();
9995 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9996 // out. There is no reason to make this a preinc/predec.
9997 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9998 Ptr.getNode()->hasOneUse())
10001 // Ask the target to do addressing mode selection.
10004 ISD::MemIndexedMode AM = ISD::UNINDEXED;
10005 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10008 // Backends without true r+i pre-indexed forms may need to pass a
10009 // constant base with a variable offset so that constant coercion
10010 // will work with the patterns in canonical form.
10011 bool Swapped = false;
10012 if (isa<ConstantSDNode>(BasePtr)) {
10013 std::swap(BasePtr, Offset);
10017 // Don't create a indexed load / store with zero offset.
10018 if (isNullConstant(Offset))
10021 // Try turning it into a pre-indexed load / store except when:
10022 // 1) The new base ptr is a frame index.
10023 // 2) If N is a store and the new base ptr is either the same as or is a
10024 // predecessor of the value being stored.
10025 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10026 // that would create a cycle.
10027 // 4) All uses are load / store ops that use it as old base ptr.
10029 // Check #1. Preinc'ing a frame index would require copying the stack pointer
10030 // (plus the implicit offset) to a register to preinc anyway.
10031 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10036 SDValue Val = cast<StoreSDNode>(N)->getValue();
10037 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
10041 // Caches for hasPredecessorHelper.
10042 SmallPtrSet<const SDNode *, 32> Visited;
10043 SmallVector<const SDNode *, 16> Worklist;
10044 Worklist.push_back(N);
10046 // If the offset is a constant, there may be other adds of constants that
10047 // can be folded with this one. We should do this to avoid having to keep
10048 // a copy of the original base pointer.
10049 SmallVector<SDNode *, 16> OtherUses;
10050 if (isa<ConstantSDNode>(Offset))
10051 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
10052 UE = BasePtr.getNode()->use_end();
10054 SDUse &Use = UI.getUse();
10055 // Skip the use that is Ptr and uses of other results from BasePtr's
10056 // node (important for nodes that return multiple results).
10057 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
10060 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
10063 if (Use.getUser()->getOpcode() != ISD::ADD &&
10064 Use.getUser()->getOpcode() != ISD::SUB) {
10069 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
10070 if (!isa<ConstantSDNode>(Op1)) {
10075 // FIXME: In some cases, we can be smarter about this.
10076 if (Op1.getValueType() != Offset.getValueType()) {
10081 OtherUses.push_back(Use.getUser());
10085 std::swap(BasePtr, Offset);
10087 // Now check for #3 and #4.
10088 bool RealUse = false;
10090 for (SDNode *Use : Ptr.getNode()->uses()) {
10093 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
10096 // If Ptr may be folded in addressing mode of other use, then it's
10097 // not profitable to do this transformation.
10098 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
10107 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10108 BasePtr, Offset, AM);
10110 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10111 BasePtr, Offset, AM);
10114 DEBUG(dbgs() << "\nReplacing.4 ";
10116 dbgs() << "\nWith: ";
10117 Result.getNode()->dump(&DAG);
10119 WorklistRemover DeadNodes(*this);
10121 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10122 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10124 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10127 // Finally, since the node is now dead, remove it from the graph.
10128 deleteAndRecombine(N);
10131 std::swap(BasePtr, Offset);
10133 // Replace other uses of BasePtr that can be updated to use Ptr
10134 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
10135 unsigned OffsetIdx = 1;
10136 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
10138 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10139 BasePtr.getNode() && "Expected BasePtr operand");
10141 // We need to replace ptr0 in the following expression:
10142 // x0 * offset0 + y0 * ptr0 = t0
10144 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10146 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10147 // indexed load/store and the expresion that needs to be re-written.
10149 // Therefore, we have:
10150 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10152 ConstantSDNode *CN =
10153 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
10154 int X0, X1, Y0, Y1;
10155 const APInt &Offset0 = CN->getAPIntValue();
10156 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10158 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10159 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10160 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10161 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10163 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10165 APInt CNV = Offset0;
10166 if (X0 < 0) CNV = -CNV;
10167 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10168 else CNV = CNV - Offset1;
10170 SDLoc DL(OtherUses[i]);
10172 // We can now generate the new expression.
10173 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10174 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10176 SDValue NewUse = DAG.getNode(Opcode,
10178 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10179 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10180 deleteAndRecombine(OtherUses[i]);
10183 // Replace the uses of Ptr with uses of the updated base value.
10184 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10185 deleteAndRecombine(Ptr.getNode());
10190 /// Try to combine a load/store with a add/sub of the base pointer node into a
10191 /// post-indexed load/store. The transformation folded the add/subtract into the
10192 /// new indexed load/store effectively and all of its uses are redirected to the
10193 /// new load/store.
10194 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10195 if (Level < AfterLegalizeDAG)
10198 bool isLoad = true;
10201 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10202 if (LD->isIndexed())
10204 VT = LD->getMemoryVT();
10205 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10206 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10208 Ptr = LD->getBasePtr();
10209 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10210 if (ST->isIndexed())
10212 VT = ST->getMemoryVT();
10213 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10214 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10216 Ptr = ST->getBasePtr();
10222 if (Ptr.getNode()->hasOneUse())
10225 for (SDNode *Op : Ptr.getNode()->uses()) {
10227 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10232 ISD::MemIndexedMode AM = ISD::UNINDEXED;
10233 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10234 // Don't create a indexed load / store with zero offset.
10235 if (isNullConstant(Offset))
10238 // Try turning it into a post-indexed load / store except when
10239 // 1) All uses are load / store ops that use it as base ptr (and
10240 // it may be folded as addressing mmode).
10241 // 2) Op must be independent of N, i.e. Op is neither a predecessor
10242 // nor a successor of N. Otherwise, if Op is folded that would
10245 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10249 bool TryNext = false;
10250 for (SDNode *Use : BasePtr.getNode()->uses()) {
10251 if (Use == Ptr.getNode())
10254 // If all the uses are load / store addresses, then don't do the
10256 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10257 bool RealUse = false;
10258 for (SDNode *UseUse : Use->uses()) {
10259 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10274 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10275 SDValue Result = isLoad
10276 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10277 BasePtr, Offset, AM)
10278 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10279 BasePtr, Offset, AM);
10280 ++PostIndexedNodes;
10282 DEBUG(dbgs() << "\nReplacing.5 ";
10284 dbgs() << "\nWith: ";
10285 Result.getNode()->dump(&DAG);
10287 WorklistRemover DeadNodes(*this);
10289 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10290 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10292 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10295 // Finally, since the node is now dead, remove it from the graph.
10296 deleteAndRecombine(N);
10298 // Replace the uses of Use with uses of the updated base value.
10299 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10300 Result.getValue(isLoad ? 1 : 0));
10301 deleteAndRecombine(Op);
10310 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10311 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10312 ISD::MemIndexedMode AM = LD->getAddressingMode();
10313 assert(AM != ISD::UNINDEXED);
10314 SDValue BP = LD->getOperand(1);
10315 SDValue Inc = LD->getOperand(2);
10317 // Some backends use TargetConstants for load offsets, but don't expect
10318 // TargetConstants in general ADD nodes. We can convert these constants into
10319 // regular Constants (if the constant is not opaque).
10320 assert((Inc.getOpcode() != ISD::TargetConstant ||
10321 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10322 "Cannot split out indexing using opaque target constants");
10323 if (Inc.getOpcode() == ISD::TargetConstant) {
10324 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10325 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10326 ConstInc->getValueType(0));
10330 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10331 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10334 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10335 LoadSDNode *LD = cast<LoadSDNode>(N);
10336 SDValue Chain = LD->getChain();
10337 SDValue Ptr = LD->getBasePtr();
10339 // If load is not volatile and there are no uses of the loaded value (and
10340 // the updated indexed value in case of indexed loads), change uses of the
10341 // chain value into uses of the chain input (i.e. delete the dead load).
10342 if (!LD->isVolatile()) {
10343 if (N->getValueType(1) == MVT::Other) {
10344 // Unindexed loads.
10345 if (!N->hasAnyUseOfValue(0)) {
10346 // It's not safe to use the two value CombineTo variant here. e.g.
10347 // v1, chain2 = load chain1, loc
10348 // v2, chain3 = load chain2, loc
10350 // Now we replace use of chain2 with chain1. This makes the second load
10351 // isomorphic to the one we are deleting, and thus makes this load live.
10352 DEBUG(dbgs() << "\nReplacing.6 ";
10354 dbgs() << "\nWith chain: ";
10355 Chain.getNode()->dump(&DAG);
10357 WorklistRemover DeadNodes(*this);
10358 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10360 if (N->use_empty())
10361 deleteAndRecombine(N);
10363 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10367 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10369 // If this load has an opaque TargetConstant offset, then we cannot split
10370 // the indexing into an add/sub directly (that TargetConstant may not be
10371 // valid for a different type of node, and we cannot convert an opaque
10372 // target constant into a regular constant).
10373 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10374 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10376 if (!N->hasAnyUseOfValue(0) &&
10377 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10378 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10380 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10381 Index = SplitIndexingFromLoad(LD);
10382 // Try to fold the base pointer arithmetic into subsequent loads and
10384 AddUsersToWorklist(N);
10386 Index = DAG.getUNDEF(N->getValueType(1));
10387 DEBUG(dbgs() << "\nReplacing.7 ";
10389 dbgs() << "\nWith: ";
10390 Undef.getNode()->dump(&DAG);
10391 dbgs() << " and 2 other values\n");
10392 WorklistRemover DeadNodes(*this);
10393 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10394 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10395 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10396 deleteAndRecombine(N);
10397 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10402 // If this load is directly stored, replace the load value with the stored
10404 // TODO: Handle store large -> read small portion.
10405 // TODO: Handle TRUNCSTORE/LOADEXT
10406 if (OptLevel != CodeGenOpt::None &&
10407 ISD::isNormalLoad(N) && !LD->isVolatile()) {
10408 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10409 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10410 if (PrevST->getBasePtr() == Ptr &&
10411 PrevST->getValue().getValueType() == N->getValueType(0))
10412 return CombineTo(N, Chain.getOperand(1), Chain);
10416 // Try to infer better alignment information than the load already has.
10417 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10418 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10419 if (Align > LD->getMemOperand()->getBaseAlignment()) {
10420 SDValue NewLoad = DAG.getExtLoad(
10421 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10422 LD->getPointerInfo(), LD->getMemoryVT(), Align,
10423 LD->getMemOperand()->getFlags(), LD->getAAInfo());
10424 if (NewLoad.getNode() != N)
10425 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10430 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10431 : DAG.getSubtarget().useAA();
10433 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10434 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10437 if (UseAA && LD->isUnindexed()) {
10438 // Walk up chain skipping non-aliasing memory nodes.
10439 SDValue BetterChain = FindBetterChain(N, Chain);
10441 // If there is a better chain.
10442 if (Chain != BetterChain) {
10445 // Replace the chain to void dependency.
10446 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10447 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10448 BetterChain, Ptr, LD->getMemOperand());
10450 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10451 LD->getValueType(0),
10452 BetterChain, Ptr, LD->getMemoryVT(),
10453 LD->getMemOperand());
10456 // Create token factor to keep old chain connected.
10457 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10458 MVT::Other, Chain, ReplLoad.getValue(1));
10460 // Make sure the new and old chains are cleaned up.
10461 AddToWorklist(Token.getNode());
10463 // Replace uses with load result and token factor. Don't add users
10465 return CombineTo(N, ReplLoad.getValue(0), Token, false);
10469 // Try transforming N to an indexed load.
10470 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10471 return SDValue(N, 0);
10473 // Try to slice up N to more direct loads if the slices are mapped to
10474 // different register banks or pairing can take place.
10475 if (SliceUpLoad(N))
10476 return SDValue(N, 0);
10482 /// \brief Helper structure used to slice a load in smaller loads.
10483 /// Basically a slice is obtained from the following sequence:
10484 /// Origin = load Ty1, Base
10485 /// Shift = srl Ty1 Origin, CstTy Amount
10486 /// Inst = trunc Shift to Ty2
10488 /// Then, it will be rewriten into:
10489 /// Slice = load SliceTy, Base + SliceOffset
10490 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10492 /// SliceTy is deduced from the number of bits that are actually used to
10494 struct LoadedSlice {
10495 /// \brief Helper structure used to compute the cost of a slice.
10497 /// Are we optimizing for code size.
10501 unsigned Truncates;
10502 unsigned CrossRegisterBanksCopies;
10506 Cost(bool ForCodeSize = false)
10507 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10508 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10510 /// \brief Get the cost of one isolated slice.
10511 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10512 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10513 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10514 EVT TruncType = LS.Inst->getValueType(0);
10515 EVT LoadedType = LS.getLoadedType();
10516 if (TruncType != LoadedType &&
10517 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10521 /// \brief Account for slicing gain in the current cost.
10522 /// Slicing provide a few gains like removing a shift or a
10523 /// truncate. This method allows to grow the cost of the original
10524 /// load with the gain from this slice.
10525 void addSliceGain(const LoadedSlice &LS) {
10526 // Each slice saves a truncate.
10527 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10528 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10529 LS.Inst->getValueType(0)))
10531 // If there is a shift amount, this slice gets rid of it.
10534 // If this slice can merge a cross register bank copy, account for it.
10535 if (LS.canMergeExpensiveCrossRegisterBankCopy())
10536 ++CrossRegisterBanksCopies;
10539 Cost &operator+=(const Cost &RHS) {
10540 Loads += RHS.Loads;
10541 Truncates += RHS.Truncates;
10542 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10543 ZExts += RHS.ZExts;
10544 Shift += RHS.Shift;
10548 bool operator==(const Cost &RHS) const {
10549 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10550 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10551 ZExts == RHS.ZExts && Shift == RHS.Shift;
10554 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10556 bool operator<(const Cost &RHS) const {
10557 // Assume cross register banks copies are as expensive as loads.
10558 // FIXME: Do we want some more target hooks?
10559 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10560 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10561 // Unless we are optimizing for code size, consider the
10562 // expensive operation first.
10563 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10564 return ExpensiveOpsLHS < ExpensiveOpsRHS;
10565 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10566 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10569 bool operator>(const Cost &RHS) const { return RHS < *this; }
10571 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10573 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10575 // The last instruction that represent the slice. This should be a
10576 // truncate instruction.
10578 // The original load instruction.
10579 LoadSDNode *Origin;
10580 // The right shift amount in bits from the original load.
10582 // The DAG from which Origin came from.
10583 // This is used to get some contextual information about legal types, etc.
10586 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10587 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10588 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10590 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10591 /// \return Result is \p BitWidth and has used bits set to 1 and
10592 /// not used bits set to 0.
10593 APInt getUsedBits() const {
10594 // Reproduce the trunc(lshr) sequence:
10595 // - Start from the truncated value.
10596 // - Zero extend to the desired bit width.
10598 assert(Origin && "No original load to compare against.");
10599 unsigned BitWidth = Origin->getValueSizeInBits(0);
10600 assert(Inst && "This slice is not bound to an instruction");
10601 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10602 "Extracted slice is bigger than the whole type!");
10603 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10604 UsedBits.setAllBits();
10605 UsedBits = UsedBits.zext(BitWidth);
10606 UsedBits <<= Shift;
10610 /// \brief Get the size of the slice to be loaded in bytes.
10611 unsigned getLoadedSize() const {
10612 unsigned SliceSize = getUsedBits().countPopulation();
10613 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10614 return SliceSize / 8;
10617 /// \brief Get the type that will be loaded for this slice.
10618 /// Note: This may not be the final type for the slice.
10619 EVT getLoadedType() const {
10620 assert(DAG && "Missing context");
10621 LLVMContext &Ctxt = *DAG->getContext();
10622 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10625 /// \brief Get the alignment of the load used for this slice.
10626 unsigned getAlignment() const {
10627 unsigned Alignment = Origin->getAlignment();
10628 unsigned Offset = getOffsetFromBase();
10630 Alignment = MinAlign(Alignment, Alignment + Offset);
10634 /// \brief Check if this slice can be rewritten with legal operations.
10635 bool isLegal() const {
10636 // An invalid slice is not legal.
10637 if (!Origin || !Inst || !DAG)
10640 // Offsets are for indexed load only, we do not handle that.
10641 if (!Origin->getOffset().isUndef())
10644 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10646 // Check that the type is legal.
10647 EVT SliceType = getLoadedType();
10648 if (!TLI.isTypeLegal(SliceType))
10651 // Check that the load is legal for this type.
10652 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10655 // Check that the offset can be computed.
10656 // 1. Check its type.
10657 EVT PtrType = Origin->getBasePtr().getValueType();
10658 if (PtrType == MVT::Untyped || PtrType.isExtended())
10661 // 2. Check that it fits in the immediate.
10662 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10665 // 3. Check that the computation is legal.
10666 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10669 // Check that the zext is legal if it needs one.
10670 EVT TruncateType = Inst->getValueType(0);
10671 if (TruncateType != SliceType &&
10672 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10678 /// \brief Get the offset in bytes of this slice in the original chunk of
10680 /// \pre DAG != nullptr.
10681 uint64_t getOffsetFromBase() const {
10682 assert(DAG && "Missing context.");
10683 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10684 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10685 uint64_t Offset = Shift / 8;
10686 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10687 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10688 "The size of the original loaded type is not a multiple of a"
10690 // If Offset is bigger than TySizeInBytes, it means we are loading all
10691 // zeros. This should have been optimized before in the process.
10692 assert(TySizeInBytes > Offset &&
10693 "Invalid shift amount for given loaded size");
10695 Offset = TySizeInBytes - Offset - getLoadedSize();
10699 /// \brief Generate the sequence of instructions to load the slice
10700 /// represented by this object and redirect the uses of this slice to
10701 /// this new sequence of instructions.
10702 /// \pre this->Inst && this->Origin are valid Instructions and this
10703 /// object passed the legal check: LoadedSlice::isLegal returned true.
10704 /// \return The last instruction of the sequence used to load the slice.
10705 SDValue loadSlice() const {
10706 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10707 const SDValue &OldBaseAddr = Origin->getBasePtr();
10708 SDValue BaseAddr = OldBaseAddr;
10709 // Get the offset in that chunk of bytes w.r.t. the endianness.
10710 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10711 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10713 // BaseAddr = BaseAddr + Offset.
10714 EVT ArithType = BaseAddr.getValueType();
10716 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10717 DAG->getConstant(Offset, DL, ArithType));
10720 // Create the type of the loaded slice according to its size.
10721 EVT SliceType = getLoadedType();
10723 // Create the load for the slice.
10725 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10726 Origin->getPointerInfo().getWithOffset(Offset),
10727 getAlignment(), Origin->getMemOperand()->getFlags());
10728 // If the final type is not the same as the loaded type, this means that
10729 // we have to pad with zero. Create a zero extend for that.
10730 EVT FinalType = Inst->getValueType(0);
10731 if (SliceType != FinalType)
10733 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10737 /// \brief Check if this slice can be merged with an expensive cross register
10738 /// bank copy. E.g.,
10740 /// f = bitcast i32 i to float
10741 bool canMergeExpensiveCrossRegisterBankCopy() const {
10742 if (!Inst || !Inst->hasOneUse())
10744 SDNode *Use = *Inst->use_begin();
10745 if (Use->getOpcode() != ISD::BITCAST)
10747 assert(DAG && "Missing context");
10748 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10749 EVT ResVT = Use->getValueType(0);
10750 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10751 const TargetRegisterClass *ArgRC =
10752 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10753 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10756 // At this point, we know that we perform a cross-register-bank copy.
10757 // Check if it is expensive.
10758 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10759 // Assume bitcasts are cheap, unless both register classes do not
10760 // explicitly share a common sub class.
10761 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10764 // Check if it will be merged with the load.
10765 // 1. Check the alignment constraint.
10766 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10767 ResVT.getTypeForEVT(*DAG->getContext()));
10769 if (RequiredAlignment > getAlignment())
10772 // 2. Check that the load is a legal operation for that type.
10773 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10776 // 3. Check that we do not have a zext in the way.
10777 if (Inst->getValueType(0) != getLoadedType())
10785 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10786 /// \p UsedBits looks like 0..0 1..1 0..0.
10787 static bool areUsedBitsDense(const APInt &UsedBits) {
10788 // If all the bits are one, this is dense!
10789 if (UsedBits.isAllOnesValue())
10792 // Get rid of the unused bits on the right.
10793 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10794 // Get rid of the unused bits on the left.
10795 if (NarrowedUsedBits.countLeadingZeros())
10796 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10797 // Check that the chunk of bits is completely used.
10798 return NarrowedUsedBits.isAllOnesValue();
10801 /// \brief Check whether or not \p First and \p Second are next to each other
10802 /// in memory. This means that there is no hole between the bits loaded
10803 /// by \p First and the bits loaded by \p Second.
10804 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10805 const LoadedSlice &Second) {
10806 assert(First.Origin == Second.Origin && First.Origin &&
10807 "Unable to match different memory origins.");
10808 APInt UsedBits = First.getUsedBits();
10809 assert((UsedBits & Second.getUsedBits()) == 0 &&
10810 "Slices are not supposed to overlap.");
10811 UsedBits |= Second.getUsedBits();
10812 return areUsedBitsDense(UsedBits);
10815 /// \brief Adjust the \p GlobalLSCost according to the target
10816 /// paring capabilities and the layout of the slices.
10817 /// \pre \p GlobalLSCost should account for at least as many loads as
10818 /// there is in the slices in \p LoadedSlices.
10819 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10820 LoadedSlice::Cost &GlobalLSCost) {
10821 unsigned NumberOfSlices = LoadedSlices.size();
10822 // If there is less than 2 elements, no pairing is possible.
10823 if (NumberOfSlices < 2)
10826 // Sort the slices so that elements that are likely to be next to each
10827 // other in memory are next to each other in the list.
10828 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10829 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10830 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10831 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10833 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10834 // First (resp. Second) is the first (resp. Second) potentially candidate
10835 // to be placed in a paired load.
10836 const LoadedSlice *First = nullptr;
10837 const LoadedSlice *Second = nullptr;
10838 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10839 // Set the beginning of the pair.
10842 Second = &LoadedSlices[CurrSlice];
10844 // If First is NULL, it means we start a new pair.
10845 // Get to the next slice.
10849 EVT LoadedType = First->getLoadedType();
10851 // If the types of the slices are different, we cannot pair them.
10852 if (LoadedType != Second->getLoadedType())
10855 // Check if the target supplies paired loads for this type.
10856 unsigned RequiredAlignment = 0;
10857 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10858 // move to the next pair, this type is hopeless.
10862 // Check if we meet the alignment requirement.
10863 if (RequiredAlignment > First->getAlignment())
10866 // Check that both loads are next to each other in memory.
10867 if (!areSlicesNextToEachOther(*First, *Second))
10870 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10871 --GlobalLSCost.Loads;
10872 // Move to the next pair.
10877 /// \brief Check the profitability of all involved LoadedSlice.
10878 /// Currently, it is considered profitable if there is exactly two
10879 /// involved slices (1) which are (2) next to each other in memory, and
10880 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10882 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10883 /// the elements themselves.
10885 /// FIXME: When the cost model will be mature enough, we can relax
10886 /// constraints (1) and (2).
10887 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10888 const APInt &UsedBits, bool ForCodeSize) {
10889 unsigned NumberOfSlices = LoadedSlices.size();
10890 if (StressLoadSlicing)
10891 return NumberOfSlices > 1;
10894 if (NumberOfSlices != 2)
10898 if (!areUsedBitsDense(UsedBits))
10902 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10903 // The original code has one big load.
10904 OrigCost.Loads = 1;
10905 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10906 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10907 // Accumulate the cost of all the slices.
10908 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10909 GlobalSlicingCost += SliceCost;
10911 // Account as cost in the original configuration the gain obtained
10912 // with the current slices.
10913 OrigCost.addSliceGain(LS);
10916 // If the target supports paired load, adjust the cost accordingly.
10917 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10918 return OrigCost > GlobalSlicingCost;
10921 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10922 /// operations, split it in the various pieces being extracted.
10924 /// This sort of thing is introduced by SROA.
10925 /// This slicing takes care not to insert overlapping loads.
10926 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10927 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10928 if (Level < AfterLegalizeDAG)
10931 LoadSDNode *LD = cast<LoadSDNode>(N);
10932 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10933 !LD->getValueType(0).isInteger())
10936 // Keep track of already used bits to detect overlapping values.
10937 // In that case, we will just abort the transformation.
10938 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10940 SmallVector<LoadedSlice, 4> LoadedSlices;
10942 // Check if this load is used as several smaller chunks of bits.
10943 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10944 // of computation for each trunc.
10945 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10946 UI != UIEnd; ++UI) {
10947 // Skip the uses of the chain.
10948 if (UI.getUse().getResNo() != 0)
10951 SDNode *User = *UI;
10952 unsigned Shift = 0;
10954 // Check if this is a trunc(lshr).
10955 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10956 isa<ConstantSDNode>(User->getOperand(1))) {
10957 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10958 User = *User->use_begin();
10961 // At this point, User is a Truncate, iff we encountered, trunc or
10963 if (User->getOpcode() != ISD::TRUNCATE)
10966 // The width of the type must be a power of 2 and greater than 8-bits.
10967 // Otherwise the load cannot be represented in LLVM IR.
10968 // Moreover, if we shifted with a non-8-bits multiple, the slice
10969 // will be across several bytes. We do not support that.
10970 unsigned Width = User->getValueSizeInBits(0);
10971 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10974 // Build the slice for this chain of computations.
10975 LoadedSlice LS(User, LD, Shift, &DAG);
10976 APInt CurrentUsedBits = LS.getUsedBits();
10978 // Check if this slice overlaps with another.
10979 if ((CurrentUsedBits & UsedBits) != 0)
10981 // Update the bits used globally.
10982 UsedBits |= CurrentUsedBits;
10984 // Check if the new slice would be legal.
10988 // Record the slice.
10989 LoadedSlices.push_back(LS);
10992 // Abort slicing if it does not seem to be profitable.
10993 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10998 // Rewrite each chain to use an independent load.
10999 // By construction, each chain can be represented by a unique load.
11001 // Prepare the argument for the new token factor for all the slices.
11002 SmallVector<SDValue, 8> ArgChains;
11003 for (SmallVectorImpl<LoadedSlice>::const_iterator
11004 LSIt = LoadedSlices.begin(),
11005 LSItEnd = LoadedSlices.end();
11006 LSIt != LSItEnd; ++LSIt) {
11007 SDValue SliceInst = LSIt->loadSlice();
11008 CombineTo(LSIt->Inst, SliceInst, true);
11009 if (SliceInst.getOpcode() != ISD::LOAD)
11010 SliceInst = SliceInst.getOperand(0);
11011 assert(SliceInst->getOpcode() == ISD::LOAD &&
11012 "It takes more than a zext to get to the loaded slice!!");
11013 ArgChains.push_back(SliceInst.getValue(1));
11016 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11018 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11022 /// Check to see if V is (and load (ptr), imm), where the load is having
11023 /// specific bytes cleared out. If so, return the byte size being masked out
11024 /// and the shift amount.
11025 static std::pair<unsigned, unsigned>
11026 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11027 std::pair<unsigned, unsigned> Result(0, 0);
11029 // Check for the structure we're looking for.
11030 if (V->getOpcode() != ISD::AND ||
11031 !isa<ConstantSDNode>(V->getOperand(1)) ||
11032 !ISD::isNormalLoad(V->getOperand(0).getNode()))
11035 // Check the chain and pointer.
11036 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11037 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
11039 // The store should be chained directly to the load or be an operand of a
11041 if (LD == Chain.getNode())
11043 else if (Chain->getOpcode() != ISD::TokenFactor)
11044 return Result; // Fail.
11047 for (const SDValue &ChainOp : Chain->op_values())
11048 if (ChainOp.getNode() == LD) {
11052 if (!isOk) return Result;
11055 // This only handles simple types.
11056 if (V.getValueType() != MVT::i16 &&
11057 V.getValueType() != MVT::i32 &&
11058 V.getValueType() != MVT::i64)
11061 // Check the constant mask. Invert it so that the bits being masked out are
11062 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
11063 // follow the sign bit for uniformity.
11064 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
11065 unsigned NotMaskLZ = countLeadingZeros(NotMask);
11066 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
11067 unsigned NotMaskTZ = countTrailingZeros(NotMask);
11068 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
11069 if (NotMaskLZ == 64) return Result; // All zero mask.
11071 // See if we have a continuous run of bits. If so, we have 0*1+0*
11072 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
11075 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
11076 if (V.getValueType() != MVT::i64 && NotMaskLZ)
11077 NotMaskLZ -= 64-V.getValueSizeInBits();
11079 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
11080 switch (MaskedBytes) {
11084 default: return Result; // All one mask, or 5-byte mask.
11087 // Verify that the first bit starts at a multiple of mask so that the access
11088 // is aligned the same as the access width.
11089 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
11091 Result.first = MaskedBytes;
11092 Result.second = NotMaskTZ/8;
11097 /// Check to see if IVal is something that provides a value as specified by
11098 /// MaskInfo. If so, replace the specified store with a narrower store of
11099 /// truncated IVal.
11101 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
11102 SDValue IVal, StoreSDNode *St,
11104 unsigned NumBytes = MaskInfo.first;
11105 unsigned ByteShift = MaskInfo.second;
11106 SelectionDAG &DAG = DC->getDAG();
11108 // Check to see if IVal is all zeros in the part being masked in by the 'or'
11109 // that uses this. If not, this is not a replacement.
11110 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
11111 ByteShift*8, (ByteShift+NumBytes)*8);
11112 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
11114 // Check that it is legal on the target to do this. It is legal if the new
11115 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
11117 MVT VT = MVT::getIntegerVT(NumBytes*8);
11118 if (!DC->isTypeLegal(VT))
11121 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
11122 // shifted by ByteShift and truncated down to NumBytes.
11125 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
11126 DAG.getConstant(ByteShift*8, DL,
11127 DC->getShiftAmountTy(IVal.getValueType())));
11130 // Figure out the offset for the store and the alignment of the access.
11132 unsigned NewAlign = St->getAlignment();
11134 if (DAG.getDataLayout().isLittleEndian())
11135 StOffset = ByteShift;
11137 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11139 SDValue Ptr = St->getBasePtr();
11142 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11143 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11144 NewAlign = MinAlign(NewAlign, StOffset);
11147 // Truncate down to the new size.
11148 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11152 .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11153 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11158 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11159 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11160 /// narrowing the load and store if it would end up being a win for performance
11162 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11163 StoreSDNode *ST = cast<StoreSDNode>(N);
11164 if (ST->isVolatile())
11167 SDValue Chain = ST->getChain();
11168 SDValue Value = ST->getValue();
11169 SDValue Ptr = ST->getBasePtr();
11170 EVT VT = Value.getValueType();
11172 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11175 unsigned Opc = Value.getOpcode();
11177 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11178 // is a byte mask indicating a consecutive number of bytes, check to see if
11179 // Y is known to provide just those bytes. If so, we try to replace the
11180 // load + replace + store sequence with a single (narrower) store, which makes
11182 if (Opc == ISD::OR) {
11183 std::pair<unsigned, unsigned> MaskedLoad;
11184 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11185 if (MaskedLoad.first)
11186 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11187 Value.getOperand(1), ST,this))
11188 return SDValue(NewST, 0);
11190 // Or is commutative, so try swapping X and Y.
11191 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11192 if (MaskedLoad.first)
11193 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11194 Value.getOperand(0), ST,this))
11195 return SDValue(NewST, 0);
11198 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11199 Value.getOperand(1).getOpcode() != ISD::Constant)
11202 SDValue N0 = Value.getOperand(0);
11203 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11204 Chain == SDValue(N0.getNode(), 1)) {
11205 LoadSDNode *LD = cast<LoadSDNode>(N0);
11206 if (LD->getBasePtr() != Ptr ||
11207 LD->getPointerInfo().getAddrSpace() !=
11208 ST->getPointerInfo().getAddrSpace())
11211 // Find the type to narrow it the load / op / store to.
11212 SDValue N1 = Value.getOperand(1);
11213 unsigned BitWidth = N1.getValueSizeInBits();
11214 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11215 if (Opc == ISD::AND)
11216 Imm ^= APInt::getAllOnesValue(BitWidth);
11217 if (Imm == 0 || Imm.isAllOnesValue())
11219 unsigned ShAmt = Imm.countTrailingZeros();
11220 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11221 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11222 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11223 // The narrowing should be profitable, the load/store operation should be
11224 // legal (or custom) and the store size should be equal to the NewVT width.
11225 while (NewBW < BitWidth &&
11226 (NewVT.getStoreSizeInBits() != NewBW ||
11227 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11228 !TLI.isNarrowingProfitable(VT, NewVT))) {
11229 NewBW = NextPowerOf2(NewBW);
11230 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11232 if (NewBW >= BitWidth)
11235 // If the lsb changed does not start at the type bitwidth boundary,
11236 // start at the previous one.
11238 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11239 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11240 std::min(BitWidth, ShAmt + NewBW));
11241 if ((Imm & Mask) == Imm) {
11242 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11243 if (Opc == ISD::AND)
11244 NewImm ^= APInt::getAllOnesValue(NewBW);
11245 uint64_t PtrOff = ShAmt / 8;
11246 // For big endian targets, we need to adjust the offset to the pointer to
11247 // load the correct bytes.
11248 if (DAG.getDataLayout().isBigEndian())
11249 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11251 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11252 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11253 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11256 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11257 Ptr.getValueType(), Ptr,
11258 DAG.getConstant(PtrOff, SDLoc(LD),
11259 Ptr.getValueType()));
11261 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11262 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11263 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11264 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11265 DAG.getConstant(NewImm, SDLoc(Value),
11268 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11269 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11271 AddToWorklist(NewPtr.getNode());
11272 AddToWorklist(NewLD.getNode());
11273 AddToWorklist(NewVal.getNode());
11274 WorklistRemover DeadNodes(*this);
11275 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11284 /// For a given floating point load / store pair, if the load value isn't used
11285 /// by any other operations, then consider transforming the pair to integer
11286 /// load / store operations if the target deems the transformation profitable.
11287 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11288 StoreSDNode *ST = cast<StoreSDNode>(N);
11289 SDValue Chain = ST->getChain();
11290 SDValue Value = ST->getValue();
11291 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11292 Value.hasOneUse() &&
11293 Chain == SDValue(Value.getNode(), 1)) {
11294 LoadSDNode *LD = cast<LoadSDNode>(Value);
11295 EVT VT = LD->getMemoryVT();
11296 if (!VT.isFloatingPoint() ||
11297 VT != ST->getMemoryVT() ||
11298 LD->isNonTemporal() ||
11299 ST->isNonTemporal() ||
11300 LD->getPointerInfo().getAddrSpace() != 0 ||
11301 ST->getPointerInfo().getAddrSpace() != 0)
11304 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11305 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11306 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11307 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11308 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11311 unsigned LDAlign = LD->getAlignment();
11312 unsigned STAlign = ST->getAlignment();
11313 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11314 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11315 if (LDAlign < ABIAlign || STAlign < ABIAlign)
11319 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11320 LD->getPointerInfo(), LDAlign);
11323 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11324 ST->getPointerInfo(), STAlign);
11326 AddToWorklist(NewLD.getNode());
11327 AddToWorklist(NewST.getNode());
11328 WorklistRemover DeadNodes(*this);
11329 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11337 // This is a helper function for visitMUL to check the profitability
11338 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11339 // MulNode is the original multiply, AddNode is (add x, c1),
11340 // and ConstNode is c2.
11342 // If the (add x, c1) has multiple uses, we could increase
11343 // the number of adds if we make this transformation.
11344 // It would only be worth doing this if we can remove a
11345 // multiply in the process. Check for that here.
11349 // We're checking for cases where we have common "c3 * A" expressions.
11350 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11352 SDValue &ConstNode) {
11355 // If the add only has one use, this would be OK to do.
11356 if (AddNode.getNode()->hasOneUse())
11359 // Walk all the users of the constant with which we're multiplying.
11360 for (SDNode *Use : ConstNode->uses()) {
11362 if (Use == MulNode) // This use is the one we're on right now. Skip it.
11365 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11367 SDNode *MulVar = AddNode.getOperand(0).getNode();
11369 // OtherOp is what we're multiplying against the constant.
11370 if (Use->getOperand(0) == ConstNode)
11371 OtherOp = Use->getOperand(1).getNode();
11373 OtherOp = Use->getOperand(0).getNode();
11375 // Check to see if multiply is with the same operand of our "add".
11377 // ConstNode = CONST
11378 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
11380 // AddNode = (A + c1) <-- MulVar is A.
11381 // = AddNode * ConstNode <-- current visiting instruction.
11383 // If we make this transformation, we will have a common
11384 // multiply (ConstNode * A) that we can save.
11385 if (OtherOp == MulVar)
11388 // Now check to see if a future expansion will give us a common
11391 // ConstNode = CONST
11392 // AddNode = (A + c1)
11393 // ... = AddNode * ConstNode <-- current visiting instruction.
11395 // OtherOp = (A + c2)
11396 // Use = OtherOp * ConstNode <-- visiting Use.
11398 // If we make this transformation, we will have a common
11399 // multiply (CONST * A) after we also do the same transformation
11400 // to the "t2" instruction.
11401 if (OtherOp->getOpcode() == ISD::ADD &&
11402 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11403 OtherOp->getOperand(0).getNode() == MulVar)
11408 // Didn't find a case where this would be profitable.
11412 SDValue DAGCombiner::getMergedConstantVectorStore(
11413 SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11414 SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11415 SmallVector<SDValue, 8> BuildVector;
11417 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11418 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11419 Chains.push_back(St->getChain());
11420 BuildVector.push_back(St->getValue());
11423 return DAG.getBuildVector(Ty, SL, BuildVector);
11426 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11427 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11428 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11429 // Make sure we have something to merge.
11433 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11434 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11435 unsigned LatestNodeUsed = 0;
11437 for (unsigned i=0; i < NumStores; ++i) {
11438 // Find a chain for the new wide-store operand. Notice that some
11439 // of the store nodes that we found may not be selected for inclusion
11440 // in the wide store. The chain we use needs to be the chain of the
11441 // latest store node which is *used* and replaced by the wide store.
11442 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11443 LatestNodeUsed = i;
11446 SmallVector<SDValue, 8> Chains;
11448 // The latest Node in the DAG.
11449 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11450 SDLoc DL(StoreNodes[0].MemNode);
11454 bool IsVec = MemVT.isVector();
11455 unsigned Elts = NumStores;
11457 // When merging vector stores, get the total number of elements.
11458 Elts *= MemVT.getVectorNumElements();
11460 // Get the type for the merged vector store.
11461 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11462 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11464 if (IsConstantSrc) {
11465 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11467 SmallVector<SDValue, 8> Ops;
11468 for (unsigned i = 0; i < NumStores; ++i) {
11469 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11470 SDValue Val = St->getValue();
11471 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11472 if (Val.getValueType() != MemVT)
11474 Ops.push_back(Val);
11475 Chains.push_back(St->getChain());
11478 // Build the extracted vector elements back into a vector.
11479 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11482 // We should always use a vector store when merging extracted vector
11483 // elements, so this path implies a store of constants.
11484 assert(IsConstantSrc && "Merged vector elements should use vector store");
11486 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11487 APInt StoreInt(SizeInBits, 0);
11489 // Construct a single integer constant which is made of the smaller
11490 // constant inputs.
11491 bool IsLE = DAG.getDataLayout().isLittleEndian();
11492 for (unsigned i = 0; i < NumStores; ++i) {
11493 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11494 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11495 Chains.push_back(St->getChain());
11497 SDValue Val = St->getValue();
11498 StoreInt <<= ElementSizeBytes * 8;
11499 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11500 StoreInt |= C->getAPIntValue().zext(SizeInBits);
11501 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11502 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11504 llvm_unreachable("Invalid constant element type");
11508 // Create the new Load and Store operations.
11509 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11510 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11513 assert(!Chains.empty());
11515 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11516 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11517 FirstInChain->getBasePtr(),
11518 FirstInChain->getPointerInfo(),
11519 FirstInChain->getAlignment());
11521 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11522 : DAG.getSubtarget().useAA();
11524 // Replace all merged stores with the new store.
11525 for (unsigned i = 0; i < NumStores; ++i)
11526 CombineTo(StoreNodes[i].MemNode, NewStore);
11528 // Replace the last store with the new store.
11529 CombineTo(LatestOp, NewStore);
11530 // Erase all other stores.
11531 for (unsigned i = 0; i < NumStores; ++i) {
11532 if (StoreNodes[i].MemNode == LatestOp)
11534 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11535 // ReplaceAllUsesWith will replace all uses that existed when it was
11536 // called, but graph optimizations may cause new ones to appear. For
11537 // example, the case in pr14333 looks like
11539 // St's chain -> St -> another store -> X
11541 // And the only difference from St to the other store is the chain.
11542 // When we change it's chain to be St's chain they become identical,
11543 // get CSEed and the net result is that X is now a use of St.
11544 // Since we know that St is redundant, just iterate.
11545 while (!St->use_empty())
11546 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11547 deleteAndRecombine(St);
11551 StoreNodes.erase(StoreNodes.begin() + NumStores, StoreNodes.end());
11555 void DAGCombiner::getStoreMergeAndAliasCandidates(
11556 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11557 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11558 // This holds the base pointer, index, and the offset in bytes from the base
11560 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11562 // We must have a base and an offset.
11563 if (!BasePtr.Base.getNode())
11566 // Do not handle stores to undef base pointers.
11567 if (BasePtr.Base.isUndef())
11570 // Walk up the chain and look for nodes with offsets from the same
11571 // base pointer. Stop when reaching an instruction with a different kind
11572 // or instruction which has a different base pointer.
11573 EVT MemVT = St->getMemoryVT();
11575 StoreSDNode *Index = St;
11578 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11579 : DAG.getSubtarget().useAA();
11582 // Look at other users of the same chain. Stores on the same chain do not
11583 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11584 // to be on the same chain, so don't bother looking at adjacent chains.
11586 SDValue Chain = St->getChain();
11587 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11588 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11589 if (I.getOperandNo() != 0)
11592 if (OtherST->isVolatile() || OtherST->isIndexed())
11595 if (OtherST->getMemoryVT() != MemVT)
11598 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11600 if (Ptr.equalBaseIndex(BasePtr))
11601 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11609 // If the chain has more than one use, then we can't reorder the mem ops.
11610 if (Index != St && !SDValue(Index, 0)->hasOneUse())
11613 // Find the base pointer and offset for this memory node.
11614 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11616 // Check that the base pointer is the same as the original one.
11617 if (!Ptr.equalBaseIndex(BasePtr))
11620 // The memory operands must not be volatile.
11621 if (Index->isVolatile() || Index->isIndexed())
11625 if (Index->isTruncatingStore())
11628 // The stored memory type must be the same.
11629 if (Index->getMemoryVT() != MemVT)
11632 // We do not allow under-aligned stores in order to prevent
11633 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11634 // be irrelevant here; what MATTERS is that we not move memory
11635 // operations that potentially overlap past each-other.
11636 if (Index->getAlignment() < MemVT.getStoreSize())
11639 // We found a potential memory operand to merge.
11640 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11642 // Find the next memory operand in the chain. If the next operand in the
11643 // chain is a store then move up and continue the scan with the next
11644 // memory operand. If the next operand is a load save it and use alias
11645 // information to check if it interferes with anything.
11646 SDNode *NextInChain = Index->getChain().getNode();
11648 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11649 // We found a store node. Use it for the next iteration.
11652 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11653 if (Ldn->isVolatile()) {
11658 // Save the load node for later. Continue the scan.
11659 AliasLoadNodes.push_back(Ldn);
11660 NextInChain = Ldn->getChain().getNode();
11670 // We need to check that merging these stores does not cause a loop
11671 // in the DAG. Any store candidate may depend on another candidate
11672 // indirectly through its operand (we already consider dependencies
11673 // through the chain). Check in parallel by searching up from
11674 // non-chain operands of candidates.
11675 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11676 SmallVectorImpl<MemOpLink> &StoreNodes) {
11677 SmallPtrSet<const SDNode *, 16> Visited;
11678 SmallVector<const SDNode *, 8> Worklist;
11679 // search ops of store candidates
11680 for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11681 SDNode *n = StoreNodes[i].MemNode;
11682 // Potential loops may happen only through non-chain operands
11683 for (unsigned j = 1; j < n->getNumOperands(); ++j)
11684 Worklist.push_back(n->getOperand(j).getNode());
11686 // search through DAG. We can stop early if we find a storenode
11687 for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11688 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11694 bool DAGCombiner::MergeConsecutiveStores(
11695 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes) {
11696 if (OptLevel == CodeGenOpt::None)
11699 EVT MemVT = St->getMemoryVT();
11700 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11701 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11702 Attribute::NoImplicitFloat);
11704 // This function cannot currently deal with non-byte-sized memory sizes.
11705 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11708 if (!MemVT.isSimple())
11711 // Perform an early exit check. Do not bother looking at stored values that
11712 // are not constants, loads, or extracted vector elements.
11713 SDValue StoredVal = St->getValue();
11714 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11715 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11716 isa<ConstantFPSDNode>(StoredVal);
11717 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11718 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11720 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11723 // Don't merge vectors into wider vectors if the source data comes from loads.
11724 // TODO: This restriction can be lifted by using logic similar to the
11725 // ExtractVecSrc case.
11726 if (MemVT.isVector() && IsLoadSrc)
11729 // Only look at ends of store sequences.
11730 SDValue Chain = SDValue(St, 0);
11731 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11734 // Save the LoadSDNodes that we find in the chain.
11735 // We need to make sure that these nodes do not interfere with
11736 // any of the store nodes.
11737 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11739 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11741 // Check if there is anything to merge.
11742 if (StoreNodes.size() < 2)
11745 // only do dependence check in AA case
11746 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11747 : DAG.getSubtarget().useAA();
11748 if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11751 // Sort the memory operands according to their distance from the
11752 // base pointer. As a secondary criteria: make sure stores coming
11753 // later in the code come first in the list. This is important for
11754 // the non-UseAA case, because we're merging stores into the FINAL
11755 // store along a chain which potentially contains aliasing stores.
11756 // Thus, if there are multiple stores to the same address, the last
11757 // one can be considered for merging but not the others.
11758 std::sort(StoreNodes.begin(), StoreNodes.end(),
11759 [](MemOpLink LHS, MemOpLink RHS) {
11760 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11761 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11762 LHS.SequenceNum < RHS.SequenceNum);
11765 // Scan the memory operations on the chain and find the first non-consecutive
11766 // store memory address.
11767 unsigned LastConsecutiveStore = 0;
11768 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11769 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11771 // Check that the addresses are consecutive starting from the second
11772 // element in the list of stores.
11774 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11775 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11779 // Check if this store interferes with any of the loads that we found.
11780 // If we find a load that alias with this store. Stop the sequence.
11781 if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) {
11782 return isAlias(Ldn, StoreNodes[i].MemNode);
11786 // Mark this node as useful.
11787 LastConsecutiveStore = i;
11790 // The node with the lowest store address.
11791 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11792 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11793 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11794 LLVMContext &Context = *DAG.getContext();
11795 const DataLayout &DL = DAG.getDataLayout();
11797 // Store the constants into memory as one consecutive store.
11798 if (IsConstantSrc) {
11799 unsigned LastLegalType = 0;
11800 unsigned LastLegalVectorType = 0;
11801 bool NonZero = false;
11802 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11803 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11804 SDValue StoredVal = St->getValue();
11806 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11807 NonZero |= !C->isNullValue();
11808 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11809 NonZero |= !C->getConstantFPValue()->isNullValue();
11815 // Find a legal type for the constant store.
11816 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11817 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11819 if (TLI.isTypeLegal(StoreTy) &&
11820 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11821 FirstStoreAlign, &IsFast) && IsFast) {
11822 LastLegalType = i+1;
11823 // Or check whether a truncstore is legal.
11824 } else if (TLI.getTypeAction(Context, StoreTy) ==
11825 TargetLowering::TypePromoteInteger) {
11826 EVT LegalizedStoredValueTy =
11827 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11828 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11829 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11830 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11832 LastLegalType = i + 1;
11836 // We only use vectors if the constant is known to be zero or the target
11837 // allows it and the function is not marked with the noimplicitfloat
11839 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11842 // Find a legal type for the vector store.
11843 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11844 if (TLI.isTypeLegal(Ty) &&
11845 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11846 FirstStoreAlign, &IsFast) && IsFast)
11847 LastLegalVectorType = i + 1;
11851 // Check if we found a legal integer type to store.
11852 if (LastLegalType == 0 && LastLegalVectorType == 0)
11855 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11856 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11858 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11862 // When extracting multiple vector elements, try to store them
11863 // in one vector store rather than a sequence of scalar stores.
11864 if (IsExtractVecSrc) {
11865 unsigned NumStoresToMerge = 0;
11866 bool IsVec = MemVT.isVector();
11867 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11868 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11869 unsigned StoreValOpcode = St->getValue().getOpcode();
11870 // This restriction could be loosened.
11871 // Bail out if any stored values are not elements extracted from a vector.
11872 // It should be possible to handle mixed sources, but load sources need
11873 // more careful handling (see the block of code below that handles
11874 // consecutive loads).
11875 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11876 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11879 // Find a legal type for the vector store.
11880 unsigned Elts = i + 1;
11882 // When merging vector stores, get the total number of elements.
11883 Elts *= MemVT.getVectorNumElements();
11885 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11887 if (TLI.isTypeLegal(Ty) &&
11888 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11889 FirstStoreAlign, &IsFast) && IsFast)
11890 NumStoresToMerge = i + 1;
11893 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11897 // Below we handle the case of multiple consecutive stores that
11898 // come from multiple consecutive loads. We merge them into a single
11899 // wide load and a single wide store.
11901 // Look for load nodes which are used by the stored values.
11902 SmallVector<MemOpLink, 8> LoadNodes;
11904 // Find acceptable loads. Loads need to have the same chain (token factor),
11905 // must not be zext, volatile, indexed, and they must be consecutive.
11906 BaseIndexOffset LdBasePtr;
11907 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11908 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11909 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11912 // Loads must only have one use.
11913 if (!Ld->hasNUsesOfValue(1, 0))
11916 // The memory operands must not be volatile.
11917 if (Ld->isVolatile() || Ld->isIndexed())
11920 // We do not accept ext loads.
11921 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11924 // The stored memory type must be the same.
11925 if (Ld->getMemoryVT() != MemVT)
11928 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11929 // If this is not the first ptr that we check.
11930 if (LdBasePtr.Base.getNode()) {
11931 // The base ptr must be the same.
11932 if (!LdPtr.equalBaseIndex(LdBasePtr))
11935 // Check that all other base pointers are the same as this one.
11939 // We found a potential memory operand to merge.
11940 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11943 if (LoadNodes.size() < 2)
11946 // If we have load/store pair instructions and we only have two values,
11948 unsigned RequiredAlignment;
11949 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11950 St->getAlignment() >= RequiredAlignment)
11953 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11954 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11955 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11957 // Scan the memory operations on the chain and find the first non-consecutive
11958 // load memory address. These variables hold the index in the store node
11960 unsigned LastConsecutiveLoad = 0;
11961 // This variable refers to the size and not index in the array.
11962 unsigned LastLegalVectorType = 0;
11963 unsigned LastLegalIntegerType = 0;
11964 StartAddress = LoadNodes[0].OffsetFromBase;
11965 SDValue FirstChain = FirstLoad->getChain();
11966 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11967 // All loads must share the same chain.
11968 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11971 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11972 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11974 LastConsecutiveLoad = i;
11975 // Find a legal type for the vector store.
11976 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11977 bool IsFastSt, IsFastLd;
11978 if (TLI.isTypeLegal(StoreTy) &&
11979 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11980 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11981 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11982 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11983 LastLegalVectorType = i + 1;
11986 // Find a legal type for the integer store.
11987 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11988 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11989 if (TLI.isTypeLegal(StoreTy) &&
11990 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11991 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11992 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11993 FirstLoadAlign, &IsFastLd) && IsFastLd)
11994 LastLegalIntegerType = i + 1;
11995 // Or check whether a truncstore and extload is legal.
11996 else if (TLI.getTypeAction(Context, StoreTy) ==
11997 TargetLowering::TypePromoteInteger) {
11998 EVT LegalizedStoredValueTy =
11999 TLI.getTypeToTransformTo(Context, StoreTy);
12000 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12001 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12002 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12003 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12004 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12005 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
12007 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12008 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
12010 LastLegalIntegerType = i+1;
12014 // Only use vector types if the vector type is larger than the integer type.
12015 // If they are the same, use integers.
12016 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
12017 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
12019 // We add +1 here because the LastXXX variables refer to location while
12020 // the NumElem refers to array/index size.
12021 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
12022 NumElem = std::min(LastLegalType, NumElem);
12027 // Collect the chains from all merged stores.
12028 SmallVector<SDValue, 8> MergeStoreChains;
12029 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
12031 // The latest Node in the DAG.
12032 unsigned LatestNodeUsed = 0;
12033 for (unsigned i=1; i<NumElem; ++i) {
12034 // Find a chain for the new wide-store operand. Notice that some
12035 // of the store nodes that we found may not be selected for inclusion
12036 // in the wide store. The chain we use needs to be the chain of the
12037 // latest store node which is *used* and replaced by the wide store.
12038 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
12039 LatestNodeUsed = i;
12041 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
12044 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
12046 // Find if it is better to use vectors or integers to load and store
12050 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12052 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12053 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12056 SDLoc LoadDL(LoadNodes[0].MemNode);
12057 SDLoc StoreDL(StoreNodes[0].MemNode);
12059 // The merged loads are required to have the same incoming chain, so
12060 // using the first's chain is acceptable.
12061 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12062 FirstLoad->getBasePtr(),
12063 FirstLoad->getPointerInfo(), FirstLoadAlign);
12065 SDValue NewStoreChain =
12066 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
12069 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12070 FirstInChain->getPointerInfo(), FirstStoreAlign);
12072 // Transfer chain users from old loads to the new load.
12073 for (unsigned i = 0; i < NumElem; ++i) {
12074 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12075 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12076 SDValue(NewLoad.getNode(), 1));
12080 // Replace the all stores with the new store.
12081 for (unsigned i = 0; i < NumElem; ++i)
12082 CombineTo(StoreNodes[i].MemNode, NewStore);
12084 // Replace the last store with the new store.
12085 CombineTo(LatestOp, NewStore);
12086 // Erase all other stores.
12087 for (unsigned i = 0; i < NumElem; ++i) {
12088 // Remove all Store nodes.
12089 if (StoreNodes[i].MemNode == LatestOp)
12091 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12092 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
12093 deleteAndRecombine(St);
12097 StoreNodes.erase(StoreNodes.begin() + NumElem, StoreNodes.end());
12101 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12105 // Replace the chain to avoid dependency.
12106 if (ST->isTruncatingStore()) {
12107 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12108 ST->getBasePtr(), ST->getMemoryVT(),
12109 ST->getMemOperand());
12111 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12112 ST->getMemOperand());
12115 // Create token to keep both nodes around.
12116 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12117 MVT::Other, ST->getChain(), ReplStore);
12119 // Make sure the new and old chains are cleaned up.
12120 AddToWorklist(Token.getNode());
12122 // Don't add users to work list.
12123 return CombineTo(ST, Token, false);
12126 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12127 SDValue Value = ST->getValue();
12128 if (Value.getOpcode() == ISD::TargetConstantFP)
12133 SDValue Chain = ST->getChain();
12134 SDValue Ptr = ST->getBasePtr();
12136 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12138 // NOTE: If the original store is volatile, this transform must not increase
12139 // the number of stores. For example, on x86-32 an f64 can be stored in one
12140 // processor operation but an i64 (which is not legal) requires two. So the
12141 // transform should not be done in this case.
12144 switch (CFP->getSimpleValueType(0).SimpleTy) {
12146 llvm_unreachable("Unknown FP type");
12147 case MVT::f16: // We don't do this for these yet.
12153 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12154 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12156 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12157 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12159 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12164 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12165 !ST->isVolatile()) ||
12166 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12168 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12169 getZExtValue(), SDLoc(CFP), MVT::i64);
12170 return DAG.getStore(Chain, DL, Tmp,
12171 Ptr, ST->getMemOperand());
12174 if (!ST->isVolatile() &&
12175 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12176 // Many FP stores are not made apparent until after legalize, e.g. for
12177 // argument passing. Since this is so common, custom legalize the
12178 // 64-bit integer store into two 32-bit stores.
12179 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12180 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12181 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12182 if (DAG.getDataLayout().isBigEndian())
12185 unsigned Alignment = ST->getAlignment();
12186 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12187 AAMDNodes AAInfo = ST->getAAInfo();
12189 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12190 ST->getAlignment(), MMOFlags, AAInfo);
12191 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12192 DAG.getConstant(4, DL, Ptr.getValueType()));
12193 Alignment = MinAlign(Alignment, 4U);
12194 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12195 ST->getPointerInfo().getWithOffset(4),
12196 Alignment, MMOFlags, AAInfo);
12197 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12205 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12206 StoreSDNode *ST = cast<StoreSDNode>(N);
12207 SDValue Chain = ST->getChain();
12208 SDValue Value = ST->getValue();
12209 SDValue Ptr = ST->getBasePtr();
12211 // If this is a store of a bit convert, store the input value if the
12212 // resultant store does not need a higher alignment than the original.
12213 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12214 ST->isUnindexed()) {
12215 EVT SVT = Value.getOperand(0).getValueType();
12216 if (((!LegalOperations && !ST->isVolatile()) ||
12217 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12218 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12219 unsigned OrigAlign = ST->getAlignment();
12221 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12222 ST->getAddressSpace(), OrigAlign, &Fast) &&
12224 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12225 ST->getPointerInfo(), OrigAlign,
12226 ST->getMemOperand()->getFlags(), ST->getAAInfo());
12231 // Turn 'store undef, Ptr' -> nothing.
12232 if (Value.isUndef() && ST->isUnindexed())
12235 // Try to infer better alignment information than the store already has.
12236 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12237 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12238 if (Align > ST->getAlignment()) {
12240 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12241 ST->getMemoryVT(), Align,
12242 ST->getMemOperand()->getFlags(), ST->getAAInfo());
12243 if (NewStore.getNode() != N)
12244 return CombineTo(ST, NewStore, true);
12249 // Try transforming a pair floating point load / store ops to integer
12250 // load / store ops.
12251 if (SDValue NewST = TransformFPLoadStorePair(N))
12254 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12255 : DAG.getSubtarget().useAA();
12257 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12258 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12261 if (UseAA && ST->isUnindexed()) {
12262 // FIXME: We should do this even without AA enabled. AA will just allow
12263 // FindBetterChain to work in more situations. The problem with this is that
12264 // any combine that expects memory operations to be on consecutive chains
12265 // first needs to be updated to look for users of the same chain.
12267 // Walk up chain skipping non-aliasing memory nodes, on this store and any
12268 // adjacent stores.
12269 if (findBetterNeighborChains(ST)) {
12270 // replaceStoreChain uses CombineTo, which handled all of the worklist
12271 // manipulation. Return the original node to not do anything else.
12272 return SDValue(ST, 0);
12274 Chain = ST->getChain();
12277 // Try transforming N to an indexed store.
12278 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12279 return SDValue(N, 0);
12281 // FIXME: is there such a thing as a truncating indexed store?
12282 if (ST->isTruncatingStore() && ST->isUnindexed() &&
12283 Value.getValueType().isInteger()) {
12284 // See if we can simplify the input to this truncstore with knowledge that
12285 // only the low bits are being used. For example:
12286 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
12287 SDValue Shorter = GetDemandedBits(
12288 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12289 ST->getMemoryVT().getScalarSizeInBits()));
12290 AddToWorklist(Value.getNode());
12291 if (Shorter.getNode())
12292 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12293 Ptr, ST->getMemoryVT(), ST->getMemOperand());
12295 // Otherwise, see if we can simplify the operation with
12296 // SimplifyDemandedBits, which only works if the value has a single use.
12297 if (SimplifyDemandedBits(
12299 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12300 ST->getMemoryVT().getScalarSizeInBits())))
12301 return SDValue(N, 0);
12304 // If this is a load followed by a store to the same location, then the store
12306 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12307 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12308 ST->isUnindexed() && !ST->isVolatile() &&
12309 // There can't be any side effects between the load and store, such as
12310 // a call or store.
12311 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12312 // The store is dead, remove it.
12317 // If this is a store followed by a store with the same value to the same
12318 // location, then the store is dead/noop.
12319 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12320 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12321 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12322 ST1->isUnindexed() && !ST1->isVolatile()) {
12323 // The store is dead, remove it.
12328 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12329 // truncating store. We can do this even if this is already a truncstore.
12330 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12331 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12332 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12333 ST->getMemoryVT())) {
12334 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12335 Ptr, ST->getMemoryVT(), ST->getMemOperand());
12338 // Only perform this optimization before the types are legal, because we
12339 // don't want to perform this optimization on every DAGCombine invocation.
12342 // There can be multiple store sequences on the same chain.
12343 // Keep trying to merge store sequences until we are unable to do so
12344 // or until we merge the last store on the chain.
12345 SmallVector<MemOpLink, 8> StoreNodes;
12346 bool Changed = MergeConsecutiveStores(ST, StoreNodes);
12347 if (!Changed) break;
12349 if (any_of(StoreNodes,
12350 [ST](const MemOpLink &Link) { return Link.MemNode == ST; })) {
12351 // ST has been merged and no longer exists.
12352 return SDValue(N, 0);
12357 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12359 // Make sure to do this only after attempting to merge stores in order to
12360 // avoid changing the types of some subset of stores due to visit order,
12361 // preventing their merging.
12362 if (isa<ConstantFPSDNode>(Value)) {
12363 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12367 if (SDValue NewSt = splitMergedValStore(ST))
12370 return ReduceLoadOpStoreWidth(N);
12373 /// For the instruction sequence of store below, F and I values
12374 /// are bundled together as an i64 value before being stored into memory.
12375 /// Sometimes it is more efficent to generate separate stores for F and I,
12376 /// which can remove the bitwise instructions or sink them to colder places.
12378 /// (store (or (zext (bitcast F to i32) to i64),
12379 /// (shl (zext I to i64), 32)), addr) -->
12380 /// (store F, addr) and (store I, addr+4)
12382 /// Similarly, splitting for other merged store can also be beneficial, like:
12383 /// For pair of {i32, i32}, i64 store --> two i32 stores.
12384 /// For pair of {i32, i16}, i64 store --> two i32 stores.
12385 /// For pair of {i16, i16}, i32 store --> two i16 stores.
12386 /// For pair of {i16, i8}, i32 store --> two i16 stores.
12387 /// For pair of {i8, i8}, i16 store --> two i8 stores.
12389 /// We allow each target to determine specifically which kind of splitting is
12392 /// The store patterns are commonly seen from the simple code snippet below
12393 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
12394 /// void goo(const std::pair<int, float> &);
12397 /// goo(std::make_pair(tmp, ftmp));
12401 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
12402 if (OptLevel == CodeGenOpt::None)
12405 SDValue Val = ST->getValue();
12408 // Match OR operand.
12409 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
12412 // Match SHL operand and get Lower and Higher parts of Val.
12413 SDValue Op1 = Val.getOperand(0);
12414 SDValue Op2 = Val.getOperand(1);
12416 if (Op1.getOpcode() != ISD::SHL) {
12417 std::swap(Op1, Op2);
12418 if (Op1.getOpcode() != ISD::SHL)
12422 Hi = Op1.getOperand(0);
12423 if (!Op1.hasOneUse())
12426 // Match shift amount to HalfValBitSize.
12427 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
12428 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
12429 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
12432 // Lo and Hi are zero-extended from int with size less equal than 32
12434 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
12435 !Lo.getOperand(0).getValueType().isScalarInteger() ||
12436 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
12437 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
12438 !Hi.getOperand(0).getValueType().isScalarInteger() ||
12439 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
12442 // Use the EVT of low and high parts before bitcast as the input
12443 // of target query.
12444 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
12445 ? Lo.getOperand(0).getValueType()
12446 : Lo.getValueType();
12447 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
12448 ? Hi.getOperand(0).getValueType()
12449 : Hi.getValueType();
12450 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
12453 // Start to split store.
12454 unsigned Alignment = ST->getAlignment();
12455 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12456 AAMDNodes AAInfo = ST->getAAInfo();
12458 // Change the sizes of Lo and Hi's value types to HalfValBitSize.
12459 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
12460 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
12461 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
12463 SDValue Chain = ST->getChain();
12464 SDValue Ptr = ST->getBasePtr();
12465 // Lower value store.
12466 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12467 ST->getAlignment(), MMOFlags, AAInfo);
12469 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12470 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
12471 // Higher value store.
12473 DAG.getStore(St0, DL, Hi, Ptr,
12474 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
12475 Alignment / 2, MMOFlags, AAInfo);
12479 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12480 SDValue InVec = N->getOperand(0);
12481 SDValue InVal = N->getOperand(1);
12482 SDValue EltNo = N->getOperand(2);
12485 // If the inserted element is an UNDEF, just use the input vector.
12486 if (InVal.isUndef())
12489 EVT VT = InVec.getValueType();
12491 // If we can't generate a legal BUILD_VECTOR, exit
12492 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12495 // Check that we know which element is being inserted
12496 if (!isa<ConstantSDNode>(EltNo))
12498 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12500 // Canonicalize insert_vector_elt dag nodes.
12502 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12503 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12505 // Do this only if the child insert_vector node has one use; also
12506 // do this only if indices are both constants and Idx1 < Idx0.
12507 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12508 && isa<ConstantSDNode>(InVec.getOperand(2))) {
12509 unsigned OtherElt =
12510 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12511 if (Elt < OtherElt) {
12513 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
12514 InVec.getOperand(0), InVal, EltNo);
12515 AddToWorklist(NewOp.getNode());
12516 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12517 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12521 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12522 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
12523 // vector elements.
12524 SmallVector<SDValue, 8> Ops;
12525 // Do not combine these two vectors if the output vector will not replace
12526 // the input vector.
12527 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12528 Ops.append(InVec.getNode()->op_begin(),
12529 InVec.getNode()->op_end());
12530 } else if (InVec.isUndef()) {
12531 unsigned NElts = VT.getVectorNumElements();
12532 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12537 // Insert the element
12538 if (Elt < Ops.size()) {
12539 // All the operands of BUILD_VECTOR must have the same type;
12540 // we enforce that here.
12541 EVT OpVT = Ops[0].getValueType();
12542 if (InVal.getValueType() != OpVT)
12543 InVal = OpVT.bitsGT(InVal.getValueType()) ?
12544 DAG.getNode(ISD::ANY_EXTEND, DL, OpVT, InVal) :
12545 DAG.getNode(ISD::TRUNCATE, DL, OpVT, InVal);
12549 // Return the new vector
12550 return DAG.getBuildVector(VT, DL, Ops);
12553 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12554 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12555 assert(!OriginalLoad->isVolatile());
12557 EVT ResultVT = EVE->getValueType(0);
12558 EVT VecEltVT = InVecVT.getVectorElementType();
12559 unsigned Align = OriginalLoad->getAlignment();
12560 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12561 VecEltVT.getTypeForEVT(*DAG.getContext()));
12563 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12568 SDValue NewPtr = OriginalLoad->getBasePtr();
12570 EVT PtrType = NewPtr.getValueType();
12571 MachinePointerInfo MPI;
12573 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12574 int Elt = ConstEltNo->getZExtValue();
12575 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12576 Offset = DAG.getConstant(PtrOff, DL, PtrType);
12577 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12579 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12580 Offset = DAG.getNode(
12581 ISD::MUL, DL, PtrType, Offset,
12582 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12583 MPI = OriginalLoad->getPointerInfo();
12585 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12587 // The replacement we need to do here is a little tricky: we need to
12588 // replace an extractelement of a load with a load.
12589 // Use ReplaceAllUsesOfValuesWith to do the replacement.
12590 // Note that this replacement assumes that the extractvalue is the only
12591 // use of the load; that's okay because we don't want to perform this
12592 // transformation in other cases anyway.
12595 if (ResultVT.bitsGT(VecEltVT)) {
12596 // If the result type of vextract is wider than the load, then issue an
12597 // extending load instead.
12598 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12602 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12603 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12604 Align, OriginalLoad->getMemOperand()->getFlags(),
12605 OriginalLoad->getAAInfo());
12606 Chain = Load.getValue(1);
12608 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12609 MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12610 OriginalLoad->getAAInfo());
12611 Chain = Load.getValue(1);
12612 if (ResultVT.bitsLT(VecEltVT))
12613 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12615 Load = DAG.getBitcast(ResultVT, Load);
12617 WorklistRemover DeadNodes(*this);
12618 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12619 SDValue To[] = { Load, Chain };
12620 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12621 // Since we're explicitly calling ReplaceAllUses, add the new node to the
12622 // worklist explicitly as well.
12623 AddToWorklist(Load.getNode());
12624 AddUsersToWorklist(Load.getNode()); // Add users too
12625 // Make sure to revisit this node to clean it up; it will usually be dead.
12626 AddToWorklist(EVE);
12628 return SDValue(EVE, 0);
12631 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12632 // (vextract (scalar_to_vector val, 0) -> val
12633 SDValue InVec = N->getOperand(0);
12634 EVT VT = InVec.getValueType();
12635 EVT NVT = N->getValueType(0);
12637 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12638 // Check if the result type doesn't match the inserted element type. A
12639 // SCALAR_TO_VECTOR may truncate the inserted element and the
12640 // EXTRACT_VECTOR_ELT may widen the extracted vector.
12641 SDValue InOp = InVec.getOperand(0);
12642 if (InOp.getValueType() != NVT) {
12643 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12644 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12649 SDValue EltNo = N->getOperand(1);
12650 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12652 // extract_vector_elt (build_vector x, y), 1 -> y
12654 InVec.getOpcode() == ISD::BUILD_VECTOR &&
12655 TLI.isTypeLegal(VT) &&
12656 (InVec.hasOneUse() ||
12657 TLI.aggressivelyPreferBuildVectorSources(VT))) {
12658 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12659 EVT InEltVT = Elt.getValueType();
12661 // Sometimes build_vector's scalar input types do not match result type.
12662 if (NVT == InEltVT)
12665 // TODO: It may be useful to truncate if free if the build_vector implicitly
12669 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12670 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12671 ConstEltNo->isNullValue() && VT.isInteger()) {
12672 SDValue BCSrc = InVec.getOperand(0);
12673 if (BCSrc.getValueType().isScalarInteger())
12674 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12677 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12679 // This only really matters if the index is non-constant since other combines
12680 // on the constant elements already work.
12681 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12682 EltNo == InVec.getOperand(2)) {
12683 SDValue Elt = InVec.getOperand(1);
12684 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12687 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12688 // We only perform this optimization before the op legalization phase because
12689 // we may introduce new vector instructions which are not backed by TD
12690 // patterns. For example on AVX, extracting elements from a wide vector
12691 // without using extract_subvector. However, if we can find an underlying
12692 // scalar value, then we can always use that.
12693 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12694 int NumElem = VT.getVectorNumElements();
12695 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12696 // Find the new index to extract from.
12697 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12699 // Extracting an undef index is undef.
12701 return DAG.getUNDEF(NVT);
12703 // Select the right vector half to extract from.
12705 if (OrigElt < NumElem) {
12706 SVInVec = InVec->getOperand(0);
12708 SVInVec = InVec->getOperand(1);
12709 OrigElt -= NumElem;
12712 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12713 SDValue InOp = SVInVec.getOperand(OrigElt);
12714 if (InOp.getValueType() != NVT) {
12715 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12716 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12722 // FIXME: We should handle recursing on other vector shuffles and
12723 // scalar_to_vector here as well.
12725 if (!LegalOperations) {
12726 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12727 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12728 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12732 bool BCNumEltsChanged = false;
12733 EVT ExtVT = VT.getVectorElementType();
12736 // If the result of load has to be truncated, then it's not necessarily
12738 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12741 if (InVec.getOpcode() == ISD::BITCAST) {
12742 // Don't duplicate a load with other uses.
12743 if (!InVec.hasOneUse())
12746 EVT BCVT = InVec.getOperand(0).getValueType();
12747 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12749 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12750 BCNumEltsChanged = true;
12751 InVec = InVec.getOperand(0);
12752 ExtVT = BCVT.getVectorElementType();
12755 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12756 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12757 ISD::isNormalLoad(InVec.getNode()) &&
12758 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12759 SDValue Index = N->getOperand(1);
12760 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12761 if (!OrigLoad->isVolatile()) {
12762 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12768 // Perform only after legalization to ensure build_vector / vector_shuffle
12769 // optimizations have already been done.
12770 if (!LegalOperations) return SDValue();
12772 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12773 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12774 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12777 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12779 LoadSDNode *LN0 = nullptr;
12780 const ShuffleVectorSDNode *SVN = nullptr;
12781 if (ISD::isNormalLoad(InVec.getNode())) {
12782 LN0 = cast<LoadSDNode>(InVec);
12783 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12784 InVec.getOperand(0).getValueType() == ExtVT &&
12785 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12786 // Don't duplicate a load with other uses.
12787 if (!InVec.hasOneUse())
12790 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12791 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12792 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12794 // (load $addr+1*size)
12796 // Don't duplicate a load with other uses.
12797 if (!InVec.hasOneUse())
12800 // If the bit convert changed the number of elements, it is unsafe
12801 // to examine the mask.
12802 if (BCNumEltsChanged)
12805 // Select the input vector, guarding against out of range extract vector.
12806 unsigned NumElems = VT.getVectorNumElements();
12807 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12808 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12810 if (InVec.getOpcode() == ISD::BITCAST) {
12811 // Don't duplicate a load with other uses.
12812 if (!InVec.hasOneUse())
12815 InVec = InVec.getOperand(0);
12817 if (ISD::isNormalLoad(InVec.getNode())) {
12818 LN0 = cast<LoadSDNode>(InVec);
12819 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12820 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12824 // Make sure we found a non-volatile load and the extractelement is
12826 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12829 // If Idx was -1 above, Elt is going to be -1, so just return undef.
12831 return DAG.getUNDEF(LVT);
12833 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12839 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12840 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12841 // We perform this optimization post type-legalization because
12842 // the type-legalizer often scalarizes integer-promoted vectors.
12843 // Performing this optimization before may create bit-casts which
12844 // will be type-legalized to complex code sequences.
12845 // We perform this optimization only before the operation legalizer because we
12846 // may introduce illegal operations.
12847 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12850 unsigned NumInScalars = N->getNumOperands();
12852 EVT VT = N->getValueType(0);
12854 // Check to see if this is a BUILD_VECTOR of a bunch of values
12855 // which come from any_extend or zero_extend nodes. If so, we can create
12856 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12857 // optimizations. We do not handle sign-extend because we can't fill the sign
12859 EVT SourceType = MVT::Other;
12860 bool AllAnyExt = true;
12862 for (unsigned i = 0; i != NumInScalars; ++i) {
12863 SDValue In = N->getOperand(i);
12864 // Ignore undef inputs.
12865 if (In.isUndef()) continue;
12867 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
12868 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12870 // Abort if the element is not an extension.
12871 if (!ZeroExt && !AnyExt) {
12872 SourceType = MVT::Other;
12876 // The input is a ZeroExt or AnyExt. Check the original type.
12877 EVT InTy = In.getOperand(0).getValueType();
12879 // Check that all of the widened source types are the same.
12880 if (SourceType == MVT::Other)
12883 else if (InTy != SourceType) {
12884 // Multiple income types. Abort.
12885 SourceType = MVT::Other;
12889 // Check if all of the extends are ANY_EXTENDs.
12890 AllAnyExt &= AnyExt;
12893 // In order to have valid types, all of the inputs must be extended from the
12894 // same source type and all of the inputs must be any or zero extend.
12895 // Scalar sizes must be a power of two.
12896 EVT OutScalarTy = VT.getScalarType();
12897 bool ValidTypes = SourceType != MVT::Other &&
12898 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12899 isPowerOf2_32(SourceType.getSizeInBits());
12901 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12902 // turn into a single shuffle instruction.
12906 bool isLE = DAG.getDataLayout().isLittleEndian();
12907 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12908 assert(ElemRatio > 1 && "Invalid element size ratio");
12909 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12910 DAG.getConstant(0, DL, SourceType);
12912 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12913 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12915 // Populate the new build_vector
12916 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12917 SDValue Cast = N->getOperand(i);
12918 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12919 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12920 Cast.isUndef()) && "Invalid cast opcode");
12922 if (Cast.isUndef())
12923 In = DAG.getUNDEF(SourceType);
12925 In = Cast->getOperand(0);
12926 unsigned Index = isLE ? (i * ElemRatio) :
12927 (i * ElemRatio + (ElemRatio - 1));
12929 assert(Index < Ops.size() && "Invalid index");
12933 // The type of the new BUILD_VECTOR node.
12934 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12935 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12936 "Invalid vector size");
12937 // Check if the new vector type is legal.
12938 if (!isTypeLegal(VecVT)) return SDValue();
12940 // Make the new BUILD_VECTOR.
12941 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
12943 // The new BUILD_VECTOR node has the potential to be further optimized.
12944 AddToWorklist(BV.getNode());
12945 // Bitcast to the desired type.
12946 return DAG.getBitcast(VT, BV);
12949 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12950 EVT VT = N->getValueType(0);
12952 unsigned NumInScalars = N->getNumOperands();
12955 EVT SrcVT = MVT::Other;
12956 unsigned Opcode = ISD::DELETED_NODE;
12957 unsigned NumDefs = 0;
12959 for (unsigned i = 0; i != NumInScalars; ++i) {
12960 SDValue In = N->getOperand(i);
12961 unsigned Opc = In.getOpcode();
12963 if (Opc == ISD::UNDEF)
12966 // If all scalar values are floats and converted from integers.
12967 if (Opcode == ISD::DELETED_NODE &&
12968 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12975 EVT InVT = In.getOperand(0).getValueType();
12977 // If all scalar values are typed differently, bail out. It's chosen to
12978 // simplify BUILD_VECTOR of integer types.
12979 if (SrcVT == MVT::Other)
12986 // If the vector has just one element defined, it's not worth to fold it into
12987 // a vectorized one.
12991 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12992 && "Should only handle conversion from integer to float.");
12993 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12995 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12997 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
13000 // Just because the floating-point vector type is legal does not necessarily
13001 // mean that the corresponding integer vector type is.
13002 if (!isTypeLegal(NVT))
13005 SmallVector<SDValue, 8> Opnds;
13006 for (unsigned i = 0; i != NumInScalars; ++i) {
13007 SDValue In = N->getOperand(i);
13010 Opnds.push_back(DAG.getUNDEF(SrcVT));
13012 Opnds.push_back(In.getOperand(0));
13014 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
13015 AddToWorklist(BV.getNode());
13017 return DAG.getNode(Opcode, DL, VT, BV);
13020 SDValue DAGCombiner::createBuildVecShuffle(SDLoc DL, SDNode *N,
13021 ArrayRef<int> VectorMask,
13022 SDValue VecIn1, SDValue VecIn2,
13023 unsigned LeftIdx) {
13024 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13025 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
13027 EVT VT = N->getValueType(0);
13028 EVT InVT1 = VecIn1.getValueType();
13029 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13031 unsigned Vec2Offset = InVT1.getVectorNumElements();
13032 unsigned NumElems = VT.getVectorNumElements();
13033 unsigned ShuffleNumElems = NumElems;
13035 // We can't generate a shuffle node with mismatched input and output types.
13036 // Try to make the types match the type of the output.
13037 if (InVT1 != VT || InVT2 != VT) {
13038 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13039 // If the output vector length is a multiple of both input lengths,
13040 // we can concatenate them and pad the rest with undefs.
13041 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13042 assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13043 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13044 ConcatOps[0] = VecIn1;
13045 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13046 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13047 VecIn2 = SDValue();
13048 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13049 if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13052 if (!VecIn2.getNode()) {
13053 // If we only have one input vector, and it's twice the size of the
13054 // output, split it in two.
13055 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13056 DAG.getConstant(NumElems, DL, IdxTy));
13057 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13058 // Since we now have shorter input vectors, adjust the offset of the
13059 // second vector's start.
13060 Vec2Offset = NumElems;
13061 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13062 // VecIn1 is wider than the output, and we have another, possibly
13063 // smaller input. Pad the smaller input with undefs, shuffle at the
13064 // input vector width, and extract the output.
13065 // The shuffle type is different than VT, so check legality again.
13066 if (LegalOperations &&
13067 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13070 if (InVT1 != InVT2)
13071 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13072 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13073 ShuffleNumElems = NumElems * 2;
13075 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13076 // than VecIn1. We can't handle this for now - this case will disappear
13077 // when we start sorting the vectors by type.
13081 // TODO: Support cases where the length mismatch isn't exactly by a
13083 // TODO: Move this check upwards, so that if we have bad type
13084 // mismatches, we don't create any DAG nodes.
13089 // Initialize mask to undef.
13090 SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13092 // Only need to run up to the number of elements actually used, not the
13093 // total number of elements in the shuffle - if we are shuffling a wider
13094 // vector, the high lanes should be set to undef.
13095 for (unsigned i = 0; i != NumElems; ++i) {
13096 if (VectorMask[i] <= 0)
13099 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13100 if (VectorMask[i] == (int)LeftIdx) {
13101 Mask[i] = ExtIndex;
13102 } else if (VectorMask[i] == (int)LeftIdx + 1) {
13103 Mask[i] = Vec2Offset + ExtIndex;
13107 // The type the input vectors may have changed above.
13108 InVT1 = VecIn1.getValueType();
13110 // If we already have a VecIn2, it should have the same type as VecIn1.
13111 // If we don't, get an undef/zero vector of the appropriate type.
13112 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13113 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13115 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13116 if (ShuffleNumElems > NumElems)
13117 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13122 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13123 // operations. If the types of the vectors we're extracting from allow it,
13124 // turn this into a vector_shuffle node.
13125 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13127 EVT VT = N->getValueType(0);
13129 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13130 if (!isTypeLegal(VT))
13133 // May only combine to shuffle after legalize if shuffle is legal.
13134 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13137 bool UsesZeroVector = false;
13138 unsigned NumElems = N->getNumOperands();
13140 // Record, for each element of the newly built vector, which input vector
13141 // that element comes from. -1 stands for undef, 0 for the zero vector,
13142 // and positive values for the input vectors.
13143 // VectorMask maps each element to its vector number, and VecIn maps vector
13144 // numbers to their initial SDValues.
13146 SmallVector<int, 8> VectorMask(NumElems, -1);
13147 SmallVector<SDValue, 8> VecIn;
13148 VecIn.push_back(SDValue());
13150 for (unsigned i = 0; i != NumElems; ++i) {
13151 SDValue Op = N->getOperand(i);
13156 // See if we can use a blend with a zero vector.
13157 // TODO: Should we generalize this to a blend with an arbitrary constant
13159 if (isNullConstant(Op) || isNullFPConstant(Op)) {
13160 UsesZeroVector = true;
13165 // Not an undef or zero. If the input is something other than an
13166 // EXTRACT_VECTOR_ELT with a constant index, bail out.
13167 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13168 !isa<ConstantSDNode>(Op.getOperand(1)))
13171 SDValue ExtractedFromVec = Op.getOperand(0);
13173 // All inputs must have the same element type as the output.
13174 if (VT.getVectorElementType() !=
13175 ExtractedFromVec.getValueType().getVectorElementType())
13178 // Have we seen this input vector before?
13179 // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13180 // a map back from SDValues to numbers isn't worth it.
13181 unsigned Idx = std::distance(
13182 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13183 if (Idx == VecIn.size())
13184 VecIn.push_back(ExtractedFromVec);
13186 VectorMask[i] = Idx;
13189 // If we didn't find at least one input vector, bail out.
13190 if (VecIn.size() < 2)
13193 // TODO: We want to sort the vectors by descending length, so that adjacent
13194 // pairs have similar length, and the longer vector is always first in the
13197 // TODO: Should this fire if some of the input vectors has illegal type (like
13198 // it does now), or should we let legalization run its course first?
13201 // Take pairs of vectors, and shuffle them so that the result has elements
13202 // from these vectors in the correct places.
13203 // For example, given:
13204 // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13205 // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13206 // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13207 // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13208 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13209 // We will generate:
13210 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13211 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13212 SmallVector<SDValue, 4> Shuffles;
13213 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13214 unsigned LeftIdx = 2 * In + 1;
13215 SDValue VecLeft = VecIn[LeftIdx];
13217 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13219 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13220 VecRight, LeftIdx))
13221 Shuffles.push_back(Shuffle);
13226 // If we need the zero vector as an "ingredient" in the blend tree, add it
13227 // to the list of shuffles.
13228 if (UsesZeroVector)
13229 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13230 : DAG.getConstantFP(0.0, DL, VT));
13232 // If we only have one shuffle, we're done.
13233 if (Shuffles.size() == 1)
13234 return Shuffles[0];
13236 // Update the vector mask to point to the post-shuffle vectors.
13237 for (int &Vec : VectorMask)
13239 Vec = Shuffles.size() - 1;
13241 Vec = (Vec - 1) / 2;
13243 // More than one shuffle. Generate a binary tree of blends, e.g. if from
13244 // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13246 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13247 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13248 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13249 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13250 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13251 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13252 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13254 // Make sure the initial size of the shuffle list is even.
13255 if (Shuffles.size() % 2)
13256 Shuffles.push_back(DAG.getUNDEF(VT));
13258 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13260 Shuffles[CurSize] = DAG.getUNDEF(VT);
13263 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13265 int Right = 2 * In + 1;
13266 SmallVector<int, 8> Mask(NumElems, -1);
13267 for (unsigned i = 0; i != NumElems; ++i) {
13268 if (VectorMask[i] == Left) {
13270 VectorMask[i] = In;
13271 } else if (VectorMask[i] == Right) {
13272 Mask[i] = i + NumElems;
13273 VectorMask[i] = In;
13278 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13282 return Shuffles[0];
13285 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13286 EVT VT = N->getValueType(0);
13288 // A vector built entirely of undefs is undef.
13289 if (ISD::allOperandsUndef(N))
13290 return DAG.getUNDEF(VT);
13292 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13295 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13298 if (SDValue V = reduceBuildVecToShuffle(N))
13304 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13305 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13306 EVT OpVT = N->getOperand(0).getValueType();
13308 // If the operands are legal vectors, leave them alone.
13309 if (TLI.isTypeLegal(OpVT))
13313 EVT VT = N->getValueType(0);
13314 SmallVector<SDValue, 8> Ops;
13316 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13317 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13319 // Keep track of what we encounter.
13320 bool AnyInteger = false;
13321 bool AnyFP = false;
13322 for (const SDValue &Op : N->ops()) {
13323 if (ISD::BITCAST == Op.getOpcode() &&
13324 !Op.getOperand(0).getValueType().isVector())
13325 Ops.push_back(Op.getOperand(0));
13326 else if (ISD::UNDEF == Op.getOpcode())
13327 Ops.push_back(ScalarUndef);
13331 // Note whether we encounter an integer or floating point scalar.
13332 // If it's neither, bail out, it could be something weird like x86mmx.
13333 EVT LastOpVT = Ops.back().getValueType();
13334 if (LastOpVT.isFloatingPoint())
13336 else if (LastOpVT.isInteger())
13342 // If any of the operands is a floating point scalar bitcast to a vector,
13343 // use floating point types throughout, and bitcast everything.
13344 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
13346 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
13347 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13349 for (SDValue &Op : Ops) {
13350 if (Op.getValueType() == SVT)
13355 Op = DAG.getBitcast(SVT, Op);
13360 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
13361 VT.getSizeInBits() / SVT.getSizeInBits());
13362 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
13365 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
13366 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
13367 // most two distinct vectors the same size as the result, attempt to turn this
13368 // into a legal shuffle.
13369 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
13370 EVT VT = N->getValueType(0);
13371 EVT OpVT = N->getOperand(0).getValueType();
13372 int NumElts = VT.getVectorNumElements();
13373 int NumOpElts = OpVT.getVectorNumElements();
13375 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
13376 SmallVector<int, 8> Mask;
13378 for (SDValue Op : N->ops()) {
13379 // Peek through any bitcast.
13380 while (Op.getOpcode() == ISD::BITCAST)
13381 Op = Op.getOperand(0);
13383 // UNDEF nodes convert to UNDEF shuffle mask values.
13384 if (Op.isUndef()) {
13385 Mask.append((unsigned)NumOpElts, -1);
13389 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13392 // What vector are we extracting the subvector from and at what index?
13393 SDValue ExtVec = Op.getOperand(0);
13395 // We want the EVT of the original extraction to correctly scale the
13396 // extraction index.
13397 EVT ExtVT = ExtVec.getValueType();
13399 // Peek through any bitcast.
13400 while (ExtVec.getOpcode() == ISD::BITCAST)
13401 ExtVec = ExtVec.getOperand(0);
13403 // UNDEF nodes convert to UNDEF shuffle mask values.
13404 if (ExtVec.isUndef()) {
13405 Mask.append((unsigned)NumOpElts, -1);
13409 if (!isa<ConstantSDNode>(Op.getOperand(1)))
13411 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13413 // Ensure that we are extracting a subvector from a vector the same
13414 // size as the result.
13415 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13418 // Scale the subvector index to account for any bitcast.
13419 int NumExtElts = ExtVT.getVectorNumElements();
13420 if (0 == (NumExtElts % NumElts))
13421 ExtIdx /= (NumExtElts / NumElts);
13422 else if (0 == (NumElts % NumExtElts))
13423 ExtIdx *= (NumElts / NumExtElts);
13427 // At most we can reference 2 inputs in the final shuffle.
13428 if (SV0.isUndef() || SV0 == ExtVec) {
13430 for (int i = 0; i != NumOpElts; ++i)
13431 Mask.push_back(i + ExtIdx);
13432 } else if (SV1.isUndef() || SV1 == ExtVec) {
13434 for (int i = 0; i != NumOpElts; ++i)
13435 Mask.push_back(i + ExtIdx + NumElts);
13441 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13444 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13445 DAG.getBitcast(VT, SV1), Mask);
13448 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13449 // If we only have one input vector, we don't need to do any concatenation.
13450 if (N->getNumOperands() == 1)
13451 return N->getOperand(0);
13453 // Check if all of the operands are undefs.
13454 EVT VT = N->getValueType(0);
13455 if (ISD::allOperandsUndef(N))
13456 return DAG.getUNDEF(VT);
13458 // Optimize concat_vectors where all but the first of the vectors are undef.
13459 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13460 return Op.isUndef();
13462 SDValue In = N->getOperand(0);
13463 assert(In.getValueType().isVector() && "Must concat vectors");
13465 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13466 if (In->getOpcode() == ISD::BITCAST &&
13467 !In->getOperand(0)->getValueType(0).isVector()) {
13468 SDValue Scalar = In->getOperand(0);
13470 // If the bitcast type isn't legal, it might be a trunc of a legal type;
13471 // look through the trunc so we can still do the transform:
13472 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13473 if (Scalar->getOpcode() == ISD::TRUNCATE &&
13474 !TLI.isTypeLegal(Scalar.getValueType()) &&
13475 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13476 Scalar = Scalar->getOperand(0);
13478 EVT SclTy = Scalar->getValueType(0);
13480 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13483 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13484 VT.getSizeInBits() / SclTy.getSizeInBits());
13485 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13488 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
13489 return DAG.getBitcast(VT, Res);
13493 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13494 // We have already tested above for an UNDEF only concatenation.
13495 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13496 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13497 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13498 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13500 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13501 SmallVector<SDValue, 8> Opnds;
13502 EVT SVT = VT.getScalarType();
13505 if (!SVT.isFloatingPoint()) {
13506 // If BUILD_VECTOR are from built from integer, they may have different
13507 // operand types. Get the smallest type and truncate all operands to it.
13508 bool FoundMinVT = false;
13509 for (const SDValue &Op : N->ops())
13510 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13511 EVT OpSVT = Op.getOperand(0)->getValueType(0);
13512 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13515 assert(FoundMinVT && "Concat vector type mismatch");
13518 for (const SDValue &Op : N->ops()) {
13519 EVT OpVT = Op.getValueType();
13520 unsigned NumElts = OpVT.getVectorNumElements();
13522 if (ISD::UNDEF == Op.getOpcode())
13523 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13525 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13526 if (SVT.isFloatingPoint()) {
13527 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13528 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13530 for (unsigned i = 0; i != NumElts; ++i)
13532 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13537 assert(VT.getVectorNumElements() == Opnds.size() &&
13538 "Concat vector type mismatch");
13539 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13542 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13543 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13546 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13547 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13548 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13551 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13552 // nodes often generate nop CONCAT_VECTOR nodes.
13553 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13554 // place the incoming vectors at the exact same location.
13555 SDValue SingleSource = SDValue();
13556 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13558 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13559 SDValue Op = N->getOperand(i);
13564 // Check if this is the identity extract:
13565 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13568 // Find the single incoming vector for the extract_subvector.
13569 if (SingleSource.getNode()) {
13570 if (Op.getOperand(0) != SingleSource)
13573 SingleSource = Op.getOperand(0);
13575 // Check the source type is the same as the type of the result.
13576 // If not, this concat may extend the vector, so we can not
13577 // optimize it away.
13578 if (SingleSource.getValueType() != N->getValueType(0))
13582 unsigned IdentityIndex = i * PartNumElem;
13583 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13584 // The extract index must be constant.
13588 // Check that we are reading from the identity index.
13589 if (CS->getZExtValue() != IdentityIndex)
13593 if (SingleSource.getNode())
13594 return SingleSource;
13599 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13600 EVT NVT = N->getValueType(0);
13601 SDValue V = N->getOperand(0);
13603 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13605 // (extract_subvec (concat V1, V2, ...), i)
13608 // Only operand 0 is checked as 'concat' assumes all inputs of the same
13610 if (V->getOperand(0).getValueType() != NVT)
13612 unsigned Idx = N->getConstantOperandVal(1);
13613 unsigned NumElems = NVT.getVectorNumElements();
13614 assert((Idx % NumElems) == 0 &&
13615 "IDX in concat is not a multiple of the result vector length.");
13616 return V->getOperand(Idx / NumElems);
13620 if (V->getOpcode() == ISD::BITCAST)
13621 V = V.getOperand(0);
13623 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13624 // Handle only simple case where vector being inserted and vector
13625 // being extracted are of same type, and are half size of larger vectors.
13626 EVT BigVT = V->getOperand(0).getValueType();
13627 EVT SmallVT = V->getOperand(1).getValueType();
13628 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13631 // Only handle cases where both indexes are constants with the same type.
13632 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13633 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13635 if (InsIdx && ExtIdx &&
13636 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13637 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13639 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13641 // indices are equal or bit offsets are equal => V1
13642 // otherwise => (extract_subvec V1, ExtIdx)
13643 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
13644 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
13645 return DAG.getBitcast(NVT, V->getOperand(1));
13646 return DAG.getNode(
13647 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
13648 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13656 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13657 SDValue V, SelectionDAG &DAG) {
13659 EVT VT = V.getValueType();
13661 switch (V.getOpcode()) {
13665 case ISD::CONCAT_VECTORS: {
13666 EVT OpVT = V->getOperand(0).getValueType();
13667 int OpSize = OpVT.getVectorNumElements();
13668 SmallBitVector OpUsedElements(OpSize, false);
13669 bool FoundSimplification = false;
13670 SmallVector<SDValue, 4> NewOps;
13671 NewOps.reserve(V->getNumOperands());
13672 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13673 SDValue Op = V->getOperand(i);
13674 bool OpUsed = false;
13675 for (int j = 0; j < OpSize; ++j)
13676 if (UsedElements[i * OpSize + j]) {
13677 OpUsedElements[j] = true;
13681 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13682 : DAG.getUNDEF(OpVT));
13683 FoundSimplification |= Op == NewOps.back();
13684 OpUsedElements.reset();
13686 if (FoundSimplification)
13687 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13691 case ISD::INSERT_SUBVECTOR: {
13692 SDValue BaseV = V->getOperand(0);
13693 SDValue SubV = V->getOperand(1);
13694 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13698 int SubSize = SubV.getValueType().getVectorNumElements();
13699 int Idx = IdxN->getZExtValue();
13700 bool SubVectorUsed = false;
13701 SmallBitVector SubUsedElements(SubSize, false);
13702 for (int i = 0; i < SubSize; ++i)
13703 if (UsedElements[i + Idx]) {
13704 SubVectorUsed = true;
13705 SubUsedElements[i] = true;
13706 UsedElements[i + Idx] = false;
13709 // Now recurse on both the base and sub vectors.
13710 SDValue SimplifiedSubV =
13712 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13713 : DAG.getUNDEF(SubV.getValueType());
13714 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13715 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13716 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13717 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13723 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13724 SDValue N1, SelectionDAG &DAG) {
13725 EVT VT = SVN->getValueType(0);
13726 int NumElts = VT.getVectorNumElements();
13727 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13728 for (int M : SVN->getMask())
13729 if (M >= 0 && M < NumElts)
13730 N0UsedElements[M] = true;
13731 else if (M >= NumElts)
13732 N1UsedElements[M - NumElts] = true;
13734 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13735 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13736 if (S0 == N0 && S1 == N1)
13739 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13742 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13743 // or turn a shuffle of a single concat into simpler shuffle then concat.
13744 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13745 EVT VT = N->getValueType(0);
13746 unsigned NumElts = VT.getVectorNumElements();
13748 SDValue N0 = N->getOperand(0);
13749 SDValue N1 = N->getOperand(1);
13750 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13752 SmallVector<SDValue, 4> Ops;
13753 EVT ConcatVT = N0.getOperand(0).getValueType();
13754 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13755 unsigned NumConcats = NumElts / NumElemsPerConcat;
13757 // Special case: shuffle(concat(A,B)) can be more efficiently represented
13758 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13759 // half vector elements.
13760 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13761 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13762 SVN->getMask().end(), [](int i) { return i == -1; })) {
13763 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13764 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13765 N1 = DAG.getUNDEF(ConcatVT);
13766 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13769 // Look at every vector that's inserted. We're looking for exact
13770 // subvector-sized copies from a concatenated vector
13771 for (unsigned I = 0; I != NumConcats; ++I) {
13772 // Make sure we're dealing with a copy.
13773 unsigned Begin = I * NumElemsPerConcat;
13774 bool AllUndef = true, NoUndef = true;
13775 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13776 if (SVN->getMaskElt(J) >= 0)
13783 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13786 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13787 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13790 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13791 if (FirstElt < N0.getNumOperands())
13792 Ops.push_back(N0.getOperand(FirstElt));
13794 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13796 } else if (AllUndef) {
13797 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13798 } else { // Mixed with general masks and undefs, can't do optimization.
13803 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13806 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13807 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13809 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
13810 // a simplification in some sense, but it isn't appropriate in general: some
13811 // BUILD_VECTORs are substantially cheaper than others. The general case
13812 // of a BUILD_VECTOR requires inserting each element individually (or
13813 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
13814 // all constants is a single constant pool load. A BUILD_VECTOR where each
13815 // element is identical is a splat. A BUILD_VECTOR where most of the operands
13816 // are undef lowers to a small number of element insertions.
13818 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
13819 // We don't fold shuffles where one side is a non-zero constant, and we don't
13820 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
13821 // non-constant operands. This seems to work out reasonably well in practice.
13822 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
13824 const TargetLowering &TLI) {
13825 EVT VT = SVN->getValueType(0);
13826 unsigned NumElts = VT.getVectorNumElements();
13827 SDValue N0 = SVN->getOperand(0);
13828 SDValue N1 = SVN->getOperand(1);
13830 if (!N0->hasOneUse() || !N1->hasOneUse())
13832 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
13833 // discussed above.
13834 if (!N1.isUndef()) {
13835 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
13836 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
13837 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
13839 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
13843 SmallVector<SDValue, 8> Ops;
13844 SmallSet<SDValue, 16> DuplicateOps;
13845 for (int M : SVN->getMask()) {
13846 SDValue Op = DAG.getUNDEF(VT.getScalarType());
13848 int Idx = M < (int)NumElts ? M : M - NumElts;
13849 SDValue &S = (M < (int)NumElts ? N0 : N1);
13850 if (S.getOpcode() == ISD::BUILD_VECTOR) {
13851 Op = S.getOperand(Idx);
13852 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13854 Op = S.getOperand(0);
13856 // Operand can't be combined - bail out.
13861 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
13862 // fine, but it's likely to generate low-quality code if the target can't
13863 // reconstruct an appropriate shuffle.
13864 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
13865 if (!DuplicateOps.insert(Op).second)
13870 // BUILD_VECTOR requires all inputs to be of the same type, find the
13871 // maximum type and extend them all.
13872 EVT SVT = VT.getScalarType();
13873 if (SVT.isInteger())
13874 for (SDValue &Op : Ops)
13875 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13876 if (SVT != VT.getScalarType())
13877 for (SDValue &Op : Ops)
13878 Op = TLI.isZExtFree(Op.getValueType(), SVT)
13879 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
13880 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
13881 return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
13884 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13885 EVT VT = N->getValueType(0);
13886 unsigned NumElts = VT.getVectorNumElements();
13888 SDValue N0 = N->getOperand(0);
13889 SDValue N1 = N->getOperand(1);
13891 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13893 // Canonicalize shuffle undef, undef -> undef
13894 if (N0.isUndef() && N1.isUndef())
13895 return DAG.getUNDEF(VT);
13897 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13899 // Canonicalize shuffle v, v -> v, undef
13901 SmallVector<int, 8> NewMask;
13902 for (unsigned i = 0; i != NumElts; ++i) {
13903 int Idx = SVN->getMaskElt(i);
13904 if (Idx >= (int)NumElts) Idx -= NumElts;
13905 NewMask.push_back(Idx);
13907 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
13910 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
13912 return DAG.getCommutedVectorShuffle(*SVN);
13914 // Remove references to rhs if it is undef
13915 if (N1.isUndef()) {
13916 bool Changed = false;
13917 SmallVector<int, 8> NewMask;
13918 for (unsigned i = 0; i != NumElts; ++i) {
13919 int Idx = SVN->getMaskElt(i);
13920 if (Idx >= (int)NumElts) {
13924 NewMask.push_back(Idx);
13927 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
13930 // If it is a splat, check if the argument vector is another splat or a
13932 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13933 SDNode *V = N0.getNode();
13935 // If this is a bit convert that changes the element type of the vector but
13936 // not the number of vector elements, look through it. Be careful not to
13937 // look though conversions that change things like v4f32 to v2f64.
13938 if (V->getOpcode() == ISD::BITCAST) {
13939 SDValue ConvInput = V->getOperand(0);
13940 if (ConvInput.getValueType().isVector() &&
13941 ConvInput.getValueType().getVectorNumElements() == NumElts)
13942 V = ConvInput.getNode();
13945 if (V->getOpcode() == ISD::BUILD_VECTOR) {
13946 assert(V->getNumOperands() == NumElts &&
13947 "BUILD_VECTOR has wrong number of operands");
13949 bool AllSame = true;
13950 for (unsigned i = 0; i != NumElts; ++i) {
13951 if (!V->getOperand(i).isUndef()) {
13952 Base = V->getOperand(i);
13956 // Splat of <u, u, u, u>, return <u, u, u, u>
13957 if (!Base.getNode())
13959 for (unsigned i = 0; i != NumElts; ++i) {
13960 if (V->getOperand(i) != Base) {
13965 // Splat of <x, x, x, x>, return <x, x, x, x>
13969 // Canonicalize any other splat as a build_vector.
13970 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13971 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13972 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13974 // We may have jumped through bitcasts, so the type of the
13975 // BUILD_VECTOR may not match the type of the shuffle.
13976 if (V->getValueType(0) != VT)
13977 NewBV = DAG.getBitcast(VT, NewBV);
13982 // There are various patterns used to build up a vector from smaller vectors,
13983 // subvectors, or elements. Scan chains of these and replace unused insertions
13984 // or components with undef.
13985 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13988 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13989 Level < AfterLegalizeVectorOps &&
13991 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13992 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13993 if (SDValue V = partitionShuffleOfConcats(N, DAG))
13997 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13998 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13999 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14000 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
14003 // If this shuffle only has a single input that is a bitcasted shuffle,
14004 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
14005 // back to their original types.
14006 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
14007 N1.isUndef() && Level < AfterLegalizeVectorOps &&
14008 TLI.isTypeLegal(VT)) {
14010 // Peek through the bitcast only if there is one user.
14012 while (BC0.getOpcode() == ISD::BITCAST) {
14013 if (!BC0.hasOneUse())
14015 BC0 = BC0.getOperand(0);
14018 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
14020 return SmallVector<int, 8>(Mask.begin(), Mask.end());
14022 SmallVector<int, 8> NewMask;
14024 for (int s = 0; s != Scale; ++s)
14025 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
14029 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
14030 EVT SVT = VT.getScalarType();
14031 EVT InnerVT = BC0->getValueType(0);
14032 EVT InnerSVT = InnerVT.getScalarType();
14034 // Determine which shuffle works with the smaller scalar type.
14035 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
14036 EVT ScaleSVT = ScaleVT.getScalarType();
14038 if (TLI.isTypeLegal(ScaleVT) &&
14039 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
14040 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
14042 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14043 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14045 // Scale the shuffle masks to the smaller scalar type.
14046 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
14047 SmallVector<int, 8> InnerMask =
14048 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
14049 SmallVector<int, 8> OuterMask =
14050 ScaleShuffleMask(SVN->getMask(), OuterScale);
14052 // Merge the shuffle masks.
14053 SmallVector<int, 8> NewMask;
14054 for (int M : OuterMask)
14055 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
14057 // Test for shuffle mask legality over both commutations.
14058 SDValue SV0 = BC0->getOperand(0);
14059 SDValue SV1 = BC0->getOperand(1);
14060 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14062 std::swap(SV0, SV1);
14063 ShuffleVectorSDNode::commuteMask(NewMask);
14064 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14068 SV0 = DAG.getBitcast(ScaleVT, SV0);
14069 SV1 = DAG.getBitcast(ScaleVT, SV1);
14070 return DAG.getBitcast(
14071 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
14077 // Canonicalize shuffles according to rules:
14078 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
14079 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
14080 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
14081 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
14082 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
14083 TLI.isTypeLegal(VT)) {
14084 // The incoming shuffle must be of the same type as the result of the
14085 // current shuffle.
14086 assert(N1->getOperand(0).getValueType() == VT &&
14087 "Shuffle types don't match");
14089 SDValue SV0 = N1->getOperand(0);
14090 SDValue SV1 = N1->getOperand(1);
14091 bool HasSameOp0 = N0 == SV0;
14092 bool IsSV1Undef = SV1.isUndef();
14093 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
14094 // Commute the operands of this shuffle so that next rule
14096 return DAG.getCommutedVectorShuffle(*SVN);
14099 // Try to fold according to rules:
14100 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14101 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14102 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14103 // Don't try to fold shuffles with illegal type.
14104 // Only fold if this shuffle is the only user of the other shuffle.
14105 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14106 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14107 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14109 // Don't try to fold splats; they're likely to simplify somehow, or they
14111 if (OtherSV->isSplat())
14114 // The incoming shuffle must be of the same type as the result of the
14115 // current shuffle.
14116 assert(OtherSV->getOperand(0).getValueType() == VT &&
14117 "Shuffle types don't match");
14120 SmallVector<int, 4> Mask;
14121 // Compute the combined shuffle mask for a shuffle with SV0 as the first
14122 // operand, and SV1 as the second operand.
14123 for (unsigned i = 0; i != NumElts; ++i) {
14124 int Idx = SVN->getMaskElt(i);
14126 // Propagate Undef.
14127 Mask.push_back(Idx);
14131 SDValue CurrentVec;
14132 if (Idx < (int)NumElts) {
14133 // This shuffle index refers to the inner shuffle N0. Lookup the inner
14134 // shuffle mask to identify which vector is actually referenced.
14135 Idx = OtherSV->getMaskElt(Idx);
14137 // Propagate Undef.
14138 Mask.push_back(Idx);
14142 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14143 : OtherSV->getOperand(1);
14145 // This shuffle index references an element within N1.
14149 // Simple case where 'CurrentVec' is UNDEF.
14150 if (CurrentVec.isUndef()) {
14151 Mask.push_back(-1);
14155 // Canonicalize the shuffle index. We don't know yet if CurrentVec
14156 // will be the first or second operand of the combined shuffle.
14157 Idx = Idx % NumElts;
14158 if (!SV0.getNode() || SV0 == CurrentVec) {
14159 // Ok. CurrentVec is the left hand side.
14160 // Update the mask accordingly.
14162 Mask.push_back(Idx);
14166 // Bail out if we cannot convert the shuffle pair into a single shuffle.
14167 if (SV1.getNode() && SV1 != CurrentVec)
14170 // Ok. CurrentVec is the right hand side.
14171 // Update the mask accordingly.
14173 Mask.push_back(Idx + NumElts);
14176 // Check if all indices in Mask are Undef. In case, propagate Undef.
14177 bool isUndefMask = true;
14178 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14179 isUndefMask &= Mask[i] < 0;
14182 return DAG.getUNDEF(VT);
14184 if (!SV0.getNode())
14185 SV0 = DAG.getUNDEF(VT);
14186 if (!SV1.getNode())
14187 SV1 = DAG.getUNDEF(VT);
14189 // Avoid introducing shuffles with illegal mask.
14190 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14191 ShuffleVectorSDNode::commuteMask(Mask);
14193 if (!TLI.isShuffleMaskLegal(Mask, VT))
14196 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14197 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14198 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14199 std::swap(SV0, SV1);
14202 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14203 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14204 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14205 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14211 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14212 SDValue InVal = N->getOperand(0);
14213 EVT VT = N->getValueType(0);
14215 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14216 // with a VECTOR_SHUFFLE.
14217 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14218 SDValue InVec = InVal->getOperand(0);
14219 SDValue EltNo = InVal->getOperand(1);
14221 // FIXME: We could support implicit truncation if the shuffle can be
14222 // scaled to a smaller vector scalar type.
14223 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
14224 if (C0 && VT == InVec.getValueType() &&
14225 VT.getScalarType() == InVal.getValueType()) {
14226 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
14227 int Elt = C0->getZExtValue();
14230 if (TLI.isShuffleMaskLegal(NewMask, VT))
14231 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
14239 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
14240 EVT VT = N->getValueType(0);
14241 SDValue N0 = N->getOperand(0);
14242 SDValue N1 = N->getOperand(1);
14243 SDValue N2 = N->getOperand(2);
14245 // Combine INSERT_SUBVECTORs where we are inserting to the same index.
14246 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
14247 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
14248 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
14249 N0.getOperand(1).getValueType() == N1.getValueType() &&
14250 N0.getOperand(2) == N2)
14251 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
14254 if (N0.getValueType() != N1.getValueType())
14257 // If the input vector is a concatenation, and the insert replaces
14258 // one of the halves, we can optimize into a single concat_vectors.
14259 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
14260 N2.getOpcode() == ISD::Constant) {
14261 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
14263 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14264 // (concat_vectors Z, Y)
14266 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
14269 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14270 // (concat_vectors X, Z)
14271 if (InsIdx == VT.getVectorNumElements() / 2)
14272 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
14279 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
14280 SDValue N0 = N->getOperand(0);
14282 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
14283 if (N0->getOpcode() == ISD::FP16_TO_FP)
14284 return N0->getOperand(0);
14289 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
14290 SDValue N0 = N->getOperand(0);
14292 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
14293 if (N0->getOpcode() == ISD::AND) {
14294 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
14295 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
14296 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
14304 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
14305 /// with the destination vector and a zero vector.
14306 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
14307 /// vector_shuffle V, Zero, <0, 4, 2, 4>
14308 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
14309 EVT VT = N->getValueType(0);
14310 SDValue LHS = N->getOperand(0);
14311 SDValue RHS = N->getOperand(1);
14314 // Make sure we're not running after operation legalization where it
14315 // may have custom lowered the vector shuffles.
14316 if (LegalOperations)
14319 if (N->getOpcode() != ISD::AND)
14322 if (RHS.getOpcode() == ISD::BITCAST)
14323 RHS = RHS.getOperand(0);
14325 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
14328 EVT RVT = RHS.getValueType();
14329 unsigned NumElts = RHS.getNumOperands();
14331 // Attempt to create a valid clear mask, splitting the mask into
14332 // sub elements and checking to see if each is
14333 // all zeros or all ones - suitable for shuffle masking.
14334 auto BuildClearMask = [&](int Split) {
14335 int NumSubElts = NumElts * Split;
14336 int NumSubBits = RVT.getScalarSizeInBits() / Split;
14338 SmallVector<int, 8> Indices;
14339 for (int i = 0; i != NumSubElts; ++i) {
14340 int EltIdx = i / Split;
14341 int SubIdx = i % Split;
14342 SDValue Elt = RHS.getOperand(EltIdx);
14343 if (Elt.isUndef()) {
14344 Indices.push_back(-1);
14349 if (isa<ConstantSDNode>(Elt))
14350 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
14351 else if (isa<ConstantFPSDNode>(Elt))
14352 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
14356 // Extract the sub element from the constant bit mask.
14357 if (DAG.getDataLayout().isBigEndian()) {
14358 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
14360 Bits = Bits.lshr(SubIdx * NumSubBits);
14364 Bits = Bits.trunc(NumSubBits);
14366 if (Bits.isAllOnesValue())
14367 Indices.push_back(i);
14368 else if (Bits == 0)
14369 Indices.push_back(i + NumSubElts);
14374 // Let's see if the target supports this vector_shuffle.
14375 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
14376 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
14377 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
14380 SDValue Zero = DAG.getConstant(0, DL, ClearVT);
14381 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
14382 DAG.getBitcast(ClearVT, LHS),
14386 // Determine maximum split level (byte level masking).
14388 if (RVT.getScalarSizeInBits() % 8 == 0)
14389 MaxSplit = RVT.getScalarSizeInBits() / 8;
14391 for (int Split = 1; Split <= MaxSplit; ++Split)
14392 if (RVT.getScalarSizeInBits() % Split == 0)
14393 if (SDValue S = BuildClearMask(Split))
14399 /// Visit a binary vector operation, like ADD.
14400 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
14401 assert(N->getValueType(0).isVector() &&
14402 "SimplifyVBinOp only works on vectors!");
14404 SDValue LHS = N->getOperand(0);
14405 SDValue RHS = N->getOperand(1);
14406 SDValue Ops[] = {LHS, RHS};
14408 // See if we can constant fold the vector operation.
14409 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
14410 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
14413 // Try to convert a constant mask AND into a shuffle clear mask.
14414 if (SDValue Shuffle = XformToShuffleWithZero(N))
14417 // Type legalization might introduce new shuffles in the DAG.
14418 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
14419 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
14420 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
14421 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
14422 LHS.getOperand(1).isUndef() &&
14423 RHS.getOperand(1).isUndef()) {
14424 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
14425 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
14427 if (SVN0->getMask().equals(SVN1->getMask())) {
14428 EVT VT = N->getValueType(0);
14429 SDValue UndefVector = LHS.getOperand(1);
14430 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
14431 LHS.getOperand(0), RHS.getOperand(0),
14433 AddUsersToWorklist(N);
14434 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
14442 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
14444 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14446 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14447 cast<CondCodeSDNode>(N0.getOperand(2))->get());
14449 // If we got a simplified select_cc node back from SimplifySelectCC, then
14450 // break it down into a new SETCC node, and a new SELECT node, and then return
14451 // the SELECT node, since we were called with a SELECT node.
14452 if (SCC.getNode()) {
14453 // Check to see if we got a select_cc back (to turn into setcc/select).
14454 // Otherwise, just return whatever node we got back, like fabs.
14455 if (SCC.getOpcode() == ISD::SELECT_CC) {
14456 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14458 SCC.getOperand(0), SCC.getOperand(1),
14459 SCC.getOperand(4));
14460 AddToWorklist(SETCC.getNode());
14461 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14462 SCC.getOperand(2), SCC.getOperand(3));
14470 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14471 /// being selected between, see if we can simplify the select. Callers of this
14472 /// should assume that TheSelect is deleted if this returns true. As such, they
14473 /// should return the appropriate thing (e.g. the node) back to the top-level of
14474 /// the DAG combiner loop to avoid it being looked at.
14475 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14478 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14479 // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14480 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14481 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14482 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14483 SDValue Sqrt = RHS;
14486 const ConstantFPSDNode *Zero = nullptr;
14488 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14489 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14490 CmpLHS = TheSelect->getOperand(0);
14491 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14493 // SELECT or VSELECT
14494 SDValue Cmp = TheSelect->getOperand(0);
14495 if (Cmp.getOpcode() == ISD::SETCC) {
14496 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14497 CmpLHS = Cmp.getOperand(0);
14498 Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14501 if (Zero && Zero->isZero() &&
14502 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14503 CC == ISD::SETULT || CC == ISD::SETLT)) {
14504 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14505 CombineTo(TheSelect, Sqrt);
14510 // Cannot simplify select with vector condition
14511 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14513 // If this is a select from two identical things, try to pull the operation
14514 // through the select.
14515 if (LHS.getOpcode() != RHS.getOpcode() ||
14516 !LHS.hasOneUse() || !RHS.hasOneUse())
14519 // If this is a load and the token chain is identical, replace the select
14520 // of two loads with a load through a select of the address to load from.
14521 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14522 // constants have been dropped into the constant pool.
14523 if (LHS.getOpcode() == ISD::LOAD) {
14524 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14525 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14527 // Token chains must be identical.
14528 if (LHS.getOperand(0) != RHS.getOperand(0) ||
14529 // Do not let this transformation reduce the number of volatile loads.
14530 LLD->isVolatile() || RLD->isVolatile() ||
14531 // FIXME: If either is a pre/post inc/dec load,
14532 // we'd need to split out the address adjustment.
14533 LLD->isIndexed() || RLD->isIndexed() ||
14534 // If this is an EXTLOAD, the VT's must match.
14535 LLD->getMemoryVT() != RLD->getMemoryVT() ||
14536 // If this is an EXTLOAD, the kind of extension must match.
14537 (LLD->getExtensionType() != RLD->getExtensionType() &&
14538 // The only exception is if one of the extensions is anyext.
14539 LLD->getExtensionType() != ISD::EXTLOAD &&
14540 RLD->getExtensionType() != ISD::EXTLOAD) ||
14541 // FIXME: this discards src value information. This is
14542 // over-conservative. It would be beneficial to be able to remember
14543 // both potential memory locations. Since we are discarding
14544 // src value info, don't do the transformation if the memory
14545 // locations are not in the default address space.
14546 LLD->getPointerInfo().getAddrSpace() != 0 ||
14547 RLD->getPointerInfo().getAddrSpace() != 0 ||
14548 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14549 LLD->getBasePtr().getValueType()))
14552 // Check that the select condition doesn't reach either load. If so,
14553 // folding this will induce a cycle into the DAG. If not, this is safe to
14554 // xform, so create a select of the addresses.
14556 if (TheSelect->getOpcode() == ISD::SELECT) {
14557 SDNode *CondNode = TheSelect->getOperand(0).getNode();
14558 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14559 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14561 // The loads must not depend on one another.
14562 if (LLD->isPredecessorOf(RLD) ||
14563 RLD->isPredecessorOf(LLD))
14565 Addr = DAG.getSelect(SDLoc(TheSelect),
14566 LLD->getBasePtr().getValueType(),
14567 TheSelect->getOperand(0), LLD->getBasePtr(),
14568 RLD->getBasePtr());
14569 } else { // Otherwise SELECT_CC
14570 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14571 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14573 if ((LLD->hasAnyUseOfValue(1) &&
14574 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14575 (RLD->hasAnyUseOfValue(1) &&
14576 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14579 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14580 LLD->getBasePtr().getValueType(),
14581 TheSelect->getOperand(0),
14582 TheSelect->getOperand(1),
14583 LLD->getBasePtr(), RLD->getBasePtr(),
14584 TheSelect->getOperand(4));
14588 // It is safe to replace the two loads if they have different alignments,
14589 // but the new load must be the minimum (most restrictive) alignment of the
14591 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14592 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14593 if (!RLD->isInvariant())
14594 MMOFlags &= ~MachineMemOperand::MOInvariant;
14595 if (!RLD->isDereferenceable())
14596 MMOFlags &= ~MachineMemOperand::MODereferenceable;
14597 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14598 // FIXME: Discards pointer and AA info.
14599 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14600 LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14603 // FIXME: Discards pointer and AA info.
14604 Load = DAG.getExtLoad(
14605 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14606 : LLD->getExtensionType(),
14607 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14608 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14611 // Users of the select now use the result of the load.
14612 CombineTo(TheSelect, Load);
14614 // Users of the old loads now use the new load's chain. We know the
14615 // old-load value is dead now.
14616 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14617 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14624 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
14626 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
14627 SDValue N1, SDValue N2, SDValue N3,
14628 ISD::CondCode CC) {
14629 // If this is a select where the false operand is zero and the compare is a
14630 // check of the sign bit, see if we can perform the "gzip trick":
14631 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
14632 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
14633 EVT XType = N0.getValueType();
14634 EVT AType = N2.getValueType();
14635 if (!isNullConstant(N3) || !XType.bitsGE(AType))
14638 // If the comparison is testing for a positive value, we have to invert
14639 // the sign bit mask, so only do that transform if the target has a bitwise
14640 // 'and not' instruction (the invert is free).
14641 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
14642 // (X > -1) ? A : 0
14643 // (X > 0) ? X : 0 <-- This is canonical signed max.
14644 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
14646 } else if (CC == ISD::SETLT) {
14648 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
14649 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
14655 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
14657 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
14658 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14659 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14660 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
14661 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
14662 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
14663 AddToWorklist(Shift.getNode());
14665 if (XType.bitsGT(AType)) {
14666 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14667 AddToWorklist(Shift.getNode());
14670 if (CC == ISD::SETGT)
14671 Shift = DAG.getNOT(DL, Shift, AType);
14673 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14676 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
14677 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
14678 AddToWorklist(Shift.getNode());
14680 if (XType.bitsGT(AType)) {
14681 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14682 AddToWorklist(Shift.getNode());
14685 if (CC == ISD::SETGT)
14686 Shift = DAG.getNOT(DL, Shift, AType);
14688 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14691 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14692 /// where 'cond' is the comparison specified by CC.
14693 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14694 SDValue N2, SDValue N3, ISD::CondCode CC,
14695 bool NotExtCompare) {
14696 // (x ? y : y) -> y.
14697 if (N2 == N3) return N2;
14699 EVT VT = N2.getValueType();
14700 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14701 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14703 // Determine if the condition we're dealing with is constant
14704 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14705 N0, N1, CC, DL, false);
14706 if (SCC.getNode()) AddToWorklist(SCC.getNode());
14708 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14709 // fold select_cc true, x, y -> x
14710 // fold select_cc false, x, y -> y
14711 return !SCCC->isNullValue() ? N2 : N3;
14714 // Check to see if we can simplify the select into an fabs node
14715 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14716 // Allow either -0.0 or 0.0
14717 if (CFP->isZero()) {
14718 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14719 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14720 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14721 N2 == N3.getOperand(0))
14722 return DAG.getNode(ISD::FABS, DL, VT, N0);
14724 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14725 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14726 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14727 N2.getOperand(0) == N3)
14728 return DAG.getNode(ISD::FABS, DL, VT, N3);
14732 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14733 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14734 // in it. This is a win when the constant is not otherwise available because
14735 // it replaces two constant pool loads with one. We only do this if the FP
14736 // type is known to be legal, because if it isn't, then we are before legalize
14737 // types an we want the other legalization to happen first (e.g. to avoid
14738 // messing with soft float) and if the ConstantFP is not legal, because if
14739 // it is legal, we may not need to store the FP constant in a constant pool.
14740 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14741 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14742 if (TLI.isTypeLegal(N2.getValueType()) &&
14743 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14744 TargetLowering::Legal &&
14745 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14746 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14747 // If both constants have multiple uses, then we won't need to do an
14748 // extra load, they are likely around in registers for other users.
14749 (TV->hasOneUse() || FV->hasOneUse())) {
14750 Constant *Elts[] = {
14751 const_cast<ConstantFP*>(FV->getConstantFPValue()),
14752 const_cast<ConstantFP*>(TV->getConstantFPValue())
14754 Type *FPTy = Elts[0]->getType();
14755 const DataLayout &TD = DAG.getDataLayout();
14757 // Create a ConstantArray of the two constants.
14758 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14760 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14761 TD.getPrefTypeAlignment(FPTy));
14762 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14764 // Get the offsets to the 0 and 1 element of the array so that we can
14765 // select between them.
14766 SDValue Zero = DAG.getIntPtrConstant(0, DL);
14767 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14768 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14770 SDValue Cond = DAG.getSetCC(DL,
14771 getSetCCResultType(N0.getValueType()),
14773 AddToWorklist(Cond.getNode());
14774 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14776 AddToWorklist(CstOffset.getNode());
14777 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14779 AddToWorklist(CPIdx.getNode());
14780 return DAG.getLoad(
14781 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14782 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14787 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
14790 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14791 // where y is has a single bit set.
14792 // A plaintext description would be, we can turn the SELECT_CC into an AND
14793 // when the condition can be materialized as an all-ones register. Any
14794 // single bit-test can be materialized as an all-ones register with
14795 // shift-left and shift-right-arith.
14796 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14797 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14798 SDValue AndLHS = N0->getOperand(0);
14799 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14800 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14801 // Shift the tested bit over the sign bit.
14802 const APInt &AndMask = ConstAndRHS->getAPIntValue();
14804 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14805 getShiftAmountTy(AndLHS.getValueType()));
14806 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14808 // Now arithmetic right shift it all the way over, so the result is either
14809 // all-ones, or zero.
14811 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14812 getShiftAmountTy(Shl.getValueType()));
14813 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14815 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14819 // fold select C, 16, 0 -> shl C, 4
14820 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14821 TLI.getBooleanContents(N0.getValueType()) ==
14822 TargetLowering::ZeroOrOneBooleanContent) {
14824 // If the caller doesn't want us to simplify this into a zext of a compare,
14826 if (NotExtCompare && N2C->isOne())
14829 // Get a SetCC of the condition
14830 // NOTE: Don't create a SETCC if it's not legal on this target.
14831 if (!LegalOperations ||
14832 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14834 // cast from setcc result type to select result type
14836 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14838 if (N2.getValueType().bitsLT(SCC.getValueType()))
14839 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14840 N2.getValueType());
14842 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14843 N2.getValueType(), SCC);
14845 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14846 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14847 N2.getValueType(), SCC);
14850 AddToWorklist(SCC.getNode());
14851 AddToWorklist(Temp.getNode());
14856 // shl setcc result by log2 n2c
14857 return DAG.getNode(
14858 ISD::SHL, DL, N2.getValueType(), Temp,
14859 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14860 getShiftAmountTy(Temp.getValueType())));
14864 // Check to see if this is an integer abs.
14865 // select_cc setg[te] X, 0, X, -X ->
14866 // select_cc setgt X, -1, X, -X ->
14867 // select_cc setl[te] X, 0, -X, X ->
14868 // select_cc setlt X, 1, -X, X ->
14869 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14871 ConstantSDNode *SubC = nullptr;
14872 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14873 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14874 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14875 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14876 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14877 (N1C->isOne() && CC == ISD::SETLT)) &&
14878 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14879 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14881 EVT XType = N0.getValueType();
14882 if (SubC && SubC->isNullValue() && XType.isInteger()) {
14884 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14886 DAG.getConstant(XType.getSizeInBits() - 1, DL,
14887 getShiftAmountTy(N0.getValueType())));
14888 SDValue Add = DAG.getNode(ISD::ADD, DL,
14890 AddToWorklist(Shift.getNode());
14891 AddToWorklist(Add.getNode());
14892 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14896 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14897 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14898 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14899 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14900 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14901 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14902 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14903 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14904 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14905 SDValue ValueOnZero = N2;
14906 SDValue Count = N3;
14907 // If the condition is NE instead of E, swap the operands.
14908 if (CC == ISD::SETNE)
14909 std::swap(ValueOnZero, Count);
14910 // Check if the value on zero is a constant equal to the bits in the type.
14911 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14912 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14913 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14914 // legal, combine to just cttz.
14915 if ((Count.getOpcode() == ISD::CTTZ ||
14916 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14917 N0 == Count.getOperand(0) &&
14918 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14919 return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14920 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14921 // legal, combine to just ctlz.
14922 if ((Count.getOpcode() == ISD::CTLZ ||
14923 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14924 N0 == Count.getOperand(0) &&
14925 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14926 return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14934 /// This is a stub for TargetLowering::SimplifySetCC.
14935 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14936 ISD::CondCode Cond, const SDLoc &DL,
14937 bool foldBooleans) {
14938 TargetLowering::DAGCombinerInfo
14939 DagCombineInfo(DAG, Level, false, this);
14940 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14943 /// Given an ISD::SDIV node expressing a divide by constant, return
14944 /// a DAG expression to select that will generate the same value by multiplying
14945 /// by a magic number.
14946 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14947 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14948 // when optimising for minimum size, we don't want to expand a div to a mul
14950 if (DAG.getMachineFunction().getFunction()->optForMinSize())
14953 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14957 // Avoid division by zero.
14958 if (C->isNullValue())
14961 std::vector<SDNode*> Built;
14963 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14965 for (SDNode *N : Built)
14970 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14971 /// DAG expression that will generate the same value by right shifting.
14972 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14973 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14977 // Avoid division by zero.
14978 if (C->isNullValue())
14981 std::vector<SDNode *> Built;
14982 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14984 for (SDNode *N : Built)
14989 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14990 /// expression that will generate the same value by multiplying by a magic
14992 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14993 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14994 // when optimising for minimum size, we don't want to expand a div to a mul
14996 if (DAG.getMachineFunction().getFunction()->optForMinSize())
14999 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15003 // Avoid division by zero.
15004 if (C->isNullValue())
15007 std::vector<SDNode*> Built;
15009 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15011 for (SDNode *N : Built)
15016 /// Determines the LogBase2 value for a non-null input value using the
15017 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
15018 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
15019 EVT VT = V.getValueType();
15020 unsigned EltBits = VT.getScalarSizeInBits();
15021 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
15022 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
15023 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
15027 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15028 /// For the reciprocal, we need to find the zero of the function:
15029 /// F(X) = A X - 1 [which has a zero at X = 1/A]
15031 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
15032 /// does not require additional intermediate precision]
15033 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
15034 if (Level >= AfterLegalizeDAG)
15037 // TODO: Handle half and/or extended types?
15038 EVT VT = Op.getValueType();
15039 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15042 // If estimates are explicitly disabled for this function, we're done.
15043 MachineFunction &MF = DAG.getMachineFunction();
15044 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
15045 if (Enabled == TLI.ReciprocalEstimate::Disabled)
15048 // Estimates may be explicitly enabled for this type with a custom number of
15049 // refinement steps.
15050 int Iterations = TLI.getDivRefinementSteps(VT, MF);
15051 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
15052 AddToWorklist(Est.getNode());
15055 EVT VT = Op.getValueType();
15057 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
15059 // Newton iterations: Est = Est + Est (1 - Arg * Est)
15060 for (int i = 0; i < Iterations; ++i) {
15061 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
15062 AddToWorklist(NewEst.getNode());
15064 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
15065 AddToWorklist(NewEst.getNode());
15067 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15068 AddToWorklist(NewEst.getNode());
15070 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
15071 AddToWorklist(Est.getNode());
15080 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15081 /// For the reciprocal sqrt, we need to find the zero of the function:
15082 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15084 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
15085 /// As a result, we precompute A/2 prior to the iteration loop.
15086 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
15087 unsigned Iterations,
15088 SDNodeFlags *Flags, bool Reciprocal) {
15089 EVT VT = Arg.getValueType();
15091 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
15093 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
15094 // this entire sequence requires only one FP constant.
15095 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
15096 AddToWorklist(HalfArg.getNode());
15098 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
15099 AddToWorklist(HalfArg.getNode());
15101 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
15102 for (unsigned i = 0; i < Iterations; ++i) {
15103 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
15104 AddToWorklist(NewEst.getNode());
15106 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
15107 AddToWorklist(NewEst.getNode());
15109 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
15110 AddToWorklist(NewEst.getNode());
15112 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15113 AddToWorklist(Est.getNode());
15116 // If non-reciprocal square root is requested, multiply the result by Arg.
15118 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
15119 AddToWorklist(Est.getNode());
15125 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15126 /// For the reciprocal sqrt, we need to find the zero of the function:
15127 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15129 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
15130 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
15131 unsigned Iterations,
15132 SDNodeFlags *Flags, bool Reciprocal) {
15133 EVT VT = Arg.getValueType();
15135 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
15136 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
15138 // This routine must enter the loop below to work correctly
15139 // when (Reciprocal == false).
15140 assert(Iterations > 0);
15142 // Newton iterations for reciprocal square root:
15143 // E = (E * -0.5) * ((A * E) * E + -3.0)
15144 for (unsigned i = 0; i < Iterations; ++i) {
15145 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15146 AddToWorklist(AE.getNode());
15148 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15149 AddToWorklist(AEE.getNode());
15151 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15152 AddToWorklist(RHS.getNode());
15154 // When calculating a square root at the last iteration build:
15155 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15156 // (notice a common subexpression)
15158 if (Reciprocal || (i + 1) < Iterations) {
15159 // RSQRT: LHS = (E * -0.5)
15160 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15162 // SQRT: LHS = (A * E) * -0.5
15163 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15165 AddToWorklist(LHS.getNode());
15167 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15168 AddToWorklist(Est.getNode());
15174 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15175 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15176 /// Op can be zero.
15177 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15179 if (Level >= AfterLegalizeDAG)
15182 // TODO: Handle half and/or extended types?
15183 EVT VT = Op.getValueType();
15184 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15187 // If estimates are explicitly disabled for this function, we're done.
15188 MachineFunction &MF = DAG.getMachineFunction();
15189 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
15190 if (Enabled == TLI.ReciprocalEstimate::Disabled)
15193 // Estimates may be explicitly enabled for this type with a custom number of
15194 // refinement steps.
15195 int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
15197 bool UseOneConstNR = false;
15199 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
15201 AddToWorklist(Est.getNode());
15204 Est = UseOneConstNR
15205 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
15206 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
15209 // Unfortunately, Est is now NaN if the input was exactly 0.0.
15210 // Select out this case and force the answer to 0.0.
15211 EVT VT = Op.getValueType();
15214 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
15215 EVT CCVT = getSetCCResultType(VT);
15216 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
15217 AddToWorklist(ZeroCmp.getNode());
15219 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
15220 ZeroCmp, FPZero, Est);
15221 AddToWorklist(Est.getNode());
15230 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15231 return buildSqrtEstimateImpl(Op, Flags, true);
15234 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15235 return buildSqrtEstimateImpl(Op, Flags, false);
15238 /// Return true if base is a frame index, which is known not to alias with
15239 /// anything but itself. Provides base object and offset as results.
15240 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
15241 const GlobalValue *&GV, const void *&CV) {
15242 // Assume it is a primitive operation.
15243 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
15245 // If it's an adding a simple constant then integrate the offset.
15246 if (Base.getOpcode() == ISD::ADD) {
15247 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
15248 Base = Base.getOperand(0);
15249 Offset += C->getZExtValue();
15253 // Return the underlying GlobalValue, and update the Offset. Return false
15254 // for GlobalAddressSDNode since the same GlobalAddress may be represented
15255 // by multiple nodes with different offsets.
15256 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
15257 GV = G->getGlobal();
15258 Offset += G->getOffset();
15262 // Return the underlying Constant value, and update the Offset. Return false
15263 // for ConstantSDNodes since the same constant pool entry may be represented
15264 // by multiple nodes with different offsets.
15265 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
15266 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
15267 : (const void *)C->getConstVal();
15268 Offset += C->getOffset();
15271 // If it's any of the following then it can't alias with anything but itself.
15272 return isa<FrameIndexSDNode>(Base);
15275 /// Return true if there is any possibility that the two addresses overlap.
15276 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
15277 // If they are the same then they must be aliases.
15278 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
15280 // If they are both volatile then they cannot be reordered.
15281 if (Op0->isVolatile() && Op1->isVolatile()) return true;
15283 // If one operation reads from invariant memory, and the other may store, they
15284 // cannot alias. These should really be checking the equivalent of mayWrite,
15285 // but it only matters for memory nodes other than load /store.
15286 if (Op0->isInvariant() && Op1->writeMem())
15289 if (Op1->isInvariant() && Op0->writeMem())
15292 // Gather base node and offset information.
15293 SDValue Base1, Base2;
15294 int64_t Offset1, Offset2;
15295 const GlobalValue *GV1, *GV2;
15296 const void *CV1, *CV2;
15297 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
15298 Base1, Offset1, GV1, CV1);
15299 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
15300 Base2, Offset2, GV2, CV2);
15302 // If they have a same base address then check to see if they overlap.
15303 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
15304 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15305 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15307 // It is possible for different frame indices to alias each other, mostly
15308 // when tail call optimization reuses return address slots for arguments.
15309 // To catch this case, look up the actual index of frame indices to compute
15310 // the real alias relationship.
15311 if (isFrameIndex1 && isFrameIndex2) {
15312 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
15313 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
15314 Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
15315 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15316 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15319 // Otherwise, if we know what the bases are, and they aren't identical, then
15320 // we know they cannot alias.
15321 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
15324 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
15325 // compared to the size and offset of the access, we may be able to prove they
15326 // do not alias. This check is conservative for now to catch cases created by
15327 // splitting vector types.
15328 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
15329 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
15330 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
15331 Op1->getMemoryVT().getSizeInBits() >> 3) &&
15332 (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
15333 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
15334 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
15336 // There is no overlap between these relatively aligned accesses of similar
15337 // size, return no alias.
15338 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
15339 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
15343 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
15345 : DAG.getSubtarget().useAA();
15347 if (CombinerAAOnlyFunc.getNumOccurrences() &&
15348 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
15352 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
15353 // Use alias analysis information.
15354 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
15355 Op1->getSrcValueOffset());
15356 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
15357 Op0->getSrcValueOffset() - MinOffset;
15358 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
15359 Op1->getSrcValueOffset() - MinOffset;
15360 AliasResult AAResult =
15361 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
15362 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
15363 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
15364 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
15365 if (AAResult == NoAlias)
15369 // Otherwise we have to assume they alias.
15373 /// Walk up chain skipping non-aliasing memory nodes,
15374 /// looking for aliasing nodes and adding them to the Aliases vector.
15375 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
15376 SmallVectorImpl<SDValue> &Aliases) {
15377 SmallVector<SDValue, 8> Chains; // List of chains to visit.
15378 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
15380 // Get alias information for node.
15381 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
15384 Chains.push_back(OriginalChain);
15385 unsigned Depth = 0;
15387 // Look at each chain and determine if it is an alias. If so, add it to the
15388 // aliases list. If not, then continue up the chain looking for the next
15390 while (!Chains.empty()) {
15391 SDValue Chain = Chains.pop_back_val();
15393 // For TokenFactor nodes, look at each operand and only continue up the
15394 // chain until we reach the depth limit.
15396 // FIXME: The depth check could be made to return the last non-aliasing
15397 // chain we found before we hit a tokenfactor rather than the original
15399 if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
15401 Aliases.push_back(OriginalChain);
15405 // Don't bother if we've been before.
15406 if (!Visited.insert(Chain.getNode()).second)
15409 switch (Chain.getOpcode()) {
15410 case ISD::EntryToken:
15411 // Entry token is ideal chain operand, but handled in FindBetterChain.
15416 // Get alias information for Chain.
15417 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
15418 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
15420 // If chain is alias then stop here.
15421 if (!(IsLoad && IsOpLoad) &&
15422 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
15423 Aliases.push_back(Chain);
15425 // Look further up the chain.
15426 Chains.push_back(Chain.getOperand(0));
15432 case ISD::TokenFactor:
15433 // We have to check each of the operands of the token factor for "small"
15434 // token factors, so we queue them up. Adding the operands to the queue
15435 // (stack) in reverse order maintains the original order and increases the
15436 // likelihood that getNode will find a matching token factor (CSE.)
15437 if (Chain.getNumOperands() > 16) {
15438 Aliases.push_back(Chain);
15441 for (unsigned n = Chain.getNumOperands(); n;)
15442 Chains.push_back(Chain.getOperand(--n));
15447 // For all other instructions we will just have to take what we can get.
15448 Aliases.push_back(Chain);
15454 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
15455 /// (aliasing node.)
15456 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
15457 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
15459 // Accumulate all the aliases to this node.
15460 GatherAllAliases(N, OldChain, Aliases);
15462 // If no operands then chain to entry token.
15463 if (Aliases.size() == 0)
15464 return DAG.getEntryNode();
15466 // If a single operand then chain to it. We don't need to revisit it.
15467 if (Aliases.size() == 1)
15470 // Construct a custom tailored token factor.
15471 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
15474 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
15475 // This holds the base pointer, index, and the offset in bytes from the base
15477 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
15479 // We must have a base and an offset.
15480 if (!BasePtr.Base.getNode())
15483 // Do not handle stores to undef base pointers.
15484 if (BasePtr.Base.isUndef())
15487 SmallVector<StoreSDNode *, 8> ChainedStores;
15488 ChainedStores.push_back(St);
15490 // Walk up the chain and look for nodes with offsets from the same
15491 // base pointer. Stop when reaching an instruction with a different kind
15492 // or instruction which has a different base pointer.
15493 StoreSDNode *Index = St;
15495 // If the chain has more than one use, then we can't reorder the mem ops.
15496 if (Index != St && !SDValue(Index, 0)->hasOneUse())
15499 if (Index->isVolatile() || Index->isIndexed())
15502 // Find the base pointer and offset for this memory node.
15503 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
15505 // Check that the base pointer is the same as the original one.
15506 if (!Ptr.equalBaseIndex(BasePtr))
15509 // Find the next memory operand in the chain. If the next operand in the
15510 // chain is a store then move up and continue the scan with the next
15511 // memory operand. If the next operand is a load save it and use alias
15512 // information to check if it interferes with anything.
15513 SDNode *NextInChain = Index->getChain().getNode();
15515 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
15516 // We found a store node. Use it for the next iteration.
15517 if (STn->isVolatile() || STn->isIndexed()) {
15521 ChainedStores.push_back(STn);
15524 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
15525 NextInChain = Ldn->getChain().getNode();
15534 bool MadeChangeToSt = false;
15535 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15537 for (StoreSDNode *ChainedStore : ChainedStores) {
15538 SDValue Chain = ChainedStore->getChain();
15539 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15541 if (Chain != BetterChain) {
15542 if (ChainedStore == St)
15543 MadeChangeToSt = true;
15544 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15548 // Do all replacements after finding the replacements to make to avoid making
15549 // the chains more complicated by introducing new TokenFactors.
15550 for (auto Replacement : BetterChains)
15551 replaceStoreChain(Replacement.first, Replacement.second);
15553 return MadeChangeToSt;
15556 /// This is the entry point for the file.
15557 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15558 CodeGenOpt::Level OptLevel) {
15559 /// This is the main entry point to this class.
15560 DAGCombiner(*this, AA, OptLevel).Run(Level);