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 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Enable DAG combiner's use of IR alias analysis"));
60 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
61 cl::desc("Enable DAG combiner's use of TBAA"));
64 static cl::opt<std::string>
65 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
66 cl::desc("Only use DAG-combiner alias analysis in this"
70 /// Hidden option to stress test load slicing, i.e., when this option
71 /// is enabled, load slicing bypasses most of its profitability guards.
73 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
74 cl::desc("Bypass the profitability model of load "
79 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
80 cl::desc("DAG combiner may split indexing from loads"));
82 //------------------------------ DAGCombiner ---------------------------------//
86 const TargetLowering &TLI;
88 CodeGenOpt::Level OptLevel;
93 /// \brief Worklist of all of the nodes that need to be simplified.
95 /// This must behave as a stack -- new nodes to process are pushed onto the
96 /// back and when processing we pop off of the back.
98 /// The worklist will not contain duplicates but may contain null entries
99 /// due to nodes being deleted from the underlying DAG.
100 SmallVector<SDNode *, 64> Worklist;
102 /// \brief Mapping from an SDNode to its position on the worklist.
104 /// This is used to find and remove nodes from the worklist (by nulling
105 /// them) when they are deleted from the underlying DAG. It relies on
106 /// stable indices of nodes within the worklist.
107 DenseMap<SDNode *, unsigned> WorklistMap;
109 /// \brief Set of nodes which have been combined (at least once).
111 /// This is used to allow us to reliably add any operands of a DAG node
112 /// which have not yet been combined to the worklist.
113 SmallPtrSet<SDNode *, 32> CombinedNodes;
115 // AA - Used for DAG load/store alias analysis.
118 /// When an instruction is simplified, add all users of the instruction to
119 /// the work lists because they might get more simplified now.
120 void AddUsersToWorklist(SDNode *N) {
121 for (SDNode *Node : N->uses())
125 /// Call the node-specific routine that folds each particular type of node.
126 SDValue visit(SDNode *N);
129 /// Add to the worklist making sure its instance is at the back (next to be
131 void AddToWorklist(SDNode *N) {
132 assert(N->getOpcode() != ISD::DELETED_NODE &&
133 "Deleted Node added to Worklist");
135 // Skip handle nodes as they can't usefully be combined and confuse the
136 // zero-use deletion strategy.
137 if (N->getOpcode() == ISD::HANDLENODE)
140 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141 Worklist.push_back(N);
144 /// Remove all instances of N from the worklist.
145 void removeFromWorklist(SDNode *N) {
146 CombinedNodes.erase(N);
148 auto It = WorklistMap.find(N);
149 if (It == WorklistMap.end())
150 return; // Not in the worklist.
152 // Null out the entry rather than erasing it to avoid a linear operation.
153 Worklist[It->second] = nullptr;
154 WorklistMap.erase(It);
157 void deleteAndRecombine(SDNode *N);
158 bool recursivelyDeleteUnusedNodes(SDNode *N);
160 /// Replaces all uses of the results of one DAG node with new values.
161 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
164 /// Replaces all uses of the results of one DAG node with new values.
165 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
166 return CombineTo(N, &Res, 1, AddTo);
169 /// Replaces all uses of the results of one DAG node with new values.
170 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
172 SDValue To[] = { Res0, Res1 };
173 return CombineTo(N, To, 2, AddTo);
176 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
179 unsigned MaximumLegalStoreInBits;
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 visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
236 SDValue visitSUB(SDNode *N);
237 SDValue visitADDC(SDNode *N);
238 SDValue visitUADDO(SDNode *N);
239 SDValue visitSUBC(SDNode *N);
240 SDValue visitUSUBO(SDNode *N);
241 SDValue visitADDE(SDNode *N);
242 SDValue visitSUBE(SDNode *N);
243 SDValue visitMUL(SDNode *N);
244 SDValue useDivRem(SDNode *N);
245 SDValue visitSDIV(SDNode *N);
246 SDValue visitUDIV(SDNode *N);
247 SDValue visitREM(SDNode *N);
248 SDValue visitMULHU(SDNode *N);
249 SDValue visitMULHS(SDNode *N);
250 SDValue visitSMUL_LOHI(SDNode *N);
251 SDValue visitUMUL_LOHI(SDNode *N);
252 SDValue visitSMULO(SDNode *N);
253 SDValue visitUMULO(SDNode *N);
254 SDValue visitIMINMAX(SDNode *N);
255 SDValue visitAND(SDNode *N);
256 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
257 SDValue visitOR(SDNode *N);
258 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
259 SDValue visitXOR(SDNode *N);
260 SDValue SimplifyVBinOp(SDNode *N);
261 SDValue visitSHL(SDNode *N);
262 SDValue visitSRA(SDNode *N);
263 SDValue visitSRL(SDNode *N);
264 SDValue visitRotate(SDNode *N);
265 SDValue visitABS(SDNode *N);
266 SDValue visitBSWAP(SDNode *N);
267 SDValue visitBITREVERSE(SDNode *N);
268 SDValue visitCTLZ(SDNode *N);
269 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
270 SDValue visitCTTZ(SDNode *N);
271 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
272 SDValue visitCTPOP(SDNode *N);
273 SDValue visitSELECT(SDNode *N);
274 SDValue visitVSELECT(SDNode *N);
275 SDValue visitSELECT_CC(SDNode *N);
276 SDValue visitSETCC(SDNode *N);
277 SDValue visitSETCCE(SDNode *N);
278 SDValue visitSIGN_EXTEND(SDNode *N);
279 SDValue visitZERO_EXTEND(SDNode *N);
280 SDValue visitANY_EXTEND(SDNode *N);
281 SDValue visitAssertZext(SDNode *N);
282 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
283 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
284 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
285 SDValue visitTRUNCATE(SDNode *N);
286 SDValue visitBITCAST(SDNode *N);
287 SDValue visitBUILD_PAIR(SDNode *N);
288 SDValue visitFADD(SDNode *N);
289 SDValue visitFSUB(SDNode *N);
290 SDValue visitFMUL(SDNode *N);
291 SDValue visitFMA(SDNode *N);
292 SDValue visitFDIV(SDNode *N);
293 SDValue visitFREM(SDNode *N);
294 SDValue visitFSQRT(SDNode *N);
295 SDValue visitFCOPYSIGN(SDNode *N);
296 SDValue visitSINT_TO_FP(SDNode *N);
297 SDValue visitUINT_TO_FP(SDNode *N);
298 SDValue visitFP_TO_SINT(SDNode *N);
299 SDValue visitFP_TO_UINT(SDNode *N);
300 SDValue visitFP_ROUND(SDNode *N);
301 SDValue visitFP_ROUND_INREG(SDNode *N);
302 SDValue visitFP_EXTEND(SDNode *N);
303 SDValue visitFNEG(SDNode *N);
304 SDValue visitFABS(SDNode *N);
305 SDValue visitFCEIL(SDNode *N);
306 SDValue visitFTRUNC(SDNode *N);
307 SDValue visitFFLOOR(SDNode *N);
308 SDValue visitFMINNUM(SDNode *N);
309 SDValue visitFMAXNUM(SDNode *N);
310 SDValue visitBRCOND(SDNode *N);
311 SDValue visitBR_CC(SDNode *N);
312 SDValue visitLOAD(SDNode *N);
314 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
315 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
317 SDValue visitSTORE(SDNode *N);
318 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
319 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
320 SDValue visitBUILD_VECTOR(SDNode *N);
321 SDValue visitCONCAT_VECTORS(SDNode *N);
322 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
323 SDValue visitVECTOR_SHUFFLE(SDNode *N);
324 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
325 SDValue visitINSERT_SUBVECTOR(SDNode *N);
326 SDValue visitMLOAD(SDNode *N);
327 SDValue visitMSTORE(SDNode *N);
328 SDValue visitMGATHER(SDNode *N);
329 SDValue visitMSCATTER(SDNode *N);
330 SDValue visitFP_TO_FP16(SDNode *N);
331 SDValue visitFP16_TO_FP(SDNode *N);
333 SDValue visitFADDForFMACombine(SDNode *N);
334 SDValue visitFSUBForFMACombine(SDNode *N);
335 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
337 SDValue XformToShuffleWithZero(SDNode *N);
338 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
341 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
343 SDValue foldSelectOfConstants(SDNode *N);
344 SDValue foldBinOpIntoSelect(SDNode *BO);
345 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
346 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
347 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
348 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
349 SDValue N2, SDValue N3, ISD::CondCode CC,
350 bool NotExtCompare = false);
351 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
352 SDValue N2, SDValue N3, ISD::CondCode CC);
353 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
355 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
356 const SDLoc &DL, bool foldBooleans = true);
358 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
360 bool isOneUseSetCC(SDValue N) const;
362 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
364 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
365 SDValue CombineExtLoad(SDNode *N);
366 SDValue combineRepeatedFPDivisors(SDNode *N);
367 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
368 SDValue BuildSDIV(SDNode *N);
369 SDValue BuildSDIVPow2(SDNode *N);
370 SDValue BuildUDIV(SDNode *N);
371 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
372 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
373 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
374 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
375 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
376 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
377 SDNodeFlags *Flags, bool Reciprocal);
378 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
379 SDNodeFlags *Flags, bool Reciprocal);
380 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
381 bool DemandHighBits = true);
382 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
383 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
384 SDValue InnerPos, SDValue InnerNeg,
385 unsigned PosOpcode, unsigned NegOpcode,
387 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
388 SDValue MatchLoadCombine(SDNode *N);
389 SDValue ReduceLoadWidth(SDNode *N);
390 SDValue ReduceLoadOpStoreWidth(SDNode *N);
391 SDValue splitMergedValStore(StoreSDNode *ST);
392 SDValue TransformFPLoadStorePair(SDNode *N);
393 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
394 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
395 SDValue reduceBuildVecToShuffle(SDNode *N);
396 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
397 ArrayRef<int> VectorMask, SDValue VecIn1,
398 SDValue VecIn2, unsigned LeftIdx);
400 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
402 /// Walk up chain skipping non-aliasing memory nodes,
403 /// looking for aliasing nodes and adding them to the Aliases vector.
404 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
405 SmallVectorImpl<SDValue> &Aliases);
407 /// Return true if there is any possibility that the two addresses overlap.
408 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
410 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
411 /// chain (aliasing node.)
412 SDValue FindBetterChain(SDNode *N, SDValue Chain);
414 /// Try to replace a store and any possibly adjacent stores on
415 /// consecutive chains with better chains. Return true only if St is
418 /// Notice that other chains may still be replaced even if the function
420 bool findBetterNeighborChains(StoreSDNode *St);
422 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
423 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
425 /// Holds a pointer to an LSBaseSDNode as well as information on where it
426 /// is located in a sequence of memory operations connected by a chain.
428 MemOpLink(LSBaseSDNode *N, int64_t Offset)
429 : MemNode(N), OffsetFromBase(Offset) {}
430 // Ptr to the mem node.
431 LSBaseSDNode *MemNode;
432 // Offset from the base ptr.
433 int64_t OffsetFromBase;
436 /// This is a helper function for visitMUL to check the profitability
437 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
438 /// MulNode is the original multiply, AddNode is (add x, c1),
439 /// and ConstNode is c2.
440 bool isMulAddWithConstProfitable(SDNode *MulNode,
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 /// Helper function for MergeConsecutiveStores which merges the
455 /// component store chains.
456 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
459 /// This is a helper function for MergeConsecutiveStores. When the source
460 /// elements of the consecutive stores are all constants or all extracted
461 /// vector elements, try to merge them into one larger store.
462 /// \return True if a merged store was created.
463 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
464 EVT MemVT, unsigned NumStores,
465 bool IsConstantSrc, bool UseVector);
467 /// This is a helper function for MergeConsecutiveStores.
468 /// Stores that may be merged are placed in StoreNodes.
469 void getStoreMergeCandidates(StoreSDNode *St,
470 SmallVectorImpl<MemOpLink> &StoreNodes);
472 /// Helper function for MergeConsecutiveStores. Checks if
473 /// Candidate stores have indirect dependency through their
474 /// operands. \return True if safe to merge
475 bool checkMergeStoreCandidatesForDependencies(
476 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
478 /// Merge consecutive store operations into a wide store.
479 /// This optimization uses wide integers or vectors when possible.
480 /// \return number of stores that were merged into a merged store (the
481 /// affected nodes are stored as a prefix in \p StoreNodes).
482 bool MergeConsecutiveStores(StoreSDNode *N);
484 /// \brief Try to transform a truncation where C is a constant:
485 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
487 /// \p N needs to be a truncation and its first operand an AND. Other
488 /// requirements are checked by the function (e.g. that trunc is
489 /// single-use) and if missed an empty SDValue is returned.
490 SDValue distributeTruncateThroughAnd(SDNode *N);
493 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
494 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
495 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
496 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
498 MaximumLegalStoreInBits = 0;
499 for (MVT VT : MVT::all_valuetypes())
500 if (EVT(VT).isSimple() && VT != MVT::Other &&
501 TLI.isTypeLegal(EVT(VT)) &&
502 VT.getSizeInBits() >= MaximumLegalStoreInBits)
503 MaximumLegalStoreInBits = VT.getSizeInBits();
506 /// Runs the dag combiner on all nodes in the work list
507 void Run(CombineLevel AtLevel);
509 SelectionDAG &getDAG() const { return DAG; }
511 /// Returns a type large enough to hold any valid shift amount - before type
512 /// legalization these can be huge.
513 EVT getShiftAmountTy(EVT LHSTy) {
514 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
515 if (LHSTy.isVector())
517 auto &DL = DAG.getDataLayout();
518 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
519 : TLI.getPointerTy(DL);
522 /// This method returns true if we are running before type legalization or
523 /// if the specified VT is legal.
524 bool isTypeLegal(const EVT &VT) {
525 if (!LegalTypes) return true;
526 return TLI.isTypeLegal(VT);
529 /// Convenience wrapper around TargetLowering::getSetCCResultType
530 EVT getSetCCResultType(EVT VT) const {
531 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
538 /// This class is a DAGUpdateListener that removes any deleted
539 /// nodes from the worklist.
540 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
543 explicit WorklistRemover(DAGCombiner &dc)
544 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
546 void NodeDeleted(SDNode *N, SDNode *E) override {
547 DC.removeFromWorklist(N);
552 //===----------------------------------------------------------------------===//
553 // TargetLowering::DAGCombinerInfo implementation
554 //===----------------------------------------------------------------------===//
556 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
557 ((DAGCombiner*)DC)->AddToWorklist(N);
560 SDValue TargetLowering::DAGCombinerInfo::
561 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
562 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
565 SDValue TargetLowering::DAGCombinerInfo::
566 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
567 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
571 SDValue TargetLowering::DAGCombinerInfo::
572 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
573 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
576 void TargetLowering::DAGCombinerInfo::
577 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
578 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
581 //===----------------------------------------------------------------------===//
583 //===----------------------------------------------------------------------===//
585 void DAGCombiner::deleteAndRecombine(SDNode *N) {
586 removeFromWorklist(N);
588 // If the operands of this node are only used by the node, they will now be
589 // dead. Make sure to re-visit them and recursively delete dead nodes.
590 for (const SDValue &Op : N->ops())
591 // For an operand generating multiple values, one of the values may
592 // become dead allowing further simplification (e.g. split index
593 // arithmetic from an indexed load).
594 if (Op->hasOneUse() || Op->getNumValues() > 1)
595 AddToWorklist(Op.getNode());
600 /// Return 1 if we can compute the negated form of the specified expression for
601 /// the same cost as the expression itself, or 2 if we can compute the negated
602 /// form more cheaply than the expression itself.
603 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
604 const TargetLowering &TLI,
605 const TargetOptions *Options,
606 unsigned Depth = 0) {
607 // fneg is removable even if it has multiple uses.
608 if (Op.getOpcode() == ISD::FNEG) return 2;
610 // Don't allow anything with multiple uses.
611 if (!Op.hasOneUse()) return 0;
613 // Don't recurse exponentially.
614 if (Depth > 6) return 0;
616 switch (Op.getOpcode()) {
617 default: return false;
618 case ISD::ConstantFP: {
619 if (!LegalOperations)
622 // Don't invert constant FP values after legalization unless the target says
623 // the negated constant is legal.
624 EVT VT = Op.getValueType();
625 return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
626 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
629 // FIXME: determine better conditions for this xform.
630 if (!Options->UnsafeFPMath) return 0;
632 // After operation legalization, it might not be legal to create new FSUBs.
633 if (LegalOperations &&
634 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
637 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
638 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
641 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
642 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
645 // We can't turn -(A-B) into B-A when we honor signed zeros.
646 if (!Options->NoSignedZerosFPMath &&
647 !Op.getNode()->getFlags()->hasNoSignedZeros())
650 // fold (fneg (fsub A, B)) -> (fsub B, A)
655 if (Options->HonorSignDependentRoundingFPMath()) return 0;
657 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
658 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
662 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
668 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
673 /// If isNegatibleForFree returns true, return the newly negated expression.
674 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
675 bool LegalOperations, unsigned Depth = 0) {
676 const TargetOptions &Options = DAG.getTarget().Options;
677 // fneg is removable even if it has multiple uses.
678 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
680 // Don't allow anything with multiple uses.
681 assert(Op.hasOneUse() && "Unknown reuse!");
683 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
685 const SDNodeFlags *Flags = Op.getNode()->getFlags();
687 switch (Op.getOpcode()) {
688 default: llvm_unreachable("Unknown code");
689 case ISD::ConstantFP: {
690 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
692 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
695 // FIXME: determine better conditions for this xform.
696 assert(Options.UnsafeFPMath);
698 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
699 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
700 DAG.getTargetLoweringInfo(), &Options, Depth+1))
701 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
702 GetNegatedExpression(Op.getOperand(0), DAG,
703 LegalOperations, Depth+1),
704 Op.getOperand(1), Flags);
705 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
706 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
707 GetNegatedExpression(Op.getOperand(1), DAG,
708 LegalOperations, Depth+1),
709 Op.getOperand(0), Flags);
711 // fold (fneg (fsub 0, B)) -> B
712 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
714 return Op.getOperand(1);
716 // fold (fneg (fsub A, B)) -> (fsub B, A)
717 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
718 Op.getOperand(1), Op.getOperand(0), Flags);
722 assert(!Options.HonorSignDependentRoundingFPMath());
724 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
725 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
726 DAG.getTargetLoweringInfo(), &Options, Depth+1))
727 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
728 GetNegatedExpression(Op.getOperand(0), DAG,
729 LegalOperations, Depth+1),
730 Op.getOperand(1), Flags);
732 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
733 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
735 GetNegatedExpression(Op.getOperand(1), DAG,
736 LegalOperations, Depth+1), Flags);
740 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
741 GetNegatedExpression(Op.getOperand(0), DAG,
742 LegalOperations, Depth+1));
744 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
745 GetNegatedExpression(Op.getOperand(0), DAG,
746 LegalOperations, Depth+1),
751 // APInts must be the same size for most operations, this helper
752 // function zero extends the shorter of the pair so that they match.
753 // We provide an Offset so that we can create bitwidths that won't overflow.
754 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
755 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
756 LHS = LHS.zextOrSelf(Bits);
757 RHS = RHS.zextOrSelf(Bits);
760 // Return true if this node is a setcc, or is a select_cc
761 // that selects between the target values used for true and false, making it
762 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
763 // the appropriate nodes based on the type of node we are checking. This
764 // simplifies life a bit for the callers.
765 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
767 if (N.getOpcode() == ISD::SETCC) {
768 LHS = N.getOperand(0);
769 RHS = N.getOperand(1);
770 CC = N.getOperand(2);
774 if (N.getOpcode() != ISD::SELECT_CC ||
775 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
776 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
779 if (TLI.getBooleanContents(N.getValueType()) ==
780 TargetLowering::UndefinedBooleanContent)
783 LHS = N.getOperand(0);
784 RHS = N.getOperand(1);
785 CC = N.getOperand(4);
789 /// Return true if this is a SetCC-equivalent operation with only one use.
790 /// If this is true, it allows the users to invert the operation for free when
791 /// it is profitable to do so.
792 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
794 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
799 // \brief Returns the SDNode if it is a constant float BuildVector
800 // or constant float.
801 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
802 if (isa<ConstantFPSDNode>(N))
804 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
809 // Determines if it is a constant integer or a build vector of constant
810 // integers (and undefs).
811 // Do not permit build vector implicit truncation.
812 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
813 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
814 return !(Const->isOpaque() && NoOpaques);
815 if (N.getOpcode() != ISD::BUILD_VECTOR)
817 unsigned BitWidth = N.getScalarValueSizeInBits();
818 for (const SDValue &Op : N->op_values()) {
821 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
822 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
823 (Const->isOpaque() && NoOpaques))
829 // Determines if it is a constant null integer or a splatted vector of a
830 // constant null integer (with no undefs).
831 // Build vector implicit truncation is not an issue for null values.
832 static bool isNullConstantOrNullSplatConstant(SDValue N) {
833 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
834 return Splat->isNullValue();
838 // Determines if it is a constant integer of one or a splatted vector of a
839 // constant integer of one (with no undefs).
840 // Do not permit build vector implicit truncation.
841 static bool isOneConstantOrOneSplatConstant(SDValue N) {
842 unsigned BitWidth = N.getScalarValueSizeInBits();
843 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
844 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
848 // Determines if it is a constant integer of all ones or a splatted vector of a
849 // constant integer of all ones (with no undefs).
850 // Do not permit build vector implicit truncation.
851 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
852 unsigned BitWidth = N.getScalarValueSizeInBits();
853 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
854 return Splat->isAllOnesValue() &&
855 Splat->getAPIntValue().getBitWidth() == BitWidth;
859 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
861 static bool isAnyConstantBuildVector(const SDNode *N) {
862 return ISD::isBuildVectorOfConstantSDNodes(N) ||
863 ISD::isBuildVectorOfConstantFPSDNodes(N);
866 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
868 EVT VT = N0.getValueType();
869 if (N0.getOpcode() == Opc) {
870 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
871 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
872 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
873 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
874 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
877 if (N0.hasOneUse()) {
878 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
880 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
881 if (!OpNode.getNode())
883 AddToWorklist(OpNode.getNode());
884 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
889 if (N1.getOpcode() == Opc) {
890 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
891 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
892 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
893 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
894 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
897 if (N1.hasOneUse()) {
898 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
900 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
901 if (!OpNode.getNode())
903 AddToWorklist(OpNode.getNode());
904 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
912 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
914 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
916 DEBUG(dbgs() << "\nReplacing.1 ";
918 dbgs() << "\nWith: ";
919 To[0].getNode()->dump(&DAG);
920 dbgs() << " and " << NumTo-1 << " other values\n");
921 for (unsigned i = 0, e = NumTo; i != e; ++i)
922 assert((!To[i].getNode() ||
923 N->getValueType(i) == To[i].getValueType()) &&
924 "Cannot combine value to value of different type!");
926 WorklistRemover DeadNodes(*this);
927 DAG.ReplaceAllUsesWith(N, To);
929 // Push the new nodes and any users onto the worklist
930 for (unsigned i = 0, e = NumTo; i != e; ++i) {
931 if (To[i].getNode()) {
932 AddToWorklist(To[i].getNode());
933 AddUsersToWorklist(To[i].getNode());
938 // Finally, if the node is now dead, remove it from the graph. The node
939 // may not be dead if the replacement process recursively simplified to
940 // something else needing this node.
942 deleteAndRecombine(N);
943 return SDValue(N, 0);
947 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
948 // Replace all uses. If any nodes become isomorphic to other nodes and
949 // are deleted, make sure to remove them from our worklist.
950 WorklistRemover DeadNodes(*this);
951 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
953 // Push the new node and any (possibly new) users onto the worklist.
954 AddToWorklist(TLO.New.getNode());
955 AddUsersToWorklist(TLO.New.getNode());
957 // Finally, if the node is now dead, remove it from the graph. The node
958 // may not be dead if the replacement process recursively simplified to
959 // something else needing this node.
960 if (TLO.Old.getNode()->use_empty())
961 deleteAndRecombine(TLO.Old.getNode());
964 /// Check the specified integer node value to see if it can be simplified or if
965 /// things it uses can be simplified by bit propagation. If so, return true.
966 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
967 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
968 APInt KnownZero, KnownOne;
969 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
973 AddToWorklist(Op.getNode());
975 // Replace the old value with the new one.
977 DEBUG(dbgs() << "\nReplacing.2 ";
978 TLO.Old.getNode()->dump(&DAG);
979 dbgs() << "\nWith: ";
980 TLO.New.getNode()->dump(&DAG);
983 CommitTargetLoweringOpt(TLO);
987 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
989 EVT VT = Load->getValueType(0);
990 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
992 DEBUG(dbgs() << "\nReplacing.9 ";
994 dbgs() << "\nWith: ";
995 Trunc.getNode()->dump(&DAG);
997 WorklistRemover DeadNodes(*this);
998 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
999 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1000 deleteAndRecombine(Load);
1001 AddToWorklist(Trunc.getNode());
1004 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1007 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1008 LoadSDNode *LD = cast<LoadSDNode>(Op);
1009 EVT MemVT = LD->getMemoryVT();
1010 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1011 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1013 : LD->getExtensionType();
1015 return DAG.getExtLoad(ExtType, DL, PVT,
1016 LD->getChain(), LD->getBasePtr(),
1017 MemVT, LD->getMemOperand());
1020 unsigned Opc = Op.getOpcode();
1023 case ISD::AssertSext:
1024 return DAG.getNode(ISD::AssertSext, DL, PVT,
1025 SExtPromoteOperand(Op.getOperand(0), PVT),
1027 case ISD::AssertZext:
1028 return DAG.getNode(ISD::AssertZext, DL, PVT,
1029 ZExtPromoteOperand(Op.getOperand(0), PVT),
1031 case ISD::Constant: {
1033 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1034 return DAG.getNode(ExtOpc, DL, PVT, Op);
1038 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1040 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1043 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1044 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 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.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1057 DAG.getValueType(OldVT));
1060 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1061 EVT OldVT = Op.getValueType();
1063 bool Replace = false;
1064 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1065 if (!NewOp.getNode())
1067 AddToWorklist(NewOp.getNode());
1070 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1071 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1074 /// Promote the specified integer binary operation if the target indicates it is
1075 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1076 /// i32 since i16 instructions are longer.
1077 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1078 if (!LegalOperations)
1081 EVT VT = Op.getValueType();
1082 if (VT.isVector() || !VT.isInteger())
1085 // If operation type is 'undesirable', e.g. i16 on x86, consider
1087 unsigned Opc = Op.getOpcode();
1088 if (TLI.isTypeDesirableForOp(Opc, VT))
1092 // Consult target whether it is a good idea to promote this operation and
1093 // what's the right type to promote it to.
1094 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1095 assert(PVT != VT && "Don't know what type to promote to!");
1097 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1099 bool Replace0 = false;
1100 SDValue N0 = Op.getOperand(0);
1101 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1103 bool Replace1 = false;
1104 SDValue N1 = Op.getOperand(1);
1105 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1109 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1111 // New replace instances of N0 and N1
1112 if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
1113 NN0.getOpcode() != ISD::DELETED_NODE) {
1114 AddToWorklist(NN0.getNode());
1115 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1118 if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
1119 NN1.getOpcode() != ISD::DELETED_NODE) {
1120 AddToWorklist(NN1.getNode());
1121 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1124 // Deal with Op being deleted.
1125 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1131 /// Promote the specified integer shift operation if the target indicates it is
1132 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1133 /// i32 since i16 instructions are longer.
1134 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1135 if (!LegalOperations)
1138 EVT VT = Op.getValueType();
1139 if (VT.isVector() || !VT.isInteger())
1142 // If operation type is 'undesirable', e.g. i16 on x86, consider
1144 unsigned Opc = Op.getOpcode();
1145 if (TLI.isTypeDesirableForOp(Opc, VT))
1149 // Consult target whether it is a good idea to promote this operation and
1150 // what's the right type to promote it to.
1151 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1152 assert(PVT != VT && "Don't know what type to promote to!");
1154 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1156 bool Replace = false;
1157 SDValue N0 = Op.getOperand(0);
1158 SDValue N1 = Op.getOperand(1);
1159 if (Opc == ISD::SRA)
1160 N0 = SExtPromoteOperand(N0, PVT);
1161 else if (Opc == ISD::SRL)
1162 N0 = ZExtPromoteOperand(N0, PVT);
1164 N0 = PromoteOperand(N0, PVT, Replace);
1171 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1173 AddToWorklist(N0.getNode());
1175 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1177 // Deal with Op being deleted.
1178 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1184 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1185 if (!LegalOperations)
1188 EVT VT = Op.getValueType();
1189 if (VT.isVector() || !VT.isInteger())
1192 // If operation type is 'undesirable', e.g. i16 on x86, consider
1194 unsigned Opc = Op.getOpcode();
1195 if (TLI.isTypeDesirableForOp(Opc, VT))
1199 // Consult target whether it is a good idea to promote this operation and
1200 // what's the right type to promote it to.
1201 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1202 assert(PVT != VT && "Don't know what type to promote to!");
1203 // fold (aext (aext x)) -> (aext x)
1204 // fold (aext (zext x)) -> (zext x)
1205 // fold (aext (sext x)) -> (sext x)
1206 DEBUG(dbgs() << "\nPromoting ";
1207 Op.getNode()->dump(&DAG));
1208 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1213 bool DAGCombiner::PromoteLoad(SDValue Op) {
1214 if (!LegalOperations)
1217 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1220 EVT VT = Op.getValueType();
1221 if (VT.isVector() || !VT.isInteger())
1224 // If operation type is 'undesirable', e.g. i16 on x86, consider
1226 unsigned Opc = Op.getOpcode();
1227 if (TLI.isTypeDesirableForOp(Opc, VT))
1231 // Consult target whether it is a good idea to promote this operation and
1232 // what's the right type to promote it to.
1233 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1234 assert(PVT != VT && "Don't know what type to promote to!");
1237 SDNode *N = Op.getNode();
1238 LoadSDNode *LD = cast<LoadSDNode>(N);
1239 EVT MemVT = LD->getMemoryVT();
1240 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1241 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1243 : LD->getExtensionType();
1244 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1245 LD->getChain(), LD->getBasePtr(),
1246 MemVT, LD->getMemOperand());
1247 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1249 DEBUG(dbgs() << "\nPromoting ";
1252 Result.getNode()->dump(&DAG);
1254 WorklistRemover DeadNodes(*this);
1255 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1256 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1257 deleteAndRecombine(N);
1258 AddToWorklist(Result.getNode());
1264 /// \brief Recursively delete a node which has no uses and any operands for
1265 /// which it is the only use.
1267 /// Note that this both deletes the nodes and removes them from the worklist.
1268 /// It also adds any nodes who have had a user deleted to the worklist as they
1269 /// may now have only one use and subject to other combines.
1270 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1271 if (!N->use_empty())
1274 SmallSetVector<SDNode *, 16> Nodes;
1277 N = Nodes.pop_back_val();
1281 if (N->use_empty()) {
1282 for (const SDValue &ChildN : N->op_values())
1283 Nodes.insert(ChildN.getNode());
1285 removeFromWorklist(N);
1290 } while (!Nodes.empty());
1294 //===----------------------------------------------------------------------===//
1295 // Main DAG Combiner implementation
1296 //===----------------------------------------------------------------------===//
1298 void DAGCombiner::Run(CombineLevel AtLevel) {
1299 // set the instance variables, so that the various visit routines may use it.
1301 LegalOperations = Level >= AfterLegalizeVectorOps;
1302 LegalTypes = Level >= AfterLegalizeTypes;
1304 // Add all the dag nodes to the worklist.
1305 for (SDNode &Node : DAG.allnodes())
1306 AddToWorklist(&Node);
1308 // Create a dummy node (which is not added to allnodes), that adds a reference
1309 // to the root node, preventing it from being deleted, and tracking any
1310 // changes of the root.
1311 HandleSDNode Dummy(DAG.getRoot());
1313 // While the worklist isn't empty, find a node and try to combine it.
1314 while (!WorklistMap.empty()) {
1316 // The Worklist holds the SDNodes in order, but it may contain null entries.
1318 N = Worklist.pop_back_val();
1321 bool GoodWorklistEntry = WorklistMap.erase(N);
1322 (void)GoodWorklistEntry;
1323 assert(GoodWorklistEntry &&
1324 "Found a worklist entry without a corresponding map entry!");
1326 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1327 // N is deleted from the DAG, since they too may now be dead or may have a
1328 // reduced number of uses, allowing other xforms.
1329 if (recursivelyDeleteUnusedNodes(N))
1332 WorklistRemover DeadNodes(*this);
1334 // If this combine is running after legalizing the DAG, re-legalize any
1335 // nodes pulled off the worklist.
1336 if (Level == AfterLegalizeDAG) {
1337 SmallSetVector<SDNode *, 16> UpdatedNodes;
1338 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1340 for (SDNode *LN : UpdatedNodes) {
1342 AddUsersToWorklist(LN);
1348 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1350 // Add any operands of the new node which have not yet been combined to the
1351 // worklist as well. Because the worklist uniques things already, this
1352 // won't repeatedly process the same operand.
1353 CombinedNodes.insert(N);
1354 for (const SDValue &ChildN : N->op_values())
1355 if (!CombinedNodes.count(ChildN.getNode()))
1356 AddToWorklist(ChildN.getNode());
1358 SDValue RV = combine(N);
1365 // If we get back the same node we passed in, rather than a new node or
1366 // zero, we know that the node must have defined multiple values and
1367 // CombineTo was used. Since CombineTo takes care of the worklist
1368 // mechanics for us, we have no work to do in this case.
1369 if (RV.getNode() == N)
1372 assert(N->getOpcode() != ISD::DELETED_NODE &&
1373 RV.getOpcode() != ISD::DELETED_NODE &&
1374 "Node was deleted but visit returned new node!");
1376 DEBUG(dbgs() << " ... into: ";
1377 RV.getNode()->dump(&DAG));
1379 if (N->getNumValues() == RV.getNode()->getNumValues())
1380 DAG.ReplaceAllUsesWith(N, RV.getNode());
1382 assert(N->getValueType(0) == RV.getValueType() &&
1383 N->getNumValues() == 1 && "Type mismatch");
1384 DAG.ReplaceAllUsesWith(N, &RV);
1387 // Push the new node and any users onto the worklist
1388 AddToWorklist(RV.getNode());
1389 AddUsersToWorklist(RV.getNode());
1391 // Finally, if the node is now dead, remove it from the graph. The node
1392 // may not be dead if the replacement process recursively simplified to
1393 // something else needing this node. This will also take care of adding any
1394 // operands which have lost a user to the worklist.
1395 recursivelyDeleteUnusedNodes(N);
1398 // If the root changed (e.g. it was a dead load, update the root).
1399 DAG.setRoot(Dummy.getValue());
1400 DAG.RemoveDeadNodes();
1403 SDValue DAGCombiner::visit(SDNode *N) {
1404 switch (N->getOpcode()) {
1406 case ISD::TokenFactor: return visitTokenFactor(N);
1407 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1408 case ISD::ADD: return visitADD(N);
1409 case ISD::SUB: return visitSUB(N);
1410 case ISD::ADDC: return visitADDC(N);
1411 case ISD::UADDO: return visitUADDO(N);
1412 case ISD::SUBC: return visitSUBC(N);
1413 case ISD::USUBO: return visitUSUBO(N);
1414 case ISD::ADDE: return visitADDE(N);
1415 case ISD::SUBE: return visitSUBE(N);
1416 case ISD::MUL: return visitMUL(N);
1417 case ISD::SDIV: return visitSDIV(N);
1418 case ISD::UDIV: return visitUDIV(N);
1420 case ISD::UREM: return visitREM(N);
1421 case ISD::MULHU: return visitMULHU(N);
1422 case ISD::MULHS: return visitMULHS(N);
1423 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1424 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1425 case ISD::SMULO: return visitSMULO(N);
1426 case ISD::UMULO: return visitUMULO(N);
1430 case ISD::UMAX: return visitIMINMAX(N);
1431 case ISD::AND: return visitAND(N);
1432 case ISD::OR: return visitOR(N);
1433 case ISD::XOR: return visitXOR(N);
1434 case ISD::SHL: return visitSHL(N);
1435 case ISD::SRA: return visitSRA(N);
1436 case ISD::SRL: return visitSRL(N);
1438 case ISD::ROTL: return visitRotate(N);
1439 case ISD::ABS: return visitABS(N);
1440 case ISD::BSWAP: return visitBSWAP(N);
1441 case ISD::BITREVERSE: return visitBITREVERSE(N);
1442 case ISD::CTLZ: return visitCTLZ(N);
1443 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1444 case ISD::CTTZ: return visitCTTZ(N);
1445 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1446 case ISD::CTPOP: return visitCTPOP(N);
1447 case ISD::SELECT: return visitSELECT(N);
1448 case ISD::VSELECT: return visitVSELECT(N);
1449 case ISD::SELECT_CC: return visitSELECT_CC(N);
1450 case ISD::SETCC: return visitSETCC(N);
1451 case ISD::SETCCE: return visitSETCCE(N);
1452 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1453 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1454 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1455 case ISD::AssertZext: return visitAssertZext(N);
1456 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1457 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1458 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1459 case ISD::TRUNCATE: return visitTRUNCATE(N);
1460 case ISD::BITCAST: return visitBITCAST(N);
1461 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1462 case ISD::FADD: return visitFADD(N);
1463 case ISD::FSUB: return visitFSUB(N);
1464 case ISD::FMUL: return visitFMUL(N);
1465 case ISD::FMA: return visitFMA(N);
1466 case ISD::FDIV: return visitFDIV(N);
1467 case ISD::FREM: return visitFREM(N);
1468 case ISD::FSQRT: return visitFSQRT(N);
1469 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1470 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1471 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1472 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1473 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1474 case ISD::FP_ROUND: return visitFP_ROUND(N);
1475 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1476 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1477 case ISD::FNEG: return visitFNEG(N);
1478 case ISD::FABS: return visitFABS(N);
1479 case ISD::FFLOOR: return visitFFLOOR(N);
1480 case ISD::FMINNUM: return visitFMINNUM(N);
1481 case ISD::FMAXNUM: return visitFMAXNUM(N);
1482 case ISD::FCEIL: return visitFCEIL(N);
1483 case ISD::FTRUNC: return visitFTRUNC(N);
1484 case ISD::BRCOND: return visitBRCOND(N);
1485 case ISD::BR_CC: return visitBR_CC(N);
1486 case ISD::LOAD: return visitLOAD(N);
1487 case ISD::STORE: return visitSTORE(N);
1488 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1489 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1490 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1491 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1492 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1493 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1494 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1495 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1496 case ISD::MGATHER: return visitMGATHER(N);
1497 case ISD::MLOAD: return visitMLOAD(N);
1498 case ISD::MSCATTER: return visitMSCATTER(N);
1499 case ISD::MSTORE: return visitMSTORE(N);
1500 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1501 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1506 SDValue DAGCombiner::combine(SDNode *N) {
1507 SDValue RV = visit(N);
1509 // If nothing happened, try a target-specific DAG combine.
1510 if (!RV.getNode()) {
1511 assert(N->getOpcode() != ISD::DELETED_NODE &&
1512 "Node was deleted but visit returned NULL!");
1514 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1515 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1517 // Expose the DAG combiner to the target combiner impls.
1518 TargetLowering::DAGCombinerInfo
1519 DagCombineInfo(DAG, Level, false, this);
1521 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1525 // If nothing happened still, try promoting the operation.
1526 if (!RV.getNode()) {
1527 switch (N->getOpcode()) {
1535 RV = PromoteIntBinOp(SDValue(N, 0));
1540 RV = PromoteIntShiftOp(SDValue(N, 0));
1542 case ISD::SIGN_EXTEND:
1543 case ISD::ZERO_EXTEND:
1544 case ISD::ANY_EXTEND:
1545 RV = PromoteExtend(SDValue(N, 0));
1548 if (PromoteLoad(SDValue(N, 0)))
1554 // If N is a commutative binary node, try commuting it to enable more
1556 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1557 N->getNumValues() == 1) {
1558 SDValue N0 = N->getOperand(0);
1559 SDValue N1 = N->getOperand(1);
1561 // Constant operands are canonicalized to RHS.
1562 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1563 SDValue Ops[] = {N1, N0};
1564 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1567 return SDValue(CSENode, 0);
1574 /// Given a node, return its input chain if it has one, otherwise return a null
1576 static SDValue getInputChainForNode(SDNode *N) {
1577 if (unsigned NumOps = N->getNumOperands()) {
1578 if (N->getOperand(0).getValueType() == MVT::Other)
1579 return N->getOperand(0);
1580 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1581 return N->getOperand(NumOps-1);
1582 for (unsigned i = 1; i < NumOps-1; ++i)
1583 if (N->getOperand(i).getValueType() == MVT::Other)
1584 return N->getOperand(i);
1589 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1590 // If N has two operands, where one has an input chain equal to the other,
1591 // the 'other' chain is redundant.
1592 if (N->getNumOperands() == 2) {
1593 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1594 return N->getOperand(0);
1595 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1596 return N->getOperand(1);
1599 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1600 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1601 SmallPtrSet<SDNode*, 16> SeenOps;
1602 bool Changed = false; // If we should replace this token factor.
1604 // Start out with this token factor.
1607 // Iterate through token factors. The TFs grows when new token factors are
1609 for (unsigned i = 0; i < TFs.size(); ++i) {
1610 SDNode *TF = TFs[i];
1612 // Check each of the operands.
1613 for (const SDValue &Op : TF->op_values()) {
1615 switch (Op.getOpcode()) {
1616 case ISD::EntryToken:
1617 // Entry tokens don't need to be added to the list. They are
1622 case ISD::TokenFactor:
1623 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1624 // Queue up for processing.
1625 TFs.push_back(Op.getNode());
1626 // Clean up in case the token factor is removed.
1627 AddToWorklist(Op.getNode());
1634 // Only add if it isn't already in the list.
1635 if (SeenOps.insert(Op.getNode()).second)
1644 // Remove Nodes that are chained to another node in the list. Do so
1645 // by walking up chains breath-first stopping when we've seen
1646 // another operand. In general we must climb to the EntryNode, but we can exit
1647 // early if we find all remaining work is associated with just one operand as
1648 // no further pruning is possible.
1650 // List of nodes to search through and original Ops from which they originate.
1651 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1652 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1653 SmallPtrSet<SDNode *, 16> SeenChains;
1654 bool DidPruneOps = false;
1656 unsigned NumLeftToConsider = 0;
1657 for (const SDValue &Op : Ops) {
1658 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1659 OpWorkCount.push_back(1);
1662 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1663 // If this is an Op, we can remove the op from the list. Remark any
1664 // search associated with it as from the current OpNumber.
1665 if (SeenOps.count(Op) != 0) {
1668 unsigned OrigOpNumber = 0;
1669 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1671 assert((OrigOpNumber != Ops.size()) &&
1672 "expected to find TokenFactor Operand");
1673 // Re-mark worklist from OrigOpNumber to OpNumber
1674 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1675 if (Worklist[i].second == OrigOpNumber) {
1676 Worklist[i].second = OpNumber;
1679 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1680 OpWorkCount[OrigOpNumber] = 0;
1681 NumLeftToConsider--;
1683 // Add if it's a new chain
1684 if (SeenChains.insert(Op).second) {
1685 OpWorkCount[OpNumber]++;
1686 Worklist.push_back(std::make_pair(Op, OpNumber));
1690 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1691 // We need at least be consider at least 2 Ops to prune.
1692 if (NumLeftToConsider <= 1)
1694 auto CurNode = Worklist[i].first;
1695 auto CurOpNumber = Worklist[i].second;
1696 assert((OpWorkCount[CurOpNumber] > 0) &&
1697 "Node should not appear in worklist");
1698 switch (CurNode->getOpcode()) {
1699 case ISD::EntryToken:
1700 // Hitting EntryToken is the only way for the search to terminate without
1702 // another operand's search. Prevent us from marking this operand
1704 NumLeftToConsider++;
1706 case ISD::TokenFactor:
1707 for (const SDValue &Op : CurNode->op_values())
1708 AddToWorklist(i, Op.getNode(), CurOpNumber);
1710 case ISD::CopyFromReg:
1711 case ISD::CopyToReg:
1712 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1715 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1716 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1719 OpWorkCount[CurOpNumber]--;
1720 if (OpWorkCount[CurOpNumber] == 0)
1721 NumLeftToConsider--;
1726 // If we've changed things around then replace token factor.
1729 // The entry token is the only possible outcome.
1730 Result = DAG.getEntryNode();
1733 SmallVector<SDValue, 8> PrunedOps;
1735 for (const SDValue &Op : Ops) {
1736 if (SeenChains.count(Op.getNode()) == 0)
1737 PrunedOps.push_back(Op);
1739 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1741 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1745 // Add users to worklist, since we may introduce a lot of new
1746 // chained token factors while removing memory deps.
1747 return CombineTo(N, Result, true /*add to worklist*/);
1753 /// MERGE_VALUES can always be eliminated.
1754 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1755 WorklistRemover DeadNodes(*this);
1756 // Replacing results may cause a different MERGE_VALUES to suddenly
1757 // be CSE'd with N, and carry its uses with it. Iterate until no
1758 // uses remain, to ensure that the node can be safely deleted.
1759 // First add the users of this node to the work list so that they
1760 // can be tried again once they have new operands.
1761 AddUsersToWorklist(N);
1763 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1764 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1765 } while (!N->use_empty());
1766 deleteAndRecombine(N);
1767 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1770 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1771 /// ConstantSDNode pointer else nullptr.
1772 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1773 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1774 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1777 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1778 auto BinOpcode = BO->getOpcode();
1779 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1780 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1781 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1782 BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1783 BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1784 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1785 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1786 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1787 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1788 "Unexpected binary operator");
1790 // Bail out if any constants are opaque because we can't constant fold those.
1791 SDValue C1 = BO->getOperand(1);
1792 if (!isConstantOrConstantVector(C1, true) &&
1793 !isConstantFPBuildVectorOrConstantFP(C1))
1796 // Don't do this unless the old select is going away. We want to eliminate the
1797 // binary operator, not replace a binop with a select.
1798 // TODO: Handle ISD::SELECT_CC.
1799 SDValue Sel = BO->getOperand(0);
1800 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1803 SDValue CT = Sel.getOperand(1);
1804 if (!isConstantOrConstantVector(CT, true) &&
1805 !isConstantFPBuildVectorOrConstantFP(CT))
1808 SDValue CF = Sel.getOperand(2);
1809 if (!isConstantOrConstantVector(CF, true) &&
1810 !isConstantFPBuildVectorOrConstantFP(CF))
1813 // We have a select-of-constants followed by a binary operator with a
1814 // constant. Eliminate the binop by pulling the constant math into the select.
1815 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1816 EVT VT = Sel.getValueType();
1818 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1819 assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1820 isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1821 "Failed to constant fold a binop with constant operands");
1823 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1824 assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1825 isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1826 "Failed to constant fold a binop with constant operands");
1828 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1831 SDValue DAGCombiner::visitADD(SDNode *N) {
1832 SDValue N0 = N->getOperand(0);
1833 SDValue N1 = N->getOperand(1);
1834 EVT VT = N0.getValueType();
1838 if (VT.isVector()) {
1839 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1842 // fold (add x, 0) -> x, vector edition
1843 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1845 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1849 // fold (add x, undef) -> undef
1856 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1857 // canonicalize constant to RHS
1858 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1859 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1860 // fold (add c1, c2) -> c1+c2
1861 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1865 // fold (add x, 0) -> x
1866 if (isNullConstant(N1))
1869 // fold ((c1-A)+c2) -> (c1+c2)-A
1870 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1871 if (N0.getOpcode() == ISD::SUB)
1872 if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1873 return DAG.getNode(ISD::SUB, DL, VT,
1874 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1879 if (SDValue NewSel = foldBinOpIntoSelect(N))
1883 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1886 // fold ((0-A) + B) -> B-A
1887 if (N0.getOpcode() == ISD::SUB &&
1888 isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1889 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1891 // fold (A + (0-B)) -> A-B
1892 if (N1.getOpcode() == ISD::SUB &&
1893 isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1894 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1896 // fold (A+(B-A)) -> B
1897 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1898 return N1.getOperand(0);
1900 // fold ((B-A)+A) -> B
1901 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1902 return N0.getOperand(0);
1904 // fold (A+(B-(A+C))) to (B-C)
1905 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1906 N0 == N1.getOperand(1).getOperand(0))
1907 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1908 N1.getOperand(1).getOperand(1));
1910 // fold (A+(B-(C+A))) to (B-C)
1911 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1912 N0 == N1.getOperand(1).getOperand(1))
1913 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1914 N1.getOperand(1).getOperand(0));
1916 // fold (A+((B-A)+or-C)) to (B+or-C)
1917 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1918 N1.getOperand(0).getOpcode() == ISD::SUB &&
1919 N0 == N1.getOperand(0).getOperand(1))
1920 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1923 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1924 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1925 SDValue N00 = N0.getOperand(0);
1926 SDValue N01 = N0.getOperand(1);
1927 SDValue N10 = N1.getOperand(0);
1928 SDValue N11 = N1.getOperand(1);
1930 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1931 return DAG.getNode(ISD::SUB, DL, VT,
1932 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1933 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1936 if (SimplifyDemandedBits(SDValue(N, 0)))
1937 return SDValue(N, 0);
1939 // fold (a+b) -> (a|b) iff a and b share no bits.
1940 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1941 VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1942 return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1944 if (SDValue Combined = visitADDLike(N0, N1, N))
1947 if (SDValue Combined = visitADDLike(N1, N0, N))
1953 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
1954 EVT VT = N0.getValueType();
1955 SDLoc DL(LocReference);
1957 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1958 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1959 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1960 return DAG.getNode(ISD::SUB, DL, VT, N0,
1961 DAG.getNode(ISD::SHL, DL, VT,
1962 N1.getOperand(0).getOperand(1),
1965 if (N1.getOpcode() == ISD::AND) {
1966 SDValue AndOp0 = N1.getOperand(0);
1967 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1968 unsigned DestBits = VT.getScalarSizeInBits();
1970 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1971 // and similar xforms where the inner op is either ~0 or 0.
1972 if (NumSignBits == DestBits &&
1973 isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1974 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
1977 // add (sext i1), X -> sub X, (zext i1)
1978 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1979 N0.getOperand(0).getValueType() == MVT::i1 &&
1980 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1981 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1982 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1985 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1986 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1987 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1988 if (TN->getVT() == MVT::i1) {
1989 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1990 DAG.getConstant(1, DL, VT));
1991 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1998 SDValue DAGCombiner::visitADDC(SDNode *N) {
1999 SDValue N0 = N->getOperand(0);
2000 SDValue N1 = N->getOperand(1);
2001 EVT VT = N0.getValueType();
2004 // If the flag result is dead, turn this into an ADD.
2005 if (!N->hasAnyUseOfValue(1))
2006 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2007 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2009 // canonicalize constant to RHS.
2010 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2011 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2013 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2015 // fold (addc x, 0) -> x + no carry out
2016 if (isNullConstant(N1))
2017 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2020 // If it cannot overflow, transform into an add.
2021 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2022 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2023 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2028 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2029 SDValue N0 = N->getOperand(0);
2030 SDValue N1 = N->getOperand(1);
2031 EVT VT = N0.getValueType();
2035 EVT CarryVT = N->getValueType(1);
2038 // If the flag result is dead, turn this into an ADD.
2039 if (!N->hasAnyUseOfValue(1))
2040 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2041 DAG.getUNDEF(CarryVT));
2043 // canonicalize constant to RHS.
2044 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2045 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2047 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2049 // fold (uaddo x, 0) -> x + no carry out
2050 if (isNullConstant(N1))
2051 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2053 // If it cannot overflow, transform into an add.
2054 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2055 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2056 DAG.getConstant(0, DL, CarryVT));
2061 SDValue DAGCombiner::visitADDE(SDNode *N) {
2062 SDValue N0 = N->getOperand(0);
2063 SDValue N1 = N->getOperand(1);
2064 SDValue CarryIn = N->getOperand(2);
2066 // canonicalize constant to RHS
2067 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2068 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2070 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2073 // fold (adde x, y, false) -> (addc x, y)
2074 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2075 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2080 // Since it may not be valid to emit a fold to zero for vector initializers
2081 // check if we can before folding.
2082 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2083 SelectionDAG &DAG, bool LegalOperations,
2086 return DAG.getConstant(0, DL, VT);
2087 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2088 return DAG.getConstant(0, DL, VT);
2092 SDValue DAGCombiner::visitSUB(SDNode *N) {
2093 SDValue N0 = N->getOperand(0);
2094 SDValue N1 = N->getOperand(1);
2095 EVT VT = N0.getValueType();
2099 if (VT.isVector()) {
2100 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2103 // fold (sub x, 0) -> x, vector edition
2104 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2108 // fold (sub x, x) -> 0
2109 // FIXME: Refactor this and xor and other similar operations together.
2111 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2112 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2113 DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2114 // fold (sub c1, c2) -> c1-c2
2115 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2119 if (SDValue NewSel = foldBinOpIntoSelect(N))
2122 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2124 // fold (sub x, c) -> (add x, -c)
2126 return DAG.getNode(ISD::ADD, DL, VT, N0,
2127 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2130 if (isNullConstantOrNullSplatConstant(N0)) {
2131 unsigned BitWidth = VT.getScalarSizeInBits();
2132 // Right-shifting everything out but the sign bit followed by negation is
2133 // the same as flipping arithmetic/logical shift type without the negation:
2134 // -(X >>u 31) -> (X >>s 31)
2135 // -(X >>s 31) -> (X >>u 31)
2136 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2137 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2138 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2139 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2140 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2141 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2145 // 0 - X --> 0 if the sub is NUW.
2146 if (N->getFlags()->hasNoUnsignedWrap())
2149 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2150 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2151 // N1 must be 0 because negating the minimum signed value is undefined.
2152 if (N->getFlags()->hasNoSignedWrap())
2155 // 0 - X --> X if X is 0 or the minimum signed value.
2160 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2161 if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2162 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2164 // fold A-(A-B) -> B
2165 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2166 return N1.getOperand(1);
2168 // fold (A+B)-A -> B
2169 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2170 return N0.getOperand(1);
2172 // fold (A+B)-B -> A
2173 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2174 return N0.getOperand(0);
2176 // fold C2-(A+C1) -> (C2-C1)-A
2177 if (N1.getOpcode() == ISD::ADD) {
2178 SDValue N11 = N1.getOperand(1);
2179 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2180 isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2181 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2182 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2186 // fold ((A+(B+or-C))-B) -> A+or-C
2187 if (N0.getOpcode() == ISD::ADD &&
2188 (N0.getOperand(1).getOpcode() == ISD::SUB ||
2189 N0.getOperand(1).getOpcode() == ISD::ADD) &&
2190 N0.getOperand(1).getOperand(0) == N1)
2191 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2192 N0.getOperand(1).getOperand(1));
2194 // fold ((A+(C+B))-B) -> A+C
2195 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2196 N0.getOperand(1).getOperand(1) == N1)
2197 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2198 N0.getOperand(1).getOperand(0));
2200 // fold ((A-(B-C))-C) -> A-B
2201 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2202 N0.getOperand(1).getOperand(1) == N1)
2203 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2204 N0.getOperand(1).getOperand(0));
2206 // If either operand of a sub is undef, the result is undef
2212 // If the relocation model supports it, consider symbol offsets.
2213 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2214 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2215 // fold (sub Sym, c) -> Sym-c
2216 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2217 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2219 (uint64_t)N1C->getSExtValue());
2220 // fold (sub Sym+c1, Sym+c2) -> c1-c2
2221 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2222 if (GA->getGlobal() == GB->getGlobal())
2223 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2227 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2228 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2229 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2230 if (TN->getVT() == MVT::i1) {
2231 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2232 DAG.getConstant(1, DL, VT));
2233 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2240 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2241 SDValue N0 = N->getOperand(0);
2242 SDValue N1 = N->getOperand(1);
2243 EVT VT = N0.getValueType();
2246 // If the flag result is dead, turn this into an SUB.
2247 if (!N->hasAnyUseOfValue(1))
2248 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2249 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2251 // fold (subc x, x) -> 0 + no borrow
2253 return CombineTo(N, DAG.getConstant(0, DL, VT),
2254 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2256 // fold (subc x, 0) -> x + no borrow
2257 if (isNullConstant(N1))
2258 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2260 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2261 if (isAllOnesConstant(N0))
2262 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2263 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2268 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2269 SDValue N0 = N->getOperand(0);
2270 SDValue N1 = N->getOperand(1);
2271 EVT VT = N0.getValueType();
2275 EVT CarryVT = N->getValueType(1);
2278 // If the flag result is dead, turn this into an SUB.
2279 if (!N->hasAnyUseOfValue(1))
2280 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2281 DAG.getUNDEF(CarryVT));
2283 // fold (usubo x, x) -> 0 + no borrow
2285 return CombineTo(N, DAG.getConstant(0, DL, VT),
2286 DAG.getConstant(0, DL, CarryVT));
2288 // fold (usubo x, 0) -> x + no borrow
2289 if (isNullConstant(N1))
2290 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2292 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2293 if (isAllOnesConstant(N0))
2294 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2295 DAG.getConstant(0, DL, CarryVT));
2300 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2301 SDValue N0 = N->getOperand(0);
2302 SDValue N1 = N->getOperand(1);
2303 SDValue CarryIn = N->getOperand(2);
2305 // fold (sube x, y, false) -> (subc x, y)
2306 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2307 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2312 SDValue DAGCombiner::visitMUL(SDNode *N) {
2313 SDValue N0 = N->getOperand(0);
2314 SDValue N1 = N->getOperand(1);
2315 EVT VT = N0.getValueType();
2317 // fold (mul x, undef) -> 0
2318 if (N0.isUndef() || N1.isUndef())
2319 return DAG.getConstant(0, SDLoc(N), VT);
2321 bool N0IsConst = false;
2322 bool N1IsConst = false;
2323 bool N1IsOpaqueConst = false;
2324 bool N0IsOpaqueConst = false;
2325 APInt ConstValue0, ConstValue1;
2327 if (VT.isVector()) {
2328 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2331 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2332 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2334 N0IsConst = isa<ConstantSDNode>(N0);
2336 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2337 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2339 N1IsConst = isa<ConstantSDNode>(N1);
2341 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2342 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2346 // fold (mul c1, c2) -> c1*c2
2347 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2348 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2349 N0.getNode(), N1.getNode());
2351 // canonicalize constant to RHS (vector doesn't have to splat)
2352 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2353 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2354 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2355 // fold (mul x, 0) -> 0
2356 if (N1IsConst && ConstValue1 == 0)
2358 // We require a splat of the entire scalar bit width for non-contiguous
2361 ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2362 // fold (mul x, 1) -> x
2363 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2366 if (SDValue NewSel = foldBinOpIntoSelect(N))
2369 // fold (mul x, -1) -> 0-x
2370 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2372 return DAG.getNode(ISD::SUB, DL, VT,
2373 DAG.getConstant(0, DL, VT), N0);
2375 // fold (mul x, (1 << c)) -> x << c
2376 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2379 return DAG.getNode(ISD::SHL, DL, VT, N0,
2380 DAG.getConstant(ConstValue1.logBase2(), DL,
2381 getShiftAmountTy(N0.getValueType())));
2383 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2384 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2386 unsigned Log2Val = (-ConstValue1).logBase2();
2388 // FIXME: If the input is something that is easily negated (e.g. a
2389 // single-use add), we should put the negate there.
2390 return DAG.getNode(ISD::SUB, DL, VT,
2391 DAG.getConstant(0, DL, VT),
2392 DAG.getNode(ISD::SHL, DL, VT, N0,
2393 DAG.getConstant(Log2Val, DL,
2394 getShiftAmountTy(N0.getValueType()))));
2397 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2398 if (N0.getOpcode() == ISD::SHL &&
2399 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2400 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2401 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2402 if (isConstantOrConstantVector(C3))
2403 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2406 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2409 SDValue Sh(nullptr, 0), Y(nullptr, 0);
2411 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2412 if (N0.getOpcode() == ISD::SHL &&
2413 isConstantOrConstantVector(N0.getOperand(1)) &&
2414 N0.getNode()->hasOneUse()) {
2416 } else if (N1.getOpcode() == ISD::SHL &&
2417 isConstantOrConstantVector(N1.getOperand(1)) &&
2418 N1.getNode()->hasOneUse()) {
2423 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2424 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2428 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2429 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2430 N0.getOpcode() == ISD::ADD &&
2431 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2432 isMulAddWithConstProfitable(N, N0, N1))
2433 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2434 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2435 N0.getOperand(0), N1),
2436 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2437 N0.getOperand(1), N1));
2440 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2446 /// Return true if divmod libcall is available.
2447 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2448 const TargetLowering &TLI) {
2450 EVT NodeType = Node->getValueType(0);
2451 if (!NodeType.isSimple())
2453 switch (NodeType.getSimpleVT().SimpleTy) {
2454 default: return false; // No libcall for vector types.
2455 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2456 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2457 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2458 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2459 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2462 return TLI.getLibcallName(LC) != nullptr;
2465 /// Issue divrem if both quotient and remainder are needed.
2466 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2467 if (Node->use_empty())
2468 return SDValue(); // This is a dead node, leave it alone.
2470 unsigned Opcode = Node->getOpcode();
2471 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2472 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2474 // DivMod lib calls can still work on non-legal types if using lib-calls.
2475 EVT VT = Node->getValueType(0);
2476 if (VT.isVector() || !VT.isInteger())
2479 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2482 // If DIVREM is going to get expanded into a libcall,
2483 // but there is no libcall available, then don't combine.
2484 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2485 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2488 // If div is legal, it's better to do the normal expansion
2489 unsigned OtherOpcode = 0;
2490 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2491 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2492 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2495 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2496 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2500 SDValue Op0 = Node->getOperand(0);
2501 SDValue Op1 = Node->getOperand(1);
2503 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2504 UE = Op0.getNode()->use_end(); UI != UE;) {
2505 SDNode *User = *UI++;
2506 if (User == Node || User->use_empty())
2508 // Convert the other matching node(s), too;
2509 // otherwise, the DIVREM may get target-legalized into something
2510 // target-specific that we won't be able to recognize.
2511 unsigned UserOpc = User->getOpcode();
2512 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2513 User->getOperand(0) == Op0 &&
2514 User->getOperand(1) == Op1) {
2516 if (UserOpc == OtherOpcode) {
2517 SDVTList VTs = DAG.getVTList(VT, VT);
2518 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2519 } else if (UserOpc == DivRemOpc) {
2520 combined = SDValue(User, 0);
2522 assert(UserOpc == Opcode);
2526 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2527 CombineTo(User, combined);
2528 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2529 CombineTo(User, combined.getValue(1));
2535 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2536 SDValue N0 = N->getOperand(0);
2537 SDValue N1 = N->getOperand(1);
2538 EVT VT = N->getValueType(0);
2541 if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2542 return DAG.getUNDEF(VT);
2547 return DAG.getConstant(0, DL, VT);
2552 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2553 SDValue N0 = N->getOperand(0);
2554 SDValue N1 = N->getOperand(1);
2555 EVT VT = N->getValueType(0);
2559 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2564 // fold (sdiv c1, c2) -> c1/c2
2565 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2566 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2567 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2568 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2569 // fold (sdiv X, 1) -> X
2570 if (N1C && N1C->isOne())
2572 // fold (sdiv X, -1) -> 0-X
2573 if (N1C && N1C->isAllOnesValue())
2574 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2576 if (SDValue V = simplifyDivRem(N, DAG))
2579 if (SDValue NewSel = foldBinOpIntoSelect(N))
2582 // If we know the sign bits of both operands are zero, strength reduce to a
2583 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2584 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2585 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2587 // fold (sdiv X, pow2) -> simple ops after legalize
2588 // FIXME: We check for the exact bit here because the generic lowering gives
2589 // better results in that case. The target-specific lowering should learn how
2590 // to handle exact sdivs efficiently.
2591 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2592 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2593 (N1C->getAPIntValue().isPowerOf2() ||
2594 (-N1C->getAPIntValue()).isPowerOf2())) {
2595 // Target-specific implementation of sdiv x, pow2.
2596 if (SDValue Res = BuildSDIVPow2(N))
2599 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2601 // Splat the sign bit into the register
2603 DAG.getNode(ISD::SRA, DL, VT, N0,
2604 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2605 getShiftAmountTy(N0.getValueType())));
2606 AddToWorklist(SGN.getNode());
2608 // Add (N0 < 0) ? abs2 - 1 : 0;
2610 DAG.getNode(ISD::SRL, DL, VT, SGN,
2611 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2612 getShiftAmountTy(SGN.getValueType())));
2613 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2614 AddToWorklist(SRL.getNode());
2615 AddToWorklist(ADD.getNode()); // Divide by pow2
2616 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2617 DAG.getConstant(lg2, DL,
2618 getShiftAmountTy(ADD.getValueType())));
2620 // If we're dividing by a positive value, we're done. Otherwise, we must
2621 // negate the result.
2622 if (N1C->getAPIntValue().isNonNegative())
2625 AddToWorklist(SRA.getNode());
2626 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2629 // If integer divide is expensive and we satisfy the requirements, emit an
2630 // alternate sequence. Targets may check function attributes for size/speed
2632 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2633 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2634 if (SDValue Op = BuildSDIV(N))
2637 // sdiv, srem -> sdivrem
2638 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2639 // true. Otherwise, we break the simplification logic in visitREM().
2640 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2641 if (SDValue DivRem = useDivRem(N))
2647 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2648 SDValue N0 = N->getOperand(0);
2649 SDValue N1 = N->getOperand(1);
2650 EVT VT = N->getValueType(0);
2654 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2659 // fold (udiv c1, c2) -> c1/c2
2660 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2661 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2663 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2667 if (SDValue V = simplifyDivRem(N, DAG))
2670 if (SDValue NewSel = foldBinOpIntoSelect(N))
2673 // fold (udiv x, (1 << c)) -> x >>u c
2674 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2675 DAG.isKnownToBeAPowerOfTwo(N1)) {
2676 SDValue LogBase2 = BuildLogBase2(N1, DL);
2677 AddToWorklist(LogBase2.getNode());
2679 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2680 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2681 AddToWorklist(Trunc.getNode());
2682 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2685 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2686 if (N1.getOpcode() == ISD::SHL) {
2687 SDValue N10 = N1.getOperand(0);
2688 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2689 DAG.isKnownToBeAPowerOfTwo(N10)) {
2690 SDValue LogBase2 = BuildLogBase2(N10, DL);
2691 AddToWorklist(LogBase2.getNode());
2693 EVT ADDVT = N1.getOperand(1).getValueType();
2694 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2695 AddToWorklist(Trunc.getNode());
2696 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2697 AddToWorklist(Add.getNode());
2698 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2702 // fold (udiv x, c) -> alternate
2703 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2704 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2705 if (SDValue Op = BuildUDIV(N))
2708 // sdiv, srem -> sdivrem
2709 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2710 // true. Otherwise, we break the simplification logic in visitREM().
2711 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2712 if (SDValue DivRem = useDivRem(N))
2718 // handles ISD::SREM and ISD::UREM
2719 SDValue DAGCombiner::visitREM(SDNode *N) {
2720 unsigned Opcode = N->getOpcode();
2721 SDValue N0 = N->getOperand(0);
2722 SDValue N1 = N->getOperand(1);
2723 EVT VT = N->getValueType(0);
2724 bool isSigned = (Opcode == ISD::SREM);
2727 // fold (rem c1, c2) -> c1%c2
2728 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2729 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2731 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2734 if (SDValue V = simplifyDivRem(N, DAG))
2737 if (SDValue NewSel = foldBinOpIntoSelect(N))
2741 // If we know the sign bits of both operands are zero, strength reduce to a
2742 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2743 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2744 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2746 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2747 if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2748 // fold (urem x, pow2) -> (and x, pow2-1)
2749 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2750 AddToWorklist(Add.getNode());
2751 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2753 if (N1.getOpcode() == ISD::SHL &&
2754 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2755 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2756 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2757 AddToWorklist(Add.getNode());
2758 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2762 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2764 // If X/C can be simplified by the division-by-constant logic, lower
2765 // X%C to the equivalent of X-X/C*C.
2766 // To avoid mangling nodes, this simplification requires that the combine()
2767 // call for the speculative DIV must not cause a DIVREM conversion. We guard
2768 // against this by skipping the simplification if isIntDivCheap(). When
2769 // div is not cheap, combine will not return a DIVREM. Regardless,
2770 // checking cheapness here makes sense since the simplification results in
2772 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2773 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2774 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2775 AddToWorklist(Div.getNode());
2776 SDValue OptimizedDiv = combine(Div.getNode());
2777 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2778 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2779 (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2780 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2781 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2782 AddToWorklist(Mul.getNode());
2787 // sdiv, srem -> sdivrem
2788 if (SDValue DivRem = useDivRem(N))
2789 return DivRem.getValue(1);
2794 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2795 SDValue N0 = N->getOperand(0);
2796 SDValue N1 = N->getOperand(1);
2797 EVT VT = N->getValueType(0);
2800 // fold (mulhs x, 0) -> 0
2801 if (isNullConstant(N1))
2803 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2804 if (isOneConstant(N1)) {
2806 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2807 DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2808 getShiftAmountTy(N0.getValueType())));
2810 // fold (mulhs x, undef) -> 0
2811 if (N0.isUndef() || N1.isUndef())
2812 return DAG.getConstant(0, SDLoc(N), VT);
2814 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2816 if (VT.isSimple() && !VT.isVector()) {
2817 MVT Simple = VT.getSimpleVT();
2818 unsigned SimpleSize = Simple.getSizeInBits();
2819 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2820 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2821 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2822 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2823 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2824 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2825 DAG.getConstant(SimpleSize, DL,
2826 getShiftAmountTy(N1.getValueType())));
2827 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2834 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2835 SDValue N0 = N->getOperand(0);
2836 SDValue N1 = N->getOperand(1);
2837 EVT VT = N->getValueType(0);
2840 // fold (mulhu x, 0) -> 0
2841 if (isNullConstant(N1))
2843 // fold (mulhu x, 1) -> 0
2844 if (isOneConstant(N1))
2845 return DAG.getConstant(0, DL, N0.getValueType());
2846 // fold (mulhu x, undef) -> 0
2847 if (N0.isUndef() || N1.isUndef())
2848 return DAG.getConstant(0, DL, VT);
2850 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2852 if (VT.isSimple() && !VT.isVector()) {
2853 MVT Simple = VT.getSimpleVT();
2854 unsigned SimpleSize = Simple.getSizeInBits();
2855 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2856 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2857 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2858 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2859 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2860 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2861 DAG.getConstant(SimpleSize, DL,
2862 getShiftAmountTy(N1.getValueType())));
2863 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2870 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2871 /// give the opcodes for the two computations that are being performed. Return
2872 /// true if a simplification was made.
2873 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2875 // If the high half is not needed, just compute the low half.
2876 bool HiExists = N->hasAnyUseOfValue(1);
2878 (!LegalOperations ||
2879 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2880 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2881 return CombineTo(N, Res, Res);
2884 // If the low half is not needed, just compute the high half.
2885 bool LoExists = N->hasAnyUseOfValue(0);
2887 (!LegalOperations ||
2888 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2889 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2890 return CombineTo(N, Res, Res);
2893 // If both halves are used, return as it is.
2894 if (LoExists && HiExists)
2897 // If the two computed results can be simplified separately, separate them.
2899 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2900 AddToWorklist(Lo.getNode());
2901 SDValue LoOpt = combine(Lo.getNode());
2902 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2903 (!LegalOperations ||
2904 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2905 return CombineTo(N, LoOpt, LoOpt);
2909 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2910 AddToWorklist(Hi.getNode());
2911 SDValue HiOpt = combine(Hi.getNode());
2912 if (HiOpt.getNode() && HiOpt != Hi &&
2913 (!LegalOperations ||
2914 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2915 return CombineTo(N, HiOpt, HiOpt);
2921 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2922 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2925 EVT VT = N->getValueType(0);
2928 // If the type is twice as wide is legal, transform the mulhu to a wider
2929 // multiply plus a shift.
2930 if (VT.isSimple() && !VT.isVector()) {
2931 MVT Simple = VT.getSimpleVT();
2932 unsigned SimpleSize = Simple.getSizeInBits();
2933 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2934 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2935 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2936 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2937 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2938 // Compute the high part as N1.
2939 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2940 DAG.getConstant(SimpleSize, DL,
2941 getShiftAmountTy(Lo.getValueType())));
2942 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2943 // Compute the low part as N0.
2944 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2945 return CombineTo(N, Lo, Hi);
2952 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2953 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2956 EVT VT = N->getValueType(0);
2959 // If the type is twice as wide is legal, transform the mulhu to a wider
2960 // multiply plus a shift.
2961 if (VT.isSimple() && !VT.isVector()) {
2962 MVT Simple = VT.getSimpleVT();
2963 unsigned SimpleSize = Simple.getSizeInBits();
2964 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2965 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2966 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2967 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2968 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2969 // Compute the high part as N1.
2970 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2971 DAG.getConstant(SimpleSize, DL,
2972 getShiftAmountTy(Lo.getValueType())));
2973 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2974 // Compute the low part as N0.
2975 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2976 return CombineTo(N, Lo, Hi);
2983 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2984 // (smulo x, 2) -> (saddo x, x)
2985 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2986 if (C2->getAPIntValue() == 2)
2987 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2988 N->getOperand(0), N->getOperand(0));
2993 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2994 // (umulo x, 2) -> (uaddo x, x)
2995 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2996 if (C2->getAPIntValue() == 2)
2997 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2998 N->getOperand(0), N->getOperand(0));
3003 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3004 SDValue N0 = N->getOperand(0);
3005 SDValue N1 = N->getOperand(1);
3006 EVT VT = N0.getValueType();
3010 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3013 // fold (add c1, c2) -> c1+c2
3014 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3015 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3017 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3019 // canonicalize constant to RHS
3020 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3021 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3022 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3027 /// If this is a binary operator with two operands of the same opcode, try to
3029 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3030 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3031 EVT VT = N0.getValueType();
3032 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3034 // Bail early if none of these transforms apply.
3035 if (N0.getNumOperands() == 0) return SDValue();
3037 // For each of OP in AND/OR/XOR:
3038 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3039 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3040 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3041 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3042 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3044 // do not sink logical op inside of a vector extend, since it may combine
3046 EVT Op0VT = N0.getOperand(0).getValueType();
3047 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3048 N0.getOpcode() == ISD::SIGN_EXTEND ||
3049 N0.getOpcode() == ISD::BSWAP ||
3050 // Avoid infinite looping with PromoteIntBinOp.
3051 (N0.getOpcode() == ISD::ANY_EXTEND &&
3052 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3053 (N0.getOpcode() == ISD::TRUNCATE &&
3054 (!TLI.isZExtFree(VT, Op0VT) ||
3055 !TLI.isTruncateFree(Op0VT, VT)) &&
3056 TLI.isTypeLegal(Op0VT))) &&
3058 Op0VT == N1.getOperand(0).getValueType() &&
3059 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3060 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3061 N0.getOperand(0).getValueType(),
3062 N0.getOperand(0), N1.getOperand(0));
3063 AddToWorklist(ORNode.getNode());
3064 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3067 // For each of OP in SHL/SRL/SRA/AND...
3068 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3069 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
3070 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3071 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3072 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3073 N0.getOperand(1) == N1.getOperand(1)) {
3074 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3075 N0.getOperand(0).getValueType(),
3076 N0.getOperand(0), N1.getOperand(0));
3077 AddToWorklist(ORNode.getNode());
3078 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3079 ORNode, N0.getOperand(1));
3082 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3083 // Only perform this optimization up until type legalization, before
3084 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3085 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3086 // we don't want to undo this promotion.
3087 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3089 if ((N0.getOpcode() == ISD::BITCAST ||
3090 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3091 Level <= AfterLegalizeTypes) {
3092 SDValue In0 = N0.getOperand(0);
3093 SDValue In1 = N1.getOperand(0);
3094 EVT In0Ty = In0.getValueType();
3095 EVT In1Ty = In1.getValueType();
3097 // If both incoming values are integers, and the original types are the
3099 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3100 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3101 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3102 AddToWorklist(Op.getNode());
3107 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3108 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3109 // If both shuffles use the same mask, and both shuffle within a single
3110 // vector, then it is worthwhile to move the swizzle after the operation.
3111 // The type-legalizer generates this pattern when loading illegal
3112 // vector types from memory. In many cases this allows additional shuffle
3114 // There are other cases where moving the shuffle after the xor/and/or
3115 // is profitable even if shuffles don't perform a swizzle.
3116 // If both shuffles use the same mask, and both shuffles have the same first
3117 // or second operand, then it might still be profitable to move the shuffle
3118 // after the xor/and/or operation.
3119 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3120 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3121 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3123 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3124 "Inputs to shuffles are not the same type");
3126 // Check that both shuffles use the same mask. The masks are known to be of
3127 // the same length because the result vector type is the same.
3128 // Check also that shuffles have only one use to avoid introducing extra
3130 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3131 SVN0->getMask().equals(SVN1->getMask())) {
3132 SDValue ShOp = N0->getOperand(1);
3134 // Don't try to fold this node if it requires introducing a
3135 // build vector of all zeros that might be illegal at this stage.
3136 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3138 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3143 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3144 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
3145 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3146 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3147 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3148 N0->getOperand(0), N1->getOperand(0));
3149 AddToWorklist(NewNode.getNode());
3150 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3154 // Don't try to fold this node if it requires introducing a
3155 // build vector of all zeros that might be illegal at this stage.
3156 ShOp = N0->getOperand(0);
3157 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3159 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3164 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3165 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
3166 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3167 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3168 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3169 N0->getOperand(1), N1->getOperand(1));
3170 AddToWorklist(NewNode.getNode());
3171 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3180 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3181 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3183 SDValue LL, LR, RL, RR, N0CC, N1CC;
3184 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3185 !isSetCCEquivalent(N1, RL, RR, N1CC))
3188 assert(N0.getValueType() == N1.getValueType() &&
3189 "Unexpected operand types for bitwise logic op");
3190 assert(LL.getValueType() == LR.getValueType() &&
3191 RL.getValueType() == RR.getValueType() &&
3192 "Unexpected operand types for setcc");
3194 // If we're here post-legalization or the logic op type is not i1, the logic
3195 // op type must match a setcc result type. Also, all folds require new
3196 // operations on the left and right operands, so those types must match.
3197 EVT VT = N0.getValueType();
3198 EVT OpVT = LL.getValueType();
3199 if (LegalOperations || VT != MVT::i1)
3200 if (VT != getSetCCResultType(OpVT))
3202 if (OpVT != RL.getValueType())
3205 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3206 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3207 bool IsInteger = OpVT.isInteger();
3208 if (LR == RR && CC0 == CC1 && IsInteger) {
3209 bool IsZero = isNullConstantOrNullSplatConstant(LR);
3210 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3213 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3214 // All sign bits clear?
3215 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3217 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3218 // Any sign bits set?
3219 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3221 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
3222 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3223 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
3224 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
3225 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3226 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3227 AddToWorklist(Or.getNode());
3228 return DAG.getSetCC(DL, VT, Or, LR, CC1);
3232 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3233 // All sign bits set?
3234 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3236 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3237 // Any sign bits clear?
3238 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3240 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3241 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
3242 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3243 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
3244 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3245 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3246 AddToWorklist(And.getNode());
3247 return DAG.getSetCC(DL, VT, And, LR, CC1);
3251 // TODO: What is the 'or' equivalent of this fold?
3252 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3253 if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3254 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3255 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3256 SDValue One = DAG.getConstant(1, DL, OpVT);
3257 SDValue Two = DAG.getConstant(2, DL, OpVT);
3258 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3259 AddToWorklist(Add.getNode());
3260 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3263 // Try more general transforms if the predicates match and the only user of
3264 // the compares is the 'and' or 'or'.
3265 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3266 N0.hasOneUse() && N1.hasOneUse()) {
3267 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3268 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3269 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3270 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3271 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3272 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3273 SDValue Zero = DAG.getConstant(0, DL, OpVT);
3274 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3278 // Canonicalize equivalent operands to LL == RL.
3279 if (LL == RR && LR == RL) {
3280 CC1 = ISD::getSetCCSwappedOperands(CC1);
3284 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3285 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3286 if (LL == RL && LR == RR) {
3287 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3288 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3289 if (NewCC != ISD::SETCC_INVALID &&
3290 (!LegalOperations ||
3291 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3292 TLI.isOperationLegal(ISD::SETCC, OpVT))))
3293 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3299 /// This contains all DAGCombine rules which reduce two values combined by
3300 /// an And operation to a single value. This makes them reusable in the context
3301 /// of visitSELECT(). Rules involving constants are not included as
3302 /// visitSELECT() already handles those cases.
3303 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3304 EVT VT = N1.getValueType();
3307 // fold (and x, undef) -> 0
3308 if (N0.isUndef() || N1.isUndef())
3309 return DAG.getConstant(0, DL, VT);
3311 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3314 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3315 VT.getSizeInBits() <= 64) {
3316 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3317 APInt ADDC = ADDI->getAPIntValue();
3318 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3319 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3320 // immediate for an add, but it is legal if its top c2 bits are set,
3321 // transform the ADD so the immediate doesn't need to be materialized
3323 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3324 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3325 SRLI->getZExtValue());
3326 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3328 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3331 DAG.getNode(ISD::ADD, DL0, VT,
3332 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3333 CombineTo(N0.getNode(), NewAdd);
3334 // Return N so it doesn't get rechecked!
3335 return SDValue(N, 0);
3343 // Reduce bit extract of low half of an integer to the narrower type.
3344 // (and (srl i64:x, K), KMask) ->
3345 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3346 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3347 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3348 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3349 unsigned Size = VT.getSizeInBits();
3350 const APInt &AndMask = CAnd->getAPIntValue();
3351 unsigned ShiftBits = CShift->getZExtValue();
3353 // Bail out, this node will probably disappear anyway.
3357 unsigned MaskBits = AndMask.countTrailingOnes();
3358 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3360 if (AndMask.isMask() &&
3361 // Required bits must not span the two halves of the integer and
3362 // must fit in the half size type.
3363 (ShiftBits + MaskBits <= Size / 2) &&
3364 TLI.isNarrowingProfitable(VT, HalfVT) &&
3365 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3366 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3367 TLI.isTruncateFree(VT, HalfVT) &&
3368 TLI.isZExtFree(HalfVT, VT)) {
3369 // The isNarrowingProfitable is to avoid regressions on PPC and
3370 // AArch64 which match a few 64-bit bit insert / bit extract patterns
3371 // on downstream users of this. Those patterns could probably be
3372 // extended to handle extensions mixed in.
3375 assert(MaskBits <= Size);
3377 // Extracting the highest bit of the low half.
3378 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3379 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3382 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3383 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3384 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3385 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3386 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3395 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3396 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3398 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3400 if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3403 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3404 LoadedVT = LoadN->getMemoryVT();
3406 if (ExtVT == LoadedVT &&
3407 (!LegalOperations ||
3408 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3409 // ZEXTLOAD will match without needing to change the size of the value being
3415 // Do not change the width of a volatile load.
3416 if (LoadN->isVolatile())
3419 // Do not generate loads of non-round integer types since these can
3420 // be expensive (and would be wrong if the type is not byte sized).
3421 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3424 if (LegalOperations &&
3425 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3428 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3435 SDValue DAGCombiner::visitAND(SDNode *N) {
3436 SDValue N0 = N->getOperand(0);
3437 SDValue N1 = N->getOperand(1);
3438 EVT VT = N1.getValueType();
3445 if (VT.isVector()) {
3446 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3449 // fold (and x, 0) -> 0, vector edition
3450 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3451 // do not return N0, because undef node may exist in N0
3452 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3453 SDLoc(N), N0.getValueType());
3454 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3455 // do not return N1, because undef node may exist in N1
3456 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3457 SDLoc(N), N1.getValueType());
3459 // fold (and x, -1) -> x, vector edition
3460 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3462 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3466 // fold (and c1, c2) -> c1&c2
3467 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3468 ConstantSDNode *N1C = isConstOrConstSplat(N1);
3469 if (N0C && N1C && !N1C->isOpaque())
3470 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3471 // canonicalize constant to RHS
3472 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3473 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3474 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3475 // fold (and x, -1) -> x
3476 if (isAllOnesConstant(N1))
3478 // if (and x, c) is known to be zero, return 0
3479 unsigned BitWidth = VT.getScalarSizeInBits();
3480 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3481 APInt::getAllOnesValue(BitWidth)))
3482 return DAG.getConstant(0, SDLoc(N), VT);
3484 if (SDValue NewSel = foldBinOpIntoSelect(N))
3488 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3490 // fold (and (or x, C), D) -> D if (C & D) == D
3491 if (N1C && N0.getOpcode() == ISD::OR)
3492 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3493 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3495 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3496 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3497 SDValue N0Op0 = N0.getOperand(0);
3498 APInt Mask = ~N1C->getAPIntValue();
3499 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3500 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3501 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3502 N0.getValueType(), N0Op0);
3504 // Replace uses of the AND with uses of the Zero extend node.
3507 // We actually want to replace all uses of the any_extend with the
3508 // zero_extend, to avoid duplicating things. This will later cause this
3509 // AND to be folded.
3510 CombineTo(N0.getNode(), Zext);
3511 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3514 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3515 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3516 // already be zero by virtue of the width of the base type of the load.
3518 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3520 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3521 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3522 N0.getOperand(0).getOpcode() == ISD::LOAD &&
3523 N0.getOperand(0).getResNo() == 0) ||
3524 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3525 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3526 N0 : N0.getOperand(0) );
3528 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3529 // This can be a pure constant or a vector splat, in which case we treat the
3530 // vector as a scalar and use the splat value.
3531 APInt Constant = APInt::getNullValue(1);
3532 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3533 Constant = C->getAPIntValue();
3534 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3535 APInt SplatValue, SplatUndef;
3536 unsigned SplatBitSize;
3538 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3539 SplatBitSize, HasAnyUndefs);
3541 // Undef bits can contribute to a possible optimisation if set, so
3543 SplatValue |= SplatUndef;
3545 // The splat value may be something like "0x00FFFFFF", which means 0 for
3546 // the first vector value and FF for the rest, repeating. We need a mask
3547 // that will apply equally to all members of the vector, so AND all the
3548 // lanes of the constant together.
3549 EVT VT = Vector->getValueType(0);
3550 unsigned BitWidth = VT.getScalarSizeInBits();
3552 // If the splat value has been compressed to a bitlength lower
3553 // than the size of the vector lane, we need to re-expand it to
3555 if (BitWidth > SplatBitSize)
3556 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3557 SplatBitSize < BitWidth;
3558 SplatBitSize = SplatBitSize * 2)
3559 SplatValue |= SplatValue.shl(SplatBitSize);
3561 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3562 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3563 if (SplatBitSize % BitWidth == 0) {
3564 Constant = APInt::getAllOnesValue(BitWidth);
3565 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3566 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3571 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3572 // actually legal and isn't going to get expanded, else this is a false
3574 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3575 Load->getValueType(0),
3576 Load->getMemoryVT());
3578 // Resize the constant to the same size as the original memory access before
3579 // extension. If it is still the AllOnesValue then this AND is completely
3581 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3584 switch (Load->getExtensionType()) {
3585 default: B = false; break;
3586 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3588 case ISD::NON_EXTLOAD: B = true; break;
3591 if (B && Constant.isAllOnesValue()) {
3592 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3593 // preserve semantics once we get rid of the AND.
3594 SDValue NewLoad(Load, 0);
3596 // Fold the AND away. NewLoad may get replaced immediately.
3597 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3599 if (Load->getExtensionType() == ISD::EXTLOAD) {
3600 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3601 Load->getValueType(0), SDLoc(Load),
3602 Load->getChain(), Load->getBasePtr(),
3603 Load->getOffset(), Load->getMemoryVT(),
3604 Load->getMemOperand());
3605 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3606 if (Load->getNumValues() == 3) {
3607 // PRE/POST_INC loads have 3 values.
3608 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3609 NewLoad.getValue(2) };
3610 CombineTo(Load, To, 3, true);
3612 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3616 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3620 // fold (and (load x), 255) -> (zextload x, i8)
3621 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3622 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3623 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3624 (N0.getOpcode() == ISD::ANY_EXTEND &&
3625 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3626 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3627 LoadSDNode *LN0 = HasAnyExt
3628 ? cast<LoadSDNode>(N0.getOperand(0))
3629 : cast<LoadSDNode>(N0);
3630 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3631 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3632 auto NarrowLoad = false;
3633 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3634 EVT ExtVT, LoadedVT;
3635 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3639 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3640 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3641 LN0->getMemOperand());
3643 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3644 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3646 EVT PtrType = LN0->getOperand(1).getValueType();
3648 unsigned Alignment = LN0->getAlignment();
3649 SDValue NewPtr = LN0->getBasePtr();
3651 // For big endian targets, we need to add an offset to the pointer
3652 // to load the correct bytes. For little endian systems, we merely
3653 // need to read fewer bytes from the same pointer.
3654 if (DAG.getDataLayout().isBigEndian()) {
3655 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3656 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3657 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3659 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3660 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3661 Alignment = MinAlign(Alignment, PtrOff);
3664 AddToWorklist(NewPtr.getNode());
3666 SDValue Load = DAG.getExtLoad(
3667 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3668 LN0->getPointerInfo(), ExtVT, Alignment,
3669 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3671 CombineTo(LN0, Load, Load.getValue(1));
3672 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3678 if (SDValue Combined = visitANDLike(N0, N1, N))
3681 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3682 if (N0.getOpcode() == N1.getOpcode())
3683 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3686 // Masking the negated extension of a boolean is just the zero-extended
3688 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3689 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3691 // Note: the SimplifyDemandedBits fold below can make an information-losing
3692 // transform, and then we have no way to find this better fold.
3693 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3694 ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3695 SDValue SubRHS = N0.getOperand(1);
3696 if (SubLHS && SubLHS->isNullValue()) {
3697 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3698 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3700 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3701 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3702 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3706 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3707 // fold (and (sra)) -> (and (srl)) when possible.
3708 if (SimplifyDemandedBits(SDValue(N, 0)))
3709 return SDValue(N, 0);
3711 // fold (zext_inreg (extload x)) -> (zextload x)
3712 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3713 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3714 EVT MemVT = LN0->getMemoryVT();
3715 // If we zero all the possible extended bits, then we can turn this into
3716 // a zextload if we are running before legalize or the operation is legal.
3717 unsigned BitWidth = N1.getScalarValueSizeInBits();
3718 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3719 BitWidth - MemVT.getScalarSizeInBits())) &&
3720 ((!LegalOperations && !LN0->isVolatile()) ||
3721 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3722 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3723 LN0->getChain(), LN0->getBasePtr(),
3724 MemVT, LN0->getMemOperand());
3726 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3727 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3730 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3731 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3733 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3734 EVT MemVT = LN0->getMemoryVT();
3735 // If we zero all the possible extended bits, then we can turn this into
3736 // a zextload if we are running before legalize or the operation is legal.
3737 unsigned BitWidth = N1.getScalarValueSizeInBits();
3738 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3739 BitWidth - MemVT.getScalarSizeInBits())) &&
3740 ((!LegalOperations && !LN0->isVolatile()) ||
3741 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3742 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3743 LN0->getChain(), LN0->getBasePtr(),
3744 MemVT, LN0->getMemOperand());
3746 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3747 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3750 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3751 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3752 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3753 N0.getOperand(1), false))
3760 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3761 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3762 bool DemandHighBits) {
3763 if (!LegalOperations)
3766 EVT VT = N->getValueType(0);
3767 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3769 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3772 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3773 bool LookPassAnd0 = false;
3774 bool LookPassAnd1 = false;
3775 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3777 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3779 if (N0.getOpcode() == ISD::AND) {
3780 if (!N0.getNode()->hasOneUse())
3782 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3783 if (!N01C || N01C->getZExtValue() != 0xFF00)
3785 N0 = N0.getOperand(0);
3786 LookPassAnd0 = true;
3789 if (N1.getOpcode() == ISD::AND) {
3790 if (!N1.getNode()->hasOneUse())
3792 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3793 if (!N11C || N11C->getZExtValue() != 0xFF)
3795 N1 = N1.getOperand(0);
3796 LookPassAnd1 = true;
3799 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3801 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3803 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3806 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3807 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3810 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3813 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3814 SDValue N00 = N0->getOperand(0);
3815 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3816 if (!N00.getNode()->hasOneUse())
3818 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3819 if (!N001C || N001C->getZExtValue() != 0xFF)
3821 N00 = N00.getOperand(0);
3822 LookPassAnd0 = true;
3825 SDValue N10 = N1->getOperand(0);
3826 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3827 if (!N10.getNode()->hasOneUse())
3829 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3830 if (!N101C || N101C->getZExtValue() != 0xFF00)
3832 N10 = N10.getOperand(0);
3833 LookPassAnd1 = true;
3839 // Make sure everything beyond the low halfword gets set to zero since the SRL
3840 // 16 will clear the top bits.
3841 unsigned OpSizeInBits = VT.getSizeInBits();
3842 if (DemandHighBits && OpSizeInBits > 16) {
3843 // If the left-shift isn't masked out then the only way this is a bswap is
3844 // if all bits beyond the low 8 are 0. In that case the entire pattern
3845 // reduces to a left shift anyway: leave it for other parts of the combiner.
3849 // However, if the right shift isn't masked out then it might be because
3850 // it's not needed. See if we can spot that too.
3851 if (!LookPassAnd1 &&
3852 !DAG.MaskedValueIsZero(
3853 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3857 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3858 if (OpSizeInBits > 16) {
3860 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3861 DAG.getConstant(OpSizeInBits - 16, DL,
3862 getShiftAmountTy(VT)));
3867 /// Return true if the specified node is an element that makes up a 32-bit
3868 /// packed halfword byteswap.
3869 /// ((x & 0x000000ff) << 8) |
3870 /// ((x & 0x0000ff00) >> 8) |
3871 /// ((x & 0x00ff0000) << 8) |
3872 /// ((x & 0xff000000) >> 8)
3873 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3874 if (!N.getNode()->hasOneUse())
3877 unsigned Opc = N.getOpcode();
3878 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3881 SDValue N0 = N.getOperand(0);
3882 unsigned Opc0 = N0.getOpcode();
3884 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3888 unsigned MaskByteOffset;
3889 switch (N1C->getZExtValue()) {
3892 case 0xFF: MaskByteOffset = 0; break;
3893 case 0xFF00: MaskByteOffset = 1; break;
3894 case 0xFF0000: MaskByteOffset = 2; break;
3895 case 0xFF000000: MaskByteOffset = 3; break;
3898 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3899 if (Opc == ISD::AND) {
3900 if (MaskByteOffset == 0 || MaskByteOffset == 2) {
3902 // (x >> 8) & 0xff0000
3903 if (Opc0 != ISD::SRL)
3905 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3906 if (!C || C->getZExtValue() != 8)
3909 // (x << 8) & 0xff00
3910 // (x << 8) & 0xff000000
3911 if (Opc0 != ISD::SHL)
3913 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3914 if (!C || C->getZExtValue() != 8)
3917 } else if (Opc == ISD::SHL) {
3919 // (x & 0xff0000) << 8
3920 if (MaskByteOffset != 0 && MaskByteOffset != 2)
3922 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3923 if (!C || C->getZExtValue() != 8)
3925 } else { // Opc == ISD::SRL
3926 // (x & 0xff00) >> 8
3927 // (x & 0xff000000) >> 8
3928 if (MaskByteOffset != 1 && MaskByteOffset != 3)
3930 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3931 if (!C || C->getZExtValue() != 8)
3935 if (Parts[MaskByteOffset])
3938 Parts[MaskByteOffset] = N0.getOperand(0).getNode();
3942 /// Match a 32-bit packed halfword bswap. That is
3943 /// ((x & 0x000000ff) << 8) |
3944 /// ((x & 0x0000ff00) >> 8) |
3945 /// ((x & 0x00ff0000) << 8) |
3946 /// ((x & 0xff000000) >> 8)
3947 /// => (rotl (bswap x), 16)
3948 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3949 if (!LegalOperations)
3952 EVT VT = N->getValueType(0);
3955 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3959 // (or (or (and), (and)), (or (and), (and)))
3960 // (or (or (or (and), (and)), (and)), (and))
3961 if (N0.getOpcode() != ISD::OR)
3963 SDValue N00 = N0.getOperand(0);
3964 SDValue N01 = N0.getOperand(1);
3965 SDNode *Parts[4] = {};
3967 if (N1.getOpcode() == ISD::OR &&
3968 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3969 // (or (or (and), (and)), (or (and), (and)))
3970 SDValue N000 = N00.getOperand(0);
3971 if (!isBSwapHWordElement(N000, Parts))
3974 SDValue N001 = N00.getOperand(1);
3975 if (!isBSwapHWordElement(N001, Parts))
3977 SDValue N010 = N01.getOperand(0);
3978 if (!isBSwapHWordElement(N010, Parts))
3980 SDValue N011 = N01.getOperand(1);
3981 if (!isBSwapHWordElement(N011, Parts))
3984 // (or (or (or (and), (and)), (and)), (and))
3985 if (!isBSwapHWordElement(N1, Parts))
3987 if (!isBSwapHWordElement(N01, Parts))
3989 if (N00.getOpcode() != ISD::OR)
3991 SDValue N000 = N00.getOperand(0);
3992 if (!isBSwapHWordElement(N000, Parts))
3994 SDValue N001 = N00.getOperand(1);
3995 if (!isBSwapHWordElement(N001, Parts))
3999 // Make sure the parts are all coming from the same node.
4000 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4004 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4005 SDValue(Parts[0], 0));
4007 // Result of the bswap should be rotated by 16. If it's not legal, then
4008 // do (x << 16) | (x >> 16).
4009 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4010 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4011 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4012 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4013 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4014 return DAG.getNode(ISD::OR, DL, VT,
4015 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4016 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4019 /// This contains all DAGCombine rules which reduce two values combined by
4020 /// an Or operation to a single value \see visitANDLike().
4021 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4022 EVT VT = N1.getValueType();
4025 // fold (or x, undef) -> -1
4026 if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4027 return DAG.getAllOnesConstant(DL, VT);
4029 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4032 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
4033 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4034 // Don't increase # computations.
4035 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4036 // We can only do this xform if we know that bits from X that are set in C2
4037 // but not in C1 are already zero. Likewise for Y.
4038 if (const ConstantSDNode *N0O1C =
4039 getAsNonOpaqueConstant(N0.getOperand(1))) {
4040 if (const ConstantSDNode *N1O1C =
4041 getAsNonOpaqueConstant(N1.getOperand(1))) {
4042 // We can only do this xform if we know that bits from X that are set in
4043 // C2 but not in C1 are already zero. Likewise for Y.
4044 const APInt &LHSMask = N0O1C->getAPIntValue();
4045 const APInt &RHSMask = N1O1C->getAPIntValue();
4047 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4048 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4049 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4050 N0.getOperand(0), N1.getOperand(0));
4051 return DAG.getNode(ISD::AND, DL, VT, X,
4052 DAG.getConstant(LHSMask | RHSMask, DL, VT));
4058 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4059 if (N0.getOpcode() == ISD::AND &&
4060 N1.getOpcode() == ISD::AND &&
4061 N0.getOperand(0) == N1.getOperand(0) &&
4062 // Don't increase # computations.
4063 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4064 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4065 N0.getOperand(1), N1.getOperand(1));
4066 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4072 SDValue DAGCombiner::visitOR(SDNode *N) {
4073 SDValue N0 = N->getOperand(0);
4074 SDValue N1 = N->getOperand(1);
4075 EVT VT = N1.getValueType();
4082 if (VT.isVector()) {
4083 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4086 // fold (or x, 0) -> x, vector edition
4087 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4089 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4092 // fold (or x, -1) -> -1, vector edition
4093 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4094 // do not return N0, because undef node may exist in N0
4095 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4096 if (ISD::isBuildVectorAllOnes(N1.getNode()))
4097 // do not return N1, because undef node may exist in N1
4098 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4100 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4101 // Do this only if the resulting shuffle is legal.
4102 if (isa<ShuffleVectorSDNode>(N0) &&
4103 isa<ShuffleVectorSDNode>(N1) &&
4104 // Avoid folding a node with illegal type.
4105 TLI.isTypeLegal(VT)) {
4106 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4107 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4108 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4109 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4110 // Ensure both shuffles have a zero input.
4111 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4112 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4113 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4114 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4115 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4116 bool CanFold = true;
4117 int NumElts = VT.getVectorNumElements();
4118 SmallVector<int, 4> Mask(NumElts);
4120 for (int i = 0; i != NumElts; ++i) {
4121 int M0 = SV0->getMaskElt(i);
4122 int M1 = SV1->getMaskElt(i);
4124 // Determine if either index is pointing to a zero vector.
4125 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4126 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4128 // If one element is zero and the otherside is undef, keep undef.
4129 // This also handles the case that both are undef.
4130 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4135 // Make sure only one of the elements is zero.
4136 if (M0Zero == M1Zero) {
4141 assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4143 // We have a zero and non-zero element. If the non-zero came from
4144 // SV0 make the index a LHS index. If it came from SV1, make it
4145 // a RHS index. We need to mod by NumElts because we don't care
4146 // which operand it came from in the original shuffles.
4147 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4151 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4152 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4154 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4156 std::swap(NewLHS, NewRHS);
4157 ShuffleVectorSDNode::commuteMask(Mask);
4158 LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4162 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4168 // fold (or c1, c2) -> c1|c2
4169 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4170 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4171 if (N0C && N1C && !N1C->isOpaque())
4172 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4173 // canonicalize constant to RHS
4174 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4175 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4176 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4177 // fold (or x, 0) -> x
4178 if (isNullConstant(N1))
4180 // fold (or x, -1) -> -1
4181 if (isAllOnesConstant(N1))
4184 if (SDValue NewSel = foldBinOpIntoSelect(N))
4187 // fold (or x, c) -> c iff (x & ~c) == 0
4188 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4191 if (SDValue Combined = visitORLike(N0, N1, N))
4194 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4195 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4197 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4201 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4204 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4205 // iff (c1 & c2) != 0.
4206 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4207 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4208 if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4210 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4212 ISD::AND, SDLoc(N), VT,
4213 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4219 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
4220 if (N0.getOpcode() == N1.getOpcode())
4221 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4224 // See if this is some rotate idiom.
4225 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4226 return SDValue(Rot, 0);
4228 if (SDValue Load = MatchLoadCombine(N))
4231 // Simplify the operands using demanded-bits information.
4232 if (SimplifyDemandedBits(SDValue(N, 0)))
4233 return SDValue(N, 0);
4238 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4239 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4240 if (Op.getOpcode() == ISD::AND) {
4241 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4242 Mask = Op.getOperand(1);
4243 Op = Op.getOperand(0);
4249 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4257 // Return true if we can prove that, whenever Neg and Pos are both in the
4258 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
4259 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4261 // (or (shift1 X, Neg), (shift2 X, Pos))
4263 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4264 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
4265 // to consider shift amounts with defined behavior.
4266 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4267 // If EltSize is a power of 2 then:
4269 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4270 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4272 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4273 // for the stronger condition:
4275 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
4277 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4278 // we can just replace Neg with Neg' for the rest of the function.
4280 // In other cases we check for the even stronger condition:
4282 // Neg == EltSize - Pos [B]
4284 // for all Neg and Pos. Note that the (or ...) then invokes undefined
4285 // behavior if Pos == 0 (and consequently Neg == EltSize).
4287 // We could actually use [A] whenever EltSize is a power of 2, but the
4288 // only extra cases that it would match are those uninteresting ones
4289 // where Neg and Pos are never in range at the same time. E.g. for
4290 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4291 // as well as (sub 32, Pos), but:
4293 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4295 // always invokes undefined behavior for 32-bit X.
4297 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4298 unsigned MaskLoBits = 0;
4299 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4300 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4301 if (NegC->getAPIntValue() == EltSize - 1) {
4302 Neg = Neg.getOperand(0);
4303 MaskLoBits = Log2_64(EltSize);
4308 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4309 if (Neg.getOpcode() != ISD::SUB)
4311 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4314 SDValue NegOp1 = Neg.getOperand(1);
4316 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4317 // Pos'. The truncation is redundant for the purpose of the equality.
4318 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4319 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4320 if (PosC->getAPIntValue() == EltSize - 1)
4321 Pos = Pos.getOperand(0);
4323 // The condition we need is now:
4325 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4327 // If NegOp1 == Pos then we need:
4329 // EltSize & Mask == NegC & Mask
4331 // (because "x & Mask" is a truncation and distributes through subtraction).
4334 Width = NegC->getAPIntValue();
4336 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4337 // Then the condition we want to prove becomes:
4339 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4341 // which, again because "x & Mask" is a truncation, becomes:
4343 // NegC & Mask == (EltSize - PosC) & Mask
4344 // EltSize & Mask == (NegC + PosC) & Mask
4345 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4346 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4347 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4353 // Now we just need to check that EltSize & Mask == Width & Mask.
4355 // EltSize & Mask is 0 since Mask is EltSize - 1.
4356 return Width.getLoBits(MaskLoBits) == 0;
4357 return Width == EltSize;
4360 // A subroutine of MatchRotate used once we have found an OR of two opposite
4361 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
4362 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4363 // former being preferred if supported. InnerPos and InnerNeg are Pos and
4364 // Neg with outer conversions stripped away.
4365 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4366 SDValue Neg, SDValue InnerPos,
4367 SDValue InnerNeg, unsigned PosOpcode,
4368 unsigned NegOpcode, const SDLoc &DL) {
4369 // fold (or (shl x, (*ext y)),
4370 // (srl x, (*ext (sub 32, y)))) ->
4371 // (rotl x, y) or (rotr x, (sub 32, y))
4373 // fold (or (shl x, (*ext (sub 32, y))),
4374 // (srl x, (*ext y))) ->
4375 // (rotr x, y) or (rotl x, (sub 32, y))
4376 EVT VT = Shifted.getValueType();
4377 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4378 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4379 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4380 HasPos ? Pos : Neg).getNode();
4386 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
4387 // idioms for rotate, and if the target supports rotation instructions, generate
4389 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4390 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
4391 EVT VT = LHS.getValueType();
4392 if (!TLI.isTypeLegal(VT)) return nullptr;
4394 // The target must have at least one rotate flavor.
4395 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4396 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4397 if (!HasROTL && !HasROTR) return nullptr;
4399 // Match "(X shl/srl V1) & V2" where V2 may not be present.
4400 SDValue LHSShift; // The shift.
4401 SDValue LHSMask; // AND value if any.
4402 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4403 return nullptr; // Not part of a rotate.
4405 SDValue RHSShift; // The shift.
4406 SDValue RHSMask; // AND value if any.
4407 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4408 return nullptr; // Not part of a rotate.
4410 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4411 return nullptr; // Not shifting the same value.
4413 if (LHSShift.getOpcode() == RHSShift.getOpcode())
4414 return nullptr; // Shifts must disagree.
4416 // Canonicalize shl to left side in a shl/srl pair.
4417 if (RHSShift.getOpcode() == ISD::SHL) {
4418 std::swap(LHS, RHS);
4419 std::swap(LHSShift, RHSShift);
4420 std::swap(LHSMask, RHSMask);
4423 unsigned EltSizeInBits = VT.getScalarSizeInBits();
4424 SDValue LHSShiftArg = LHSShift.getOperand(0);
4425 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4426 SDValue RHSShiftArg = RHSShift.getOperand(0);
4427 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4429 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4430 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4431 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4432 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4433 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4434 if ((LShVal + RShVal) != EltSizeInBits)
4437 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4438 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4440 // If there is an AND of either shifted operand, apply it to the result.
4441 if (LHSMask.getNode() || RHSMask.getNode()) {
4442 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
4444 if (LHSMask.getNode()) {
4445 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4446 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4447 DAG.getNode(ISD::OR, DL, VT, LHSMask,
4448 DAG.getConstant(RHSBits, DL, VT)));
4450 if (RHSMask.getNode()) {
4451 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4452 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4453 DAG.getNode(ISD::OR, DL, VT, RHSMask,
4454 DAG.getConstant(LHSBits, DL, VT)));
4457 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4460 return Rot.getNode();
4463 // If there is a mask here, and we have a variable shift, we can't be sure
4464 // that we're masking out the right stuff.
4465 if (LHSMask.getNode() || RHSMask.getNode())
4468 // If the shift amount is sign/zext/any-extended just peel it off.
4469 SDValue LExtOp0 = LHSShiftAmt;
4470 SDValue RExtOp0 = RHSShiftAmt;
4471 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4472 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4473 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4474 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4475 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4476 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4477 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4478 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4479 LExtOp0 = LHSShiftAmt.getOperand(0);
4480 RExtOp0 = RHSShiftAmt.getOperand(0);
4483 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4484 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4488 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4489 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4497 /// Helper struct to parse and store a memory address as base + index + offset.
4498 /// We ignore sign extensions when it is safe to do so.
4499 /// The following two expressions are not equivalent. To differentiate we need
4500 /// to store whether there was a sign extension involved in the index
4502 /// (load (i64 add (i64 copyfromreg %c)
4503 /// (i64 signextend (add (i8 load %index)
4507 /// (load (i64 add (i64 copyfromreg %c)
4508 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
4510 struct BaseIndexOffset {
4514 bool IsIndexSignExt;
4516 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
4518 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
4519 bool IsIndexSignExt) :
4520 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
4522 bool equalBaseIndex(const BaseIndexOffset &Other) {
4523 return Other.Base == Base && Other.Index == Index &&
4524 Other.IsIndexSignExt == IsIndexSignExt;
4527 /// Parses tree in Ptr for base, index, offset addresses.
4528 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG,
4529 int64_t PartialOffset = 0) {
4530 bool IsIndexSignExt = false;
4532 // Split up a folded GlobalAddress+Offset into its component parts.
4533 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
4534 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
4535 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
4537 GA->getValueType(0),
4538 /*Offset=*/PartialOffset,
4539 /*isTargetGA=*/false,
4540 GA->getTargetFlags()),
4546 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
4547 // instruction, then it could be just the BASE or everything else we don't
4548 // know how to handle. Just use Ptr as BASE and give up.
4549 if (Ptr->getOpcode() != ISD::ADD)
4550 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4552 // We know that we have at least an ADD instruction. Try to pattern match
4553 // the simple case of BASE + OFFSET.
4554 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
4555 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
4556 return match(Ptr->getOperand(0), DAG, Offset + PartialOffset);
4559 // Inside a loop the current BASE pointer is calculated using an ADD and a
4560 // MUL instruction. In this case Ptr is the actual BASE pointer.
4561 // (i64 add (i64 %array_ptr)
4562 // (i64 mul (i64 %induction_var)
4563 // (i64 %element_size)))
4564 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
4565 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4567 // Look at Base + Index + Offset cases.
4568 SDValue Base = Ptr->getOperand(0);
4569 SDValue IndexOffset = Ptr->getOperand(1);
4571 // Skip signextends.
4572 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
4573 IndexOffset = IndexOffset->getOperand(0);
4574 IsIndexSignExt = true;
4577 // Either the case of Base + Index (no offset) or something else.
4578 if (IndexOffset->getOpcode() != ISD::ADD)
4579 return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt);
4581 // Now we have the case of Base + Index + offset.
4582 SDValue Index = IndexOffset->getOperand(0);
4583 SDValue Offset = IndexOffset->getOperand(1);
4585 if (!isa<ConstantSDNode>(Offset))
4586 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4588 // Ignore signextends.
4589 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
4590 Index = Index->getOperand(0);
4591 IsIndexSignExt = true;
4592 } else IsIndexSignExt = false;
4594 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
4595 return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt);
4601 /// Represents known origin of an individual byte in load combine pattern. The
4602 /// value of the byte is either constant zero or comes from memory.
4603 struct ByteProvider {
4604 // For constant zero providers Load is set to nullptr. For memory providers
4605 // Load represents the node which loads the byte from memory.
4606 // ByteOffset is the offset of the byte in the value produced by the load.
4608 unsigned ByteOffset;
4610 ByteProvider() : Load(nullptr), ByteOffset(0) {}
4612 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4613 return ByteProvider(Load, ByteOffset);
4615 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4617 bool isConstantZero() const { return !Load; }
4618 bool isMemory() const { return Load; }
4620 bool operator==(const ByteProvider &Other) const {
4621 return Other.Load == Load && Other.ByteOffset == ByteOffset;
4625 ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4626 : Load(Load), ByteOffset(ByteOffset) {}
4629 /// Recursively traverses the expression calculating the origin of the requested
4630 /// byte of the given value. Returns None if the provider can't be calculated.
4632 /// For all the values except the root of the expression verifies that the value
4633 /// has exactly one use and if it's not true return None. This way if the origin
4634 /// of the byte is returned it's guaranteed that the values which contribute to
4635 /// the byte are not used outside of this expression.
4637 /// Because the parts of the expression are not allowed to have more than one
4638 /// use this function iterates over trees, not DAGs. So it never visits the same
4639 /// node more than once.
4640 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4642 bool Root = false) {
4643 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4647 if (!Root && !Op.hasOneUse())
4650 assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4651 unsigned BitWidth = Op.getValueSizeInBits();
4652 if (BitWidth % 8 != 0)
4654 unsigned ByteWidth = BitWidth / 8;
4655 assert(Index < ByteWidth && "invalid index requested");
4658 switch (Op.getOpcode()) {
4660 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4663 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4667 if (LHS->isConstantZero())
4669 if (RHS->isConstantZero())
4674 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4678 uint64_t BitShift = ShiftOp->getZExtValue();
4679 if (BitShift % 8 != 0)
4681 uint64_t ByteShift = BitShift / 8;
4683 return Index < ByteShift
4684 ? ByteProvider::getConstantZero()
4685 : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4688 case ISD::ANY_EXTEND:
4689 case ISD::SIGN_EXTEND:
4690 case ISD::ZERO_EXTEND: {
4691 SDValue NarrowOp = Op->getOperand(0);
4692 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4693 if (NarrowBitWidth % 8 != 0)
4695 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4697 if (Index >= NarrowByteWidth)
4698 return Op.getOpcode() == ISD::ZERO_EXTEND
4699 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4701 return calculateByteProvider(NarrowOp, Index, Depth + 1);
4704 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4707 auto L = cast<LoadSDNode>(Op.getNode());
4708 if (L->isVolatile() || L->isIndexed())
4711 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4712 if (NarrowBitWidth % 8 != 0)
4714 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4716 if (Index >= NarrowByteWidth)
4717 return L->getExtensionType() == ISD::ZEXTLOAD
4718 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4720 return ByteProvider::getMemory(L, Index);
4728 /// Match a pattern where a wide type scalar value is loaded by several narrow
4729 /// loads and combined by shifts and ors. Fold it into a single load or a load
4730 /// and a BSWAP if the targets supports it.
4732 /// Assuming little endian target:
4734 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4736 /// i32 val = *((i32)a)
4739 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4741 /// i32 val = BSWAP(*((i32)a))
4743 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4744 /// interact well with the worklist mechanism. When a part of the pattern is
4745 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4746 /// but the root node of the pattern which triggers the load combine is not
4747 /// necessarily a direct user of the changed node. For example, once the address
4748 /// of t28 load is reassociated load combine won't be triggered:
4749 /// t25: i32 = add t4, Constant:i32<2>
4750 /// t26: i64 = sign_extend t25
4751 /// t27: i64 = add t2, t26
4752 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4753 /// t29: i32 = zero_extend t28
4754 /// t32: i32 = shl t29, Constant:i8<8>
4755 /// t33: i32 = or t23, t32
4756 /// As a possible fix visitLoad can check if the load can be a part of a load
4757 /// combine pattern and add corresponding OR roots to the worklist.
4758 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4759 assert(N->getOpcode() == ISD::OR &&
4760 "Can only match load combining against OR nodes");
4762 // Handles simple types only
4763 EVT VT = N->getValueType(0);
4764 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4766 unsigned ByteWidth = VT.getSizeInBits() / 8;
4768 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4769 // Before legalize we can introduce too wide illegal loads which will be later
4770 // split into legal sized loads. This enables us to combine i64 load by i8
4771 // patterns to a couple of i32 loads on 32 bit targets.
4772 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4775 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4776 unsigned BW, unsigned i) { return i; };
4777 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4778 unsigned BW, unsigned i) { return BW - i - 1; };
4780 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4781 auto MemoryByteOffset = [&] (ByteProvider P) {
4782 assert(P.isMemory() && "Must be a memory byte provider");
4783 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4784 assert(LoadBitWidth % 8 == 0 &&
4785 "can only analyze providers for individual bytes not bit");
4786 unsigned LoadByteWidth = LoadBitWidth / 8;
4787 return IsBigEndianTarget
4788 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4789 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4792 Optional<BaseIndexOffset> Base;
4795 SmallSet<LoadSDNode *, 8> Loads;
4796 Optional<ByteProvider> FirstByteProvider;
4797 int64_t FirstOffset = INT64_MAX;
4799 // Check if all the bytes of the OR we are looking at are loaded from the same
4800 // base address. Collect bytes offsets from Base address in ByteOffsets.
4801 SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4802 for (unsigned i = 0; i < ByteWidth; i++) {
4803 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4804 if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4807 LoadSDNode *L = P->Load;
4808 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4809 "Must be enforced by calculateByteProvider");
4810 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4812 // All loads must share the same chain
4813 SDValue LChain = L->getChain();
4816 else if (Chain != LChain)
4819 // Loads must share the same base address
4820 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4823 else if (!Base->equalBaseIndex(Ptr))
4826 // Calculate the offset of the current byte from the base address
4827 int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P);
4828 ByteOffsets[i] = ByteOffsetFromBase;
4830 // Remember the first byte load
4831 if (ByteOffsetFromBase < FirstOffset) {
4832 FirstByteProvider = P;
4833 FirstOffset = ByteOffsetFromBase;
4838 assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4839 "memory, so there must be at least one load which produces the value");
4840 assert(Base && "Base address of the accessed memory location must be set");
4841 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4843 // Check if the bytes of the OR we are looking at match with either big or
4844 // little endian value load
4845 bool BigEndian = true, LittleEndian = true;
4846 for (unsigned i = 0; i < ByteWidth; i++) {
4847 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
4848 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
4849 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
4850 if (!BigEndian && !LittleEndian)
4853 assert((BigEndian != LittleEndian) && "should be either or");
4854 assert(FirstByteProvider && "must be set");
4856 // Ensure that the first byte is loaded from zero offset of the first load.
4857 // So the combined value can be loaded from the first load address.
4858 if (MemoryByteOffset(*FirstByteProvider) != 0)
4860 LoadSDNode *FirstLoad = FirstByteProvider->Load;
4862 // The node we are looking at matches with the pattern, check if we can
4863 // replace it with a single load and bswap if needed.
4865 // If the load needs byte swap check if the target supports it
4866 bool NeedsBswap = IsBigEndianTarget != BigEndian;
4868 // Before legalize we can introduce illegal bswaps which will be later
4869 // converted to an explicit bswap sequence. This way we end up with a single
4870 // load and byte shuffling instead of several loads and byte shuffling.
4871 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4874 // Check that a load of the wide type is both allowed and fast on the target
4876 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4877 VT, FirstLoad->getAddressSpace(),
4878 FirstLoad->getAlignment(), &Fast);
4879 if (!Allowed || !Fast)
4883 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4884 FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
4886 // Transfer chain users from old loads to the new load.
4887 for (LoadSDNode *L : Loads)
4888 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
4890 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
4893 SDValue DAGCombiner::visitXOR(SDNode *N) {
4894 SDValue N0 = N->getOperand(0);
4895 SDValue N1 = N->getOperand(1);
4896 EVT VT = N0.getValueType();
4899 if (VT.isVector()) {
4900 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4903 // fold (xor x, 0) -> x, vector edition
4904 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4906 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4910 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4911 if (N0.isUndef() && N1.isUndef())
4912 return DAG.getConstant(0, SDLoc(N), VT);
4913 // fold (xor x, undef) -> undef
4918 // fold (xor c1, c2) -> c1^c2
4919 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4920 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4922 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4923 // canonicalize constant to RHS
4924 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4925 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4926 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4927 // fold (xor x, 0) -> x
4928 if (isNullConstant(N1))
4931 if (SDValue NewSel = foldBinOpIntoSelect(N))
4935 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4938 // fold !(x cc y) -> (x !cc y)
4939 SDValue LHS, RHS, CC;
4940 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4941 bool isInt = LHS.getValueType().isInteger();
4942 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4945 if (!LegalOperations ||
4946 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4947 switch (N0.getOpcode()) {
4949 llvm_unreachable("Unhandled SetCC Equivalent!");
4951 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
4952 case ISD::SELECT_CC:
4953 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
4954 N0.getOperand(3), NotCC);
4959 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4960 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4961 N0.getNode()->hasOneUse() &&
4962 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4963 SDValue V = N0.getOperand(0);
4965 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4966 DAG.getConstant(1, DL, V.getValueType()));
4967 AddToWorklist(V.getNode());
4968 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4971 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4972 if (isOneConstant(N1) && VT == MVT::i1 &&
4973 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4974 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4975 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4976 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4977 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4978 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4979 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4980 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4983 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4984 if (isAllOnesConstant(N1) &&
4985 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4986 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4987 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4988 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4989 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4990 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4991 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4992 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4995 // fold (xor (and x, y), y) -> (and (not x), y)
4996 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4997 N0->getOperand(1) == N1) {
4998 SDValue X = N0->getOperand(0);
4999 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5000 AddToWorklist(NotX.getNode());
5001 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5003 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5004 if (N1C && N0.getOpcode() == ISD::XOR) {
5005 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5007 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5008 DAG.getConstant(N1C->getAPIntValue() ^
5009 N00C->getAPIntValue(), DL, VT));
5011 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5013 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5014 DAG.getConstant(N1C->getAPIntValue() ^
5015 N01C->getAPIntValue(), DL, VT));
5019 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5020 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5021 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5022 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5023 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5024 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5025 if (C->getAPIntValue() == (OpSizeInBits - 1))
5026 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5029 // fold (xor x, x) -> 0
5031 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5033 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5034 // Here is a concrete example of this equivalence:
5036 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
5037 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5041 // i16 ~1 == 0b1111111111111110
5042 // i16 rol(~1, 14) == 0b1011111111111111
5044 // Some additional tips to help conceptualize this transform:
5045 // - Try to see the operation as placing a single zero in a value of all ones.
5046 // - There exists no value for x which would allow the result to contain zero.
5047 // - Values of x larger than the bitwidth are undefined and do not require a
5048 // consistent result.
5049 // - Pushing the zero left requires shifting one bits in from the right.
5050 // A rotate left of ~1 is a nice way of achieving the desired result.
5051 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5052 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5054 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5058 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
5059 if (N0.getOpcode() == N1.getOpcode())
5060 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5063 // Simplify the expression using non-local knowledge.
5064 if (SimplifyDemandedBits(SDValue(N, 0)))
5065 return SDValue(N, 0);
5070 /// Handle transforms common to the three shifts, when the shift amount is a
5072 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5073 SDNode *LHS = N->getOperand(0).getNode();
5074 if (!LHS->hasOneUse()) return SDValue();
5076 // We want to pull some binops through shifts, so that we have (and (shift))
5077 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
5078 // thing happens with address calculations, so it's important to canonicalize
5080 bool HighBitSet = false; // Can we transform this if the high bit is set?
5082 switch (LHS->getOpcode()) {
5083 default: return SDValue();
5086 HighBitSet = false; // We can only transform sra if the high bit is clear.
5089 HighBitSet = true; // We can only transform sra if the high bit is set.
5092 if (N->getOpcode() != ISD::SHL)
5093 return SDValue(); // only shl(add) not sr[al](add).
5094 HighBitSet = false; // We can only transform sra if the high bit is clear.
5098 // We require the RHS of the binop to be a constant and not opaque as well.
5099 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5100 if (!BinOpCst) return SDValue();
5102 // FIXME: disable this unless the input to the binop is a shift by a constant
5103 // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5104 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5105 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5106 BinOpLHSVal->getOpcode() == ISD::SRA ||
5107 BinOpLHSVal->getOpcode() == ISD::SRL;
5108 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5109 BinOpLHSVal->getOpcode() == ISD::SELECT;
5111 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5115 if (isCopyOrSelect && N->hasOneUse())
5118 EVT VT = N->getValueType(0);
5120 // If this is a signed shift right, and the high bit is modified by the
5121 // logical operation, do not perform the transformation. The highBitSet
5122 // boolean indicates the value of the high bit of the constant which would
5123 // cause it to be modified for this operation.
5124 if (N->getOpcode() == ISD::SRA) {
5125 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5126 if (BinOpRHSSignSet != HighBitSet)
5130 if (!TLI.isDesirableToCommuteWithShift(LHS))
5133 // Fold the constants, shifting the binop RHS by the shift amount.
5134 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5136 LHS->getOperand(1), N->getOperand(1));
5137 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5139 // Create the new shift.
5140 SDValue NewShift = DAG.getNode(N->getOpcode(),
5141 SDLoc(LHS->getOperand(0)),
5142 VT, LHS->getOperand(0), N->getOperand(1));
5144 // Create the new binop.
5145 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5148 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5149 assert(N->getOpcode() == ISD::TRUNCATE);
5150 assert(N->getOperand(0).getOpcode() == ISD::AND);
5152 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5153 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5154 SDValue N01 = N->getOperand(0).getOperand(1);
5155 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5157 EVT TruncVT = N->getValueType(0);
5158 SDValue N00 = N->getOperand(0).getOperand(0);
5159 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5160 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5161 AddToWorklist(Trunc00.getNode());
5162 AddToWorklist(Trunc01.getNode());
5163 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5170 SDValue DAGCombiner::visitRotate(SDNode *N) {
5171 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5172 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
5173 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
5174 if (SDValue NewOp1 =
5175 distributeTruncateThroughAnd(N->getOperand(1).getNode()))
5176 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
5177 N->getOperand(0), NewOp1);
5182 SDValue DAGCombiner::visitSHL(SDNode *N) {
5183 SDValue N0 = N->getOperand(0);
5184 SDValue N1 = N->getOperand(1);
5185 EVT VT = N0.getValueType();
5186 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5189 if (VT.isVector()) {
5190 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5193 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5194 // If setcc produces all-one true value then:
5195 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5196 if (N1CV && N1CV->isConstant()) {
5197 if (N0.getOpcode() == ISD::AND) {
5198 SDValue N00 = N0->getOperand(0);
5199 SDValue N01 = N0->getOperand(1);
5200 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5202 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5203 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5204 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5205 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5207 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5213 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5215 // fold (shl c1, c2) -> c1<<c2
5216 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5217 if (N0C && N1C && !N1C->isOpaque())
5218 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5219 // fold (shl 0, x) -> 0
5220 if (isNullConstant(N0))
5222 // fold (shl x, c >= size(x)) -> undef
5223 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5224 return DAG.getUNDEF(VT);
5225 // fold (shl x, 0) -> x
5226 if (N1C && N1C->isNullValue())
5228 // fold (shl undef, x) -> 0
5230 return DAG.getConstant(0, SDLoc(N), VT);
5232 if (SDValue NewSel = foldBinOpIntoSelect(N))
5235 // if (shl x, c) is known to be zero, return 0
5236 if (DAG.MaskedValueIsZero(SDValue(N, 0),
5237 APInt::getAllOnesValue(OpSizeInBits)))
5238 return DAG.getConstant(0, SDLoc(N), VT);
5239 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5240 if (N1.getOpcode() == ISD::TRUNCATE &&
5241 N1.getOperand(0).getOpcode() == ISD::AND) {
5242 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5243 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5246 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5247 return SDValue(N, 0);
5249 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5250 if (N1C && N0.getOpcode() == ISD::SHL) {
5251 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5253 APInt c1 = N0C1->getAPIntValue();
5254 APInt c2 = N1C->getAPIntValue();
5255 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5257 APInt Sum = c1 + c2;
5258 if (Sum.uge(OpSizeInBits))
5259 return DAG.getConstant(0, DL, VT);
5262 ISD::SHL, DL, VT, N0.getOperand(0),
5263 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5267 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5268 // For this to be valid, the second form must not preserve any of the bits
5269 // that are shifted out by the inner shift in the first form. This means
5270 // the outer shift size must be >= the number of bits added by the ext.
5271 // As a corollary, we don't care what kind of ext it is.
5272 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5273 N0.getOpcode() == ISD::ANY_EXTEND ||
5274 N0.getOpcode() == ISD::SIGN_EXTEND) &&
5275 N0.getOperand(0).getOpcode() == ISD::SHL) {
5276 SDValue N0Op0 = N0.getOperand(0);
5277 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5278 APInt c1 = N0Op0C1->getAPIntValue();
5279 APInt c2 = N1C->getAPIntValue();
5280 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5282 EVT InnerShiftVT = N0Op0.getValueType();
5283 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5284 if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5286 APInt Sum = c1 + c2;
5287 if (Sum.uge(OpSizeInBits))
5288 return DAG.getConstant(0, DL, VT);
5292 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5293 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5298 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5299 // Only fold this if the inner zext has no other uses to avoid increasing
5300 // the total number of instructions.
5301 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5302 N0.getOperand(0).getOpcode() == ISD::SRL) {
5303 SDValue N0Op0 = N0.getOperand(0);
5304 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5305 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5306 uint64_t c1 = N0Op0C1->getZExtValue();
5307 uint64_t c2 = N1C->getZExtValue();
5309 SDValue NewOp0 = N0.getOperand(0);
5310 EVT CountVT = NewOp0.getOperand(1).getValueType();
5312 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5314 DAG.getConstant(c2, DL, CountVT));
5315 AddToWorklist(NewSHL.getNode());
5316 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5322 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
5323 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
5324 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5325 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
5326 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5327 uint64_t C1 = N0C1->getZExtValue();
5328 uint64_t C2 = N1C->getZExtValue();
5331 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5332 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5333 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5334 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5338 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5339 // (and (srl x, (sub c1, c2), MASK)
5340 // Only fold this if the inner shift has no other uses -- if it does, folding
5341 // this will increase the total number of instructions.
5342 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5343 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5344 uint64_t c1 = N0C1->getZExtValue();
5345 if (c1 < OpSizeInBits) {
5346 uint64_t c2 = N1C->getZExtValue();
5347 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5350 Mask = Mask.shl(c2 - c1);
5352 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5353 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5355 Mask.lshrInPlace(c1 - c2);
5357 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5358 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5361 return DAG.getNode(ISD::AND, DL, VT, Shift,
5362 DAG.getConstant(Mask, DL, VT));
5367 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5368 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5369 isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5371 SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5372 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5373 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5376 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5377 // Variant of version done on multiply, except mul by a power of 2 is turned
5379 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5380 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5381 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5382 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5383 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5384 AddToWorklist(Shl0.getNode());
5385 AddToWorklist(Shl1.getNode());
5386 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5389 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5390 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5391 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5392 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5393 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5394 if (isConstantOrConstantVector(Shl))
5395 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5398 if (N1C && !N1C->isOpaque())
5399 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5405 SDValue DAGCombiner::visitSRA(SDNode *N) {
5406 SDValue N0 = N->getOperand(0);
5407 SDValue N1 = N->getOperand(1);
5408 EVT VT = N0.getValueType();
5409 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5411 // Arithmetic shifting an all-sign-bit value is a no-op.
5412 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5417 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5420 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5422 // fold (sra c1, c2) -> (sra c1, c2)
5423 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5424 if (N0C && N1C && !N1C->isOpaque())
5425 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5426 // fold (sra 0, x) -> 0
5427 if (isNullConstant(N0))
5429 // fold (sra -1, x) -> -1
5430 if (isAllOnesConstant(N0))
5432 // fold (sra x, c >= size(x)) -> undef
5433 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5434 return DAG.getUNDEF(VT);
5435 // fold (sra x, 0) -> x
5436 if (N1C && N1C->isNullValue())
5439 if (SDValue NewSel = foldBinOpIntoSelect(N))
5442 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5444 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5445 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5446 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5448 ExtVT = EVT::getVectorVT(*DAG.getContext(),
5449 ExtVT, VT.getVectorNumElements());
5450 if ((!LegalOperations ||
5451 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5452 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5453 N0.getOperand(0), DAG.getValueType(ExtVT));
5456 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5457 if (N1C && N0.getOpcode() == ISD::SRA) {
5458 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5460 APInt c1 = N0C1->getAPIntValue();
5461 APInt c2 = N1C->getAPIntValue();
5462 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5464 APInt Sum = c1 + c2;
5465 if (Sum.uge(OpSizeInBits))
5466 Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5469 ISD::SRA, DL, VT, N0.getOperand(0),
5470 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5474 // fold (sra (shl X, m), (sub result_size, n))
5475 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5476 // result_size - n != m.
5477 // If truncate is free for the target sext(shl) is likely to result in better
5479 if (N0.getOpcode() == ISD::SHL && N1C) {
5480 // Get the two constanst of the shifts, CN0 = m, CN = n.
5481 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5483 LLVMContext &Ctx = *DAG.getContext();
5484 // Determine what the truncate's result bitsize and type would be.
5485 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5488 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5490 // Determine the residual right-shift amount.
5491 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5493 // If the shift is not a no-op (in which case this should be just a sign
5494 // extend already), the truncated to type is legal, sign_extend is legal
5495 // on that type, and the truncate to that type is both legal and free,
5496 // perform the transform.
5497 if ((ShiftAmt > 0) &&
5498 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5499 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5500 TLI.isTruncateFree(VT, TruncVT)) {
5503 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5504 getShiftAmountTy(N0.getOperand(0).getValueType()));
5505 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5506 N0.getOperand(0), Amt);
5507 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5509 return DAG.getNode(ISD::SIGN_EXTEND, DL,
5510 N->getValueType(0), Trunc);
5515 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5516 if (N1.getOpcode() == ISD::TRUNCATE &&
5517 N1.getOperand(0).getOpcode() == ISD::AND) {
5518 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5519 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5522 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5523 // if c1 is equal to the number of bits the trunc removes
5524 if (N0.getOpcode() == ISD::TRUNCATE &&
5525 (N0.getOperand(0).getOpcode() == ISD::SRL ||
5526 N0.getOperand(0).getOpcode() == ISD::SRA) &&
5527 N0.getOperand(0).hasOneUse() &&
5528 N0.getOperand(0).getOperand(1).hasOneUse() &&
5530 SDValue N0Op0 = N0.getOperand(0);
5531 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5532 unsigned LargeShiftVal = LargeShift->getZExtValue();
5533 EVT LargeVT = N0Op0.getValueType();
5535 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5538 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5539 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5540 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5541 N0Op0.getOperand(0), Amt);
5542 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5547 // Simplify, based on bits shifted out of the LHS.
5548 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5549 return SDValue(N, 0);
5552 // If the sign bit is known to be zero, switch this to a SRL.
5553 if (DAG.SignBitIsZero(N0))
5554 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5556 if (N1C && !N1C->isOpaque())
5557 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5563 SDValue DAGCombiner::visitSRL(SDNode *N) {
5564 SDValue N0 = N->getOperand(0);
5565 SDValue N1 = N->getOperand(1);
5566 EVT VT = N0.getValueType();
5567 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5571 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5574 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5576 // fold (srl c1, c2) -> c1 >>u c2
5577 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5578 if (N0C && N1C && !N1C->isOpaque())
5579 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5580 // fold (srl 0, x) -> 0
5581 if (isNullConstant(N0))
5583 // fold (srl x, c >= size(x)) -> undef
5584 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5585 return DAG.getUNDEF(VT);
5586 // fold (srl x, 0) -> x
5587 if (N1C && N1C->isNullValue())
5590 if (SDValue NewSel = foldBinOpIntoSelect(N))
5593 // if (srl x, c) is known to be zero, return 0
5594 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5595 APInt::getAllOnesValue(OpSizeInBits)))
5596 return DAG.getConstant(0, SDLoc(N), VT);
5598 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5599 if (N1C && N0.getOpcode() == ISD::SRL) {
5600 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5602 APInt c1 = N0C1->getAPIntValue();
5603 APInt c2 = N1C->getAPIntValue();
5604 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5606 APInt Sum = c1 + c2;
5607 if (Sum.uge(OpSizeInBits))
5608 return DAG.getConstant(0, DL, VT);
5611 ISD::SRL, DL, VT, N0.getOperand(0),
5612 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5616 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5617 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5618 N0.getOperand(0).getOpcode() == ISD::SRL) {
5619 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5620 uint64_t c1 = N001C->getZExtValue();
5621 uint64_t c2 = N1C->getZExtValue();
5622 EVT InnerShiftVT = N0.getOperand(0).getValueType();
5623 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5624 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5625 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5626 if (c1 + OpSizeInBits == InnerShiftSize) {
5628 if (c1 + c2 >= InnerShiftSize)
5629 return DAG.getConstant(0, DL, VT);
5630 return DAG.getNode(ISD::TRUNCATE, DL, VT,
5631 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5632 N0.getOperand(0).getOperand(0),
5633 DAG.getConstant(c1 + c2, DL,
5639 // fold (srl (shl x, c), c) -> (and x, cst2)
5640 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5641 isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5644 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5645 AddToWorklist(Mask.getNode());
5646 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5649 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5650 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5651 // Shifting in all undef bits?
5652 EVT SmallVT = N0.getOperand(0).getValueType();
5653 unsigned BitSize = SmallVT.getScalarSizeInBits();
5654 if (N1C->getZExtValue() >= BitSize)
5655 return DAG.getUNDEF(VT);
5657 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5658 uint64_t ShiftAmt = N1C->getZExtValue();
5660 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5662 DAG.getConstant(ShiftAmt, DL0,
5663 getShiftAmountTy(SmallVT)));
5664 AddToWorklist(SmallShift.getNode());
5665 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5667 return DAG.getNode(ISD::AND, DL, VT,
5668 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5669 DAG.getConstant(Mask, DL, VT));
5673 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
5674 // bit, which is unmodified by sra.
5675 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5676 if (N0.getOpcode() == ISD::SRA)
5677 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5680 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
5681 if (N1C && N0.getOpcode() == ISD::CTLZ &&
5682 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5683 APInt KnownZero, KnownOne;
5684 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
5686 // If any of the input bits are KnownOne, then the input couldn't be all
5687 // zeros, thus the result of the srl will always be zero.
5688 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5690 // If all of the bits input the to ctlz node are known to be zero, then
5691 // the result of the ctlz is "32" and the result of the shift is one.
5692 APInt UnknownBits = ~KnownZero;
5693 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5695 // Otherwise, check to see if there is exactly one bit input to the ctlz.
5696 if ((UnknownBits & (UnknownBits - 1)) == 0) {
5697 // Okay, we know that only that the single bit specified by UnknownBits
5698 // could be set on input to the CTLZ node. If this bit is set, the SRL
5699 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5700 // to an SRL/XOR pair, which is likely to simplify more.
5701 unsigned ShAmt = UnknownBits.countTrailingZeros();
5702 SDValue Op = N0.getOperand(0);
5706 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5707 DAG.getConstant(ShAmt, DL,
5708 getShiftAmountTy(Op.getValueType())));
5709 AddToWorklist(Op.getNode());
5713 return DAG.getNode(ISD::XOR, DL, VT,
5714 Op, DAG.getConstant(1, DL, VT));
5718 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5719 if (N1.getOpcode() == ISD::TRUNCATE &&
5720 N1.getOperand(0).getOpcode() == ISD::AND) {
5721 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5722 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5725 // fold operands of srl based on knowledge that the low bits are not
5727 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5728 return SDValue(N, 0);
5730 if (N1C && !N1C->isOpaque())
5731 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5734 // Attempt to convert a srl of a load into a narrower zero-extending load.
5735 if (SDValue NarrowLoad = ReduceLoadWidth(N))
5738 // Here is a common situation. We want to optimize:
5741 // %b = and i32 %a, 2
5742 // %c = srl i32 %b, 1
5743 // brcond i32 %c ...
5749 // %c = setcc eq %b, 0
5752 // However when after the source operand of SRL is optimized into AND, the SRL
5753 // itself may not be optimized further. Look for it and add the BRCOND into
5755 if (N->hasOneUse()) {
5756 SDNode *Use = *N->use_begin();
5757 if (Use->getOpcode() == ISD::BRCOND)
5759 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5760 // Also look pass the truncate.
5761 Use = *Use->use_begin();
5762 if (Use->getOpcode() == ISD::BRCOND)
5770 SDValue DAGCombiner::visitABS(SDNode *N) {
5771 SDValue N0 = N->getOperand(0);
5772 EVT VT = N->getValueType(0);
5774 // fold (abs c1) -> c2
5775 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5776 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5777 // fold (abs (abs x)) -> (abs x)
5778 if (N0.getOpcode() == ISD::ABS)
5780 // fold (abs x) -> x iff not-negative
5781 if (DAG.SignBitIsZero(N0))
5786 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5787 SDValue N0 = N->getOperand(0);
5788 EVT VT = N->getValueType(0);
5790 // fold (bswap c1) -> c2
5791 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5792 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5793 // fold (bswap (bswap x)) -> x
5794 if (N0.getOpcode() == ISD::BSWAP)
5795 return N0->getOperand(0);
5799 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5800 SDValue N0 = N->getOperand(0);
5801 EVT VT = N->getValueType(0);
5803 // fold (bitreverse c1) -> c2
5804 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5805 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5806 // fold (bitreverse (bitreverse x)) -> x
5807 if (N0.getOpcode() == ISD::BITREVERSE)
5808 return N0.getOperand(0);
5812 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5813 SDValue N0 = N->getOperand(0);
5814 EVT VT = N->getValueType(0);
5816 // fold (ctlz c1) -> c2
5817 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5818 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5822 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5823 SDValue N0 = N->getOperand(0);
5824 EVT VT = N->getValueType(0);
5826 // fold (ctlz_zero_undef c1) -> c2
5827 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5828 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5832 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5833 SDValue N0 = N->getOperand(0);
5834 EVT VT = N->getValueType(0);
5836 // fold (cttz c1) -> c2
5837 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5838 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5842 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5843 SDValue N0 = N->getOperand(0);
5844 EVT VT = N->getValueType(0);
5846 // fold (cttz_zero_undef c1) -> c2
5847 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5848 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5852 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5853 SDValue N0 = N->getOperand(0);
5854 EVT VT = N->getValueType(0);
5856 // fold (ctpop c1) -> c2
5857 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5858 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5863 /// \brief Generate Min/Max node
5864 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5865 SDValue RHS, SDValue True, SDValue False,
5866 ISD::CondCode CC, const TargetLowering &TLI,
5867 SelectionDAG &DAG) {
5868 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5878 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5879 if (TLI.isOperationLegal(Opcode, VT))
5880 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5889 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5890 if (TLI.isOperationLegal(Opcode, VT))
5891 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5899 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5900 SDValue Cond = N->getOperand(0);
5901 SDValue N1 = N->getOperand(1);
5902 SDValue N2 = N->getOperand(2);
5903 EVT VT = N->getValueType(0);
5904 EVT CondVT = Cond.getValueType();
5907 if (!VT.isInteger())
5910 auto *C1 = dyn_cast<ConstantSDNode>(N1);
5911 auto *C2 = dyn_cast<ConstantSDNode>(N2);
5915 // Only do this before legalization to avoid conflicting with target-specific
5916 // transforms in the other direction (create a select from a zext/sext). There
5917 // is also a target-independent combine here in DAGCombiner in the other
5918 // direction for (select Cond, -1, 0) when the condition is not i1.
5919 if (CondVT == MVT::i1 && !LegalOperations) {
5920 if (C1->isNullValue() && C2->isOne()) {
5921 // select Cond, 0, 1 --> zext (!Cond)
5922 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
5924 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
5927 if (C1->isNullValue() && C2->isAllOnesValue()) {
5928 // select Cond, 0, -1 --> sext (!Cond)
5929 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
5931 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
5934 if (C1->isOne() && C2->isNullValue()) {
5935 // select Cond, 1, 0 --> zext (Cond)
5937 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
5940 if (C1->isAllOnesValue() && C2->isNullValue()) {
5941 // select Cond, -1, 0 --> sext (Cond)
5943 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
5947 // For any constants that differ by 1, we can transform the select into an
5948 // extend and add. Use a target hook because some targets may prefer to
5949 // transform in the other direction.
5950 if (TLI.convertSelectOfConstantsToMath()) {
5951 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
5952 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
5954 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
5955 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
5957 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
5958 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
5960 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
5961 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
5968 // fold (select Cond, 0, 1) -> (xor Cond, 1)
5969 // We can't do this reliably if integer based booleans have different contents
5970 // to floating point based booleans. This is because we can't tell whether we
5971 // have an integer-based boolean or a floating-point-based boolean unless we
5972 // can find the SETCC that produced it and inspect its operands. This is
5973 // fairly easy if C is the SETCC node, but it can potentially be
5974 // undiscoverable (or not reasonably discoverable). For example, it could be
5975 // in another basic block or it could require searching a complicated
5977 if (CondVT.isInteger() &&
5978 TLI.getBooleanContents(false, true) ==
5979 TargetLowering::ZeroOrOneBooleanContent &&
5980 TLI.getBooleanContents(false, false) ==
5981 TargetLowering::ZeroOrOneBooleanContent &&
5982 C1->isNullValue() && C2->isOne()) {
5984 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
5985 if (VT.bitsEq(CondVT))
5987 return DAG.getZExtOrTrunc(NotCond, DL, VT);
5993 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5994 SDValue N0 = N->getOperand(0);
5995 SDValue N1 = N->getOperand(1);
5996 SDValue N2 = N->getOperand(2);
5997 EVT VT = N->getValueType(0);
5998 EVT VT0 = N0.getValueType();
6000 // fold (select C, X, X) -> X
6003 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6004 // fold (select true, X, Y) -> X
6005 // fold (select false, X, Y) -> Y
6006 return !N0C->isNullValue() ? N1 : N2;
6008 // fold (select X, X, Y) -> (or X, Y)
6009 // fold (select X, 1, Y) -> (or C, Y)
6010 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6011 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
6013 if (SDValue V = foldSelectOfConstants(N))
6016 // fold (select C, 0, X) -> (and (not C), X)
6017 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6018 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6019 AddToWorklist(NOTNode.getNode());
6020 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
6022 // fold (select C, X, 1) -> (or (not C), X)
6023 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6024 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6025 AddToWorklist(NOTNode.getNode());
6026 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
6028 // fold (select X, Y, X) -> (and X, Y)
6029 // fold (select X, Y, 0) -> (and X, Y)
6030 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6031 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
6033 // If we can fold this based on the true/false value, do so.
6034 if (SimplifySelectOps(N, N1, N2))
6035 return SDValue(N, 0); // Don't revisit N.
6037 if (VT0 == MVT::i1) {
6038 // The code in this block deals with the following 2 equivalences:
6039 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6040 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6041 // The target can specify its preferred form with the
6042 // shouldNormalizeToSelectSequence() callback. However we always transform
6043 // to the right anyway if we find the inner select exists in the DAG anyway
6044 // and we always transform to the left side if we know that we can further
6045 // optimize the combination of the conditions.
6046 bool normalizeToSequence
6047 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6048 // select (and Cond0, Cond1), X, Y
6049 // -> select Cond0, (select Cond1, X, Y), Y
6050 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6051 SDValue Cond0 = N0->getOperand(0);
6052 SDValue Cond1 = N0->getOperand(1);
6053 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6054 N1.getValueType(), Cond1, N1, N2);
6055 if (normalizeToSequence || !InnerSelect.use_empty())
6056 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
6059 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6060 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6061 SDValue Cond0 = N0->getOperand(0);
6062 SDValue Cond1 = N0->getOperand(1);
6063 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6064 N1.getValueType(), Cond1, N1, N2);
6065 if (normalizeToSequence || !InnerSelect.use_empty())
6066 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
6070 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6071 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6072 SDValue N1_0 = N1->getOperand(0);
6073 SDValue N1_1 = N1->getOperand(1);
6074 SDValue N1_2 = N1->getOperand(2);
6075 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6076 // Create the actual and node if we can generate good code for it.
6077 if (!normalizeToSequence) {
6078 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
6080 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
6083 // Otherwise see if we can optimize the "and" to a better pattern.
6084 if (SDValue Combined = visitANDLike(N0, N1_0, N))
6085 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6089 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6090 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6091 SDValue N2_0 = N2->getOperand(0);
6092 SDValue N2_1 = N2->getOperand(1);
6093 SDValue N2_2 = N2->getOperand(2);
6094 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6095 // Create the actual or node if we can generate good code for it.
6096 if (!normalizeToSequence) {
6097 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
6099 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
6102 // Otherwise see if we can optimize to a better pattern.
6103 if (SDValue Combined = visitORLike(N0, N2_0, N))
6104 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6110 // select (xor Cond, 1), X, Y -> select Cond, Y, X
6111 if (VT0 == MVT::i1) {
6112 if (N0->getOpcode() == ISD::XOR) {
6113 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6114 SDValue Cond0 = N0->getOperand(0);
6116 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
6122 // fold selects based on a setcc into other things, such as min/max/abs
6123 if (N0.getOpcode() == ISD::SETCC) {
6124 // select x, y (fcmp lt x, y) -> fminnum x, y
6125 // select x, y (fcmp gt x, y) -> fmaxnum x, y
6127 // This is OK if we don't care about what happens if either operand is a
6131 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6132 // no signed zeros as well as no nans.
6133 const TargetOptions &Options = DAG.getTarget().Options;
6134 if (Options.UnsafeFPMath &&
6135 VT.isFloatingPoint() && N0.hasOneUse() &&
6136 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6137 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6139 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
6140 N0.getOperand(1), N1, N2, CC,
6145 if ((!LegalOperations &&
6146 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6147 TLI.isOperationLegal(ISD::SELECT_CC, VT))
6148 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
6149 N0.getOperand(0), N0.getOperand(1),
6150 N1, N2, N0.getOperand(2));
6151 return SimplifySelect(SDLoc(N), N0, N1, N2);
6158 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6161 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6163 // Split the inputs.
6164 SDValue Lo, Hi, LL, LH, RL, RH;
6165 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6166 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6168 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6169 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6171 return std::make_pair(Lo, Hi);
6174 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6175 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6176 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6178 SDValue Cond = N->getOperand(0);
6179 SDValue LHS = N->getOperand(1);
6180 SDValue RHS = N->getOperand(2);
6181 EVT VT = N->getValueType(0);
6182 int NumElems = VT.getVectorNumElements();
6183 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6184 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6185 Cond.getOpcode() == ISD::BUILD_VECTOR);
6187 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6188 // binary ones here.
6189 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6192 // We're sure we have an even number of elements due to the
6193 // concat_vectors we have as arguments to vselect.
6194 // Skip BV elements until we find one that's not an UNDEF
6195 // After we find an UNDEF element, keep looping until we get to half the
6196 // length of the BV and see if all the non-undef nodes are the same.
6197 ConstantSDNode *BottomHalf = nullptr;
6198 for (int i = 0; i < NumElems / 2; ++i) {
6199 if (Cond->getOperand(i)->isUndef())
6202 if (BottomHalf == nullptr)
6203 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6204 else if (Cond->getOperand(i).getNode() != BottomHalf)
6208 // Do the same for the second half of the BuildVector
6209 ConstantSDNode *TopHalf = nullptr;
6210 for (int i = NumElems / 2; i < NumElems; ++i) {
6211 if (Cond->getOperand(i)->isUndef())
6214 if (TopHalf == nullptr)
6215 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6216 else if (Cond->getOperand(i).getNode() != TopHalf)
6220 assert(TopHalf && BottomHalf &&
6221 "One half of the selector was all UNDEFs and the other was all the "
6222 "same value. This should have been addressed before this function.");
6224 ISD::CONCAT_VECTORS, DL, VT,
6225 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6226 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6229 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6231 if (Level >= AfterLegalizeTypes)
6234 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6235 SDValue Mask = MSC->getMask();
6236 SDValue Data = MSC->getValue();
6239 // If the MSCATTER data type requires splitting and the mask is provided by a
6240 // SETCC, then split both nodes and its operands before legalization. This
6241 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6242 // and enables future optimizations (e.g. min/max pattern matching on X86).
6243 if (Mask.getOpcode() != ISD::SETCC)
6246 // Check if any splitting is required.
6247 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6248 TargetLowering::TypeSplitVector)
6250 SDValue MaskLo, MaskHi, Lo, Hi;
6251 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6254 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6256 SDValue Chain = MSC->getChain();
6258 EVT MemoryVT = MSC->getMemoryVT();
6259 unsigned Alignment = MSC->getOriginalAlignment();
6261 EVT LoMemVT, HiMemVT;
6262 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6264 SDValue DataLo, DataHi;
6265 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6267 SDValue BasePtr = MSC->getBasePtr();
6268 SDValue IndexLo, IndexHi;
6269 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6271 MachineMemOperand *MMO = DAG.getMachineFunction().
6272 getMachineMemOperand(MSC->getPointerInfo(),
6273 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6274 Alignment, MSC->getAAInfo(), MSC->getRanges());
6276 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6277 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6280 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6281 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6284 AddToWorklist(Lo.getNode());
6285 AddToWorklist(Hi.getNode());
6287 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6290 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6292 if (Level >= AfterLegalizeTypes)
6295 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6296 SDValue Mask = MST->getMask();
6297 SDValue Data = MST->getValue();
6298 EVT VT = Data.getValueType();
6301 // If the MSTORE data type requires splitting and the mask is provided by a
6302 // SETCC, then split both nodes and its operands before legalization. This
6303 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6304 // and enables future optimizations (e.g. min/max pattern matching on X86).
6305 if (Mask.getOpcode() == ISD::SETCC) {
6307 // Check if any splitting is required.
6308 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6309 TargetLowering::TypeSplitVector)
6312 SDValue MaskLo, MaskHi, Lo, Hi;
6313 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6315 SDValue Chain = MST->getChain();
6316 SDValue Ptr = MST->getBasePtr();
6318 EVT MemoryVT = MST->getMemoryVT();
6319 unsigned Alignment = MST->getOriginalAlignment();
6321 // if Alignment is equal to the vector size,
6322 // take the half of it for the second part
6323 unsigned SecondHalfAlignment =
6324 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6326 EVT LoMemVT, HiMemVT;
6327 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6329 SDValue DataLo, DataHi;
6330 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6332 MachineMemOperand *MMO = DAG.getMachineFunction().
6333 getMachineMemOperand(MST->getPointerInfo(),
6334 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6335 Alignment, MST->getAAInfo(), MST->getRanges());
6337 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6338 MST->isTruncatingStore(),
6339 MST->isCompressingStore());
6341 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6342 MST->isCompressingStore());
6344 MMO = DAG.getMachineFunction().
6345 getMachineMemOperand(MST->getPointerInfo(),
6346 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
6347 SecondHalfAlignment, MST->getAAInfo(),
6350 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6351 MST->isTruncatingStore(),
6352 MST->isCompressingStore());
6354 AddToWorklist(Lo.getNode());
6355 AddToWorklist(Hi.getNode());
6357 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6362 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6364 if (Level >= AfterLegalizeTypes)
6367 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6368 SDValue Mask = MGT->getMask();
6371 // If the MGATHER result requires splitting and the mask is provided by a
6372 // SETCC, then split both nodes and its operands before legalization. This
6373 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6374 // and enables future optimizations (e.g. min/max pattern matching on X86).
6376 if (Mask.getOpcode() != ISD::SETCC)
6379 EVT VT = N->getValueType(0);
6381 // Check if any splitting is required.
6382 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6383 TargetLowering::TypeSplitVector)
6386 SDValue MaskLo, MaskHi, Lo, Hi;
6387 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6389 SDValue Src0 = MGT->getValue();
6390 SDValue Src0Lo, Src0Hi;
6391 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6394 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6396 SDValue Chain = MGT->getChain();
6397 EVT MemoryVT = MGT->getMemoryVT();
6398 unsigned Alignment = MGT->getOriginalAlignment();
6400 EVT LoMemVT, HiMemVT;
6401 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6403 SDValue BasePtr = MGT->getBasePtr();
6404 SDValue Index = MGT->getIndex();
6405 SDValue IndexLo, IndexHi;
6406 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6408 MachineMemOperand *MMO = DAG.getMachineFunction().
6409 getMachineMemOperand(MGT->getPointerInfo(),
6410 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6411 Alignment, MGT->getAAInfo(), MGT->getRanges());
6413 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6414 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6417 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6418 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6421 AddToWorklist(Lo.getNode());
6422 AddToWorklist(Hi.getNode());
6424 // Build a factor node to remember that this load is independent of the
6426 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6429 // Legalized the chain result - switch anything that used the old chain to
6431 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6433 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6435 SDValue RetOps[] = { GatherRes, Chain };
6436 return DAG.getMergeValues(RetOps, DL);
6439 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6441 if (Level >= AfterLegalizeTypes)
6444 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6445 SDValue Mask = MLD->getMask();
6448 // If the MLOAD result requires splitting and the mask is provided by a
6449 // SETCC, then split both nodes and its operands before legalization. This
6450 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6451 // and enables future optimizations (e.g. min/max pattern matching on X86).
6453 if (Mask.getOpcode() == ISD::SETCC) {
6454 EVT VT = N->getValueType(0);
6456 // Check if any splitting is required.
6457 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6458 TargetLowering::TypeSplitVector)
6461 SDValue MaskLo, MaskHi, Lo, Hi;
6462 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6464 SDValue Src0 = MLD->getSrc0();
6465 SDValue Src0Lo, Src0Hi;
6466 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6469 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6471 SDValue Chain = MLD->getChain();
6472 SDValue Ptr = MLD->getBasePtr();
6473 EVT MemoryVT = MLD->getMemoryVT();
6474 unsigned Alignment = MLD->getOriginalAlignment();
6476 // if Alignment is equal to the vector size,
6477 // take the half of it for the second part
6478 unsigned SecondHalfAlignment =
6479 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6480 Alignment/2 : Alignment;
6482 EVT LoMemVT, HiMemVT;
6483 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6485 MachineMemOperand *MMO = DAG.getMachineFunction().
6486 getMachineMemOperand(MLD->getPointerInfo(),
6487 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6488 Alignment, MLD->getAAInfo(), MLD->getRanges());
6490 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6491 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6493 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6494 MLD->isExpandingLoad());
6496 MMO = DAG.getMachineFunction().
6497 getMachineMemOperand(MLD->getPointerInfo(),
6498 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
6499 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6501 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6502 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6504 AddToWorklist(Lo.getNode());
6505 AddToWorklist(Hi.getNode());
6507 // Build a factor node to remember that this load is independent of the
6509 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6512 // Legalized the chain result - switch anything that used the old chain to
6514 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6516 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6518 SDValue RetOps[] = { LoadRes, Chain };
6519 return DAG.getMergeValues(RetOps, DL);
6524 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6525 SDValue N0 = N->getOperand(0);
6526 SDValue N1 = N->getOperand(1);
6527 SDValue N2 = N->getOperand(2);
6530 // fold (vselect C, X, X) -> X
6534 // Canonicalize integer abs.
6535 // vselect (setg[te] X, 0), X, -X ->
6536 // vselect (setgt X, -1), X, -X ->
6537 // vselect (setl[te] X, 0), -X, X ->
6538 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6539 if (N0.getOpcode() == ISD::SETCC) {
6540 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6541 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6543 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6545 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6546 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6547 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6548 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6549 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6550 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6551 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6554 EVT VT = LHS.getValueType();
6555 SDValue Shift = DAG.getNode(
6556 ISD::SRA, DL, VT, LHS,
6557 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6558 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6559 AddToWorklist(Shift.getNode());
6560 AddToWorklist(Add.getNode());
6561 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6565 if (SimplifySelectOps(N, N1, N2))
6566 return SDValue(N, 0); // Don't revisit N.
6568 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6569 if (ISD::isBuildVectorAllOnes(N0.getNode()))
6571 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6572 if (ISD::isBuildVectorAllZeros(N0.getNode()))
6575 // The ConvertSelectToConcatVector function is assuming both the above
6576 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6578 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6579 N2.getOpcode() == ISD::CONCAT_VECTORS &&
6580 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6581 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6588 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6589 SDValue N0 = N->getOperand(0);
6590 SDValue N1 = N->getOperand(1);
6591 SDValue N2 = N->getOperand(2);
6592 SDValue N3 = N->getOperand(3);
6593 SDValue N4 = N->getOperand(4);
6594 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6596 // fold select_cc lhs, rhs, x, x, cc -> x
6600 // Determine if the condition we're dealing with is constant
6601 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6602 CC, SDLoc(N), false)) {
6603 AddToWorklist(SCC.getNode());
6605 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6606 if (!SCCC->isNullValue())
6607 return N2; // cond always true -> true val
6609 return N3; // cond always false -> false val
6610 } else if (SCC->isUndef()) {
6611 // When the condition is UNDEF, just return the first operand. This is
6612 // coherent the DAG creation, no setcc node is created in this case
6614 } else if (SCC.getOpcode() == ISD::SETCC) {
6615 // Fold to a simpler select_cc
6616 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6617 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6622 // If we can fold this based on the true/false value, do so.
6623 if (SimplifySelectOps(N, N2, N3))
6624 return SDValue(N, 0); // Don't revisit N.
6626 // fold select_cc into other things, such as min/max/abs
6627 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6630 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6631 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6632 cast<CondCodeSDNode>(N->getOperand(2))->get(),
6636 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6637 SDValue LHS = N->getOperand(0);
6638 SDValue RHS = N->getOperand(1);
6639 SDValue Carry = N->getOperand(2);
6640 SDValue Cond = N->getOperand(3);
6642 // If Carry is false, fold to a regular SETCC.
6643 if (Carry.getOpcode() == ISD::CARRY_FALSE)
6644 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6649 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6650 /// a build_vector of constants.
6651 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6652 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6653 /// Vector extends are not folded if operations are legal; this is to
6654 /// avoid introducing illegal build_vector dag nodes.
6655 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6656 SelectionDAG &DAG, bool LegalTypes,
6657 bool LegalOperations) {
6658 unsigned Opcode = N->getOpcode();
6659 SDValue N0 = N->getOperand(0);
6660 EVT VT = N->getValueType(0);
6662 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6663 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6664 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6665 && "Expected EXTEND dag node in input!");
6667 // fold (sext c1) -> c1
6668 // fold (zext c1) -> c1
6669 // fold (aext c1) -> c1
6670 if (isa<ConstantSDNode>(N0))
6671 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6673 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6674 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6675 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6676 EVT SVT = VT.getScalarType();
6677 if (!(VT.isVector() &&
6678 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6679 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6682 // We can fold this node into a build_vector.
6683 unsigned VTBits = SVT.getSizeInBits();
6684 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6685 SmallVector<SDValue, 8> Elts;
6686 unsigned NumElts = VT.getVectorNumElements();
6689 for (unsigned i=0; i != NumElts; ++i) {
6690 SDValue Op = N0->getOperand(i);
6691 if (Op->isUndef()) {
6692 Elts.push_back(DAG.getUNDEF(SVT));
6697 // Get the constant value and if needed trunc it to the size of the type.
6698 // Nodes like build_vector might have constants wider than the scalar type.
6699 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6700 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6701 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6703 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6706 return DAG.getBuildVector(VT, DL, Elts).getNode();
6709 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6710 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6711 // transformation. Returns true if extension are possible and the above
6712 // mentioned transformation is profitable.
6713 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6715 SmallVectorImpl<SDNode *> &ExtendNodes,
6716 const TargetLowering &TLI) {
6717 bool HasCopyToRegUses = false;
6718 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6719 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6720 UE = N0.getNode()->use_end();
6725 if (UI.getUse().getResNo() != N0.getResNo())
6727 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6728 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6729 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6730 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6731 // Sign bits will be lost after a zext.
6734 for (unsigned i = 0; i != 2; ++i) {
6735 SDValue UseOp = User->getOperand(i);
6738 if (!isa<ConstantSDNode>(UseOp))
6743 ExtendNodes.push_back(User);
6746 // If truncates aren't free and there are users we can't
6747 // extend, it isn't worthwhile.
6750 // Remember if this value is live-out.
6751 if (User->getOpcode() == ISD::CopyToReg)
6752 HasCopyToRegUses = true;
6755 if (HasCopyToRegUses) {
6756 bool BothLiveOut = false;
6757 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6759 SDUse &Use = UI.getUse();
6760 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6766 // Both unextended and extended values are live out. There had better be
6767 // a good reason for the transformation.
6768 return ExtendNodes.size();
6773 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6774 SDValue Trunc, SDValue ExtLoad,
6775 const SDLoc &DL, ISD::NodeType ExtType) {
6776 // Extend SetCC uses if necessary.
6777 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6778 SDNode *SetCC = SetCCs[i];
6779 SmallVector<SDValue, 4> Ops;
6781 for (unsigned j = 0; j != 2; ++j) {
6782 SDValue SOp = SetCC->getOperand(j);
6784 Ops.push_back(ExtLoad);
6786 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6789 Ops.push_back(SetCC->getOperand(2));
6790 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6794 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6795 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6796 SDValue N0 = N->getOperand(0);
6797 EVT DstVT = N->getValueType(0);
6798 EVT SrcVT = N0.getValueType();
6800 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6801 N->getOpcode() == ISD::ZERO_EXTEND) &&
6802 "Unexpected node type (not an extend)!");
6804 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6805 // For example, on a target with legal v4i32, but illegal v8i32, turn:
6806 // (v8i32 (sext (v8i16 (load x))))
6808 // (v8i32 (concat_vectors (v4i32 (sextload x)),
6809 // (v4i32 (sextload (x + 16)))))
6810 // Where uses of the original load, i.e.:
6812 // are replaced with:
6814 // (v8i32 (concat_vectors (v4i32 (sextload x)),
6815 // (v4i32 (sextload (x + 16)))))))
6817 // This combine is only applicable to illegal, but splittable, vectors.
6818 // All legal types, and illegal non-vector types, are handled elsewhere.
6819 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6821 if (N0->getOpcode() != ISD::LOAD)
6824 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6826 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6827 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6828 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6831 SmallVector<SDNode *, 4> SetCCs;
6832 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6835 ISD::LoadExtType ExtType =
6836 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6838 // Try to split the vector types to get down to legal types.
6839 EVT SplitSrcVT = SrcVT;
6840 EVT SplitDstVT = DstVT;
6841 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6842 SplitSrcVT.getVectorNumElements() > 1) {
6843 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6844 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6847 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6851 const unsigned NumSplits =
6852 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6853 const unsigned Stride = SplitSrcVT.getStoreSize();
6854 SmallVector<SDValue, 4> Loads;
6855 SmallVector<SDValue, 4> Chains;
6857 SDValue BasePtr = LN0->getBasePtr();
6858 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6859 const unsigned Offset = Idx * Stride;
6860 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6862 SDValue SplitLoad = DAG.getExtLoad(
6863 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6864 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6865 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6867 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6868 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6870 Loads.push_back(SplitLoad.getValue(0));
6871 Chains.push_back(SplitLoad.getValue(1));
6874 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6875 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6878 AddToWorklist(NewChain.getNode());
6880 CombineTo(N, NewValue);
6882 // Replace uses of the original load (before extension)
6883 // with a truncate of the concatenated sextloaded vectors.
6885 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6886 CombineTo(N0.getNode(), Trunc, NewChain);
6887 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6888 (ISD::NodeType)N->getOpcode());
6889 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6892 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6893 SDValue N0 = N->getOperand(0);
6894 EVT VT = N->getValueType(0);
6897 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6899 return SDValue(Res, 0);
6901 // fold (sext (sext x)) -> (sext x)
6902 // fold (sext (aext x)) -> (sext x)
6903 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6904 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
6906 if (N0.getOpcode() == ISD::TRUNCATE) {
6907 // fold (sext (truncate (load x))) -> (sext (smaller load x))
6908 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6909 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6910 SDNode *oye = N0.getOperand(0).getNode();
6911 if (NarrowLoad.getNode() != N0.getNode()) {
6912 CombineTo(N0.getNode(), NarrowLoad);
6913 // CombineTo deleted the truncate, if needed, but not what's under it.
6916 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6919 // See if the value being truncated is already sign extended. If so, just
6920 // eliminate the trunc/sext pair.
6921 SDValue Op = N0.getOperand(0);
6922 unsigned OpBits = Op.getScalarValueSizeInBits();
6923 unsigned MidBits = N0.getScalarValueSizeInBits();
6924 unsigned DestBits = VT.getScalarSizeInBits();
6925 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6927 if (OpBits == DestBits) {
6928 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
6929 // bits, it is already ready.
6930 if (NumSignBits > DestBits-MidBits)
6932 } else if (OpBits < DestBits) {
6933 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
6934 // bits, just sext from i32.
6935 if (NumSignBits > OpBits-MidBits)
6936 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
6938 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
6939 // bits, just truncate to i32.
6940 if (NumSignBits > OpBits-MidBits)
6941 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
6944 // fold (sext (truncate x)) -> (sextinreg x).
6945 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6946 N0.getValueType())) {
6947 if (OpBits < DestBits)
6948 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6949 else if (OpBits > DestBits)
6950 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6951 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
6952 DAG.getValueType(N0.getValueType()));
6956 // fold (sext (load x)) -> (sext (truncate (sextload x)))
6957 // Only generate vector extloads when 1) they're legal, and 2) they are
6958 // deemed desirable by the target.
6959 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6960 ((!LegalOperations && !VT.isVector() &&
6961 !cast<LoadSDNode>(N0)->isVolatile()) ||
6962 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6963 bool DoXform = true;
6964 SmallVector<SDNode*, 4> SetCCs;
6965 if (!N0.hasOneUse())
6966 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6968 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6970 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6971 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
6972 LN0->getBasePtr(), N0.getValueType(),
6973 LN0->getMemOperand());
6974 CombineTo(N, ExtLoad);
6975 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6976 N0.getValueType(), ExtLoad);
6977 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6978 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
6979 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6983 // fold (sext (load x)) to multiple smaller sextloads.
6984 // Only on illegal but splittable vectors.
6985 if (SDValue ExtLoad = CombineExtLoad(N))
6988 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6989 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6990 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6991 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6992 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6993 EVT MemVT = LN0->getMemoryVT();
6994 if ((!LegalOperations && !LN0->isVolatile()) ||
6995 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6996 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
6997 LN0->getBasePtr(), MemVT,
6998 LN0->getMemOperand());
6999 CombineTo(N, ExtLoad);
7000 CombineTo(N0.getNode(),
7001 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7002 N0.getValueType(), ExtLoad),
7003 ExtLoad.getValue(1));
7004 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7008 // fold (sext (and/or/xor (load x), cst)) ->
7009 // (and/or/xor (sextload x), (sext cst))
7010 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7011 N0.getOpcode() == ISD::XOR) &&
7012 isa<LoadSDNode>(N0.getOperand(0)) &&
7013 N0.getOperand(1).getOpcode() == ISD::Constant &&
7014 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7015 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7016 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7017 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7018 bool DoXform = true;
7019 SmallVector<SDNode*, 4> SetCCs;
7020 if (!N0.hasOneUse())
7021 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7024 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7025 LN0->getChain(), LN0->getBasePtr(),
7027 LN0->getMemOperand());
7028 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7029 Mask = Mask.sext(VT.getSizeInBits());
7030 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7031 ExtLoad, DAG.getConstant(Mask, DL, VT));
7032 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7033 SDLoc(N0.getOperand(0)),
7034 N0.getOperand(0).getValueType(), ExtLoad);
7036 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7037 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7038 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7043 if (N0.getOpcode() == ISD::SETCC) {
7044 SDValue N00 = N0.getOperand(0);
7045 SDValue N01 = N0.getOperand(1);
7046 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7047 EVT N00VT = N0.getOperand(0).getValueType();
7049 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7050 // Only do this before legalize for now.
7051 if (VT.isVector() && !LegalOperations &&
7052 TLI.getBooleanContents(N00VT) ==
7053 TargetLowering::ZeroOrNegativeOneBooleanContent) {
7054 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7055 // of the same size as the compared operands. Only optimize sext(setcc())
7056 // if this is the case.
7057 EVT SVT = getSetCCResultType(N00VT);
7059 // We know that the # elements of the results is the same as the
7060 // # elements of the compare (and the # elements of the compare result
7061 // for that matter). Check to see that they are the same size. If so,
7062 // we know that the element size of the sext'd result matches the
7063 // element size of the compare operands.
7064 if (VT.getSizeInBits() == SVT.getSizeInBits())
7065 return DAG.getSetCC(DL, VT, N00, N01, CC);
7067 // If the desired elements are smaller or larger than the source
7068 // elements, we can use a matching integer vector type and then
7069 // truncate/sign extend.
7070 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7071 if (SVT == MatchingVecType) {
7072 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7073 return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7077 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7078 // Here, T can be 1 or -1, depending on the type of the setcc and
7079 // getBooleanContents().
7080 unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7082 // To determine the "true" side of the select, we need to know the high bit
7083 // of the value returned by the setcc if it evaluates to true.
7084 // If the type of the setcc is i1, then the true case of the select is just
7085 // sext(i1 1), that is, -1.
7086 // If the type of the setcc is larger (say, i8) then the value of the high
7087 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7088 // of the appropriate width.
7089 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7090 : TLI.getConstTrueVal(DAG, VT, DL);
7091 SDValue Zero = DAG.getConstant(0, DL, VT);
7093 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7096 if (!VT.isVector()) {
7097 EVT SetCCVT = getSetCCResultType(N00VT);
7098 // Don't do this transform for i1 because there's a select transform
7099 // that would reverse it.
7100 // TODO: We should not do this transform at all without a target hook
7101 // because a sext is likely cheaper than a select?
7102 if (SetCCVT.getScalarSizeInBits() != 1 &&
7103 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7104 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7105 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7110 // fold (sext x) -> (zext x) if the sign bit is known zero.
7111 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7112 DAG.SignBitIsZero(N0))
7113 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7118 // isTruncateOf - If N is a truncate of some other value, return true, record
7119 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
7120 // This function computes KnownZero to avoid a duplicated call to
7121 // computeKnownBits in the caller.
7122 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7125 if (N->getOpcode() == ISD::TRUNCATE) {
7126 Op = N->getOperand(0);
7127 DAG.computeKnownBits(Op, KnownZero, KnownOne);
7131 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7132 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7135 SDValue Op0 = N->getOperand(0);
7136 SDValue Op1 = N->getOperand(1);
7137 assert(Op0.getValueType() == Op1.getValueType());
7139 if (isNullConstant(Op0))
7141 else if (isNullConstant(Op1))
7146 DAG.computeKnownBits(Op, KnownZero, KnownOne);
7148 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
7154 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7155 SDValue N0 = N->getOperand(0);
7156 EVT VT = N->getValueType(0);
7158 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7160 return SDValue(Res, 0);
7162 // fold (zext (zext x)) -> (zext x)
7163 // fold (zext (aext x)) -> (zext x)
7164 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7165 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7168 // fold (zext (truncate x)) -> (zext x) or
7169 // (zext (truncate x)) -> (truncate x)
7170 // This is valid when the truncated bits of x are already zero.
7171 // FIXME: We should extend this to work for vectors too.
7174 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
7175 APInt TruncatedBits =
7176 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7177 APInt(Op.getValueSizeInBits(), 0) :
7178 APInt::getBitsSet(Op.getValueSizeInBits(),
7179 N0.getValueSizeInBits(),
7180 std::min(Op.getValueSizeInBits(),
7181 VT.getSizeInBits()));
7182 if (TruncatedBits == (KnownZero & TruncatedBits)) {
7183 if (VT.bitsGT(Op.getValueType()))
7184 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
7185 if (VT.bitsLT(Op.getValueType()))
7186 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
7192 // fold (zext (truncate (load x))) -> (zext (smaller load x))
7193 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7194 if (N0.getOpcode() == ISD::TRUNCATE) {
7195 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7196 SDNode *oye = N0.getOperand(0).getNode();
7197 if (NarrowLoad.getNode() != N0.getNode()) {
7198 CombineTo(N0.getNode(), NarrowLoad);
7199 // CombineTo deleted the truncate, if needed, but not what's under it.
7202 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7206 // fold (zext (truncate x)) -> (and x, mask)
7207 if (N0.getOpcode() == ISD::TRUNCATE) {
7208 // fold (zext (truncate (load x))) -> (zext (smaller load x))
7209 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7210 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7211 SDNode *oye = N0.getOperand(0).getNode();
7212 if (NarrowLoad.getNode() != N0.getNode()) {
7213 CombineTo(N0.getNode(), NarrowLoad);
7214 // CombineTo deleted the truncate, if needed, but not what's under it.
7217 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7220 EVT SrcVT = N0.getOperand(0).getValueType();
7221 EVT MinVT = N0.getValueType();
7223 // Try to mask before the extension to avoid having to generate a larger mask,
7224 // possibly over several sub-vectors.
7225 if (SrcVT.bitsLT(VT)) {
7226 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7227 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7228 SDValue Op = N0.getOperand(0);
7229 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7230 AddToWorklist(Op.getNode());
7231 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7235 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7236 SDValue Op = N0.getOperand(0);
7237 if (SrcVT.bitsLT(VT)) {
7238 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
7239 AddToWorklist(Op.getNode());
7240 } else if (SrcVT.bitsGT(VT)) {
7241 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
7242 AddToWorklist(Op.getNode());
7244 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7248 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7249 // if either of the casts is not free.
7250 if (N0.getOpcode() == ISD::AND &&
7251 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7252 N0.getOperand(1).getOpcode() == ISD::Constant &&
7253 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7254 N0.getValueType()) ||
7255 !TLI.isZExtFree(N0.getValueType(), VT))) {
7256 SDValue X = N0.getOperand(0).getOperand(0);
7257 if (X.getValueType().bitsLT(VT)) {
7258 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
7259 } else if (X.getValueType().bitsGT(VT)) {
7260 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7262 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7263 Mask = Mask.zext(VT.getSizeInBits());
7265 return DAG.getNode(ISD::AND, DL, VT,
7266 X, DAG.getConstant(Mask, DL, VT));
7269 // fold (zext (load x)) -> (zext (truncate (zextload x)))
7270 // Only generate vector extloads when 1) they're legal, and 2) they are
7271 // deemed desirable by the target.
7272 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7273 ((!LegalOperations && !VT.isVector() &&
7274 !cast<LoadSDNode>(N0)->isVolatile()) ||
7275 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7276 bool DoXform = true;
7277 SmallVector<SDNode*, 4> SetCCs;
7278 if (!N0.hasOneUse())
7279 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7281 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7283 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7284 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7286 LN0->getBasePtr(), N0.getValueType(),
7287 LN0->getMemOperand());
7289 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7290 N0.getValueType(), ExtLoad);
7291 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7293 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7295 CombineTo(N, ExtLoad);
7296 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7300 // fold (zext (load x)) to multiple smaller zextloads.
7301 // Only on illegal but splittable vectors.
7302 if (SDValue ExtLoad = CombineExtLoad(N))
7305 // fold (zext (and/or/xor (load x), cst)) ->
7306 // (and/or/xor (zextload x), (zext cst))
7307 // Unless (and (load x) cst) will match as a zextload already and has
7308 // additional users.
7309 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7310 N0.getOpcode() == ISD::XOR) &&
7311 isa<LoadSDNode>(N0.getOperand(0)) &&
7312 N0.getOperand(1).getOpcode() == ISD::Constant &&
7313 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7314 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7315 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7316 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7317 bool DoXform = true;
7318 SmallVector<SDNode*, 4> SetCCs;
7319 if (!N0.hasOneUse()) {
7320 if (N0.getOpcode() == ISD::AND) {
7321 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7322 auto NarrowLoad = false;
7323 EVT LoadResultTy = AndC->getValueType(0);
7324 EVT ExtVT, LoadedVT;
7325 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7330 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7331 ISD::ZERO_EXTEND, SetCCs, TLI);
7334 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7335 LN0->getChain(), LN0->getBasePtr(),
7337 LN0->getMemOperand());
7338 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7339 Mask = Mask.zext(VT.getSizeInBits());
7341 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7342 ExtLoad, DAG.getConstant(Mask, DL, VT));
7343 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7344 SDLoc(N0.getOperand(0)),
7345 N0.getOperand(0).getValueType(), ExtLoad);
7347 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7348 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
7350 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7355 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7356 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7357 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7358 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7359 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7360 EVT MemVT = LN0->getMemoryVT();
7361 if ((!LegalOperations && !LN0->isVolatile()) ||
7362 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7363 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7365 LN0->getBasePtr(), MemVT,
7366 LN0->getMemOperand());
7367 CombineTo(N, ExtLoad);
7368 CombineTo(N0.getNode(),
7369 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7371 ExtLoad.getValue(1));
7372 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7376 if (N0.getOpcode() == ISD::SETCC) {
7377 // Only do this before legalize for now.
7378 if (!LegalOperations && VT.isVector() &&
7379 N0.getValueType().getVectorElementType() == MVT::i1) {
7380 EVT N00VT = N0.getOperand(0).getValueType();
7381 if (getSetCCResultType(N00VT) == N0.getValueType())
7384 // We know that the # elements of the results is the same as the #
7385 // elements of the compare (and the # elements of the compare result for
7386 // that matter). Check to see that they are the same size. If so, we know
7387 // that the element size of the sext'd result matches the element size of
7388 // the compare operands.
7390 SDValue VecOnes = DAG.getConstant(1, DL, VT);
7391 if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7392 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7393 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7394 N0.getOperand(1), N0.getOperand(2));
7395 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7398 // If the desired elements are smaller or larger than the source
7399 // elements we can use a matching integer vector type and then
7400 // truncate/sign extend.
7401 EVT MatchingElementType = EVT::getIntegerVT(
7402 *DAG.getContext(), N00VT.getScalarSizeInBits());
7403 EVT MatchingVectorType = EVT::getVectorVT(
7404 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7406 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7407 N0.getOperand(1), N0.getOperand(2));
7408 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7412 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7414 if (SDValue SCC = SimplifySelectCC(
7415 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7416 DAG.getConstant(0, DL, VT),
7417 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7421 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7422 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7423 isa<ConstantSDNode>(N0.getOperand(1)) &&
7424 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7426 SDValue ShAmt = N0.getOperand(1);
7427 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7428 if (N0.getOpcode() == ISD::SHL) {
7429 SDValue InnerZExt = N0.getOperand(0);
7430 // If the original shl may be shifting out bits, do not perform this
7432 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7433 InnerZExt.getOperand(0).getValueSizeInBits();
7434 if (ShAmtVal > KnownZeroBits)
7440 // Ensure that the shift amount is wide enough for the shifted value.
7441 if (VT.getSizeInBits() >= 256)
7442 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7444 return DAG.getNode(N0.getOpcode(), DL, VT,
7445 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7452 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7453 SDValue N0 = N->getOperand(0);
7454 EVT VT = N->getValueType(0);
7456 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7458 return SDValue(Res, 0);
7460 // fold (aext (aext x)) -> (aext x)
7461 // fold (aext (zext x)) -> (zext x)
7462 // fold (aext (sext x)) -> (sext x)
7463 if (N0.getOpcode() == ISD::ANY_EXTEND ||
7464 N0.getOpcode() == ISD::ZERO_EXTEND ||
7465 N0.getOpcode() == ISD::SIGN_EXTEND)
7466 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7468 // fold (aext (truncate (load x))) -> (aext (smaller load x))
7469 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7470 if (N0.getOpcode() == ISD::TRUNCATE) {
7471 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7472 SDNode *oye = N0.getOperand(0).getNode();
7473 if (NarrowLoad.getNode() != N0.getNode()) {
7474 CombineTo(N0.getNode(), NarrowLoad);
7475 // CombineTo deleted the truncate, if needed, but not what's under it.
7478 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7482 // fold (aext (truncate x))
7483 if (N0.getOpcode() == ISD::TRUNCATE) {
7484 SDValue TruncOp = N0.getOperand(0);
7485 if (TruncOp.getValueType() == VT)
7486 return TruncOp; // x iff x size == zext size.
7487 if (TruncOp.getValueType().bitsGT(VT))
7488 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
7489 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
7492 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7493 // if the trunc is not free.
7494 if (N0.getOpcode() == ISD::AND &&
7495 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7496 N0.getOperand(1).getOpcode() == ISD::Constant &&
7497 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7498 N0.getValueType())) {
7500 SDValue X = N0.getOperand(0).getOperand(0);
7501 if (X.getValueType().bitsLT(VT)) {
7502 X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
7503 } else if (X.getValueType().bitsGT(VT)) {
7504 X = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
7506 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7507 Mask = Mask.zext(VT.getSizeInBits());
7508 return DAG.getNode(ISD::AND, DL, VT,
7509 X, DAG.getConstant(Mask, DL, VT));
7512 // fold (aext (load x)) -> (aext (truncate (extload x)))
7513 // None of the supported targets knows how to perform load and any_ext
7514 // on vectors in one instruction. We only perform this transformation on
7516 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7517 ISD::isUNINDEXEDLoad(N0.getNode()) &&
7518 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7519 bool DoXform = true;
7520 SmallVector<SDNode*, 4> SetCCs;
7521 if (!N0.hasOneUse())
7522 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7524 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7525 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7527 LN0->getBasePtr(), N0.getValueType(),
7528 LN0->getMemOperand());
7529 CombineTo(N, ExtLoad);
7530 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7531 N0.getValueType(), ExtLoad);
7532 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7533 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7535 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7539 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7540 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7541 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
7542 if (N0.getOpcode() == ISD::LOAD &&
7543 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7545 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7546 ISD::LoadExtType ExtType = LN0->getExtensionType();
7547 EVT MemVT = LN0->getMemoryVT();
7548 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7549 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7550 VT, LN0->getChain(), LN0->getBasePtr(),
7551 MemVT, LN0->getMemOperand());
7552 CombineTo(N, ExtLoad);
7553 CombineTo(N0.getNode(),
7554 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7555 N0.getValueType(), ExtLoad),
7556 ExtLoad.getValue(1));
7557 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7561 if (N0.getOpcode() == ISD::SETCC) {
7563 // aext(setcc) -> vsetcc
7564 // aext(setcc) -> truncate(vsetcc)
7565 // aext(setcc) -> aext(vsetcc)
7566 // Only do this before legalize for now.
7567 if (VT.isVector() && !LegalOperations) {
7568 EVT N0VT = N0.getOperand(0).getValueType();
7569 // We know that the # elements of the results is the same as the
7570 // # elements of the compare (and the # elements of the compare result
7571 // for that matter). Check to see that they are the same size. If so,
7572 // we know that the element size of the sext'd result matches the
7573 // element size of the compare operands.
7574 if (VT.getSizeInBits() == N0VT.getSizeInBits())
7575 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7577 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7578 // If the desired elements are smaller or larger than the source
7579 // elements we can use a matching integer vector type and then
7580 // truncate/any extend
7582 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7584 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7586 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7587 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7591 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7593 if (SDValue SCC = SimplifySelectCC(
7594 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7595 DAG.getConstant(0, DL, VT),
7596 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7603 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7604 SDValue N0 = N->getOperand(0);
7605 SDValue N1 = N->getOperand(1);
7606 EVT EVT = cast<VTSDNode>(N1)->getVT();
7608 // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7609 if (N0.getOpcode() == ISD::AssertZext &&
7610 EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7616 /// See if the specified operand can be simplified with the knowledge that only
7617 /// the bits specified by Mask are used. If so, return the simpler operand,
7618 /// otherwise return a null SDValue.
7620 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7621 /// simplify nodes with multiple uses more aggressively.)
7622 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7623 switch (V.getOpcode()) {
7625 case ISD::Constant: {
7626 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7627 assert(CV && "Const value should be ConstSDNode.");
7628 const APInt &CVal = CV->getAPIntValue();
7629 APInt NewVal = CVal & Mask;
7631 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7636 // If the LHS or RHS don't contribute bits to the or, drop them.
7637 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7638 return V.getOperand(1);
7639 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7640 return V.getOperand(0);
7643 // Only look at single-use SRLs.
7644 if (!V.getNode()->hasOneUse())
7646 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7647 // See if we can recursively simplify the LHS.
7648 unsigned Amt = RHSC->getZExtValue();
7650 // Watch out for shift count overflow though.
7651 if (Amt >= Mask.getBitWidth()) break;
7652 APInt NewMask = Mask << Amt;
7653 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7654 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7655 SimplifyLHS, V.getOperand(1));
7659 // X & -1 -> X (ignoring bits which aren't demanded).
7660 ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7661 if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7662 return V.getOperand(0);
7669 /// If the result of a wider load is shifted to right of N bits and then
7670 /// truncated to a narrower type and where N is a multiple of number of bits of
7671 /// the narrower type, transform it to a narrower load from address + N / num of
7672 /// bits of new type. If the result is to be extended, also fold the extension
7673 /// to form a extending load.
7674 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7675 unsigned Opc = N->getOpcode();
7677 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7678 SDValue N0 = N->getOperand(0);
7679 EVT VT = N->getValueType(0);
7682 // This transformation isn't valid for vector loads.
7686 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7688 if (Opc == ISD::SIGN_EXTEND_INREG) {
7689 ExtType = ISD::SEXTLOAD;
7690 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7691 } else if (Opc == ISD::SRL) {
7692 // Another special-case: SRL is basically zero-extending a narrower value.
7693 ExtType = ISD::ZEXTLOAD;
7695 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7696 if (!N01) return SDValue();
7697 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7698 VT.getSizeInBits() - N01->getZExtValue());
7700 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7703 unsigned EVTBits = ExtVT.getSizeInBits();
7705 // Do not generate loads of non-round integer types since these can
7706 // be expensive (and would be wrong if the type is not byte sized).
7707 if (!ExtVT.isRound())
7711 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7712 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7713 ShAmt = N01->getZExtValue();
7714 // Is the shift amount a multiple of size of VT?
7715 if ((ShAmt & (EVTBits-1)) == 0) {
7716 N0 = N0.getOperand(0);
7717 // Is the load width a multiple of size of VT?
7718 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7722 // At this point, we must have a load or else we can't do the transform.
7723 if (!isa<LoadSDNode>(N0)) return SDValue();
7725 // Because a SRL must be assumed to *need* to zero-extend the high bits
7726 // (as opposed to anyext the high bits), we can't combine the zextload
7727 // lowering of SRL and an sextload.
7728 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7731 // If the shift amount is larger than the input type then we're not
7732 // accessing any of the loaded bytes. If the load was a zextload/extload
7733 // then the result of the shift+trunc is zero/undef (handled elsewhere).
7734 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7739 // If the load is shifted left (and the result isn't shifted back right),
7740 // we can fold the truncate through the shift.
7741 unsigned ShLeftAmt = 0;
7742 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7743 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7744 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7745 ShLeftAmt = N01->getZExtValue();
7746 N0 = N0.getOperand(0);
7750 // If we haven't found a load, we can't narrow it. Don't transform one with
7751 // multiple uses, this would require adding a new load.
7752 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7755 // Don't change the width of a volatile load.
7756 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7757 if (LN0->isVolatile())
7760 // Verify that we are actually reducing a load width here.
7761 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7764 // For the transform to be legal, the load must produce only two values
7765 // (the value loaded and the chain). Don't transform a pre-increment
7766 // load, for example, which produces an extra value. Otherwise the
7767 // transformation is not equivalent, and the downstream logic to replace
7768 // uses gets things wrong.
7769 if (LN0->getNumValues() > 2)
7772 // If the load that we're shrinking is an extload and we're not just
7773 // discarding the extension we can't simply shrink the load. Bail.
7774 // TODO: It would be possible to merge the extensions in some cases.
7775 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7776 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7779 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7782 EVT PtrType = N0.getOperand(1).getValueType();
7784 if (PtrType == MVT::Untyped || PtrType.isExtended())
7785 // It's not possible to generate a constant of extended or untyped type.
7788 // For big endian targets, we need to adjust the offset to the pointer to
7789 // load the correct bytes.
7790 if (DAG.getDataLayout().isBigEndian()) {
7791 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7792 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7793 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7796 uint64_t PtrOff = ShAmt / 8;
7797 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7799 // The original load itself didn't wrap, so an offset within it doesn't.
7801 Flags.setNoUnsignedWrap(true);
7802 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7803 PtrType, LN0->getBasePtr(),
7804 DAG.getConstant(PtrOff, DL, PtrType),
7806 AddToWorklist(NewPtr.getNode());
7809 if (ExtType == ISD::NON_EXTLOAD)
7810 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7811 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7812 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7814 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7815 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7816 NewAlign, LN0->getMemOperand()->getFlags(),
7819 // Replace the old load's chain with the new load's chain.
7820 WorklistRemover DeadNodes(*this);
7821 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7823 // Shift the result left, if we've swallowed a left shift.
7824 SDValue Result = Load;
7825 if (ShLeftAmt != 0) {
7826 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7827 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7829 // If the shift amount is as large as the result size (but, presumably,
7830 // no larger than the source) then the useful bits of the result are
7831 // zero; we can't simply return the shortened shift, because the result
7832 // of that operation is undefined.
7834 if (ShLeftAmt >= VT.getSizeInBits())
7835 Result = DAG.getConstant(0, DL, VT);
7837 Result = DAG.getNode(ISD::SHL, DL, VT,
7838 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7841 // Return the new loaded value.
7845 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7846 SDValue N0 = N->getOperand(0);
7847 SDValue N1 = N->getOperand(1);
7848 EVT VT = N->getValueType(0);
7849 EVT EVT = cast<VTSDNode>(N1)->getVT();
7850 unsigned VTBits = VT.getScalarSizeInBits();
7851 unsigned EVTBits = EVT.getScalarSizeInBits();
7854 return DAG.getUNDEF(VT);
7856 // fold (sext_in_reg c1) -> c1
7857 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7858 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7860 // If the input is already sign extended, just drop the extension.
7861 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7864 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7865 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7866 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7867 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7868 N0.getOperand(0), N1);
7870 // fold (sext_in_reg (sext x)) -> (sext x)
7871 // fold (sext_in_reg (aext x)) -> (sext x)
7872 // if x is small enough.
7873 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7874 SDValue N00 = N0.getOperand(0);
7875 if (N00.getScalarValueSizeInBits() <= EVTBits &&
7876 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7877 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7880 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
7881 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
7882 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
7883 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
7884 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
7885 if (!LegalOperations ||
7886 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
7887 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
7890 // fold (sext_in_reg (zext x)) -> (sext x)
7891 // iff we are extending the source sign bit.
7892 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
7893 SDValue N00 = N0.getOperand(0);
7894 if (N00.getScalarValueSizeInBits() == EVTBits &&
7895 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7896 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7899 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7900 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
7901 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7903 // fold operands of sext_in_reg based on knowledge that the top bits are not
7905 if (SimplifyDemandedBits(SDValue(N, 0)))
7906 return SDValue(N, 0);
7908 // fold (sext_in_reg (load x)) -> (smaller sextload x)
7909 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7910 if (SDValue NarrowLoad = ReduceLoadWidth(N))
7913 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7914 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7915 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7916 if (N0.getOpcode() == ISD::SRL) {
7917 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7918 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7919 // We can turn this into an SRA iff the input to the SRL is already sign
7921 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7922 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7923 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7924 N0.getOperand(0), N0.getOperand(1));
7928 // fold (sext_inreg (extload x)) -> (sextload x)
7929 if (ISD::isEXTLoad(N0.getNode()) &&
7930 ISD::isUNINDEXEDLoad(N0.getNode()) &&
7931 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7932 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7933 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7934 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7935 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7937 LN0->getBasePtr(), EVT,
7938 LN0->getMemOperand());
7939 CombineTo(N, ExtLoad);
7940 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7941 AddToWorklist(ExtLoad.getNode());
7942 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7944 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7945 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7947 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7948 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7949 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7950 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7951 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7953 LN0->getBasePtr(), EVT,
7954 LN0->getMemOperand());
7955 CombineTo(N, ExtLoad);
7956 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7957 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7960 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7961 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7962 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7963 N0.getOperand(1), false))
7964 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7971 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7972 SDValue N0 = N->getOperand(0);
7973 EVT VT = N->getValueType(0);
7976 return DAG.getUNDEF(VT);
7978 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7980 return SDValue(Res, 0);
7985 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7986 SDValue N0 = N->getOperand(0);
7987 EVT VT = N->getValueType(0);
7990 return DAG.getUNDEF(VT);
7992 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7994 return SDValue(Res, 0);
7999 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8000 SDValue N0 = N->getOperand(0);
8001 EVT VT = N->getValueType(0);
8002 bool isLE = DAG.getDataLayout().isLittleEndian();
8005 if (N0.getValueType() == N->getValueType(0))
8007 // fold (truncate c1) -> c1
8008 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8009 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8010 // fold (truncate (truncate x)) -> (truncate x)
8011 if (N0.getOpcode() == ISD::TRUNCATE)
8012 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8013 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8014 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8015 N0.getOpcode() == ISD::SIGN_EXTEND ||
8016 N0.getOpcode() == ISD::ANY_EXTEND) {
8017 // if the source is smaller than the dest, we still need an extend.
8018 if (N0.getOperand(0).getValueType().bitsLT(VT))
8019 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8020 // if the source is larger than the dest, than we just need the truncate.
8021 if (N0.getOperand(0).getValueType().bitsGT(VT))
8022 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8023 // if the source and dest are the same type, we can drop both the extend
8024 // and the truncate.
8025 return N0.getOperand(0);
8028 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8029 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8032 // Fold extract-and-trunc into a narrow extract. For example:
8033 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8034 // i32 y = TRUNCATE(i64 x)
8036 // v16i8 b = BITCAST (v2i64 val)
8037 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8039 // Note: We only run this optimization after type legalization (which often
8040 // creates this pattern) and before operation legalization after which
8041 // we need to be more careful about the vector instructions that we generate.
8042 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8043 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8045 EVT VecTy = N0.getOperand(0).getValueType();
8046 EVT ExTy = N0.getValueType();
8047 EVT TrTy = N->getValueType(0);
8049 unsigned NumElem = VecTy.getVectorNumElements();
8050 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8052 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8053 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8055 SDValue EltNo = N0->getOperand(1);
8056 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8057 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8058 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8059 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8062 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8063 DAG.getBitcast(NVT, N0.getOperand(0)),
8064 DAG.getConstant(Index, DL, IndexTy));
8068 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8069 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8070 EVT SrcVT = N0.getValueType();
8071 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8072 TLI.isTruncateFree(SrcVT, VT)) {
8074 SDValue Cond = N0.getOperand(0);
8075 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8076 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8077 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8081 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8082 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8083 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8084 TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8085 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
8086 uint64_t Amt = CAmt->getZExtValue();
8087 unsigned Size = VT.getScalarSizeInBits();
8091 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8093 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8094 return DAG.getNode(ISD::SHL, SL, VT, Trunc,
8095 DAG.getConstant(Amt, SL, AmtVT));
8100 // Fold a series of buildvector, bitcast, and truncate if possible.
8102 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8103 // (2xi32 (buildvector x, y)).
8104 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8105 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8106 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8107 N0.getOperand(0).hasOneUse()) {
8109 SDValue BuildVect = N0.getOperand(0);
8110 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8111 EVT TruncVecEltTy = VT.getVectorElementType();
8113 // Check that the element types match.
8114 if (BuildVectEltTy == TruncVecEltTy) {
8115 // Now we only need to compute the offset of the truncated elements.
8116 unsigned BuildVecNumElts = BuildVect.getNumOperands();
8117 unsigned TruncVecNumElts = VT.getVectorNumElements();
8118 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8120 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8121 "Invalid number of elements");
8123 SmallVector<SDValue, 8> Opnds;
8124 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8125 Opnds.push_back(BuildVect.getOperand(i));
8127 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8131 // See if we can simplify the input to this truncate through knowledge that
8132 // only the low bits are being used.
8133 // For example "trunc (or (shl x, 8), y)" // -> trunc y
8134 // Currently we only perform this optimization on scalars because vectors
8135 // may have different active low bits.
8136 if (!VT.isVector()) {
8137 if (SDValue Shorter =
8138 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8139 VT.getSizeInBits())))
8140 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8143 // fold (truncate (load x)) -> (smaller load x)
8144 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8145 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8146 if (SDValue Reduced = ReduceLoadWidth(N))
8149 // Handle the case where the load remains an extending load even
8150 // after truncation.
8151 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8152 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8153 if (!LN0->isVolatile() &&
8154 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8155 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8156 VT, LN0->getChain(), LN0->getBasePtr(),
8158 LN0->getMemOperand());
8159 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8165 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8166 // where ... are all 'undef'.
8167 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8168 SmallVector<EVT, 8> VTs;
8171 unsigned NumDefs = 0;
8173 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8174 SDValue X = N0.getOperand(i);
8180 // Stop if more than one members are non-undef.
8183 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8184 VT.getVectorElementType(),
8185 X.getValueType().getVectorNumElements()));
8189 return DAG.getUNDEF(VT);
8192 assert(V.getNode() && "The single defined operand is empty!");
8193 SmallVector<SDValue, 8> Opnds;
8194 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8196 Opnds.push_back(DAG.getUNDEF(VTs[i]));
8199 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8200 AddToWorklist(NV.getNode());
8201 Opnds.push_back(NV);
8203 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8207 // Fold truncate of a bitcast of a vector to an extract of the low vector
8210 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8211 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8212 SDValue VecSrc = N0.getOperand(0);
8213 EVT SrcVT = VecSrc.getValueType();
8214 if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8215 (!LegalOperations ||
8216 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8219 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8220 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8221 VecSrc, DAG.getConstant(0, SL, IdxVT));
8225 // Simplify the operands using demanded-bits information.
8226 if (!VT.isVector() &&
8227 SimplifyDemandedBits(SDValue(N, 0)))
8228 return SDValue(N, 0);
8230 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8231 // When the adde's carry is not used.
8232 if (N0.getOpcode() == ISD::ADDE && N0.hasOneUse() &&
8233 !N0.getNode()->hasAnyUseOfValue(1) &&
8234 (!LegalOperations || TLI.isOperationLegal(ISD::ADDE, VT))) {
8236 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8237 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8238 return DAG.getNode(ISD::ADDE, SL, DAG.getVTList(VT, MVT::Glue),
8239 X, Y, N0.getOperand(2));
8245 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8246 SDValue Elt = N->getOperand(i);
8247 if (Elt.getOpcode() != ISD::MERGE_VALUES)
8248 return Elt.getNode();
8249 return Elt.getOperand(Elt.getResNo()).getNode();
8252 /// build_pair (load, load) -> load
8253 /// if load locations are consecutive.
8254 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8255 assert(N->getOpcode() == ISD::BUILD_PAIR);
8257 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8258 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8259 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8260 LD1->getAddressSpace() != LD2->getAddressSpace())
8262 EVT LD1VT = LD1->getValueType(0);
8263 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8264 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8265 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8266 unsigned Align = LD1->getAlignment();
8267 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8268 VT.getTypeForEVT(*DAG.getContext()));
8270 if (NewAlign <= Align &&
8271 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8272 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8273 LD1->getPointerInfo(), Align);
8279 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8280 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8281 // and Lo parts; on big-endian machines it doesn't.
8282 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8285 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8286 const TargetLowering &TLI) {
8287 // If this is not a bitcast to an FP type or if the target doesn't have
8288 // IEEE754-compliant FP logic, we're done.
8289 EVT VT = N->getValueType(0);
8290 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8293 // TODO: Use splat values for the constant-checking below and remove this
8295 SDValue N0 = N->getOperand(0);
8296 EVT SourceVT = N0.getValueType();
8297 if (SourceVT.isVector())
8302 switch (N0.getOpcode()) {
8304 FPOpcode = ISD::FABS;
8305 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8308 FPOpcode = ISD::FNEG;
8309 SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8311 // TODO: ISD::OR --> ISD::FNABS?
8316 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8317 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8318 SDValue LogicOp0 = N0.getOperand(0);
8319 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8320 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8321 LogicOp0.getOpcode() == ISD::BITCAST &&
8322 LogicOp0->getOperand(0).getValueType() == VT)
8323 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8328 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8329 SDValue N0 = N->getOperand(0);
8330 EVT VT = N->getValueType(0);
8333 return DAG.getUNDEF(VT);
8335 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8336 // Only do this before legalize, since afterward the target may be depending
8337 // on the bitconvert.
8338 // First check to see if this is all constant.
8340 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8342 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8344 EVT DestEltVT = N->getValueType(0).getVectorElementType();
8345 assert(!DestEltVT.isVector() &&
8346 "Element type of vector ValueType must not be vector!");
8348 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8351 // If the input is a constant, let getNode fold it.
8352 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8353 // If we can't allow illegal operations, we need to check that this is just
8354 // a fp -> int or int -> conversion and that the resulting operation will
8356 if (!LegalOperations ||
8357 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8358 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8359 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8360 TLI.isOperationLegal(ISD::Constant, VT)))
8361 return DAG.getBitcast(VT, N0);
8364 // (conv (conv x, t1), t2) -> (conv x, t2)
8365 if (N0.getOpcode() == ISD::BITCAST)
8366 return DAG.getBitcast(VT, N0.getOperand(0));
8368 // fold (conv (load x)) -> (load (conv*)x)
8369 // If the resultant load doesn't need a higher alignment than the original!
8370 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8371 // Do not change the width of a volatile load.
8372 !cast<LoadSDNode>(N0)->isVolatile() &&
8373 // Do not remove the cast if the types differ in endian layout.
8374 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8375 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8376 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8377 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8378 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8379 unsigned OrigAlign = LN0->getAlignment();
8382 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8383 LN0->getAddressSpace(), OrigAlign, &Fast) &&
8386 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8387 LN0->getPointerInfo(), OrigAlign,
8388 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8389 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8394 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8397 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8398 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8401 // fold (bitcast (fneg x)) ->
8402 // flipbit = signbit
8403 // (xor (bitcast x) (build_pair flipbit, flipbit))
8405 // fold (bitcast (fabs x)) ->
8406 // flipbit = (and (extract_element (bitcast x), 0), signbit)
8407 // (xor (bitcast x) (build_pair flipbit, flipbit))
8408 // This often reduces constant pool loads.
8409 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8410 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8411 N0.getNode()->hasOneUse() && VT.isInteger() &&
8412 !VT.isVector() && !N0.getValueType().isVector()) {
8413 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8414 AddToWorklist(NewConv.getNode());
8417 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8418 assert(VT.getSizeInBits() == 128);
8419 SDValue SignBit = DAG.getConstant(
8420 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8422 if (N0.getOpcode() == ISD::FNEG) {
8424 AddToWorklist(FlipBit.getNode());
8426 assert(N0.getOpcode() == ISD::FABS);
8428 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8429 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8431 AddToWorklist(Hi.getNode());
8432 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8433 AddToWorklist(FlipBit.getNode());
8436 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8437 AddToWorklist(FlipBits.getNode());
8438 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8440 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8441 if (N0.getOpcode() == ISD::FNEG)
8442 return DAG.getNode(ISD::XOR, DL, VT,
8443 NewConv, DAG.getConstant(SignBit, DL, VT));
8444 assert(N0.getOpcode() == ISD::FABS);
8445 return DAG.getNode(ISD::AND, DL, VT,
8446 NewConv, DAG.getConstant(~SignBit, DL, VT));
8449 // fold (bitconvert (fcopysign cst, x)) ->
8450 // (or (and (bitconvert x), sign), (and cst, (not sign)))
8451 // Note that we don't handle (copysign x, cst) because this can always be
8452 // folded to an fneg or fabs.
8455 // fold (bitcast (fcopysign cst, x)) ->
8456 // flipbit = (and (extract_element
8457 // (xor (bitcast cst), (bitcast x)), 0),
8459 // (xor (bitcast cst) (build_pair flipbit, flipbit))
8460 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8461 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8462 VT.isInteger() && !VT.isVector()) {
8463 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8464 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8465 if (isTypeLegal(IntXVT)) {
8466 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8467 AddToWorklist(X.getNode());
8469 // If X has a different width than the result/lhs, sext it or truncate it.
8470 unsigned VTWidth = VT.getSizeInBits();
8471 if (OrigXWidth < VTWidth) {
8472 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8473 AddToWorklist(X.getNode());
8474 } else if (OrigXWidth > VTWidth) {
8475 // To get the sign bit in the right place, we have to shift it right
8476 // before truncating.
8478 X = DAG.getNode(ISD::SRL, DL,
8479 X.getValueType(), X,
8480 DAG.getConstant(OrigXWidth-VTWidth, DL,
8482 AddToWorklist(X.getNode());
8483 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8484 AddToWorklist(X.getNode());
8487 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8488 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8489 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8490 AddToWorklist(Cst.getNode());
8491 SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8492 AddToWorklist(X.getNode());
8493 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8494 AddToWorklist(XorResult.getNode());
8495 SDValue XorResult64 = DAG.getNode(
8496 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8497 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8499 AddToWorklist(XorResult64.getNode());
8501 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8502 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8503 AddToWorklist(FlipBit.getNode());
8505 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8506 AddToWorklist(FlipBits.getNode());
8507 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8509 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8510 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8511 X, DAG.getConstant(SignBit, SDLoc(X), VT));
8512 AddToWorklist(X.getNode());
8514 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8515 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8516 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8517 AddToWorklist(Cst.getNode());
8519 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8523 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8524 if (N0.getOpcode() == ISD::BUILD_PAIR)
8525 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8528 // Remove double bitcasts from shuffles - this is often a legacy of
8529 // XformToShuffleWithZero being used to combine bitmaskings (of
8530 // float vectors bitcast to integer vectors) into shuffles.
8531 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8532 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8533 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8534 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8535 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8536 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8538 // If operands are a bitcast, peek through if it casts the original VT.
8539 // If operands are a constant, just bitcast back to original VT.
8540 auto PeekThroughBitcast = [&](SDValue Op) {
8541 if (Op.getOpcode() == ISD::BITCAST &&
8542 Op.getOperand(0).getValueType() == VT)
8543 return SDValue(Op.getOperand(0));
8544 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8545 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8546 return DAG.getBitcast(VT, Op);
8550 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8551 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8556 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8557 SmallVector<int, 8> NewMask;
8558 for (int M : SVN->getMask())
8559 for (int i = 0; i != MaskScale; ++i)
8560 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8562 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8564 std::swap(SV0, SV1);
8565 ShuffleVectorSDNode::commuteMask(NewMask);
8566 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8570 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8576 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8577 EVT VT = N->getValueType(0);
8578 return CombineConsecutiveLoads(N, VT);
8581 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8582 /// operands. DstEltVT indicates the destination element value type.
8583 SDValue DAGCombiner::
8584 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8585 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8587 // If this is already the right type, we're done.
8588 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8590 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8591 unsigned DstBitSize = DstEltVT.getSizeInBits();
8593 // If this is a conversion of N elements of one type to N elements of another
8594 // type, convert each element. This handles FP<->INT cases.
8595 if (SrcBitSize == DstBitSize) {
8596 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8597 BV->getValueType(0).getVectorNumElements());
8599 // Due to the FP element handling below calling this routine recursively,
8600 // we can end up with a scalar-to-vector node here.
8601 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8602 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8603 DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8605 SmallVector<SDValue, 8> Ops;
8606 for (SDValue Op : BV->op_values()) {
8607 // If the vector element type is not legal, the BUILD_VECTOR operands
8608 // are promoted and implicitly truncated. Make that explicit here.
8609 if (Op.getValueType() != SrcEltVT)
8610 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8611 Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8612 AddToWorklist(Ops.back().getNode());
8614 return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8617 // Otherwise, we're growing or shrinking the elements. To avoid having to
8618 // handle annoying details of growing/shrinking FP values, we convert them to
8620 if (SrcEltVT.isFloatingPoint()) {
8621 // Convert the input float vector to a int vector where the elements are the
8623 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8624 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8628 // Now we know the input is an integer vector. If the output is a FP type,
8629 // convert to integer first, then to FP of the right size.
8630 if (DstEltVT.isFloatingPoint()) {
8631 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8632 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8634 // Next, convert to FP elements of the same size.
8635 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8640 // Okay, we know the src/dst types are both integers of differing types.
8641 // Handling growing first.
8642 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8643 if (SrcBitSize < DstBitSize) {
8644 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8646 SmallVector<SDValue, 8> Ops;
8647 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8648 i += NumInputsPerOutput) {
8649 bool isLE = DAG.getDataLayout().isLittleEndian();
8650 APInt NewBits = APInt(DstBitSize, 0);
8651 bool EltIsUndef = true;
8652 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8653 // Shift the previously computed bits over.
8654 NewBits <<= SrcBitSize;
8655 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8656 if (Op.isUndef()) continue;
8659 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8660 zextOrTrunc(SrcBitSize).zext(DstBitSize);
8664 Ops.push_back(DAG.getUNDEF(DstEltVT));
8666 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8669 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8670 return DAG.getBuildVector(VT, DL, Ops);
8673 // Finally, this must be the case where we are shrinking elements: each input
8674 // turns into multiple outputs.
8675 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8676 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8677 NumOutputsPerInput*BV->getNumOperands());
8678 SmallVector<SDValue, 8> Ops;
8680 for (const SDValue &Op : BV->op_values()) {
8682 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8686 APInt OpVal = cast<ConstantSDNode>(Op)->
8687 getAPIntValue().zextOrTrunc(SrcBitSize);
8689 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8690 APInt ThisVal = OpVal.trunc(DstBitSize);
8691 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8692 OpVal.lshrInPlace(DstBitSize);
8695 // For big endian targets, swap the order of the pieces of each element.
8696 if (DAG.getDataLayout().isBigEndian())
8697 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8700 return DAG.getBuildVector(VT, DL, Ops);
8703 static bool isContractable(SDNode *N) {
8704 SDNodeFlags F = cast<BinaryWithFlagsSDNode>(N)->Flags;
8705 return F.hasAllowContract() || F.hasUnsafeAlgebra();
8708 /// Try to perform FMA combining on a given FADD node.
8709 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8710 SDValue N0 = N->getOperand(0);
8711 SDValue N1 = N->getOperand(1);
8712 EVT VT = N->getValueType(0);
8715 const TargetOptions &Options = DAG.getTarget().Options;
8717 // Floating-point multiply-add with intermediate rounding.
8718 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8720 // Floating-point multiply-add without intermediate rounding.
8722 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8723 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8725 // No valid opcode, do not combine.
8726 if (!HasFMAD && !HasFMA)
8729 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8730 Options.UnsafeFPMath || HasFMAD);
8731 // If the addition is not contractable, do not combine.
8732 if (!AllowFusionGlobally && !isContractable(N))
8735 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8736 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8739 // Always prefer FMAD to FMA for precision.
8740 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8741 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8742 bool LookThroughFPExt = TLI.isFPExtFree(VT);
8744 // Is the node an FMUL and contractable either due to global flags or
8746 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8747 if (N.getOpcode() != ISD::FMUL)
8749 return AllowFusionGlobally || isContractable(N.getNode());
8751 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8752 // prefer to fold the multiply with fewer uses.
8753 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8754 if (N0.getNode()->use_size() > N1.getNode()->use_size())
8758 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8759 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8760 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8761 N0.getOperand(0), N0.getOperand(1), N1);
8764 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8765 // Note: Commutes FADD operands.
8766 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8767 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8768 N1.getOperand(0), N1.getOperand(1), N0);
8771 // Look through FP_EXTEND nodes to do more combining.
8772 if (LookThroughFPExt) {
8773 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8774 if (N0.getOpcode() == ISD::FP_EXTEND) {
8775 SDValue N00 = N0.getOperand(0);
8776 if (isContractableFMUL(N00))
8777 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8778 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8780 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8781 N00.getOperand(1)), N1);
8784 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8785 // Note: Commutes FADD operands.
8786 if (N1.getOpcode() == ISD::FP_EXTEND) {
8787 SDValue N10 = N1.getOperand(0);
8788 if (isContractableFMUL(N10))
8789 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8790 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8792 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8793 N10.getOperand(1)), N0);
8797 // More folding opportunities when target permits.
8799 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8800 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8801 // are currently only supported on binary nodes.
8802 if (Options.UnsafeFPMath &&
8803 N0.getOpcode() == PreferredFusedOpcode &&
8804 N0.getOperand(2).getOpcode() == ISD::FMUL &&
8805 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
8806 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8807 N0.getOperand(0), N0.getOperand(1),
8808 DAG.getNode(PreferredFusedOpcode, SL, VT,
8809 N0.getOperand(2).getOperand(0),
8810 N0.getOperand(2).getOperand(1),
8814 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8815 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8816 // are currently only supported on binary nodes.
8817 if (Options.UnsafeFPMath &&
8818 N1->getOpcode() == PreferredFusedOpcode &&
8819 N1.getOperand(2).getOpcode() == ISD::FMUL &&
8820 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
8821 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8822 N1.getOperand(0), N1.getOperand(1),
8823 DAG.getNode(PreferredFusedOpcode, SL, VT,
8824 N1.getOperand(2).getOperand(0),
8825 N1.getOperand(2).getOperand(1),
8829 if (LookThroughFPExt) {
8830 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8831 // -> (fma x, y, (fma (fpext u), (fpext v), z))
8832 auto FoldFAddFMAFPExtFMul = [&] (
8833 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8834 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8835 DAG.getNode(PreferredFusedOpcode, SL, VT,
8836 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8837 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8840 if (N0.getOpcode() == PreferredFusedOpcode) {
8841 SDValue N02 = N0.getOperand(2);
8842 if (N02.getOpcode() == ISD::FP_EXTEND) {
8843 SDValue N020 = N02.getOperand(0);
8844 if (isContractableFMUL(N020))
8845 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8846 N020.getOperand(0), N020.getOperand(1),
8851 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8852 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8853 // FIXME: This turns two single-precision and one double-precision
8854 // operation into two double-precision operations, which might not be
8855 // interesting for all targets, especially GPUs.
8856 auto FoldFAddFPExtFMAFMul = [&] (
8857 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8858 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8859 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8860 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8861 DAG.getNode(PreferredFusedOpcode, SL, VT,
8862 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8863 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8866 if (N0.getOpcode() == ISD::FP_EXTEND) {
8867 SDValue N00 = N0.getOperand(0);
8868 if (N00.getOpcode() == PreferredFusedOpcode) {
8869 SDValue N002 = N00.getOperand(2);
8870 if (isContractableFMUL(N002))
8871 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8872 N002.getOperand(0), N002.getOperand(1),
8877 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8878 // -> (fma y, z, (fma (fpext u), (fpext v), x))
8879 if (N1.getOpcode() == PreferredFusedOpcode) {
8880 SDValue N12 = N1.getOperand(2);
8881 if (N12.getOpcode() == ISD::FP_EXTEND) {
8882 SDValue N120 = N12.getOperand(0);
8883 if (isContractableFMUL(N120))
8884 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8885 N120.getOperand(0), N120.getOperand(1),
8890 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8891 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8892 // FIXME: This turns two single-precision and one double-precision
8893 // operation into two double-precision operations, which might not be
8894 // interesting for all targets, especially GPUs.
8895 if (N1.getOpcode() == ISD::FP_EXTEND) {
8896 SDValue N10 = N1.getOperand(0);
8897 if (N10.getOpcode() == PreferredFusedOpcode) {
8898 SDValue N102 = N10.getOperand(2);
8899 if (isContractableFMUL(N102))
8900 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8901 N102.getOperand(0), N102.getOperand(1),
8911 /// Try to perform FMA combining on a given FSUB node.
8912 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8913 SDValue N0 = N->getOperand(0);
8914 SDValue N1 = N->getOperand(1);
8915 EVT VT = N->getValueType(0);
8918 const TargetOptions &Options = DAG.getTarget().Options;
8919 // Floating-point multiply-add with intermediate rounding.
8920 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8922 // Floating-point multiply-add without intermediate rounding.
8924 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8925 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8927 // No valid opcode, do not combine.
8928 if (!HasFMAD && !HasFMA)
8931 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8932 Options.UnsafeFPMath || HasFMAD);
8933 // If the subtraction is not contractable, do not combine.
8934 if (!AllowFusionGlobally && !isContractable(N))
8937 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8938 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8941 // Always prefer FMAD to FMA for precision.
8942 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8943 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8944 bool LookThroughFPExt = TLI.isFPExtFree(VT);
8946 // Is the node an FMUL and contractable either due to global flags or
8948 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8949 if (N.getOpcode() != ISD::FMUL)
8951 return AllowFusionGlobally || isContractable(N.getNode());
8954 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8955 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8956 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8957 N0.getOperand(0), N0.getOperand(1),
8958 DAG.getNode(ISD::FNEG, SL, VT, N1));
8961 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8962 // Note: Commutes FSUB operands.
8963 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
8964 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8965 DAG.getNode(ISD::FNEG, SL, VT,
8967 N1.getOperand(1), N0);
8969 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8970 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
8971 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8972 SDValue N00 = N0.getOperand(0).getOperand(0);
8973 SDValue N01 = N0.getOperand(0).getOperand(1);
8974 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8975 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8976 DAG.getNode(ISD::FNEG, SL, VT, N1));
8979 // Look through FP_EXTEND nodes to do more combining.
8980 if (LookThroughFPExt) {
8981 // fold (fsub (fpext (fmul x, y)), z)
8982 // -> (fma (fpext x), (fpext y), (fneg z))
8983 if (N0.getOpcode() == ISD::FP_EXTEND) {
8984 SDValue N00 = N0.getOperand(0);
8985 if (isContractableFMUL(N00))
8986 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8987 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8989 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8991 DAG.getNode(ISD::FNEG, SL, VT, N1));
8994 // fold (fsub x, (fpext (fmul y, z)))
8995 // -> (fma (fneg (fpext y)), (fpext z), x)
8996 // Note: Commutes FSUB operands.
8997 if (N1.getOpcode() == ISD::FP_EXTEND) {
8998 SDValue N10 = N1.getOperand(0);
8999 if (isContractableFMUL(N10))
9000 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9001 DAG.getNode(ISD::FNEG, SL, VT,
9002 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9003 N10.getOperand(0))),
9004 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9009 // fold (fsub (fpext (fneg (fmul, x, y))), z)
9010 // -> (fneg (fma (fpext x), (fpext y), z))
9011 // Note: This could be removed with appropriate canonicalization of the
9012 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9013 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9014 // from implementing the canonicalization in visitFSUB.
9015 if (N0.getOpcode() == ISD::FP_EXTEND) {
9016 SDValue N00 = N0.getOperand(0);
9017 if (N00.getOpcode() == ISD::FNEG) {
9018 SDValue N000 = N00.getOperand(0);
9019 if (isContractableFMUL(N000)) {
9020 return DAG.getNode(ISD::FNEG, SL, VT,
9021 DAG.getNode(PreferredFusedOpcode, SL, VT,
9022 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9023 N000.getOperand(0)),
9024 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9025 N000.getOperand(1)),
9031 // fold (fsub (fneg (fpext (fmul, x, y))), z)
9032 // -> (fneg (fma (fpext x)), (fpext y), z)
9033 // Note: This could be removed with appropriate canonicalization of the
9034 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9035 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9036 // from implementing the canonicalization in visitFSUB.
9037 if (N0.getOpcode() == ISD::FNEG) {
9038 SDValue N00 = N0.getOperand(0);
9039 if (N00.getOpcode() == ISD::FP_EXTEND) {
9040 SDValue N000 = N00.getOperand(0);
9041 if (isContractableFMUL(N000)) {
9042 return DAG.getNode(ISD::FNEG, SL, VT,
9043 DAG.getNode(PreferredFusedOpcode, SL, VT,
9044 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9045 N000.getOperand(0)),
9046 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9047 N000.getOperand(1)),
9055 // More folding opportunities when target permits.
9057 // fold (fsub (fma x, y, (fmul u, v)), z)
9058 // -> (fma x, y (fma u, v, (fneg z)))
9059 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9060 // are currently only supported on binary nodes.
9061 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9062 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9063 N0.getOperand(2)->hasOneUse()) {
9064 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9065 N0.getOperand(0), N0.getOperand(1),
9066 DAG.getNode(PreferredFusedOpcode, SL, VT,
9067 N0.getOperand(2).getOperand(0),
9068 N0.getOperand(2).getOperand(1),
9069 DAG.getNode(ISD::FNEG, SL, VT,
9073 // fold (fsub x, (fma y, z, (fmul u, v)))
9074 // -> (fma (fneg y), z, (fma (fneg u), v, x))
9075 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9076 // are currently only supported on binary nodes.
9077 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9078 isContractableFMUL(N1.getOperand(2))) {
9079 SDValue N20 = N1.getOperand(2).getOperand(0);
9080 SDValue N21 = N1.getOperand(2).getOperand(1);
9081 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9082 DAG.getNode(ISD::FNEG, SL, VT,
9085 DAG.getNode(PreferredFusedOpcode, SL, VT,
9086 DAG.getNode(ISD::FNEG, SL, VT, N20),
9091 if (LookThroughFPExt) {
9092 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9093 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9094 if (N0.getOpcode() == PreferredFusedOpcode) {
9095 SDValue N02 = N0.getOperand(2);
9096 if (N02.getOpcode() == ISD::FP_EXTEND) {
9097 SDValue N020 = N02.getOperand(0);
9098 if (isContractableFMUL(N020))
9099 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9100 N0.getOperand(0), N0.getOperand(1),
9101 DAG.getNode(PreferredFusedOpcode, SL, VT,
9102 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9103 N020.getOperand(0)),
9104 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9105 N020.getOperand(1)),
9106 DAG.getNode(ISD::FNEG, SL, VT,
9111 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9112 // -> (fma (fpext x), (fpext y),
9113 // (fma (fpext u), (fpext v), (fneg z)))
9114 // FIXME: This turns two single-precision and one double-precision
9115 // operation into two double-precision operations, which might not be
9116 // interesting for all targets, especially GPUs.
9117 if (N0.getOpcode() == ISD::FP_EXTEND) {
9118 SDValue N00 = N0.getOperand(0);
9119 if (N00.getOpcode() == PreferredFusedOpcode) {
9120 SDValue N002 = N00.getOperand(2);
9121 if (isContractableFMUL(N002))
9122 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9123 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9125 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9127 DAG.getNode(PreferredFusedOpcode, SL, VT,
9128 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9129 N002.getOperand(0)),
9130 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9131 N002.getOperand(1)),
9132 DAG.getNode(ISD::FNEG, SL, VT,
9137 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9138 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9139 if (N1.getOpcode() == PreferredFusedOpcode &&
9140 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9141 SDValue N120 = N1.getOperand(2).getOperand(0);
9142 if (isContractableFMUL(N120)) {
9143 SDValue N1200 = N120.getOperand(0);
9144 SDValue N1201 = N120.getOperand(1);
9145 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9146 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9148 DAG.getNode(PreferredFusedOpcode, SL, VT,
9149 DAG.getNode(ISD::FNEG, SL, VT,
9150 DAG.getNode(ISD::FP_EXTEND, SL,
9152 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9158 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9159 // -> (fma (fneg (fpext y)), (fpext z),
9160 // (fma (fneg (fpext u)), (fpext v), x))
9161 // FIXME: This turns two single-precision and one double-precision
9162 // operation into two double-precision operations, which might not be
9163 // interesting for all targets, especially GPUs.
9164 if (N1.getOpcode() == ISD::FP_EXTEND &&
9165 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9166 SDValue N100 = N1.getOperand(0).getOperand(0);
9167 SDValue N101 = N1.getOperand(0).getOperand(1);
9168 SDValue N102 = N1.getOperand(0).getOperand(2);
9169 if (isContractableFMUL(N102)) {
9170 SDValue N1020 = N102.getOperand(0);
9171 SDValue N1021 = N102.getOperand(1);
9172 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9173 DAG.getNode(ISD::FNEG, SL, VT,
9174 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9176 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9177 DAG.getNode(PreferredFusedOpcode, SL, VT,
9178 DAG.getNode(ISD::FNEG, SL, VT,
9179 DAG.getNode(ISD::FP_EXTEND, SL,
9181 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9192 /// Try to perform FMA combining on a given FMUL node based on the distributive
9193 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9194 /// subtraction instead of addition).
9195 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9196 SDValue N0 = N->getOperand(0);
9197 SDValue N1 = N->getOperand(1);
9198 EVT VT = N->getValueType(0);
9201 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9203 const TargetOptions &Options = DAG.getTarget().Options;
9205 // The transforms below are incorrect when x == 0 and y == inf, because the
9206 // intermediate multiplication produces a nan.
9207 if (!Options.NoInfsFPMath)
9210 // Floating-point multiply-add without intermediate rounding.
9212 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9213 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9214 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9216 // Floating-point multiply-add with intermediate rounding. This can result
9217 // in a less precise result due to the changed rounding order.
9218 bool HasFMAD = Options.UnsafeFPMath &&
9219 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9221 // No valid opcode, do not combine.
9222 if (!HasFMAD && !HasFMA)
9225 // Always prefer FMAD to FMA for precision.
9226 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9227 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9229 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9230 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9231 auto FuseFADD = [&](SDValue X, SDValue Y) {
9232 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9233 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9234 if (XC1 && XC1->isExactlyValue(+1.0))
9235 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9236 if (XC1 && XC1->isExactlyValue(-1.0))
9237 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9238 DAG.getNode(ISD::FNEG, SL, VT, Y));
9243 if (SDValue FMA = FuseFADD(N0, N1))
9245 if (SDValue FMA = FuseFADD(N1, N0))
9248 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9249 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9250 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9251 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9252 auto FuseFSUB = [&](SDValue X, SDValue Y) {
9253 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9254 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9255 if (XC0 && XC0->isExactlyValue(+1.0))
9256 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9257 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9259 if (XC0 && XC0->isExactlyValue(-1.0))
9260 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9261 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9262 DAG.getNode(ISD::FNEG, SL, VT, Y));
9264 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9265 if (XC1 && XC1->isExactlyValue(+1.0))
9266 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9267 DAG.getNode(ISD::FNEG, SL, VT, Y));
9268 if (XC1 && XC1->isExactlyValue(-1.0))
9269 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9274 if (SDValue FMA = FuseFSUB(N0, N1))
9276 if (SDValue FMA = FuseFSUB(N1, N0))
9282 SDValue DAGCombiner::visitFADD(SDNode *N) {
9283 SDValue N0 = N->getOperand(0);
9284 SDValue N1 = N->getOperand(1);
9285 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9286 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9287 EVT VT = N->getValueType(0);
9289 const TargetOptions &Options = DAG.getTarget().Options;
9290 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9294 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9297 // fold (fadd c1, c2) -> c1 + c2
9299 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9301 // canonicalize constant to RHS
9302 if (N0CFP && !N1CFP)
9303 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9305 if (SDValue NewSel = foldBinOpIntoSelect(N))
9308 // fold (fadd A, (fneg B)) -> (fsub A, B)
9309 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9310 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9311 return DAG.getNode(ISD::FSUB, DL, VT, N0,
9312 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9314 // fold (fadd (fneg A), B) -> (fsub B, A)
9315 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9316 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9317 return DAG.getNode(ISD::FSUB, DL, VT, N1,
9318 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9320 // FIXME: Auto-upgrade the target/function-level option.
9321 if (Options.NoSignedZerosFPMath || N->getFlags()->hasNoSignedZeros()) {
9322 // fold (fadd A, 0) -> A
9323 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9328 // If 'unsafe math' is enabled, fold lots of things.
9329 if (Options.UnsafeFPMath) {
9330 // No FP constant should be created after legalization as Instruction
9331 // Selection pass has a hard time dealing with FP constants.
9332 bool AllowNewConst = (Level < AfterLegalizeDAG);
9334 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9335 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9336 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9337 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9338 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9342 // If allowed, fold (fadd (fneg x), x) -> 0.0
9343 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9344 return DAG.getConstantFP(0.0, DL, VT);
9346 // If allowed, fold (fadd x, (fneg x)) -> 0.0
9347 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9348 return DAG.getConstantFP(0.0, DL, VT);
9350 // We can fold chains of FADD's of the same value into multiplications.
9351 // This transform is not safe in general because we are reducing the number
9352 // of rounding steps.
9353 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9354 if (N0.getOpcode() == ISD::FMUL) {
9355 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9356 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9358 // (fadd (fmul x, c), x) -> (fmul x, c+1)
9359 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9360 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9361 DAG.getConstantFP(1.0, DL, VT), Flags);
9362 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9365 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9366 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9367 N1.getOperand(0) == N1.getOperand(1) &&
9368 N0.getOperand(0) == N1.getOperand(0)) {
9369 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9370 DAG.getConstantFP(2.0, DL, VT), Flags);
9371 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9375 if (N1.getOpcode() == ISD::FMUL) {
9376 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9377 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9379 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9380 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9381 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9382 DAG.getConstantFP(1.0, DL, VT), Flags);
9383 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9386 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9387 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9388 N0.getOperand(0) == N0.getOperand(1) &&
9389 N1.getOperand(0) == N0.getOperand(0)) {
9390 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9391 DAG.getConstantFP(2.0, DL, VT), Flags);
9392 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9396 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9397 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9398 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9399 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9400 (N0.getOperand(0) == N1)) {
9401 return DAG.getNode(ISD::FMUL, DL, VT,
9402 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9406 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9407 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9408 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9409 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9410 N1.getOperand(0) == N0) {
9411 return DAG.getNode(ISD::FMUL, DL, VT,
9412 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9416 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9417 if (AllowNewConst &&
9418 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9419 N0.getOperand(0) == N0.getOperand(1) &&
9420 N1.getOperand(0) == N1.getOperand(1) &&
9421 N0.getOperand(0) == N1.getOperand(0)) {
9422 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9423 DAG.getConstantFP(4.0, DL, VT), Flags);
9426 } // enable-unsafe-fp-math
9428 // FADD -> FMA combines:
9429 if (SDValue Fused = visitFADDForFMACombine(N)) {
9430 AddToWorklist(Fused.getNode());
9436 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9437 SDValue N0 = N->getOperand(0);
9438 SDValue N1 = N->getOperand(1);
9439 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9440 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9441 EVT VT = N->getValueType(0);
9443 const TargetOptions &Options = DAG.getTarget().Options;
9444 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9448 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9451 // fold (fsub c1, c2) -> c1-c2
9453 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9455 if (SDValue NewSel = foldBinOpIntoSelect(N))
9458 // fold (fsub A, (fneg B)) -> (fadd A, B)
9459 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9460 return DAG.getNode(ISD::FADD, DL, VT, N0,
9461 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9463 // FIXME: Auto-upgrade the target/function-level option.
9464 if (Options.NoSignedZerosFPMath || N->getFlags()->hasNoSignedZeros()) {
9465 // (fsub 0, B) -> -B
9466 if (N0CFP && N0CFP->isZero()) {
9467 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9468 return GetNegatedExpression(N1, DAG, LegalOperations);
9469 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9470 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9474 // If 'unsafe math' is enabled, fold lots of things.
9475 if (Options.UnsafeFPMath) {
9477 if (N1CFP && N1CFP->isZero())
9480 // (fsub x, x) -> 0.0
9482 return DAG.getConstantFP(0.0f, DL, VT);
9484 // (fsub x, (fadd x, y)) -> (fneg y)
9485 // (fsub x, (fadd y, x)) -> (fneg y)
9486 if (N1.getOpcode() == ISD::FADD) {
9487 SDValue N10 = N1->getOperand(0);
9488 SDValue N11 = N1->getOperand(1);
9490 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9491 return GetNegatedExpression(N11, DAG, LegalOperations);
9493 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9494 return GetNegatedExpression(N10, DAG, LegalOperations);
9498 // FSUB -> FMA combines:
9499 if (SDValue Fused = visitFSUBForFMACombine(N)) {
9500 AddToWorklist(Fused.getNode());
9507 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9508 SDValue N0 = N->getOperand(0);
9509 SDValue N1 = N->getOperand(1);
9510 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9511 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9512 EVT VT = N->getValueType(0);
9514 const TargetOptions &Options = DAG.getTarget().Options;
9515 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9518 if (VT.isVector()) {
9519 // This just handles C1 * C2 for vectors. Other vector folds are below.
9520 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9524 // fold (fmul c1, c2) -> c1*c2
9526 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9528 // canonicalize constant to RHS
9529 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9530 !isConstantFPBuildVectorOrConstantFP(N1))
9531 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9533 // fold (fmul A, 1.0) -> A
9534 if (N1CFP && N1CFP->isExactlyValue(1.0))
9537 if (SDValue NewSel = foldBinOpIntoSelect(N))
9540 if (Options.UnsafeFPMath) {
9541 // fold (fmul A, 0) -> 0
9542 if (N1CFP && N1CFP->isZero())
9545 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9546 if (N0.getOpcode() == ISD::FMUL) {
9547 // Fold scalars or any vector constants (not just splats).
9548 // This fold is done in general by InstCombine, but extra fmul insts
9549 // may have been generated during lowering.
9550 SDValue N00 = N0.getOperand(0);
9551 SDValue N01 = N0.getOperand(1);
9552 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9553 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9554 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9556 // Check 1: Make sure that the first operand of the inner multiply is NOT
9557 // a constant. Otherwise, we may induce infinite looping.
9558 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9559 // Check 2: Make sure that the second operand of the inner multiply and
9560 // the second operand of the outer multiply are constants.
9561 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9562 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9563 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9564 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9569 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9570 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9571 // during an early run of DAGCombiner can prevent folding with fmuls
9572 // inserted during lowering.
9573 if (N0.getOpcode() == ISD::FADD &&
9574 (N0.getOperand(0) == N0.getOperand(1)) &&
9576 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9577 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9578 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9582 // fold (fmul X, 2.0) -> (fadd X, X)
9583 if (N1CFP && N1CFP->isExactlyValue(+2.0))
9584 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9586 // fold (fmul X, -1.0) -> (fneg X)
9587 if (N1CFP && N1CFP->isExactlyValue(-1.0))
9588 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9589 return DAG.getNode(ISD::FNEG, DL, VT, N0);
9591 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9592 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9593 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9594 // Both can be negated for free, check to see if at least one is cheaper
9596 if (LHSNeg == 2 || RHSNeg == 2)
9597 return DAG.getNode(ISD::FMUL, DL, VT,
9598 GetNegatedExpression(N0, DAG, LegalOperations),
9599 GetNegatedExpression(N1, DAG, LegalOperations),
9604 // FMUL -> FMA combines:
9605 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9606 AddToWorklist(Fused.getNode());
9613 SDValue DAGCombiner::visitFMA(SDNode *N) {
9614 SDValue N0 = N->getOperand(0);
9615 SDValue N1 = N->getOperand(1);
9616 SDValue N2 = N->getOperand(2);
9617 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9618 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9619 EVT VT = N->getValueType(0);
9621 const TargetOptions &Options = DAG.getTarget().Options;
9623 // Constant fold FMA.
9624 if (isa<ConstantFPSDNode>(N0) &&
9625 isa<ConstantFPSDNode>(N1) &&
9626 isa<ConstantFPSDNode>(N2)) {
9627 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9630 if (Options.UnsafeFPMath) {
9631 if (N0CFP && N0CFP->isZero())
9633 if (N1CFP && N1CFP->isZero())
9636 // TODO: The FMA node should have flags that propagate to these nodes.
9637 if (N0CFP && N0CFP->isExactlyValue(1.0))
9638 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9639 if (N1CFP && N1CFP->isExactlyValue(1.0))
9640 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9642 // Canonicalize (fma c, x, y) -> (fma x, c, y)
9643 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9644 !isConstantFPBuildVectorOrConstantFP(N1))
9645 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9647 // TODO: FMA nodes should have flags that propagate to the created nodes.
9648 // For now, create a Flags object for use with all unsafe math transforms.
9650 Flags.setUnsafeAlgebra(true);
9652 if (Options.UnsafeFPMath) {
9653 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9654 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9655 isConstantFPBuildVectorOrConstantFP(N1) &&
9656 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9657 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9658 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9662 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9663 if (N0.getOpcode() == ISD::FMUL &&
9664 isConstantFPBuildVectorOrConstantFP(N1) &&
9665 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9666 return DAG.getNode(ISD::FMA, DL, VT,
9668 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9674 // (fma x, 1, y) -> (fadd x, y)
9675 // (fma x, -1, y) -> (fadd (fneg x), y)
9677 if (N1CFP->isExactlyValue(1.0))
9678 // TODO: The FMA node should have flags that propagate to this node.
9679 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9681 if (N1CFP->isExactlyValue(-1.0) &&
9682 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9683 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9684 AddToWorklist(RHSNeg.getNode());
9685 // TODO: The FMA node should have flags that propagate to this node.
9686 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9690 if (Options.UnsafeFPMath) {
9691 // (fma x, c, x) -> (fmul x, (c+1))
9692 if (N1CFP && N0 == N2) {
9693 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9694 DAG.getNode(ISD::FADD, DL, VT, N1,
9695 DAG.getConstantFP(1.0, DL, VT), &Flags),
9699 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9700 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9701 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9702 DAG.getNode(ISD::FADD, DL, VT, N1,
9703 DAG.getConstantFP(-1.0, DL, VT), &Flags),
9711 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9713 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9714 // Notice that this is not always beneficial. One reason is different targets
9715 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9716 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9717 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9718 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9719 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9720 const SDNodeFlags *Flags = N->getFlags();
9721 if (!UnsafeMath && !Flags->hasAllowReciprocal())
9724 // Skip if current node is a reciprocal.
9725 SDValue N0 = N->getOperand(0);
9726 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9727 if (N0CFP && N0CFP->isExactlyValue(1.0))
9730 // Exit early if the target does not want this transform or if there can't
9731 // possibly be enough uses of the divisor to make the transform worthwhile.
9732 SDValue N1 = N->getOperand(1);
9733 unsigned MinUses = TLI.combineRepeatedFPDivisors();
9734 if (!MinUses || N1->use_size() < MinUses)
9737 // Find all FDIV users of the same divisor.
9738 // Use a set because duplicates may be present in the user list.
9739 SetVector<SDNode *> Users;
9740 for (auto *U : N1->uses()) {
9741 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
9742 // This division is eligible for optimization only if global unsafe math
9743 // is enabled or if this division allows reciprocal formation.
9744 if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
9749 // Now that we have the actual number of divisor uses, make sure it meets
9750 // the minimum threshold specified by the target.
9751 if (Users.size() < MinUses)
9754 EVT VT = N->getValueType(0);
9756 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
9757 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
9759 // Dividend / Divisor -> Dividend * Reciprocal
9760 for (auto *U : Users) {
9761 SDValue Dividend = U->getOperand(0);
9762 if (Dividend != FPOne) {
9763 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
9765 CombineTo(U, NewNode);
9766 } else if (U != Reciprocal.getNode()) {
9767 // In the absence of fast-math-flags, this user node is always the
9768 // same node as Reciprocal, but with FMF they may be different nodes.
9769 CombineTo(U, Reciprocal);
9772 return SDValue(N, 0); // N was replaced.
9775 SDValue DAGCombiner::visitFDIV(SDNode *N) {
9776 SDValue N0 = N->getOperand(0);
9777 SDValue N1 = N->getOperand(1);
9778 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9779 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9780 EVT VT = N->getValueType(0);
9782 const TargetOptions &Options = DAG.getTarget().Options;
9783 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9787 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9790 // fold (fdiv c1, c2) -> c1/c2
9792 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
9794 if (SDValue NewSel = foldBinOpIntoSelect(N))
9797 if (Options.UnsafeFPMath) {
9798 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
9800 // Compute the reciprocal 1.0 / c2.
9801 const APFloat &N1APF = N1CFP->getValueAPF();
9802 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
9803 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
9804 // Only do the transform if the reciprocal is a legal fp immediate that
9805 // isn't too nasty (eg NaN, denormal, ...).
9806 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
9807 (!LegalOperations ||
9808 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
9809 // backend)... we should handle this gracefully after Legalize.
9810 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
9811 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
9812 TLI.isFPImmLegal(Recip, VT)))
9813 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9814 DAG.getConstantFP(Recip, DL, VT), Flags);
9817 // If this FDIV is part of a reciprocal square root, it may be folded
9818 // into a target-specific square root estimate instruction.
9819 if (N1.getOpcode() == ISD::FSQRT) {
9820 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
9821 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9823 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
9824 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9825 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9827 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
9828 AddToWorklist(RV.getNode());
9829 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9831 } else if (N1.getOpcode() == ISD::FP_ROUND &&
9832 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9833 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9835 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9836 AddToWorklist(RV.getNode());
9837 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9839 } else if (N1.getOpcode() == ISD::FMUL) {
9840 // Look through an FMUL. Even though this won't remove the FDIV directly,
9841 // it's still worthwhile to get rid of the FSQRT if possible.
9844 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9845 SqrtOp = N1.getOperand(0);
9846 OtherOp = N1.getOperand(1);
9847 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9848 SqrtOp = N1.getOperand(1);
9849 OtherOp = N1.getOperand(0);
9851 if (SqrtOp.getNode()) {
9852 // We found a FSQRT, so try to make this fold:
9853 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9854 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9855 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9856 AddToWorklist(RV.getNode());
9857 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9862 // Fold into a reciprocal estimate and multiply instead of a real divide.
9863 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9864 AddToWorklist(RV.getNode());
9865 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9869 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9870 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9871 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9872 // Both can be negated for free, check to see if at least one is cheaper
9874 if (LHSNeg == 2 || RHSNeg == 2)
9875 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9876 GetNegatedExpression(N0, DAG, LegalOperations),
9877 GetNegatedExpression(N1, DAG, LegalOperations),
9882 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9883 return CombineRepeatedDivisors;
9888 SDValue DAGCombiner::visitFREM(SDNode *N) {
9889 SDValue N0 = N->getOperand(0);
9890 SDValue N1 = N->getOperand(1);
9891 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9892 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9893 EVT VT = N->getValueType(0);
9895 // fold (frem c1, c2) -> fmod(c1,c2)
9897 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9898 &cast<BinaryWithFlagsSDNode>(N)->Flags);
9900 if (SDValue NewSel = foldBinOpIntoSelect(N))
9906 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9907 if (!DAG.getTarget().Options.UnsafeFPMath)
9910 SDValue N0 = N->getOperand(0);
9911 if (TLI.isFsqrtCheap(N0, DAG))
9914 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9915 // For now, create a Flags object for use with all unsafe math transforms.
9917 Flags.setUnsafeAlgebra(true);
9918 return buildSqrtEstimate(N0, &Flags);
9921 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9922 /// copysign(x, fp_round(y)) -> copysign(x, y)
9923 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9924 SDValue N1 = N->getOperand(1);
9925 if ((N1.getOpcode() == ISD::FP_EXTEND ||
9926 N1.getOpcode() == ISD::FP_ROUND)) {
9927 // Do not optimize out type conversion of f128 type yet.
9928 // For some targets like x86_64, configuration is changed to keep one f128
9929 // value in one SSE register, but instruction selection cannot handle
9930 // FCOPYSIGN on SSE registers yet.
9931 EVT N1VT = N1->getValueType(0);
9932 EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9933 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9938 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9939 SDValue N0 = N->getOperand(0);
9940 SDValue N1 = N->getOperand(1);
9941 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9942 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9943 EVT VT = N->getValueType(0);
9945 if (N0CFP && N1CFP) // Constant fold
9946 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9949 const APFloat &V = N1CFP->getValueAPF();
9950 // copysign(x, c1) -> fabs(x) iff ispos(c1)
9951 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9952 if (!V.isNegative()) {
9953 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9954 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9956 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9957 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9958 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9962 // copysign(fabs(x), y) -> copysign(x, y)
9963 // copysign(fneg(x), y) -> copysign(x, y)
9964 // copysign(copysign(x,z), y) -> copysign(x, y)
9965 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9966 N0.getOpcode() == ISD::FCOPYSIGN)
9967 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9969 // copysign(x, abs(y)) -> abs(x)
9970 if (N1.getOpcode() == ISD::FABS)
9971 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9973 // copysign(x, copysign(y,z)) -> copysign(x, z)
9974 if (N1.getOpcode() == ISD::FCOPYSIGN)
9975 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9977 // copysign(x, fp_extend(y)) -> copysign(x, y)
9978 // copysign(x, fp_round(y)) -> copysign(x, y)
9979 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9980 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9985 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9986 SDValue N0 = N->getOperand(0);
9987 EVT VT = N->getValueType(0);
9988 EVT OpVT = N0.getValueType();
9990 // fold (sint_to_fp c1) -> c1fp
9991 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9992 // ...but only if the target supports immediate floating-point values
9993 (!LegalOperations ||
9994 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9995 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9997 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9998 // but UINT_TO_FP is legal on this target, try to convert.
9999 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10000 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10001 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10002 if (DAG.SignBitIsZero(N0))
10003 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10006 // The next optimizations are desirable only if SELECT_CC can be lowered.
10007 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10008 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10009 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10011 (!LegalOperations ||
10012 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10015 { N0.getOperand(0), N0.getOperand(1),
10016 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10017 N0.getOperand(2) };
10018 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10021 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10022 // (select_cc x, y, 1.0, 0.0,, cc)
10023 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10024 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10025 (!LegalOperations ||
10026 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10029 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10030 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10031 N0.getOperand(0).getOperand(2) };
10032 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10039 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10040 SDValue N0 = N->getOperand(0);
10041 EVT VT = N->getValueType(0);
10042 EVT OpVT = N0.getValueType();
10044 // fold (uint_to_fp c1) -> c1fp
10045 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10046 // ...but only if the target supports immediate floating-point values
10047 (!LegalOperations ||
10048 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10049 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10051 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10052 // but SINT_TO_FP is legal on this target, try to convert.
10053 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10054 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10055 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10056 if (DAG.SignBitIsZero(N0))
10057 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10060 // The next optimizations are desirable only if SELECT_CC can be lowered.
10061 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10062 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10064 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10065 (!LegalOperations ||
10066 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10069 { N0.getOperand(0), N0.getOperand(1),
10070 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10071 N0.getOperand(2) };
10072 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10079 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10080 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10081 SDValue N0 = N->getOperand(0);
10082 EVT VT = N->getValueType(0);
10084 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10087 SDValue Src = N0.getOperand(0);
10088 EVT SrcVT = Src.getValueType();
10089 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10090 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10092 // We can safely assume the conversion won't overflow the output range,
10093 // because (for example) (uint8_t)18293.f is undefined behavior.
10095 // Since we can assume the conversion won't overflow, our decision as to
10096 // whether the input will fit in the float should depend on the minimum
10097 // of the input range and output range.
10099 // This means this is also safe for a signed input and unsigned output, since
10100 // a negative input would lead to undefined behavior.
10101 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10102 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10103 unsigned ActualSize = std::min(InputSize, OutputSize);
10104 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10106 // We can only fold away the float conversion if the input range can be
10107 // represented exactly in the float range.
10108 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10109 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10110 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10111 : ISD::ZERO_EXTEND;
10112 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10114 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10115 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10116 return DAG.getBitcast(VT, Src);
10121 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10122 SDValue N0 = N->getOperand(0);
10123 EVT VT = N->getValueType(0);
10125 // fold (fp_to_sint c1fp) -> c1
10126 if (isConstantFPBuildVectorOrConstantFP(N0))
10127 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10129 return FoldIntToFPToInt(N, DAG);
10132 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10133 SDValue N0 = N->getOperand(0);
10134 EVT VT = N->getValueType(0);
10136 // fold (fp_to_uint c1fp) -> c1
10137 if (isConstantFPBuildVectorOrConstantFP(N0))
10138 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10140 return FoldIntToFPToInt(N, DAG);
10143 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10144 SDValue N0 = N->getOperand(0);
10145 SDValue N1 = N->getOperand(1);
10146 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10147 EVT VT = N->getValueType(0);
10149 // fold (fp_round c1fp) -> c1fp
10151 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10153 // fold (fp_round (fp_extend x)) -> x
10154 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10155 return N0.getOperand(0);
10157 // fold (fp_round (fp_round x)) -> (fp_round x)
10158 if (N0.getOpcode() == ISD::FP_ROUND) {
10159 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10160 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10162 // Skip this folding if it results in an fp_round from f80 to f16.
10164 // f80 to f16 always generates an expensive (and as yet, unimplemented)
10165 // libcall to __truncxfhf2 instead of selecting native f16 conversion
10166 // instructions from f32 or f64. Moreover, the first (value-preserving)
10167 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10169 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10172 // If the first fp_round isn't a value preserving truncation, it might
10173 // introduce a tie in the second fp_round, that wouldn't occur in the
10174 // single-step fp_round we want to fold to.
10175 // In other words, double rounding isn't the same as rounding.
10176 // Also, this is a value preserving truncation iff both fp_round's are.
10177 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10179 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10180 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10184 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10185 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10186 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10187 N0.getOperand(0), N1);
10188 AddToWorklist(Tmp.getNode());
10189 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10190 Tmp, N0.getOperand(1));
10196 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10197 SDValue N0 = N->getOperand(0);
10198 EVT VT = N->getValueType(0);
10199 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10200 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10202 // fold (fp_round_inreg c1fp) -> c1fp
10203 if (N0CFP && isTypeLegal(EVT)) {
10205 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10206 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10212 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10213 SDValue N0 = N->getOperand(0);
10214 EVT VT = N->getValueType(0);
10216 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10217 if (N->hasOneUse() &&
10218 N->use_begin()->getOpcode() == ISD::FP_ROUND)
10221 // fold (fp_extend c1fp) -> c1fp
10222 if (isConstantFPBuildVectorOrConstantFP(N0))
10223 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10225 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10226 if (N0.getOpcode() == ISD::FP16_TO_FP &&
10227 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10228 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10230 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10232 if (N0.getOpcode() == ISD::FP_ROUND
10233 && N0.getConstantOperandVal(1) == 1) {
10234 SDValue In = N0.getOperand(0);
10235 if (In.getValueType() == VT) return In;
10236 if (VT.bitsLT(In.getValueType()))
10237 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10238 In, N0.getOperand(1));
10239 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10242 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10243 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10244 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10245 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10246 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10248 LN0->getBasePtr(), N0.getValueType(),
10249 LN0->getMemOperand());
10250 CombineTo(N, ExtLoad);
10251 CombineTo(N0.getNode(),
10252 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10253 N0.getValueType(), ExtLoad,
10254 DAG.getIntPtrConstant(1, SDLoc(N0))),
10255 ExtLoad.getValue(1));
10256 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10262 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10263 SDValue N0 = N->getOperand(0);
10264 EVT VT = N->getValueType(0);
10266 // fold (fceil c1) -> fceil(c1)
10267 if (isConstantFPBuildVectorOrConstantFP(N0))
10268 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10273 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10274 SDValue N0 = N->getOperand(0);
10275 EVT VT = N->getValueType(0);
10277 // fold (ftrunc c1) -> ftrunc(c1)
10278 if (isConstantFPBuildVectorOrConstantFP(N0))
10279 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10284 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10285 SDValue N0 = N->getOperand(0);
10286 EVT VT = N->getValueType(0);
10288 // fold (ffloor c1) -> ffloor(c1)
10289 if (isConstantFPBuildVectorOrConstantFP(N0))
10290 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10295 // FIXME: FNEG and FABS have a lot in common; refactor.
10296 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10297 SDValue N0 = N->getOperand(0);
10298 EVT VT = N->getValueType(0);
10300 // Constant fold FNEG.
10301 if (isConstantFPBuildVectorOrConstantFP(N0))
10302 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10304 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10305 &DAG.getTarget().Options))
10306 return GetNegatedExpression(N0, DAG, LegalOperations);
10308 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10309 // constant pool values.
10310 if (!TLI.isFNegFree(VT) &&
10311 N0.getOpcode() == ISD::BITCAST &&
10312 N0.getNode()->hasOneUse()) {
10313 SDValue Int = N0.getOperand(0);
10314 EVT IntVT = Int.getValueType();
10315 if (IntVT.isInteger() && !IntVT.isVector()) {
10317 if (N0.getValueType().isVector()) {
10318 // For a vector, get a mask such as 0x80... per scalar element
10320 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10321 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10323 // For a scalar, just generate 0x80...
10324 SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10327 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10328 DAG.getConstant(SignMask, DL0, IntVT));
10329 AddToWorklist(Int.getNode());
10330 return DAG.getBitcast(VT, Int);
10334 // (fneg (fmul c, x)) -> (fmul -c, x)
10335 if (N0.getOpcode() == ISD::FMUL &&
10336 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10337 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10339 APFloat CVal = CFP1->getValueAPF();
10341 if (Level >= AfterLegalizeDAG &&
10342 (TLI.isFPImmLegal(CVal, VT) ||
10343 TLI.isOperationLegal(ISD::ConstantFP, VT)))
10344 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10345 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10347 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
10354 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10355 SDValue N0 = N->getOperand(0);
10356 SDValue N1 = N->getOperand(1);
10357 EVT VT = N->getValueType(0);
10358 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10359 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10361 if (N0CFP && N1CFP) {
10362 const APFloat &C0 = N0CFP->getValueAPF();
10363 const APFloat &C1 = N1CFP->getValueAPF();
10364 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10367 // Canonicalize to constant on RHS.
10368 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10369 !isConstantFPBuildVectorOrConstantFP(N1))
10370 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10375 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10376 SDValue N0 = N->getOperand(0);
10377 SDValue N1 = N->getOperand(1);
10378 EVT VT = N->getValueType(0);
10379 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10380 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10382 if (N0CFP && N1CFP) {
10383 const APFloat &C0 = N0CFP->getValueAPF();
10384 const APFloat &C1 = N1CFP->getValueAPF();
10385 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10388 // Canonicalize to constant on RHS.
10389 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10390 !isConstantFPBuildVectorOrConstantFP(N1))
10391 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10396 SDValue DAGCombiner::visitFABS(SDNode *N) {
10397 SDValue N0 = N->getOperand(0);
10398 EVT VT = N->getValueType(0);
10400 // fold (fabs c1) -> fabs(c1)
10401 if (isConstantFPBuildVectorOrConstantFP(N0))
10402 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10404 // fold (fabs (fabs x)) -> (fabs x)
10405 if (N0.getOpcode() == ISD::FABS)
10406 return N->getOperand(0);
10408 // fold (fabs (fneg x)) -> (fabs x)
10409 // fold (fabs (fcopysign x, y)) -> (fabs x)
10410 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10411 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10413 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10414 // constant pool values.
10415 if (!TLI.isFAbsFree(VT) &&
10416 N0.getOpcode() == ISD::BITCAST &&
10417 N0.getNode()->hasOneUse()) {
10418 SDValue Int = N0.getOperand(0);
10419 EVT IntVT = Int.getValueType();
10420 if (IntVT.isInteger() && !IntVT.isVector()) {
10422 if (N0.getValueType().isVector()) {
10423 // For a vector, get a mask such as 0x7f... per scalar element
10425 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10426 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10428 // For a scalar, just generate 0x7f...
10429 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10432 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10433 DAG.getConstant(SignMask, DL, IntVT));
10434 AddToWorklist(Int.getNode());
10435 return DAG.getBitcast(N->getValueType(0), Int);
10442 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10443 SDValue Chain = N->getOperand(0);
10444 SDValue N1 = N->getOperand(1);
10445 SDValue N2 = N->getOperand(2);
10447 // If N is a constant we could fold this into a fallthrough or unconditional
10448 // branch. However that doesn't happen very often in normal code, because
10449 // Instcombine/SimplifyCFG should have handled the available opportunities.
10450 // If we did this folding here, it would be necessary to update the
10451 // MachineBasicBlock CFG, which is awkward.
10453 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10455 if (N1.getOpcode() == ISD::SETCC &&
10456 TLI.isOperationLegalOrCustom(ISD::BR_CC,
10457 N1.getOperand(0).getValueType())) {
10458 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10459 Chain, N1.getOperand(2),
10460 N1.getOperand(0), N1.getOperand(1), N2);
10463 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10464 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10465 (N1.getOperand(0).hasOneUse() &&
10466 N1.getOperand(0).getOpcode() == ISD::SRL))) {
10467 SDNode *Trunc = nullptr;
10468 if (N1.getOpcode() == ISD::TRUNCATE) {
10469 // Look pass the truncate.
10470 Trunc = N1.getNode();
10471 N1 = N1.getOperand(0);
10474 // Match this pattern so that we can generate simpler code:
10477 // %b = and i32 %a, 2
10478 // %c = srl i32 %b, 1
10479 // brcond i32 %c ...
10484 // %b = and i32 %a, 2
10485 // %c = setcc eq %b, 0
10488 // This applies only when the AND constant value has one bit set and the
10489 // SRL constant is equal to the log2 of the AND constant. The back-end is
10490 // smart enough to convert the result into a TEST/JMP sequence.
10491 SDValue Op0 = N1.getOperand(0);
10492 SDValue Op1 = N1.getOperand(1);
10494 if (Op0.getOpcode() == ISD::AND &&
10495 Op1.getOpcode() == ISD::Constant) {
10496 SDValue AndOp1 = Op0.getOperand(1);
10498 if (AndOp1.getOpcode() == ISD::Constant) {
10499 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10501 if (AndConst.isPowerOf2() &&
10502 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10506 getSetCCResultType(Op0.getValueType()),
10507 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10510 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10511 MVT::Other, Chain, SetCC, N2);
10512 // Don't add the new BRCond into the worklist or else SimplifySelectCC
10513 // will convert it back to (X & C1) >> C2.
10514 CombineTo(N, NewBRCond, false);
10515 // Truncate is dead.
10517 deleteAndRecombine(Trunc);
10518 // Replace the uses of SRL with SETCC
10519 WorklistRemover DeadNodes(*this);
10520 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10521 deleteAndRecombine(N1.getNode());
10522 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10528 // Restore N1 if the above transformation doesn't match.
10529 N1 = N->getOperand(1);
10532 // Transform br(xor(x, y)) -> br(x != y)
10533 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10534 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10535 SDNode *TheXor = N1.getNode();
10536 SDValue Op0 = TheXor->getOperand(0);
10537 SDValue Op1 = TheXor->getOperand(1);
10538 if (Op0.getOpcode() == Op1.getOpcode()) {
10539 // Avoid missing important xor optimizations.
10540 if (SDValue Tmp = visitXOR(TheXor)) {
10541 if (Tmp.getNode() != TheXor) {
10542 DEBUG(dbgs() << "\nReplacing.8 ";
10543 TheXor->dump(&DAG);
10544 dbgs() << "\nWith: ";
10545 Tmp.getNode()->dump(&DAG);
10547 WorklistRemover DeadNodes(*this);
10548 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10549 deleteAndRecombine(TheXor);
10550 return DAG.getNode(ISD::BRCOND, SDLoc(N),
10551 MVT::Other, Chain, Tmp, N2);
10554 // visitXOR has changed XOR's operands or replaced the XOR completely,
10556 return SDValue(N, 0);
10560 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10561 bool Equal = false;
10562 if (isOneConstant(Op0) && Op0.hasOneUse() &&
10563 Op0.getOpcode() == ISD::XOR) {
10564 TheXor = Op0.getNode();
10568 EVT SetCCVT = N1.getValueType();
10570 SetCCVT = getSetCCResultType(SetCCVT);
10571 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10574 Equal ? ISD::SETEQ : ISD::SETNE);
10575 // Replace the uses of XOR with SETCC
10576 WorklistRemover DeadNodes(*this);
10577 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10578 deleteAndRecombine(N1.getNode());
10579 return DAG.getNode(ISD::BRCOND, SDLoc(N),
10580 MVT::Other, Chain, SetCC, N2);
10587 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10589 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10590 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10591 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10593 // If N is a constant we could fold this into a fallthrough or unconditional
10594 // branch. However that doesn't happen very often in normal code, because
10595 // Instcombine/SimplifyCFG should have handled the available opportunities.
10596 // If we did this folding here, it would be necessary to update the
10597 // MachineBasicBlock CFG, which is awkward.
10599 // Use SimplifySetCC to simplify SETCC's.
10600 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10601 CondLHS, CondRHS, CC->get(), SDLoc(N),
10603 if (Simp.getNode()) AddToWorklist(Simp.getNode());
10605 // fold to a simpler setcc
10606 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10607 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10608 N->getOperand(0), Simp.getOperand(2),
10609 Simp.getOperand(0), Simp.getOperand(1),
10615 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10616 /// and that N may be folded in the load / store addressing mode.
10617 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10619 const TargetLowering &TLI) {
10623 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
10624 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10626 VT = LD->getMemoryVT();
10627 AS = LD->getAddressSpace();
10628 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
10629 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10631 VT = ST->getMemoryVT();
10632 AS = ST->getAddressSpace();
10636 TargetLowering::AddrMode AM;
10637 if (N->getOpcode() == ISD::ADD) {
10638 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10641 AM.BaseOffs = Offset->getSExtValue();
10645 } else if (N->getOpcode() == ISD::SUB) {
10646 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10649 AM.BaseOffs = -Offset->getSExtValue();
10656 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10657 VT.getTypeForEVT(*DAG.getContext()), AS);
10660 /// Try turning a load/store into a pre-indexed load/store when the base
10661 /// pointer is an add or subtract and it has other uses besides the load/store.
10662 /// After the transformation, the new indexed load/store has effectively folded
10663 /// the add/subtract in and all of its other uses are redirected to the
10664 /// new load/store.
10665 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10666 if (Level < AfterLegalizeDAG)
10669 bool isLoad = true;
10672 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10673 if (LD->isIndexed())
10675 VT = LD->getMemoryVT();
10676 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10677 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10679 Ptr = LD->getBasePtr();
10680 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10681 if (ST->isIndexed())
10683 VT = ST->getMemoryVT();
10684 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10685 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10687 Ptr = ST->getBasePtr();
10693 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10694 // out. There is no reason to make this a preinc/predec.
10695 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10696 Ptr.getNode()->hasOneUse())
10699 // Ask the target to do addressing mode selection.
10702 ISD::MemIndexedMode AM = ISD::UNINDEXED;
10703 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10706 // Backends without true r+i pre-indexed forms may need to pass a
10707 // constant base with a variable offset so that constant coercion
10708 // will work with the patterns in canonical form.
10709 bool Swapped = false;
10710 if (isa<ConstantSDNode>(BasePtr)) {
10711 std::swap(BasePtr, Offset);
10715 // Don't create a indexed load / store with zero offset.
10716 if (isNullConstant(Offset))
10719 // Try turning it into a pre-indexed load / store except when:
10720 // 1) The new base ptr is a frame index.
10721 // 2) If N is a store and the new base ptr is either the same as or is a
10722 // predecessor of the value being stored.
10723 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10724 // that would create a cycle.
10725 // 4) All uses are load / store ops that use it as old base ptr.
10727 // Check #1. Preinc'ing a frame index would require copying the stack pointer
10728 // (plus the implicit offset) to a register to preinc anyway.
10729 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10734 SDValue Val = cast<StoreSDNode>(N)->getValue();
10735 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
10739 // Caches for hasPredecessorHelper.
10740 SmallPtrSet<const SDNode *, 32> Visited;
10741 SmallVector<const SDNode *, 16> Worklist;
10742 Worklist.push_back(N);
10744 // If the offset is a constant, there may be other adds of constants that
10745 // can be folded with this one. We should do this to avoid having to keep
10746 // a copy of the original base pointer.
10747 SmallVector<SDNode *, 16> OtherUses;
10748 if (isa<ConstantSDNode>(Offset))
10749 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
10750 UE = BasePtr.getNode()->use_end();
10752 SDUse &Use = UI.getUse();
10753 // Skip the use that is Ptr and uses of other results from BasePtr's
10754 // node (important for nodes that return multiple results).
10755 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
10758 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
10761 if (Use.getUser()->getOpcode() != ISD::ADD &&
10762 Use.getUser()->getOpcode() != ISD::SUB) {
10767 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
10768 if (!isa<ConstantSDNode>(Op1)) {
10773 // FIXME: In some cases, we can be smarter about this.
10774 if (Op1.getValueType() != Offset.getValueType()) {
10779 OtherUses.push_back(Use.getUser());
10783 std::swap(BasePtr, Offset);
10785 // Now check for #3 and #4.
10786 bool RealUse = false;
10788 for (SDNode *Use : Ptr.getNode()->uses()) {
10791 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
10794 // If Ptr may be folded in addressing mode of other use, then it's
10795 // not profitable to do this transformation.
10796 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
10805 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10806 BasePtr, Offset, AM);
10808 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10809 BasePtr, Offset, AM);
10812 DEBUG(dbgs() << "\nReplacing.4 ";
10814 dbgs() << "\nWith: ";
10815 Result.getNode()->dump(&DAG);
10817 WorklistRemover DeadNodes(*this);
10819 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10820 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10822 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10825 // Finally, since the node is now dead, remove it from the graph.
10826 deleteAndRecombine(N);
10829 std::swap(BasePtr, Offset);
10831 // Replace other uses of BasePtr that can be updated to use Ptr
10832 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
10833 unsigned OffsetIdx = 1;
10834 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
10836 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10837 BasePtr.getNode() && "Expected BasePtr operand");
10839 // We need to replace ptr0 in the following expression:
10840 // x0 * offset0 + y0 * ptr0 = t0
10842 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10844 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10845 // indexed load/store and the expresion that needs to be re-written.
10847 // Therefore, we have:
10848 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10850 ConstantSDNode *CN =
10851 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
10852 int X0, X1, Y0, Y1;
10853 const APInt &Offset0 = CN->getAPIntValue();
10854 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10856 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10857 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10858 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10859 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10861 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10863 APInt CNV = Offset0;
10864 if (X0 < 0) CNV = -CNV;
10865 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10866 else CNV = CNV - Offset1;
10868 SDLoc DL(OtherUses[i]);
10870 // We can now generate the new expression.
10871 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10872 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10874 SDValue NewUse = DAG.getNode(Opcode,
10876 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10877 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10878 deleteAndRecombine(OtherUses[i]);
10881 // Replace the uses of Ptr with uses of the updated base value.
10882 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10883 deleteAndRecombine(Ptr.getNode());
10888 /// Try to combine a load/store with a add/sub of the base pointer node into a
10889 /// post-indexed load/store. The transformation folded the add/subtract into the
10890 /// new indexed load/store effectively and all of its uses are redirected to the
10891 /// new load/store.
10892 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10893 if (Level < AfterLegalizeDAG)
10896 bool isLoad = true;
10899 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10900 if (LD->isIndexed())
10902 VT = LD->getMemoryVT();
10903 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10904 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10906 Ptr = LD->getBasePtr();
10907 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10908 if (ST->isIndexed())
10910 VT = ST->getMemoryVT();
10911 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10912 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10914 Ptr = ST->getBasePtr();
10920 if (Ptr.getNode()->hasOneUse())
10923 for (SDNode *Op : Ptr.getNode()->uses()) {
10925 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10930 ISD::MemIndexedMode AM = ISD::UNINDEXED;
10931 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10932 // Don't create a indexed load / store with zero offset.
10933 if (isNullConstant(Offset))
10936 // Try turning it into a post-indexed load / store except when
10937 // 1) All uses are load / store ops that use it as base ptr (and
10938 // it may be folded as addressing mmode).
10939 // 2) Op must be independent of N, i.e. Op is neither a predecessor
10940 // nor a successor of N. Otherwise, if Op is folded that would
10943 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10947 bool TryNext = false;
10948 for (SDNode *Use : BasePtr.getNode()->uses()) {
10949 if (Use == Ptr.getNode())
10952 // If all the uses are load / store addresses, then don't do the
10954 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10955 bool RealUse = false;
10956 for (SDNode *UseUse : Use->uses()) {
10957 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10972 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10973 SDValue Result = isLoad
10974 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10975 BasePtr, Offset, AM)
10976 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10977 BasePtr, Offset, AM);
10978 ++PostIndexedNodes;
10980 DEBUG(dbgs() << "\nReplacing.5 ";
10982 dbgs() << "\nWith: ";
10983 Result.getNode()->dump(&DAG);
10985 WorklistRemover DeadNodes(*this);
10987 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10988 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10990 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10993 // Finally, since the node is now dead, remove it from the graph.
10994 deleteAndRecombine(N);
10996 // Replace the uses of Use with uses of the updated base value.
10997 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10998 Result.getValue(isLoad ? 1 : 0));
10999 deleteAndRecombine(Op);
11008 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11009 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11010 ISD::MemIndexedMode AM = LD->getAddressingMode();
11011 assert(AM != ISD::UNINDEXED);
11012 SDValue BP = LD->getOperand(1);
11013 SDValue Inc = LD->getOperand(2);
11015 // Some backends use TargetConstants for load offsets, but don't expect
11016 // TargetConstants in general ADD nodes. We can convert these constants into
11017 // regular Constants (if the constant is not opaque).
11018 assert((Inc.getOpcode() != ISD::TargetConstant ||
11019 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11020 "Cannot split out indexing using opaque target constants");
11021 if (Inc.getOpcode() == ISD::TargetConstant) {
11022 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11023 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11024 ConstInc->getValueType(0));
11028 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11029 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11032 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11033 LoadSDNode *LD = cast<LoadSDNode>(N);
11034 SDValue Chain = LD->getChain();
11035 SDValue Ptr = LD->getBasePtr();
11037 // If load is not volatile and there are no uses of the loaded value (and
11038 // the updated indexed value in case of indexed loads), change uses of the
11039 // chain value into uses of the chain input (i.e. delete the dead load).
11040 if (!LD->isVolatile()) {
11041 if (N->getValueType(1) == MVT::Other) {
11042 // Unindexed loads.
11043 if (!N->hasAnyUseOfValue(0)) {
11044 // It's not safe to use the two value CombineTo variant here. e.g.
11045 // v1, chain2 = load chain1, loc
11046 // v2, chain3 = load chain2, loc
11048 // Now we replace use of chain2 with chain1. This makes the second load
11049 // isomorphic to the one we are deleting, and thus makes this load live.
11050 DEBUG(dbgs() << "\nReplacing.6 ";
11052 dbgs() << "\nWith chain: ";
11053 Chain.getNode()->dump(&DAG);
11055 WorklistRemover DeadNodes(*this);
11056 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11057 AddUsersToWorklist(Chain.getNode());
11058 if (N->use_empty())
11059 deleteAndRecombine(N);
11061 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11065 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11067 // If this load has an opaque TargetConstant offset, then we cannot split
11068 // the indexing into an add/sub directly (that TargetConstant may not be
11069 // valid for a different type of node, and we cannot convert an opaque
11070 // target constant into a regular constant).
11071 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11072 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11074 if (!N->hasAnyUseOfValue(0) &&
11075 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11076 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11078 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11079 Index = SplitIndexingFromLoad(LD);
11080 // Try to fold the base pointer arithmetic into subsequent loads and
11082 AddUsersToWorklist(N);
11084 Index = DAG.getUNDEF(N->getValueType(1));
11085 DEBUG(dbgs() << "\nReplacing.7 ";
11087 dbgs() << "\nWith: ";
11088 Undef.getNode()->dump(&DAG);
11089 dbgs() << " and 2 other values\n");
11090 WorklistRemover DeadNodes(*this);
11091 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11092 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11093 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11094 deleteAndRecombine(N);
11095 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11100 // If this load is directly stored, replace the load value with the stored
11102 // TODO: Handle store large -> read small portion.
11103 // TODO: Handle TRUNCSTORE/LOADEXT
11104 if (OptLevel != CodeGenOpt::None &&
11105 ISD::isNormalLoad(N) && !LD->isVolatile()) {
11106 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11107 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11108 if (PrevST->getBasePtr() == Ptr &&
11109 PrevST->getValue().getValueType() == N->getValueType(0))
11110 return CombineTo(N, PrevST->getOperand(1), Chain);
11114 // Try to infer better alignment information than the load already has.
11115 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11116 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11117 if (Align > LD->getMemOperand()->getBaseAlignment()) {
11118 SDValue NewLoad = DAG.getExtLoad(
11119 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11120 LD->getPointerInfo(), LD->getMemoryVT(), Align,
11121 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11122 if (NewLoad.getNode() != N)
11123 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11128 if (LD->isUnindexed()) {
11129 // Walk up chain skipping non-aliasing memory nodes.
11130 SDValue BetterChain = FindBetterChain(N, Chain);
11132 // If there is a better chain.
11133 if (Chain != BetterChain) {
11136 // Replace the chain to void dependency.
11137 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11138 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11139 BetterChain, Ptr, LD->getMemOperand());
11141 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11142 LD->getValueType(0),
11143 BetterChain, Ptr, LD->getMemoryVT(),
11144 LD->getMemOperand());
11147 // Create token factor to keep old chain connected.
11148 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11149 MVT::Other, Chain, ReplLoad.getValue(1));
11151 // Make sure the new and old chains are cleaned up.
11152 AddToWorklist(Token.getNode());
11154 // Replace uses with load result and token factor. Don't add users
11156 return CombineTo(N, ReplLoad.getValue(0), Token, false);
11160 // Try transforming N to an indexed load.
11161 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11162 return SDValue(N, 0);
11164 // Try to slice up N to more direct loads if the slices are mapped to
11165 // different register banks or pairing can take place.
11166 if (SliceUpLoad(N))
11167 return SDValue(N, 0);
11173 /// \brief Helper structure used to slice a load in smaller loads.
11174 /// Basically a slice is obtained from the following sequence:
11175 /// Origin = load Ty1, Base
11176 /// Shift = srl Ty1 Origin, CstTy Amount
11177 /// Inst = trunc Shift to Ty2
11179 /// Then, it will be rewriten into:
11180 /// Slice = load SliceTy, Base + SliceOffset
11181 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11183 /// SliceTy is deduced from the number of bits that are actually used to
11185 struct LoadedSlice {
11186 /// \brief Helper structure used to compute the cost of a slice.
11188 /// Are we optimizing for code size.
11192 unsigned Truncates;
11193 unsigned CrossRegisterBanksCopies;
11197 Cost(bool ForCodeSize = false)
11198 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11199 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11201 /// \brief Get the cost of one isolated slice.
11202 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11203 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11204 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11205 EVT TruncType = LS.Inst->getValueType(0);
11206 EVT LoadedType = LS.getLoadedType();
11207 if (TruncType != LoadedType &&
11208 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11212 /// \brief Account for slicing gain in the current cost.
11213 /// Slicing provide a few gains like removing a shift or a
11214 /// truncate. This method allows to grow the cost of the original
11215 /// load with the gain from this slice.
11216 void addSliceGain(const LoadedSlice &LS) {
11217 // Each slice saves a truncate.
11218 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11219 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11220 LS.Inst->getValueType(0)))
11222 // If there is a shift amount, this slice gets rid of it.
11225 // If this slice can merge a cross register bank copy, account for it.
11226 if (LS.canMergeExpensiveCrossRegisterBankCopy())
11227 ++CrossRegisterBanksCopies;
11230 Cost &operator+=(const Cost &RHS) {
11231 Loads += RHS.Loads;
11232 Truncates += RHS.Truncates;
11233 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11234 ZExts += RHS.ZExts;
11235 Shift += RHS.Shift;
11239 bool operator==(const Cost &RHS) const {
11240 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11241 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11242 ZExts == RHS.ZExts && Shift == RHS.Shift;
11245 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11247 bool operator<(const Cost &RHS) const {
11248 // Assume cross register banks copies are as expensive as loads.
11249 // FIXME: Do we want some more target hooks?
11250 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11251 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11252 // Unless we are optimizing for code size, consider the
11253 // expensive operation first.
11254 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11255 return ExpensiveOpsLHS < ExpensiveOpsRHS;
11256 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11257 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11260 bool operator>(const Cost &RHS) const { return RHS < *this; }
11262 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11264 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11266 // The last instruction that represent the slice. This should be a
11267 // truncate instruction.
11269 // The original load instruction.
11270 LoadSDNode *Origin;
11271 // The right shift amount in bits from the original load.
11273 // The DAG from which Origin came from.
11274 // This is used to get some contextual information about legal types, etc.
11277 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11278 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11279 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11281 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11282 /// \return Result is \p BitWidth and has used bits set to 1 and
11283 /// not used bits set to 0.
11284 APInt getUsedBits() const {
11285 // Reproduce the trunc(lshr) sequence:
11286 // - Start from the truncated value.
11287 // - Zero extend to the desired bit width.
11289 assert(Origin && "No original load to compare against.");
11290 unsigned BitWidth = Origin->getValueSizeInBits(0);
11291 assert(Inst && "This slice is not bound to an instruction");
11292 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11293 "Extracted slice is bigger than the whole type!");
11294 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11295 UsedBits.setAllBits();
11296 UsedBits = UsedBits.zext(BitWidth);
11297 UsedBits <<= Shift;
11301 /// \brief Get the size of the slice to be loaded in bytes.
11302 unsigned getLoadedSize() const {
11303 unsigned SliceSize = getUsedBits().countPopulation();
11304 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11305 return SliceSize / 8;
11308 /// \brief Get the type that will be loaded for this slice.
11309 /// Note: This may not be the final type for the slice.
11310 EVT getLoadedType() const {
11311 assert(DAG && "Missing context");
11312 LLVMContext &Ctxt = *DAG->getContext();
11313 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11316 /// \brief Get the alignment of the load used for this slice.
11317 unsigned getAlignment() const {
11318 unsigned Alignment = Origin->getAlignment();
11319 unsigned Offset = getOffsetFromBase();
11321 Alignment = MinAlign(Alignment, Alignment + Offset);
11325 /// \brief Check if this slice can be rewritten with legal operations.
11326 bool isLegal() const {
11327 // An invalid slice is not legal.
11328 if (!Origin || !Inst || !DAG)
11331 // Offsets are for indexed load only, we do not handle that.
11332 if (!Origin->getOffset().isUndef())
11335 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11337 // Check that the type is legal.
11338 EVT SliceType = getLoadedType();
11339 if (!TLI.isTypeLegal(SliceType))
11342 // Check that the load is legal for this type.
11343 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11346 // Check that the offset can be computed.
11347 // 1. Check its type.
11348 EVT PtrType = Origin->getBasePtr().getValueType();
11349 if (PtrType == MVT::Untyped || PtrType.isExtended())
11352 // 2. Check that it fits in the immediate.
11353 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11356 // 3. Check that the computation is legal.
11357 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11360 // Check that the zext is legal if it needs one.
11361 EVT TruncateType = Inst->getValueType(0);
11362 if (TruncateType != SliceType &&
11363 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11369 /// \brief Get the offset in bytes of this slice in the original chunk of
11371 /// \pre DAG != nullptr.
11372 uint64_t getOffsetFromBase() const {
11373 assert(DAG && "Missing context.");
11374 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11375 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11376 uint64_t Offset = Shift / 8;
11377 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11378 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11379 "The size of the original loaded type is not a multiple of a"
11381 // If Offset is bigger than TySizeInBytes, it means we are loading all
11382 // zeros. This should have been optimized before in the process.
11383 assert(TySizeInBytes > Offset &&
11384 "Invalid shift amount for given loaded size");
11386 Offset = TySizeInBytes - Offset - getLoadedSize();
11390 /// \brief Generate the sequence of instructions to load the slice
11391 /// represented by this object and redirect the uses of this slice to
11392 /// this new sequence of instructions.
11393 /// \pre this->Inst && this->Origin are valid Instructions and this
11394 /// object passed the legal check: LoadedSlice::isLegal returned true.
11395 /// \return The last instruction of the sequence used to load the slice.
11396 SDValue loadSlice() const {
11397 assert(Inst && Origin && "Unable to replace a non-existing slice.");
11398 const SDValue &OldBaseAddr = Origin->getBasePtr();
11399 SDValue BaseAddr = OldBaseAddr;
11400 // Get the offset in that chunk of bytes w.r.t. the endianness.
11401 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11402 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11404 // BaseAddr = BaseAddr + Offset.
11405 EVT ArithType = BaseAddr.getValueType();
11407 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11408 DAG->getConstant(Offset, DL, ArithType));
11411 // Create the type of the loaded slice according to its size.
11412 EVT SliceType = getLoadedType();
11414 // Create the load for the slice.
11416 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11417 Origin->getPointerInfo().getWithOffset(Offset),
11418 getAlignment(), Origin->getMemOperand()->getFlags());
11419 // If the final type is not the same as the loaded type, this means that
11420 // we have to pad with zero. Create a zero extend for that.
11421 EVT FinalType = Inst->getValueType(0);
11422 if (SliceType != FinalType)
11424 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11428 /// \brief Check if this slice can be merged with an expensive cross register
11429 /// bank copy. E.g.,
11431 /// f = bitcast i32 i to float
11432 bool canMergeExpensiveCrossRegisterBankCopy() const {
11433 if (!Inst || !Inst->hasOneUse())
11435 SDNode *Use = *Inst->use_begin();
11436 if (Use->getOpcode() != ISD::BITCAST)
11438 assert(DAG && "Missing context");
11439 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11440 EVT ResVT = Use->getValueType(0);
11441 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11442 const TargetRegisterClass *ArgRC =
11443 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11444 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11447 // At this point, we know that we perform a cross-register-bank copy.
11448 // Check if it is expensive.
11449 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11450 // Assume bitcasts are cheap, unless both register classes do not
11451 // explicitly share a common sub class.
11452 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11455 // Check if it will be merged with the load.
11456 // 1. Check the alignment constraint.
11457 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11458 ResVT.getTypeForEVT(*DAG->getContext()));
11460 if (RequiredAlignment > getAlignment())
11463 // 2. Check that the load is a legal operation for that type.
11464 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11467 // 3. Check that we do not have a zext in the way.
11468 if (Inst->getValueType(0) != getLoadedType())
11476 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11477 /// \p UsedBits looks like 0..0 1..1 0..0.
11478 static bool areUsedBitsDense(const APInt &UsedBits) {
11479 // If all the bits are one, this is dense!
11480 if (UsedBits.isAllOnesValue())
11483 // Get rid of the unused bits on the right.
11484 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11485 // Get rid of the unused bits on the left.
11486 if (NarrowedUsedBits.countLeadingZeros())
11487 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11488 // Check that the chunk of bits is completely used.
11489 return NarrowedUsedBits.isAllOnesValue();
11492 /// \brief Check whether or not \p First and \p Second are next to each other
11493 /// in memory. This means that there is no hole between the bits loaded
11494 /// by \p First and the bits loaded by \p Second.
11495 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11496 const LoadedSlice &Second) {
11497 assert(First.Origin == Second.Origin && First.Origin &&
11498 "Unable to match different memory origins.");
11499 APInt UsedBits = First.getUsedBits();
11500 assert((UsedBits & Second.getUsedBits()) == 0 &&
11501 "Slices are not supposed to overlap.");
11502 UsedBits |= Second.getUsedBits();
11503 return areUsedBitsDense(UsedBits);
11506 /// \brief Adjust the \p GlobalLSCost according to the target
11507 /// paring capabilities and the layout of the slices.
11508 /// \pre \p GlobalLSCost should account for at least as many loads as
11509 /// there is in the slices in \p LoadedSlices.
11510 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11511 LoadedSlice::Cost &GlobalLSCost) {
11512 unsigned NumberOfSlices = LoadedSlices.size();
11513 // If there is less than 2 elements, no pairing is possible.
11514 if (NumberOfSlices < 2)
11517 // Sort the slices so that elements that are likely to be next to each
11518 // other in memory are next to each other in the list.
11519 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11520 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11521 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11522 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11524 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11525 // First (resp. Second) is the first (resp. Second) potentially candidate
11526 // to be placed in a paired load.
11527 const LoadedSlice *First = nullptr;
11528 const LoadedSlice *Second = nullptr;
11529 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11530 // Set the beginning of the pair.
11533 Second = &LoadedSlices[CurrSlice];
11535 // If First is NULL, it means we start a new pair.
11536 // Get to the next slice.
11540 EVT LoadedType = First->getLoadedType();
11542 // If the types of the slices are different, we cannot pair them.
11543 if (LoadedType != Second->getLoadedType())
11546 // Check if the target supplies paired loads for this type.
11547 unsigned RequiredAlignment = 0;
11548 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11549 // move to the next pair, this type is hopeless.
11553 // Check if we meet the alignment requirement.
11554 if (RequiredAlignment > First->getAlignment())
11557 // Check that both loads are next to each other in memory.
11558 if (!areSlicesNextToEachOther(*First, *Second))
11561 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11562 --GlobalLSCost.Loads;
11563 // Move to the next pair.
11568 /// \brief Check the profitability of all involved LoadedSlice.
11569 /// Currently, it is considered profitable if there is exactly two
11570 /// involved slices (1) which are (2) next to each other in memory, and
11571 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11573 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11574 /// the elements themselves.
11576 /// FIXME: When the cost model will be mature enough, we can relax
11577 /// constraints (1) and (2).
11578 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11579 const APInt &UsedBits, bool ForCodeSize) {
11580 unsigned NumberOfSlices = LoadedSlices.size();
11581 if (StressLoadSlicing)
11582 return NumberOfSlices > 1;
11585 if (NumberOfSlices != 2)
11589 if (!areUsedBitsDense(UsedBits))
11593 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11594 // The original code has one big load.
11595 OrigCost.Loads = 1;
11596 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11597 const LoadedSlice &LS = LoadedSlices[CurrSlice];
11598 // Accumulate the cost of all the slices.
11599 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11600 GlobalSlicingCost += SliceCost;
11602 // Account as cost in the original configuration the gain obtained
11603 // with the current slices.
11604 OrigCost.addSliceGain(LS);
11607 // If the target supports paired load, adjust the cost accordingly.
11608 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11609 return OrigCost > GlobalSlicingCost;
11612 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11613 /// operations, split it in the various pieces being extracted.
11615 /// This sort of thing is introduced by SROA.
11616 /// This slicing takes care not to insert overlapping loads.
11617 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11618 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11619 if (Level < AfterLegalizeDAG)
11622 LoadSDNode *LD = cast<LoadSDNode>(N);
11623 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11624 !LD->getValueType(0).isInteger())
11627 // Keep track of already used bits to detect overlapping values.
11628 // In that case, we will just abort the transformation.
11629 APInt UsedBits(LD->getValueSizeInBits(0), 0);
11631 SmallVector<LoadedSlice, 4> LoadedSlices;
11633 // Check if this load is used as several smaller chunks of bits.
11634 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11635 // of computation for each trunc.
11636 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11637 UI != UIEnd; ++UI) {
11638 // Skip the uses of the chain.
11639 if (UI.getUse().getResNo() != 0)
11642 SDNode *User = *UI;
11643 unsigned Shift = 0;
11645 // Check if this is a trunc(lshr).
11646 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11647 isa<ConstantSDNode>(User->getOperand(1))) {
11648 Shift = User->getConstantOperandVal(1);
11649 User = *User->use_begin();
11652 // At this point, User is a Truncate, iff we encountered, trunc or
11654 if (User->getOpcode() != ISD::TRUNCATE)
11657 // The width of the type must be a power of 2 and greater than 8-bits.
11658 // Otherwise the load cannot be represented in LLVM IR.
11659 // Moreover, if we shifted with a non-8-bits multiple, the slice
11660 // will be across several bytes. We do not support that.
11661 unsigned Width = User->getValueSizeInBits(0);
11662 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11665 // Build the slice for this chain of computations.
11666 LoadedSlice LS(User, LD, Shift, &DAG);
11667 APInt CurrentUsedBits = LS.getUsedBits();
11669 // Check if this slice overlaps with another.
11670 if ((CurrentUsedBits & UsedBits) != 0)
11672 // Update the bits used globally.
11673 UsedBits |= CurrentUsedBits;
11675 // Check if the new slice would be legal.
11679 // Record the slice.
11680 LoadedSlices.push_back(LS);
11683 // Abort slicing if it does not seem to be profitable.
11684 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11689 // Rewrite each chain to use an independent load.
11690 // By construction, each chain can be represented by a unique load.
11692 // Prepare the argument for the new token factor for all the slices.
11693 SmallVector<SDValue, 8> ArgChains;
11694 for (SmallVectorImpl<LoadedSlice>::const_iterator
11695 LSIt = LoadedSlices.begin(),
11696 LSItEnd = LoadedSlices.end();
11697 LSIt != LSItEnd; ++LSIt) {
11698 SDValue SliceInst = LSIt->loadSlice();
11699 CombineTo(LSIt->Inst, SliceInst, true);
11700 if (SliceInst.getOpcode() != ISD::LOAD)
11701 SliceInst = SliceInst.getOperand(0);
11702 assert(SliceInst->getOpcode() == ISD::LOAD &&
11703 "It takes more than a zext to get to the loaded slice!!");
11704 ArgChains.push_back(SliceInst.getValue(1));
11707 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11709 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11710 AddToWorklist(Chain.getNode());
11714 /// Check to see if V is (and load (ptr), imm), where the load is having
11715 /// specific bytes cleared out. If so, return the byte size being masked out
11716 /// and the shift amount.
11717 static std::pair<unsigned, unsigned>
11718 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11719 std::pair<unsigned, unsigned> Result(0, 0);
11721 // Check for the structure we're looking for.
11722 if (V->getOpcode() != ISD::AND ||
11723 !isa<ConstantSDNode>(V->getOperand(1)) ||
11724 !ISD::isNormalLoad(V->getOperand(0).getNode()))
11727 // Check the chain and pointer.
11728 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11729 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
11731 // The store should be chained directly to the load or be an operand of a
11733 if (LD == Chain.getNode())
11735 else if (Chain->getOpcode() != ISD::TokenFactor)
11736 return Result; // Fail.
11739 for (const SDValue &ChainOp : Chain->op_values())
11740 if (ChainOp.getNode() == LD) {
11744 if (!isOk) return Result;
11747 // This only handles simple types.
11748 if (V.getValueType() != MVT::i16 &&
11749 V.getValueType() != MVT::i32 &&
11750 V.getValueType() != MVT::i64)
11753 // Check the constant mask. Invert it so that the bits being masked out are
11754 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
11755 // follow the sign bit for uniformity.
11756 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
11757 unsigned NotMaskLZ = countLeadingZeros(NotMask);
11758 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
11759 unsigned NotMaskTZ = countTrailingZeros(NotMask);
11760 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
11761 if (NotMaskLZ == 64) return Result; // All zero mask.
11763 // See if we have a continuous run of bits. If so, we have 0*1+0*
11764 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
11767 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
11768 if (V.getValueType() != MVT::i64 && NotMaskLZ)
11769 NotMaskLZ -= 64-V.getValueSizeInBits();
11771 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
11772 switch (MaskedBytes) {
11776 default: return Result; // All one mask, or 5-byte mask.
11779 // Verify that the first bit starts at a multiple of mask so that the access
11780 // is aligned the same as the access width.
11781 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
11783 Result.first = MaskedBytes;
11784 Result.second = NotMaskTZ/8;
11789 /// Check to see if IVal is something that provides a value as specified by
11790 /// MaskInfo. If so, replace the specified store with a narrower store of
11791 /// truncated IVal.
11793 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
11794 SDValue IVal, StoreSDNode *St,
11796 unsigned NumBytes = MaskInfo.first;
11797 unsigned ByteShift = MaskInfo.second;
11798 SelectionDAG &DAG = DC->getDAG();
11800 // Check to see if IVal is all zeros in the part being masked in by the 'or'
11801 // that uses this. If not, this is not a replacement.
11802 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
11803 ByteShift*8, (ByteShift+NumBytes)*8);
11804 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
11806 // Check that it is legal on the target to do this. It is legal if the new
11807 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
11809 MVT VT = MVT::getIntegerVT(NumBytes*8);
11810 if (!DC->isTypeLegal(VT))
11813 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
11814 // shifted by ByteShift and truncated down to NumBytes.
11817 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
11818 DAG.getConstant(ByteShift*8, DL,
11819 DC->getShiftAmountTy(IVal.getValueType())));
11822 // Figure out the offset for the store and the alignment of the access.
11824 unsigned NewAlign = St->getAlignment();
11826 if (DAG.getDataLayout().isLittleEndian())
11827 StOffset = ByteShift;
11829 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11831 SDValue Ptr = St->getBasePtr();
11834 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11835 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11836 NewAlign = MinAlign(NewAlign, StOffset);
11839 // Truncate down to the new size.
11840 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11844 .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11845 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11850 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11851 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11852 /// narrowing the load and store if it would end up being a win for performance
11854 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11855 StoreSDNode *ST = cast<StoreSDNode>(N);
11856 if (ST->isVolatile())
11859 SDValue Chain = ST->getChain();
11860 SDValue Value = ST->getValue();
11861 SDValue Ptr = ST->getBasePtr();
11862 EVT VT = Value.getValueType();
11864 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11867 unsigned Opc = Value.getOpcode();
11869 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11870 // is a byte mask indicating a consecutive number of bytes, check to see if
11871 // Y is known to provide just those bytes. If so, we try to replace the
11872 // load + replace + store sequence with a single (narrower) store, which makes
11874 if (Opc == ISD::OR) {
11875 std::pair<unsigned, unsigned> MaskedLoad;
11876 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11877 if (MaskedLoad.first)
11878 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11879 Value.getOperand(1), ST,this))
11880 return SDValue(NewST, 0);
11882 // Or is commutative, so try swapping X and Y.
11883 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11884 if (MaskedLoad.first)
11885 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11886 Value.getOperand(0), ST,this))
11887 return SDValue(NewST, 0);
11890 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11891 Value.getOperand(1).getOpcode() != ISD::Constant)
11894 SDValue N0 = Value.getOperand(0);
11895 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11896 Chain == SDValue(N0.getNode(), 1)) {
11897 LoadSDNode *LD = cast<LoadSDNode>(N0);
11898 if (LD->getBasePtr() != Ptr ||
11899 LD->getPointerInfo().getAddrSpace() !=
11900 ST->getPointerInfo().getAddrSpace())
11903 // Find the type to narrow it the load / op / store to.
11904 SDValue N1 = Value.getOperand(1);
11905 unsigned BitWidth = N1.getValueSizeInBits();
11906 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11907 if (Opc == ISD::AND)
11908 Imm ^= APInt::getAllOnesValue(BitWidth);
11909 if (Imm == 0 || Imm.isAllOnesValue())
11911 unsigned ShAmt = Imm.countTrailingZeros();
11912 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11913 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11914 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11915 // The narrowing should be profitable, the load/store operation should be
11916 // legal (or custom) and the store size should be equal to the NewVT width.
11917 while (NewBW < BitWidth &&
11918 (NewVT.getStoreSizeInBits() != NewBW ||
11919 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11920 !TLI.isNarrowingProfitable(VT, NewVT))) {
11921 NewBW = NextPowerOf2(NewBW);
11922 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11924 if (NewBW >= BitWidth)
11927 // If the lsb changed does not start at the type bitwidth boundary,
11928 // start at the previous one.
11930 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11931 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11932 std::min(BitWidth, ShAmt + NewBW));
11933 if ((Imm & Mask) == Imm) {
11934 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11935 if (Opc == ISD::AND)
11936 NewImm ^= APInt::getAllOnesValue(NewBW);
11937 uint64_t PtrOff = ShAmt / 8;
11938 // For big endian targets, we need to adjust the offset to the pointer to
11939 // load the correct bytes.
11940 if (DAG.getDataLayout().isBigEndian())
11941 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11943 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11944 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11945 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11948 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11949 Ptr.getValueType(), Ptr,
11950 DAG.getConstant(PtrOff, SDLoc(LD),
11951 Ptr.getValueType()));
11953 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11954 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11955 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11956 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11957 DAG.getConstant(NewImm, SDLoc(Value),
11960 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11961 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11963 AddToWorklist(NewPtr.getNode());
11964 AddToWorklist(NewLD.getNode());
11965 AddToWorklist(NewVal.getNode());
11966 WorklistRemover DeadNodes(*this);
11967 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11976 /// For a given floating point load / store pair, if the load value isn't used
11977 /// by any other operations, then consider transforming the pair to integer
11978 /// load / store operations if the target deems the transformation profitable.
11979 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11980 StoreSDNode *ST = cast<StoreSDNode>(N);
11981 SDValue Chain = ST->getChain();
11982 SDValue Value = ST->getValue();
11983 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11984 Value.hasOneUse() &&
11985 Chain == SDValue(Value.getNode(), 1)) {
11986 LoadSDNode *LD = cast<LoadSDNode>(Value);
11987 EVT VT = LD->getMemoryVT();
11988 if (!VT.isFloatingPoint() ||
11989 VT != ST->getMemoryVT() ||
11990 LD->isNonTemporal() ||
11991 ST->isNonTemporal() ||
11992 LD->getPointerInfo().getAddrSpace() != 0 ||
11993 ST->getPointerInfo().getAddrSpace() != 0)
11996 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11997 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11998 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11999 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12000 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12003 unsigned LDAlign = LD->getAlignment();
12004 unsigned STAlign = ST->getAlignment();
12005 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12006 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12007 if (LDAlign < ABIAlign || STAlign < ABIAlign)
12011 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12012 LD->getPointerInfo(), LDAlign);
12015 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12016 ST->getPointerInfo(), STAlign);
12018 AddToWorklist(NewLD.getNode());
12019 AddToWorklist(NewST.getNode());
12020 WorklistRemover DeadNodes(*this);
12021 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12029 // This is a helper function for visitMUL to check the profitability
12030 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12031 // MulNode is the original multiply, AddNode is (add x, c1),
12032 // and ConstNode is c2.
12034 // If the (add x, c1) has multiple uses, we could increase
12035 // the number of adds if we make this transformation.
12036 // It would only be worth doing this if we can remove a
12037 // multiply in the process. Check for that here.
12041 // We're checking for cases where we have common "c3 * A" expressions.
12042 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12044 SDValue &ConstNode) {
12047 // If the add only has one use, this would be OK to do.
12048 if (AddNode.getNode()->hasOneUse())
12051 // Walk all the users of the constant with which we're multiplying.
12052 for (SDNode *Use : ConstNode->uses()) {
12054 if (Use == MulNode) // This use is the one we're on right now. Skip it.
12057 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12059 SDNode *MulVar = AddNode.getOperand(0).getNode();
12061 // OtherOp is what we're multiplying against the constant.
12062 if (Use->getOperand(0) == ConstNode)
12063 OtherOp = Use->getOperand(1).getNode();
12065 OtherOp = Use->getOperand(0).getNode();
12067 // Check to see if multiply is with the same operand of our "add".
12069 // ConstNode = CONST
12070 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
12072 // AddNode = (A + c1) <-- MulVar is A.
12073 // = AddNode * ConstNode <-- current visiting instruction.
12075 // If we make this transformation, we will have a common
12076 // multiply (ConstNode * A) that we can save.
12077 if (OtherOp == MulVar)
12080 // Now check to see if a future expansion will give us a common
12083 // ConstNode = CONST
12084 // AddNode = (A + c1)
12085 // ... = AddNode * ConstNode <-- current visiting instruction.
12087 // OtherOp = (A + c2)
12088 // Use = OtherOp * ConstNode <-- visiting Use.
12090 // If we make this transformation, we will have a common
12091 // multiply (CONST * A) after we also do the same transformation
12092 // to the "t2" instruction.
12093 if (OtherOp->getOpcode() == ISD::ADD &&
12094 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12095 OtherOp->getOperand(0).getNode() == MulVar)
12100 // Didn't find a case where this would be profitable.
12104 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12105 unsigned NumStores) {
12106 SmallVector<SDValue, 8> Chains;
12107 SmallPtrSet<const SDNode *, 8> Visited;
12108 SDLoc StoreDL(StoreNodes[0].MemNode);
12110 for (unsigned i = 0; i < NumStores; ++i) {
12111 Visited.insert(StoreNodes[i].MemNode);
12114 // don't include nodes that are children
12115 for (unsigned i = 0; i < NumStores; ++i) {
12116 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12117 Chains.push_back(StoreNodes[i].MemNode->getChain());
12120 assert(Chains.size() > 0 && "Chain should have generated a chain");
12121 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12124 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12125 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
12126 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
12127 // Make sure we have something to merge.
12131 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12133 // The latest Node in the DAG.
12134 SDLoc DL(StoreNodes[0].MemNode);
12138 bool IsVec = MemVT.isVector();
12139 unsigned Elts = NumStores;
12141 // When merging vector stores, get the total number of elements.
12142 Elts *= MemVT.getVectorNumElements();
12144 // Get the type for the merged vector store.
12145 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12146 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12148 if (IsConstantSrc) {
12149 SmallVector<SDValue, 8> BuildVector;
12150 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12151 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12152 SDValue Val = St->getValue();
12153 if (MemVT.getScalarType().isInteger())
12154 if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12155 Val = DAG.getConstant(
12156 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12157 SDLoc(CFP), MemVT);
12158 BuildVector.push_back(Val);
12160 StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12162 SmallVector<SDValue, 8> Ops;
12163 for (unsigned i = 0; i < NumStores; ++i) {
12164 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12165 SDValue Val = St->getValue();
12166 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12167 if (Val.getValueType() != MemVT)
12169 Ops.push_back(Val);
12172 // Build the extracted vector elements back into a vector.
12173 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12176 // We should always use a vector store when merging extracted vector
12177 // elements, so this path implies a store of constants.
12178 assert(IsConstantSrc && "Merged vector elements should use vector store");
12180 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12181 APInt StoreInt(SizeInBits, 0);
12183 // Construct a single integer constant which is made of the smaller
12184 // constant inputs.
12185 bool IsLE = DAG.getDataLayout().isLittleEndian();
12186 for (unsigned i = 0; i < NumStores; ++i) {
12187 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12188 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12190 SDValue Val = St->getValue();
12191 StoreInt <<= ElementSizeBytes * 8;
12192 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12193 StoreInt |= C->getAPIntValue().zext(SizeInBits);
12194 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12195 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
12197 llvm_unreachable("Invalid constant element type");
12201 // Create the new Load and Store operations.
12202 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12203 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12206 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12207 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12208 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
12209 FirstInChain->getBasePtr(),
12210 FirstInChain->getPointerInfo(),
12211 FirstInChain->getAlignment());
12213 // Replace all merged stores with the new store.
12214 for (unsigned i = 0; i < NumStores; ++i)
12215 CombineTo(StoreNodes[i].MemNode, NewStore);
12217 AddToWorklist(NewChain.getNode());
12221 void DAGCombiner::getStoreMergeCandidates(
12222 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12223 // This holds the base pointer, index, and the offset in bytes from the base
12225 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12226 EVT MemVT = St->getMemoryVT();
12228 // We must have a base and an offset.
12229 if (!BasePtr.Base.getNode())
12232 // Do not handle stores to undef base pointers.
12233 if (BasePtr.Base.isUndef())
12236 bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12237 bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12238 isa<ConstantFPSDNode>(St->getValue());
12239 bool IsExtractVecSrc =
12240 (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12241 St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12242 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr) -> bool {
12243 if (Other->isVolatile() || Other->isIndexed())
12245 // We can merge constant floats to equivalent integers
12246 if (Other->getMemoryVT() != MemVT)
12247 if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12248 isa<ConstantFPSDNode>(Other->getValue())))
12251 if (!isa<LoadSDNode>(Other->getValue()))
12254 if (!(isa<ConstantSDNode>(Other->getValue()) ||
12255 isa<ConstantFPSDNode>(Other->getValue())))
12257 if (IsExtractVecSrc)
12258 if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12259 Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12261 Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12262 return (Ptr.equalBaseIndex(BasePtr));
12264 // We looking for a root node which is an ancestor to all mergable
12265 // stores. We search up through a load, to our root and then down
12266 // through all children. For instance we will find Store{1,2,3} if
12267 // St is Store1, Store2. or Store3 where the root is not a load
12268 // which always true for nonvolatile ops. TODO: Expand
12269 // the search to find all valid candidates through multiple layers of loads.
12272 // |-------|-------|
12273 // Load Load Store3
12277 // FIXME: We should be able to climb and
12278 // descend TokenFactors to find candidates as well.
12280 SDNode *RootNode = (St->getChain()).getNode();
12282 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12283 RootNode = Ldn->getChain().getNode();
12284 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12285 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12286 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12287 if (I2.getOperandNo() == 0)
12288 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12289 BaseIndexOffset Ptr;
12290 if (CandidateMatch(OtherST, Ptr))
12291 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12294 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12295 if (I.getOperandNo() == 0)
12296 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12297 BaseIndexOffset Ptr;
12298 if (CandidateMatch(OtherST, Ptr))
12299 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12303 // We need to check that merging these stores does not cause a loop
12304 // in the DAG. Any store candidate may depend on another candidate
12305 // indirectly through its operand (we already consider dependencies
12306 // through the chain). Check in parallel by searching up from
12307 // non-chain operands of candidates.
12308 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12309 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12310 SmallPtrSet<const SDNode *, 16> Visited;
12311 SmallVector<const SDNode *, 8> Worklist;
12312 // search ops of store candidates
12313 for (unsigned i = 0; i < NumStores; ++i) {
12314 SDNode *n = StoreNodes[i].MemNode;
12315 // Potential loops may happen only through non-chain operands
12316 for (unsigned j = 1; j < n->getNumOperands(); ++j)
12317 Worklist.push_back(n->getOperand(j).getNode());
12319 // search through DAG. We can stop early if we find a storenode
12320 for (unsigned i = 0; i < NumStores; ++i) {
12321 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12327 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12328 if (OptLevel == CodeGenOpt::None)
12331 EVT MemVT = St->getMemoryVT();
12332 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12334 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12337 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12338 Attribute::NoImplicitFloat);
12340 // This function cannot currently deal with non-byte-sized memory sizes.
12341 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12344 if (!MemVT.isSimple())
12347 // Perform an early exit check. Do not bother looking at stored values that
12348 // are not constants, loads, or extracted vector elements.
12349 SDValue StoredVal = St->getValue();
12350 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12351 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12352 isa<ConstantFPSDNode>(StoredVal);
12353 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12354 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12356 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12359 // Don't merge vectors into wider vectors if the source data comes from loads.
12360 // TODO: This restriction can be lifted by using logic similar to the
12361 // ExtractVecSrc case.
12362 if (MemVT.isVector() && IsLoadSrc)
12365 SmallVector<MemOpLink, 8> StoreNodes;
12366 // Find potential store merge candidates by searching through chain sub-DAG
12367 getStoreMergeCandidates(St, StoreNodes);
12369 // Check if there is anything to merge.
12370 if (StoreNodes.size() < 2)
12373 // Sort the memory operands according to their distance from the
12375 std::sort(StoreNodes.begin(), StoreNodes.end(),
12376 [](MemOpLink LHS, MemOpLink RHS) {
12377 return LHS.OffsetFromBase < RHS.OffsetFromBase;
12380 // Store Merge attempts to merge the lowest stores. This generally
12381 // works out as if successful, as the remaining stores are checked
12382 // after the first collection of stores is merged. However, in the
12383 // case that a non-mergeable store is found first, e.g., {p[-2],
12384 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12385 // mergeable cases. To prevent this, we prune such stores from the
12386 // front of StoreNodes here.
12388 unsigned StartIdx = 0;
12389 while ((StartIdx + 1 < StoreNodes.size()) &&
12390 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12391 StoreNodes[StartIdx + 1].OffsetFromBase)
12394 // Bail if we don't have enough candidates to merge.
12395 if (StartIdx + 1 >= StoreNodes.size())
12399 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12401 // Scan the memory operations on the chain and find the first non-consecutive
12402 // store memory address.
12403 unsigned NumConsecutiveStores = 0;
12404 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12406 // Check that the addresses are consecutive starting from the second
12407 // element in the list of stores.
12408 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12409 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12410 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12412 NumConsecutiveStores = i + 1;
12415 if (NumConsecutiveStores < 2)
12418 // Check that we can merge these candidates without causing a cycle
12419 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumConsecutiveStores))
12423 // The node with the lowest store address.
12424 LLVMContext &Context = *DAG.getContext();
12425 const DataLayout &DL = DAG.getDataLayout();
12427 // Store the constants into memory as one consecutive store.
12428 if (IsConstantSrc) {
12430 while (NumConsecutiveStores > 1) {
12431 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12432 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12433 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12434 unsigned LastLegalType = 0;
12435 unsigned LastLegalVectorType = 0;
12436 bool NonZero = false;
12437 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12438 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12439 SDValue StoredVal = ST->getValue();
12441 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12442 NonZero |= !C->isNullValue();
12443 } else if (ConstantFPSDNode *C =
12444 dyn_cast<ConstantFPSDNode>(StoredVal)) {
12445 NonZero |= !C->getConstantFPValue()->isNullValue();
12451 // Find a legal type for the constant store.
12452 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12453 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12454 bool IsFast = false;
12455 if (TLI.isTypeLegal(StoreTy) &&
12456 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12457 FirstStoreAlign, &IsFast) &&
12459 LastLegalType = i + 1;
12460 // Or check whether a truncstore is legal.
12461 } else if (TLI.getTypeAction(Context, StoreTy) ==
12462 TargetLowering::TypePromoteInteger) {
12463 EVT LegalizedStoredValueTy =
12464 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12465 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12466 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12467 FirstStoreAS, FirstStoreAlign, &IsFast) &&
12469 LastLegalType = i + 1;
12473 // We only use vectors if the constant is known to be zero or the target
12474 // allows it and the function is not marked with the noimplicitfloat
12477 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12479 // Find a legal type for the vector store.
12480 EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1);
12481 if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(Ty) &&
12482 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12483 FirstStoreAlign, &IsFast) &&
12485 LastLegalVectorType = i + 1;
12489 // Check if we found a legal integer type that creates a meaningful merge.
12490 if (LastLegalType < 2 && LastLegalVectorType < 2)
12493 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12494 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12496 bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
12500 // Remove merged stores for next iteration.
12501 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12503 NumConsecutiveStores -= NumElem;
12508 // When extracting multiple vector elements, try to store them
12509 // in one vector store rather than a sequence of scalar stores.
12510 if (IsExtractVecSrc) {
12512 while (StoreNodes.size() >= 2) {
12513 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12514 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12515 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12516 unsigned NumStoresToMerge = 0;
12517 bool IsVec = MemVT.isVector();
12518 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12519 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12520 unsigned StoreValOpcode = St->getValue().getOpcode();
12521 // This restriction could be loosened.
12522 // Bail out if any stored values are not elements extracted from a
12523 // vector. It should be possible to handle mixed sources, but load
12524 // sources need more careful handling (see the block of code below that
12525 // handles consecutive loads).
12526 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12527 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12530 // Find a legal type for the vector store.
12531 unsigned Elts = i + 1;
12533 // When merging vector stores, get the total number of elements.
12534 Elts *= MemVT.getVectorNumElements();
12537 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12539 if (TLI.isTypeLegal(Ty) &&
12540 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12541 FirstStoreAlign, &IsFast) &&
12543 NumStoresToMerge = i + 1;
12546 bool Merged = MergeStoresOfConstantsOrVecElts(
12547 StoreNodes, MemVT, NumStoresToMerge, false, true);
12550 // Remove merged stores for next iteration.
12551 StoreNodes.erase(StoreNodes.begin(),
12552 StoreNodes.begin() + NumStoresToMerge);
12554 NumConsecutiveStores -= NumStoresToMerge;
12559 // Below we handle the case of multiple consecutive stores that
12560 // come from multiple consecutive loads. We merge them into a single
12561 // wide load and a single wide store.
12563 // Look for load nodes which are used by the stored values.
12564 SmallVector<MemOpLink, 8> LoadNodes;
12566 // Find acceptable loads. Loads need to have the same chain (token factor),
12567 // must not be zext, volatile, indexed, and they must be consecutive.
12568 BaseIndexOffset LdBasePtr;
12569 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12570 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12571 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12574 // Loads must only have one use.
12575 if (!Ld->hasNUsesOfValue(1, 0))
12578 // The memory operands must not be volatile.
12579 if (Ld->isVolatile() || Ld->isIndexed())
12582 // We do not accept ext loads.
12583 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12586 // The stored memory type must be the same.
12587 if (Ld->getMemoryVT() != MemVT)
12590 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12591 // If this is not the first ptr that we check.
12592 if (LdBasePtr.Base.getNode()) {
12593 // The base ptr must be the same.
12594 if (!LdPtr.equalBaseIndex(LdBasePtr))
12597 // Check that all other base pointers are the same as this one.
12601 // We found a potential memory operand to merge.
12602 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset));
12605 if (LoadNodes.size() < 2)
12608 // If we have load/store pair instructions and we only have two values,
12610 unsigned RequiredAlignment;
12611 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12612 St->getAlignment() >= RequiredAlignment)
12614 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12615 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12616 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12617 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12618 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12619 unsigned FirstLoadAlign = FirstLoad->getAlignment();
12621 // Scan the memory operations on the chain and find the first non-consecutive
12622 // load memory address. These variables hold the index in the store node
12624 unsigned LastConsecutiveLoad = 0;
12625 // This variable refers to the size and not index in the array.
12626 unsigned LastLegalVectorType = 0;
12627 unsigned LastLegalIntegerType = 0;
12628 StartAddress = LoadNodes[0].OffsetFromBase;
12629 SDValue FirstChain = FirstLoad->getChain();
12630 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12631 // All loads must share the same chain.
12632 if (LoadNodes[i].MemNode->getChain() != FirstChain)
12635 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12636 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12638 LastConsecutiveLoad = i;
12639 // Find a legal type for the vector store.
12640 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
12641 bool IsFastSt, IsFastLd;
12642 if (TLI.isTypeLegal(StoreTy) &&
12643 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12644 FirstStoreAlign, &IsFastSt) && IsFastSt &&
12645 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12646 FirstLoadAlign, &IsFastLd) && IsFastLd) {
12647 LastLegalVectorType = i + 1;
12650 // Find a legal type for the integer store.
12651 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
12652 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12653 if (TLI.isTypeLegal(StoreTy) &&
12654 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12655 FirstStoreAlign, &IsFastSt) && IsFastSt &&
12656 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12657 FirstLoadAlign, &IsFastLd) && IsFastLd)
12658 LastLegalIntegerType = i + 1;
12659 // Or check whether a truncstore and extload is legal.
12660 else if (TLI.getTypeAction(Context, StoreTy) ==
12661 TargetLowering::TypePromoteInteger) {
12662 EVT LegalizedStoredValueTy =
12663 TLI.getTypeToTransformTo(Context, StoreTy);
12664 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12665 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12666 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12667 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12668 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12669 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
12671 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12672 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
12674 LastLegalIntegerType = i+1;
12678 // Only use vector types if the vector type is larger than the integer type.
12679 // If they are the same, use integers.
12680 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
12681 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
12683 // We add +1 here because the LastXXX variables refer to location while
12684 // the NumElem refers to array/index size.
12685 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
12686 NumElem = std::min(LastLegalType, NumElem);
12691 // Find if it is better to use vectors or integers to load and store
12695 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12697 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12698 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12701 SDLoc LoadDL(LoadNodes[0].MemNode);
12702 SDLoc StoreDL(StoreNodes[0].MemNode);
12704 // The merged loads are required to have the same incoming chain, so
12705 // using the first's chain is acceptable.
12706 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12707 FirstLoad->getBasePtr(),
12708 FirstLoad->getPointerInfo(), FirstLoadAlign);
12710 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
12712 AddToWorklist(NewStoreChain.getNode());
12715 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12716 FirstInChain->getPointerInfo(), FirstStoreAlign);
12718 // Transfer chain users from old loads to the new load.
12719 for (unsigned i = 0; i < NumElem; ++i) {
12720 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12721 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12722 SDValue(NewLoad.getNode(), 1));
12725 // Replace the all stores with the new store.
12726 for (unsigned i = 0; i < NumElem; ++i)
12727 CombineTo(StoreNodes[i].MemNode, NewStore);
12731 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12735 // Replace the chain to avoid dependency.
12736 if (ST->isTruncatingStore()) {
12737 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12738 ST->getBasePtr(), ST->getMemoryVT(),
12739 ST->getMemOperand());
12741 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12742 ST->getMemOperand());
12745 // Create token to keep both nodes around.
12746 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12747 MVT::Other, ST->getChain(), ReplStore);
12749 // Make sure the new and old chains are cleaned up.
12750 AddToWorklist(Token.getNode());
12752 // Don't add users to work list.
12753 return CombineTo(ST, Token, false);
12756 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12757 SDValue Value = ST->getValue();
12758 if (Value.getOpcode() == ISD::TargetConstantFP)
12763 SDValue Chain = ST->getChain();
12764 SDValue Ptr = ST->getBasePtr();
12766 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12768 // NOTE: If the original store is volatile, this transform must not increase
12769 // the number of stores. For example, on x86-32 an f64 can be stored in one
12770 // processor operation but an i64 (which is not legal) requires two. So the
12771 // transform should not be done in this case.
12774 switch (CFP->getSimpleValueType(0).SimpleTy) {
12776 llvm_unreachable("Unknown FP type");
12777 case MVT::f16: // We don't do this for these yet.
12783 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12784 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12786 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12787 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12789 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12794 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12795 !ST->isVolatile()) ||
12796 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12798 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12799 getZExtValue(), SDLoc(CFP), MVT::i64);
12800 return DAG.getStore(Chain, DL, Tmp,
12801 Ptr, ST->getMemOperand());
12804 if (!ST->isVolatile() &&
12805 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12806 // Many FP stores are not made apparent until after legalize, e.g. for
12807 // argument passing. Since this is so common, custom legalize the
12808 // 64-bit integer store into two 32-bit stores.
12809 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12810 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12811 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12812 if (DAG.getDataLayout().isBigEndian())
12815 unsigned Alignment = ST->getAlignment();
12816 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12817 AAMDNodes AAInfo = ST->getAAInfo();
12819 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12820 ST->getAlignment(), MMOFlags, AAInfo);
12821 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12822 DAG.getConstant(4, DL, Ptr.getValueType()));
12823 Alignment = MinAlign(Alignment, 4U);
12824 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12825 ST->getPointerInfo().getWithOffset(4),
12826 Alignment, MMOFlags, AAInfo);
12827 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12835 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12836 StoreSDNode *ST = cast<StoreSDNode>(N);
12837 SDValue Chain = ST->getChain();
12838 SDValue Value = ST->getValue();
12839 SDValue Ptr = ST->getBasePtr();
12841 // If this is a store of a bit convert, store the input value if the
12842 // resultant store does not need a higher alignment than the original.
12843 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12844 ST->isUnindexed()) {
12845 EVT SVT = Value.getOperand(0).getValueType();
12846 if (((!LegalOperations && !ST->isVolatile()) ||
12847 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12848 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12849 unsigned OrigAlign = ST->getAlignment();
12851 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12852 ST->getAddressSpace(), OrigAlign, &Fast) &&
12854 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12855 ST->getPointerInfo(), OrigAlign,
12856 ST->getMemOperand()->getFlags(), ST->getAAInfo());
12861 // Turn 'store undef, Ptr' -> nothing.
12862 if (Value.isUndef() && ST->isUnindexed())
12865 // Try to infer better alignment information than the store already has.
12866 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12867 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12868 if (Align > ST->getAlignment()) {
12870 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12871 ST->getMemoryVT(), Align,
12872 ST->getMemOperand()->getFlags(), ST->getAAInfo());
12873 if (NewStore.getNode() != N)
12874 return CombineTo(ST, NewStore, true);
12879 // Try transforming a pair floating point load / store ops to integer
12880 // load / store ops.
12881 if (SDValue NewST = TransformFPLoadStorePair(N))
12884 if (ST->isUnindexed()) {
12885 // Walk up chain skipping non-aliasing memory nodes, on this store and any
12886 // adjacent stores.
12887 if (findBetterNeighborChains(ST)) {
12888 // replaceStoreChain uses CombineTo, which handled all of the worklist
12889 // manipulation. Return the original node to not do anything else.
12890 return SDValue(ST, 0);
12892 Chain = ST->getChain();
12895 // Try transforming N to an indexed store.
12896 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12897 return SDValue(N, 0);
12899 // FIXME: is there such a thing as a truncating indexed store?
12900 if (ST->isTruncatingStore() && ST->isUnindexed() &&
12901 Value.getValueType().isInteger()) {
12902 // See if we can simplify the input to this truncstore with knowledge that
12903 // only the low bits are being used. For example:
12904 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
12905 SDValue Shorter = GetDemandedBits(
12906 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12907 ST->getMemoryVT().getScalarSizeInBits()));
12908 AddToWorklist(Value.getNode());
12909 if (Shorter.getNode())
12910 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12911 Ptr, ST->getMemoryVT(), ST->getMemOperand());
12913 // Otherwise, see if we can simplify the operation with
12914 // SimplifyDemandedBits, which only works if the value has a single use.
12915 if (SimplifyDemandedBits(
12917 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12918 ST->getMemoryVT().getScalarSizeInBits()))) {
12919 // Re-visit the store if anything changed and the store hasn't been merged
12920 // with another node (N is deleted) SimplifyDemandedBits will add Value's
12921 // node back to the worklist if necessary, but we also need to re-visit
12922 // the Store node itself.
12923 if (N->getOpcode() != ISD::DELETED_NODE)
12925 return SDValue(N, 0);
12929 // If this is a load followed by a store to the same location, then the store
12931 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12932 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12933 ST->isUnindexed() && !ST->isVolatile() &&
12934 // There can't be any side effects between the load and store, such as
12935 // a call or store.
12936 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12937 // The store is dead, remove it.
12942 // If this is a store followed by a store with the same value to the same
12943 // location, then the store is dead/noop.
12944 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12945 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12946 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12947 ST1->isUnindexed() && !ST1->isVolatile()) {
12948 // The store is dead, remove it.
12953 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12954 // truncating store. We can do this even if this is already a truncstore.
12955 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12956 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12957 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12958 ST->getMemoryVT())) {
12959 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12960 Ptr, ST->getMemoryVT(), ST->getMemOperand());
12963 // Only perform this optimization before the types are legal, because we
12964 // don't want to perform this optimization on every DAGCombine invocation.
12967 // There can be multiple store sequences on the same chain.
12968 // Keep trying to merge store sequences until we are unable to do so
12969 // or until we merge the last store on the chain.
12970 bool Changed = MergeConsecutiveStores(ST);
12971 if (!Changed) break;
12972 // Return N as merge only uses CombineTo and no worklist clean
12973 // up is necessary.
12974 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
12975 return SDValue(N, 0);
12979 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12981 // Make sure to do this only after attempting to merge stores in order to
12982 // avoid changing the types of some subset of stores due to visit order,
12983 // preventing their merging.
12984 if (isa<ConstantFPSDNode>(ST->getValue())) {
12985 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12989 if (SDValue NewSt = splitMergedValStore(ST))
12992 return ReduceLoadOpStoreWidth(N);
12995 /// For the instruction sequence of store below, F and I values
12996 /// are bundled together as an i64 value before being stored into memory.
12997 /// Sometimes it is more efficent to generate separate stores for F and I,
12998 /// which can remove the bitwise instructions or sink them to colder places.
13000 /// (store (or (zext (bitcast F to i32) to i64),
13001 /// (shl (zext I to i64), 32)), addr) -->
13002 /// (store F, addr) and (store I, addr+4)
13004 /// Similarly, splitting for other merged store can also be beneficial, like:
13005 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13006 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13007 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13008 /// For pair of {i16, i8}, i32 store --> two i16 stores.
13009 /// For pair of {i8, i8}, i16 store --> two i8 stores.
13011 /// We allow each target to determine specifically which kind of splitting is
13014 /// The store patterns are commonly seen from the simple code snippet below
13015 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13016 /// void goo(const std::pair<int, float> &);
13019 /// goo(std::make_pair(tmp, ftmp));
13023 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13024 if (OptLevel == CodeGenOpt::None)
13027 SDValue Val = ST->getValue();
13030 // Match OR operand.
13031 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13034 // Match SHL operand and get Lower and Higher parts of Val.
13035 SDValue Op1 = Val.getOperand(0);
13036 SDValue Op2 = Val.getOperand(1);
13038 if (Op1.getOpcode() != ISD::SHL) {
13039 std::swap(Op1, Op2);
13040 if (Op1.getOpcode() != ISD::SHL)
13044 Hi = Op1.getOperand(0);
13045 if (!Op1.hasOneUse())
13048 // Match shift amount to HalfValBitSize.
13049 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13050 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13051 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13054 // Lo and Hi are zero-extended from int with size less equal than 32
13056 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13057 !Lo.getOperand(0).getValueType().isScalarInteger() ||
13058 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13059 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13060 !Hi.getOperand(0).getValueType().isScalarInteger() ||
13061 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13064 // Use the EVT of low and high parts before bitcast as the input
13065 // of target query.
13066 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13067 ? Lo.getOperand(0).getValueType()
13068 : Lo.getValueType();
13069 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13070 ? Hi.getOperand(0).getValueType()
13071 : Hi.getValueType();
13072 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13075 // Start to split store.
13076 unsigned Alignment = ST->getAlignment();
13077 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13078 AAMDNodes AAInfo = ST->getAAInfo();
13080 // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13081 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13082 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13083 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13085 SDValue Chain = ST->getChain();
13086 SDValue Ptr = ST->getBasePtr();
13087 // Lower value store.
13088 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13089 ST->getAlignment(), MMOFlags, AAInfo);
13091 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13092 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13093 // Higher value store.
13095 DAG.getStore(St0, DL, Hi, Ptr,
13096 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13097 Alignment / 2, MMOFlags, AAInfo);
13101 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13102 SDValue InVec = N->getOperand(0);
13103 SDValue InVal = N->getOperand(1);
13104 SDValue EltNo = N->getOperand(2);
13107 // If the inserted element is an UNDEF, just use the input vector.
13108 if (InVal.isUndef())
13111 EVT VT = InVec.getValueType();
13113 // Check that we know which element is being inserted
13114 if (!isa<ConstantSDNode>(EltNo))
13116 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13118 // Canonicalize insert_vector_elt dag nodes.
13120 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13121 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13123 // Do this only if the child insert_vector node has one use; also
13124 // do this only if indices are both constants and Idx1 < Idx0.
13125 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13126 && isa<ConstantSDNode>(InVec.getOperand(2))) {
13127 unsigned OtherElt = InVec.getConstantOperandVal(2);
13128 if (Elt < OtherElt) {
13130 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13131 InVec.getOperand(0), InVal, EltNo);
13132 AddToWorklist(NewOp.getNode());
13133 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13134 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13138 // If we can't generate a legal BUILD_VECTOR, exit
13139 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13142 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13143 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
13144 // vector elements.
13145 SmallVector<SDValue, 8> Ops;
13146 // Do not combine these two vectors if the output vector will not replace
13147 // the input vector.
13148 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13149 Ops.append(InVec.getNode()->op_begin(),
13150 InVec.getNode()->op_end());
13151 } else if (InVec.isUndef()) {
13152 unsigned NElts = VT.getVectorNumElements();
13153 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13158 // Insert the element
13159 if (Elt < Ops.size()) {
13160 // All the operands of BUILD_VECTOR must have the same type;
13161 // we enforce that here.
13162 EVT OpVT = Ops[0].getValueType();
13163 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13166 // Return the new vector
13167 return DAG.getBuildVector(VT, DL, Ops);
13170 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13171 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13172 assert(!OriginalLoad->isVolatile());
13174 EVT ResultVT = EVE->getValueType(0);
13175 EVT VecEltVT = InVecVT.getVectorElementType();
13176 unsigned Align = OriginalLoad->getAlignment();
13177 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13178 VecEltVT.getTypeForEVT(*DAG.getContext()));
13180 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13183 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13184 ISD::NON_EXTLOAD : ISD::EXTLOAD;
13185 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13190 SDValue NewPtr = OriginalLoad->getBasePtr();
13192 EVT PtrType = NewPtr.getValueType();
13193 MachinePointerInfo MPI;
13195 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13196 int Elt = ConstEltNo->getZExtValue();
13197 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13198 Offset = DAG.getConstant(PtrOff, DL, PtrType);
13199 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13201 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13202 Offset = DAG.getNode(
13203 ISD::MUL, DL, PtrType, Offset,
13204 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13205 MPI = OriginalLoad->getPointerInfo();
13207 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13209 // The replacement we need to do here is a little tricky: we need to
13210 // replace an extractelement of a load with a load.
13211 // Use ReplaceAllUsesOfValuesWith to do the replacement.
13212 // Note that this replacement assumes that the extractvalue is the only
13213 // use of the load; that's okay because we don't want to perform this
13214 // transformation in other cases anyway.
13217 if (ResultVT.bitsGT(VecEltVT)) {
13218 // If the result type of vextract is wider than the load, then issue an
13219 // extending load instead.
13220 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13224 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13225 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13226 Align, OriginalLoad->getMemOperand()->getFlags(),
13227 OriginalLoad->getAAInfo());
13228 Chain = Load.getValue(1);
13230 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13231 MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13232 OriginalLoad->getAAInfo());
13233 Chain = Load.getValue(1);
13234 if (ResultVT.bitsLT(VecEltVT))
13235 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13237 Load = DAG.getBitcast(ResultVT, Load);
13239 WorklistRemover DeadNodes(*this);
13240 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13241 SDValue To[] = { Load, Chain };
13242 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13243 // Since we're explicitly calling ReplaceAllUses, add the new node to the
13244 // worklist explicitly as well.
13245 AddToWorklist(Load.getNode());
13246 AddUsersToWorklist(Load.getNode()); // Add users too
13247 // Make sure to revisit this node to clean it up; it will usually be dead.
13248 AddToWorklist(EVE);
13250 return SDValue(EVE, 0);
13253 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13254 // (vextract (scalar_to_vector val, 0) -> val
13255 SDValue InVec = N->getOperand(0);
13256 EVT VT = InVec.getValueType();
13257 EVT NVT = N->getValueType(0);
13259 if (InVec.isUndef())
13260 return DAG.getUNDEF(NVT);
13262 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13263 // Check if the result type doesn't match the inserted element type. A
13264 // SCALAR_TO_VECTOR may truncate the inserted element and the
13265 // EXTRACT_VECTOR_ELT may widen the extracted vector.
13266 SDValue InOp = InVec.getOperand(0);
13267 if (InOp.getValueType() != NVT) {
13268 assert(InOp.getValueType().isInteger() && NVT.isInteger());
13269 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13274 SDValue EltNo = N->getOperand(1);
13275 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13277 // extract_vector_elt (build_vector x, y), 1 -> y
13279 InVec.getOpcode() == ISD::BUILD_VECTOR &&
13280 TLI.isTypeLegal(VT) &&
13281 (InVec.hasOneUse() ||
13282 TLI.aggressivelyPreferBuildVectorSources(VT))) {
13283 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13284 EVT InEltVT = Elt.getValueType();
13286 // Sometimes build_vector's scalar input types do not match result type.
13287 if (NVT == InEltVT)
13290 // TODO: It may be useful to truncate if free if the build_vector implicitly
13294 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13295 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13296 ConstEltNo->isNullValue() && VT.isInteger()) {
13297 SDValue BCSrc = InVec.getOperand(0);
13298 if (BCSrc.getValueType().isScalarInteger())
13299 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13302 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13304 // This only really matters if the index is non-constant since other combines
13305 // on the constant elements already work.
13306 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13307 EltNo == InVec.getOperand(2)) {
13308 SDValue Elt = InVec.getOperand(1);
13309 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13312 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13313 // We only perform this optimization before the op legalization phase because
13314 // we may introduce new vector instructions which are not backed by TD
13315 // patterns. For example on AVX, extracting elements from a wide vector
13316 // without using extract_subvector. However, if we can find an underlying
13317 // scalar value, then we can always use that.
13318 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13319 int NumElem = VT.getVectorNumElements();
13320 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13321 // Find the new index to extract from.
13322 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13324 // Extracting an undef index is undef.
13326 return DAG.getUNDEF(NVT);
13328 // Select the right vector half to extract from.
13330 if (OrigElt < NumElem) {
13331 SVInVec = InVec->getOperand(0);
13333 SVInVec = InVec->getOperand(1);
13334 OrigElt -= NumElem;
13337 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13338 SDValue InOp = SVInVec.getOperand(OrigElt);
13339 if (InOp.getValueType() != NVT) {
13340 assert(InOp.getValueType().isInteger() && NVT.isInteger());
13341 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13347 // FIXME: We should handle recursing on other vector shuffles and
13348 // scalar_to_vector here as well.
13350 if (!LegalOperations) {
13351 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13352 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13353 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13357 bool BCNumEltsChanged = false;
13358 EVT ExtVT = VT.getVectorElementType();
13361 // If the result of load has to be truncated, then it's not necessarily
13363 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13366 if (InVec.getOpcode() == ISD::BITCAST) {
13367 // Don't duplicate a load with other uses.
13368 if (!InVec.hasOneUse())
13371 EVT BCVT = InVec.getOperand(0).getValueType();
13372 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13374 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13375 BCNumEltsChanged = true;
13376 InVec = InVec.getOperand(0);
13377 ExtVT = BCVT.getVectorElementType();
13380 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13381 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13382 ISD::isNormalLoad(InVec.getNode()) &&
13383 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13384 SDValue Index = N->getOperand(1);
13385 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13386 if (!OrigLoad->isVolatile()) {
13387 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13393 // Perform only after legalization to ensure build_vector / vector_shuffle
13394 // optimizations have already been done.
13395 if (!LegalOperations) return SDValue();
13397 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13398 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13399 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13402 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13404 LoadSDNode *LN0 = nullptr;
13405 const ShuffleVectorSDNode *SVN = nullptr;
13406 if (ISD::isNormalLoad(InVec.getNode())) {
13407 LN0 = cast<LoadSDNode>(InVec);
13408 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13409 InVec.getOperand(0).getValueType() == ExtVT &&
13410 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13411 // Don't duplicate a load with other uses.
13412 if (!InVec.hasOneUse())
13415 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13416 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13417 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13419 // (load $addr+1*size)
13421 // Don't duplicate a load with other uses.
13422 if (!InVec.hasOneUse())
13425 // If the bit convert changed the number of elements, it is unsafe
13426 // to examine the mask.
13427 if (BCNumEltsChanged)
13430 // Select the input vector, guarding against out of range extract vector.
13431 unsigned NumElems = VT.getVectorNumElements();
13432 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13433 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13435 if (InVec.getOpcode() == ISD::BITCAST) {
13436 // Don't duplicate a load with other uses.
13437 if (!InVec.hasOneUse())
13440 InVec = InVec.getOperand(0);
13442 if (ISD::isNormalLoad(InVec.getNode())) {
13443 LN0 = cast<LoadSDNode>(InVec);
13444 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13445 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13449 // Make sure we found a non-volatile load and the extractelement is
13451 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13454 // If Idx was -1 above, Elt is going to be -1, so just return undef.
13456 return DAG.getUNDEF(LVT);
13458 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13464 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13465 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13466 // We perform this optimization post type-legalization because
13467 // the type-legalizer often scalarizes integer-promoted vectors.
13468 // Performing this optimization before may create bit-casts which
13469 // will be type-legalized to complex code sequences.
13470 // We perform this optimization only before the operation legalizer because we
13471 // may introduce illegal operations.
13472 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13475 unsigned NumInScalars = N->getNumOperands();
13477 EVT VT = N->getValueType(0);
13479 // Check to see if this is a BUILD_VECTOR of a bunch of values
13480 // which come from any_extend or zero_extend nodes. If so, we can create
13481 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13482 // optimizations. We do not handle sign-extend because we can't fill the sign
13484 EVT SourceType = MVT::Other;
13485 bool AllAnyExt = true;
13487 for (unsigned i = 0; i != NumInScalars; ++i) {
13488 SDValue In = N->getOperand(i);
13489 // Ignore undef inputs.
13490 if (In.isUndef()) continue;
13492 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
13493 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13495 // Abort if the element is not an extension.
13496 if (!ZeroExt && !AnyExt) {
13497 SourceType = MVT::Other;
13501 // The input is a ZeroExt or AnyExt. Check the original type.
13502 EVT InTy = In.getOperand(0).getValueType();
13504 // Check that all of the widened source types are the same.
13505 if (SourceType == MVT::Other)
13508 else if (InTy != SourceType) {
13509 // Multiple income types. Abort.
13510 SourceType = MVT::Other;
13514 // Check if all of the extends are ANY_EXTENDs.
13515 AllAnyExt &= AnyExt;
13518 // In order to have valid types, all of the inputs must be extended from the
13519 // same source type and all of the inputs must be any or zero extend.
13520 // Scalar sizes must be a power of two.
13521 EVT OutScalarTy = VT.getScalarType();
13522 bool ValidTypes = SourceType != MVT::Other &&
13523 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13524 isPowerOf2_32(SourceType.getSizeInBits());
13526 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13527 // turn into a single shuffle instruction.
13531 bool isLE = DAG.getDataLayout().isLittleEndian();
13532 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13533 assert(ElemRatio > 1 && "Invalid element size ratio");
13534 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13535 DAG.getConstant(0, DL, SourceType);
13537 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13538 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13540 // Populate the new build_vector
13541 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13542 SDValue Cast = N->getOperand(i);
13543 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13544 Cast.getOpcode() == ISD::ZERO_EXTEND ||
13545 Cast.isUndef()) && "Invalid cast opcode");
13547 if (Cast.isUndef())
13548 In = DAG.getUNDEF(SourceType);
13550 In = Cast->getOperand(0);
13551 unsigned Index = isLE ? (i * ElemRatio) :
13552 (i * ElemRatio + (ElemRatio - 1));
13554 assert(Index < Ops.size() && "Invalid index");
13558 // The type of the new BUILD_VECTOR node.
13559 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13560 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13561 "Invalid vector size");
13562 // Check if the new vector type is legal.
13563 if (!isTypeLegal(VecVT)) return SDValue();
13565 // Make the new BUILD_VECTOR.
13566 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13568 // The new BUILD_VECTOR node has the potential to be further optimized.
13569 AddToWorklist(BV.getNode());
13570 // Bitcast to the desired type.
13571 return DAG.getBitcast(VT, BV);
13574 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13575 EVT VT = N->getValueType(0);
13577 unsigned NumInScalars = N->getNumOperands();
13580 EVT SrcVT = MVT::Other;
13581 unsigned Opcode = ISD::DELETED_NODE;
13582 unsigned NumDefs = 0;
13584 for (unsigned i = 0; i != NumInScalars; ++i) {
13585 SDValue In = N->getOperand(i);
13586 unsigned Opc = In.getOpcode();
13588 if (Opc == ISD::UNDEF)
13591 // If all scalar values are floats and converted from integers.
13592 if (Opcode == ISD::DELETED_NODE &&
13593 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13600 EVT InVT = In.getOperand(0).getValueType();
13602 // If all scalar values are typed differently, bail out. It's chosen to
13603 // simplify BUILD_VECTOR of integer types.
13604 if (SrcVT == MVT::Other)
13611 // If the vector has just one element defined, it's not worth to fold it into
13612 // a vectorized one.
13616 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13617 && "Should only handle conversion from integer to float.");
13618 assert(SrcVT != MVT::Other && "Cannot determine source type!");
13620 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
13622 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
13625 // Just because the floating-point vector type is legal does not necessarily
13626 // mean that the corresponding integer vector type is.
13627 if (!isTypeLegal(NVT))
13630 SmallVector<SDValue, 8> Opnds;
13631 for (unsigned i = 0; i != NumInScalars; ++i) {
13632 SDValue In = N->getOperand(i);
13635 Opnds.push_back(DAG.getUNDEF(SrcVT));
13637 Opnds.push_back(In.getOperand(0));
13639 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
13640 AddToWorklist(BV.getNode());
13642 return DAG.getNode(Opcode, DL, VT, BV);
13645 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
13646 ArrayRef<int> VectorMask,
13647 SDValue VecIn1, SDValue VecIn2,
13648 unsigned LeftIdx) {
13649 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13650 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
13652 EVT VT = N->getValueType(0);
13653 EVT InVT1 = VecIn1.getValueType();
13654 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13656 unsigned Vec2Offset = InVT1.getVectorNumElements();
13657 unsigned NumElems = VT.getVectorNumElements();
13658 unsigned ShuffleNumElems = NumElems;
13660 // We can't generate a shuffle node with mismatched input and output types.
13661 // Try to make the types match the type of the output.
13662 if (InVT1 != VT || InVT2 != VT) {
13663 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13664 // If the output vector length is a multiple of both input lengths,
13665 // we can concatenate them and pad the rest with undefs.
13666 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13667 assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13668 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13669 ConcatOps[0] = VecIn1;
13670 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13671 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13672 VecIn2 = SDValue();
13673 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13674 if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13677 if (!VecIn2.getNode()) {
13678 // If we only have one input vector, and it's twice the size of the
13679 // output, split it in two.
13680 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13681 DAG.getConstant(NumElems, DL, IdxTy));
13682 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13683 // Since we now have shorter input vectors, adjust the offset of the
13684 // second vector's start.
13685 Vec2Offset = NumElems;
13686 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13687 // VecIn1 is wider than the output, and we have another, possibly
13688 // smaller input. Pad the smaller input with undefs, shuffle at the
13689 // input vector width, and extract the output.
13690 // The shuffle type is different than VT, so check legality again.
13691 if (LegalOperations &&
13692 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13695 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
13696 // lower it back into a BUILD_VECTOR. So if the inserted type is
13697 // illegal, don't even try.
13698 if (InVT1 != InVT2) {
13699 if (!TLI.isTypeLegal(InVT2))
13701 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13702 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13704 ShuffleNumElems = NumElems * 2;
13706 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13707 // than VecIn1. We can't handle this for now - this case will disappear
13708 // when we start sorting the vectors by type.
13712 // TODO: Support cases where the length mismatch isn't exactly by a
13714 // TODO: Move this check upwards, so that if we have bad type
13715 // mismatches, we don't create any DAG nodes.
13720 // Initialize mask to undef.
13721 SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13723 // Only need to run up to the number of elements actually used, not the
13724 // total number of elements in the shuffle - if we are shuffling a wider
13725 // vector, the high lanes should be set to undef.
13726 for (unsigned i = 0; i != NumElems; ++i) {
13727 if (VectorMask[i] <= 0)
13730 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13731 if (VectorMask[i] == (int)LeftIdx) {
13732 Mask[i] = ExtIndex;
13733 } else if (VectorMask[i] == (int)LeftIdx + 1) {
13734 Mask[i] = Vec2Offset + ExtIndex;
13738 // The type the input vectors may have changed above.
13739 InVT1 = VecIn1.getValueType();
13741 // If we already have a VecIn2, it should have the same type as VecIn1.
13742 // If we don't, get an undef/zero vector of the appropriate type.
13743 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13744 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13746 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13747 if (ShuffleNumElems > NumElems)
13748 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13753 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13754 // operations. If the types of the vectors we're extracting from allow it,
13755 // turn this into a vector_shuffle node.
13756 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13758 EVT VT = N->getValueType(0);
13760 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13761 if (!isTypeLegal(VT))
13764 // May only combine to shuffle after legalize if shuffle is legal.
13765 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13768 bool UsesZeroVector = false;
13769 unsigned NumElems = N->getNumOperands();
13771 // Record, for each element of the newly built vector, which input vector
13772 // that element comes from. -1 stands for undef, 0 for the zero vector,
13773 // and positive values for the input vectors.
13774 // VectorMask maps each element to its vector number, and VecIn maps vector
13775 // numbers to their initial SDValues.
13777 SmallVector<int, 8> VectorMask(NumElems, -1);
13778 SmallVector<SDValue, 8> VecIn;
13779 VecIn.push_back(SDValue());
13781 for (unsigned i = 0; i != NumElems; ++i) {
13782 SDValue Op = N->getOperand(i);
13787 // See if we can use a blend with a zero vector.
13788 // TODO: Should we generalize this to a blend with an arbitrary constant
13790 if (isNullConstant(Op) || isNullFPConstant(Op)) {
13791 UsesZeroVector = true;
13796 // Not an undef or zero. If the input is something other than an
13797 // EXTRACT_VECTOR_ELT with a constant index, bail out.
13798 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13799 !isa<ConstantSDNode>(Op.getOperand(1)))
13802 SDValue ExtractedFromVec = Op.getOperand(0);
13804 // All inputs must have the same element type as the output.
13805 if (VT.getVectorElementType() !=
13806 ExtractedFromVec.getValueType().getVectorElementType())
13809 // Have we seen this input vector before?
13810 // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13811 // a map back from SDValues to numbers isn't worth it.
13812 unsigned Idx = std::distance(
13813 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13814 if (Idx == VecIn.size())
13815 VecIn.push_back(ExtractedFromVec);
13817 VectorMask[i] = Idx;
13820 // If we didn't find at least one input vector, bail out.
13821 if (VecIn.size() < 2)
13824 // TODO: We want to sort the vectors by descending length, so that adjacent
13825 // pairs have similar length, and the longer vector is always first in the
13828 // TODO: Should this fire if some of the input vectors has illegal type (like
13829 // it does now), or should we let legalization run its course first?
13832 // Take pairs of vectors, and shuffle them so that the result has elements
13833 // from these vectors in the correct places.
13834 // For example, given:
13835 // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13836 // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13837 // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13838 // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13839 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13840 // We will generate:
13841 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13842 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13843 SmallVector<SDValue, 4> Shuffles;
13844 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13845 unsigned LeftIdx = 2 * In + 1;
13846 SDValue VecLeft = VecIn[LeftIdx];
13848 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13850 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13851 VecRight, LeftIdx))
13852 Shuffles.push_back(Shuffle);
13857 // If we need the zero vector as an "ingredient" in the blend tree, add it
13858 // to the list of shuffles.
13859 if (UsesZeroVector)
13860 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13861 : DAG.getConstantFP(0.0, DL, VT));
13863 // If we only have one shuffle, we're done.
13864 if (Shuffles.size() == 1)
13865 return Shuffles[0];
13867 // Update the vector mask to point to the post-shuffle vectors.
13868 for (int &Vec : VectorMask)
13870 Vec = Shuffles.size() - 1;
13872 Vec = (Vec - 1) / 2;
13874 // More than one shuffle. Generate a binary tree of blends, e.g. if from
13875 // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13877 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13878 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13879 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13880 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13881 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13882 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13883 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13885 // Make sure the initial size of the shuffle list is even.
13886 if (Shuffles.size() % 2)
13887 Shuffles.push_back(DAG.getUNDEF(VT));
13889 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13891 Shuffles[CurSize] = DAG.getUNDEF(VT);
13894 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13896 int Right = 2 * In + 1;
13897 SmallVector<int, 8> Mask(NumElems, -1);
13898 for (unsigned i = 0; i != NumElems; ++i) {
13899 if (VectorMask[i] == Left) {
13901 VectorMask[i] = In;
13902 } else if (VectorMask[i] == Right) {
13903 Mask[i] = i + NumElems;
13904 VectorMask[i] = In;
13909 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13913 return Shuffles[0];
13916 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13917 EVT VT = N->getValueType(0);
13919 // A vector built entirely of undefs is undef.
13920 if (ISD::allOperandsUndef(N))
13921 return DAG.getUNDEF(VT);
13923 // Check if we can express BUILD VECTOR via subvector extract.
13924 if (!LegalTypes && (N->getNumOperands() > 1)) {
13925 SDValue Op0 = N->getOperand(0);
13926 auto checkElem = [&](SDValue Op) -> uint64_t {
13927 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
13928 (Op0.getOperand(0) == Op.getOperand(0)))
13929 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
13930 return CNode->getZExtValue();
13934 int Offset = checkElem(Op0);
13935 for (unsigned i = 0; i < N->getNumOperands(); ++i) {
13936 if (Offset + i != checkElem(N->getOperand(i))) {
13942 if ((Offset == 0) &&
13943 (Op0.getOperand(0).getValueType() == N->getValueType(0)))
13944 return Op0.getOperand(0);
13945 if ((Offset != -1) &&
13946 ((Offset % N->getValueType(0).getVectorNumElements()) ==
13947 0)) // IDX must be multiple of output size.
13948 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
13949 Op0.getOperand(0), Op0.getOperand(1));
13952 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13955 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13958 if (SDValue V = reduceBuildVecToShuffle(N))
13964 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13965 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13966 EVT OpVT = N->getOperand(0).getValueType();
13968 // If the operands are legal vectors, leave them alone.
13969 if (TLI.isTypeLegal(OpVT))
13973 EVT VT = N->getValueType(0);
13974 SmallVector<SDValue, 8> Ops;
13976 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13977 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13979 // Keep track of what we encounter.
13980 bool AnyInteger = false;
13981 bool AnyFP = false;
13982 for (const SDValue &Op : N->ops()) {
13983 if (ISD::BITCAST == Op.getOpcode() &&
13984 !Op.getOperand(0).getValueType().isVector())
13985 Ops.push_back(Op.getOperand(0));
13986 else if (ISD::UNDEF == Op.getOpcode())
13987 Ops.push_back(ScalarUndef);
13991 // Note whether we encounter an integer or floating point scalar.
13992 // If it's neither, bail out, it could be something weird like x86mmx.
13993 EVT LastOpVT = Ops.back().getValueType();
13994 if (LastOpVT.isFloatingPoint())
13996 else if (LastOpVT.isInteger())
14002 // If any of the operands is a floating point scalar bitcast to a vector,
14003 // use floating point types throughout, and bitcast everything.
14004 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14006 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14007 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14009 for (SDValue &Op : Ops) {
14010 if (Op.getValueType() == SVT)
14015 Op = DAG.getBitcast(SVT, Op);
14020 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14021 VT.getSizeInBits() / SVT.getSizeInBits());
14022 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14025 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14026 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14027 // most two distinct vectors the same size as the result, attempt to turn this
14028 // into a legal shuffle.
14029 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14030 EVT VT = N->getValueType(0);
14031 EVT OpVT = N->getOperand(0).getValueType();
14032 int NumElts = VT.getVectorNumElements();
14033 int NumOpElts = OpVT.getVectorNumElements();
14035 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14036 SmallVector<int, 8> Mask;
14038 for (SDValue Op : N->ops()) {
14039 // Peek through any bitcast.
14040 while (Op.getOpcode() == ISD::BITCAST)
14041 Op = Op.getOperand(0);
14043 // UNDEF nodes convert to UNDEF shuffle mask values.
14044 if (Op.isUndef()) {
14045 Mask.append((unsigned)NumOpElts, -1);
14049 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14052 // What vector are we extracting the subvector from and at what index?
14053 SDValue ExtVec = Op.getOperand(0);
14055 // We want the EVT of the original extraction to correctly scale the
14056 // extraction index.
14057 EVT ExtVT = ExtVec.getValueType();
14059 // Peek through any bitcast.
14060 while (ExtVec.getOpcode() == ISD::BITCAST)
14061 ExtVec = ExtVec.getOperand(0);
14063 // UNDEF nodes convert to UNDEF shuffle mask values.
14064 if (ExtVec.isUndef()) {
14065 Mask.append((unsigned)NumOpElts, -1);
14069 if (!isa<ConstantSDNode>(Op.getOperand(1)))
14071 int ExtIdx = Op.getConstantOperandVal(1);
14073 // Ensure that we are extracting a subvector from a vector the same
14074 // size as the result.
14075 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14078 // Scale the subvector index to account for any bitcast.
14079 int NumExtElts = ExtVT.getVectorNumElements();
14080 if (0 == (NumExtElts % NumElts))
14081 ExtIdx /= (NumExtElts / NumElts);
14082 else if (0 == (NumElts % NumExtElts))
14083 ExtIdx *= (NumElts / NumExtElts);
14087 // At most we can reference 2 inputs in the final shuffle.
14088 if (SV0.isUndef() || SV0 == ExtVec) {
14090 for (int i = 0; i != NumOpElts; ++i)
14091 Mask.push_back(i + ExtIdx);
14092 } else if (SV1.isUndef() || SV1 == ExtVec) {
14094 for (int i = 0; i != NumOpElts; ++i)
14095 Mask.push_back(i + ExtIdx + NumElts);
14101 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14104 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14105 DAG.getBitcast(VT, SV1), Mask);
14108 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14109 // If we only have one input vector, we don't need to do any concatenation.
14110 if (N->getNumOperands() == 1)
14111 return N->getOperand(0);
14113 // Check if all of the operands are undefs.
14114 EVT VT = N->getValueType(0);
14115 if (ISD::allOperandsUndef(N))
14116 return DAG.getUNDEF(VT);
14118 // Optimize concat_vectors where all but the first of the vectors are undef.
14119 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14120 return Op.isUndef();
14122 SDValue In = N->getOperand(0);
14123 assert(In.getValueType().isVector() && "Must concat vectors");
14125 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14126 if (In->getOpcode() == ISD::BITCAST &&
14127 !In->getOperand(0)->getValueType(0).isVector()) {
14128 SDValue Scalar = In->getOperand(0);
14130 // If the bitcast type isn't legal, it might be a trunc of a legal type;
14131 // look through the trunc so we can still do the transform:
14132 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14133 if (Scalar->getOpcode() == ISD::TRUNCATE &&
14134 !TLI.isTypeLegal(Scalar.getValueType()) &&
14135 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14136 Scalar = Scalar->getOperand(0);
14138 EVT SclTy = Scalar->getValueType(0);
14140 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14143 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14144 if (VNTNumElms < 2)
14147 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14148 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14151 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14152 return DAG.getBitcast(VT, Res);
14156 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14157 // We have already tested above for an UNDEF only concatenation.
14158 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14159 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14160 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14161 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14163 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14164 SmallVector<SDValue, 8> Opnds;
14165 EVT SVT = VT.getScalarType();
14168 if (!SVT.isFloatingPoint()) {
14169 // If BUILD_VECTOR are from built from integer, they may have different
14170 // operand types. Get the smallest type and truncate all operands to it.
14171 bool FoundMinVT = false;
14172 for (const SDValue &Op : N->ops())
14173 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14174 EVT OpSVT = Op.getOperand(0)->getValueType(0);
14175 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14178 assert(FoundMinVT && "Concat vector type mismatch");
14181 for (const SDValue &Op : N->ops()) {
14182 EVT OpVT = Op.getValueType();
14183 unsigned NumElts = OpVT.getVectorNumElements();
14185 if (ISD::UNDEF == Op.getOpcode())
14186 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14188 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14189 if (SVT.isFloatingPoint()) {
14190 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14191 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14193 for (unsigned i = 0; i != NumElts; ++i)
14195 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14200 assert(VT.getVectorNumElements() == Opnds.size() &&
14201 "Concat vector type mismatch");
14202 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14205 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14206 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14209 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14210 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14211 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14214 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14215 // nodes often generate nop CONCAT_VECTOR nodes.
14216 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14217 // place the incoming vectors at the exact same location.
14218 SDValue SingleSource = SDValue();
14219 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14221 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14222 SDValue Op = N->getOperand(i);
14227 // Check if this is the identity extract:
14228 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14231 // Find the single incoming vector for the extract_subvector.
14232 if (SingleSource.getNode()) {
14233 if (Op.getOperand(0) != SingleSource)
14236 SingleSource = Op.getOperand(0);
14238 // Check the source type is the same as the type of the result.
14239 // If not, this concat may extend the vector, so we can not
14240 // optimize it away.
14241 if (SingleSource.getValueType() != N->getValueType(0))
14245 unsigned IdentityIndex = i * PartNumElem;
14246 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14247 // The extract index must be constant.
14251 // Check that we are reading from the identity index.
14252 if (CS->getZExtValue() != IdentityIndex)
14256 if (SingleSource.getNode())
14257 return SingleSource;
14262 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14263 EVT NVT = N->getValueType(0);
14264 SDValue V = N->getOperand(0);
14266 // Extract from UNDEF is UNDEF.
14268 return DAG.getUNDEF(NVT);
14271 // (extract_subvec (concat V1, V2, ...), i)
14274 // Only operand 0 is checked as 'concat' assumes all inputs of the same
14276 if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14277 isa<ConstantSDNode>(N->getOperand(1)) &&
14278 V->getOperand(0).getValueType() == NVT) {
14279 unsigned Idx = N->getConstantOperandVal(1);
14280 unsigned NumElems = NVT.getVectorNumElements();
14281 assert((Idx % NumElems) == 0 &&
14282 "IDX in concat is not a multiple of the result vector length.");
14283 return V->getOperand(Idx / NumElems);
14287 if (V->getOpcode() == ISD::BITCAST)
14288 V = V.getOperand(0);
14290 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14291 // Handle only simple case where vector being inserted and vector
14292 // being extracted are of same size.
14293 EVT SmallVT = V->getOperand(1).getValueType();
14294 if (!NVT.bitsEq(SmallVT))
14297 // Only handle cases where both indexes are constants.
14298 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14299 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14301 if (InsIdx && ExtIdx) {
14303 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14305 // indices are equal or bit offsets are equal => V1
14306 // otherwise => (extract_subvec V1, ExtIdx)
14307 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14308 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14309 return DAG.getBitcast(NVT, V->getOperand(1));
14310 return DAG.getNode(
14311 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14312 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14320 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14321 SDValue V, SelectionDAG &DAG) {
14323 EVT VT = V.getValueType();
14325 switch (V.getOpcode()) {
14329 case ISD::CONCAT_VECTORS: {
14330 EVT OpVT = V->getOperand(0).getValueType();
14331 int OpSize = OpVT.getVectorNumElements();
14332 SmallBitVector OpUsedElements(OpSize, false);
14333 bool FoundSimplification = false;
14334 SmallVector<SDValue, 4> NewOps;
14335 NewOps.reserve(V->getNumOperands());
14336 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14337 SDValue Op = V->getOperand(i);
14338 bool OpUsed = false;
14339 for (int j = 0; j < OpSize; ++j)
14340 if (UsedElements[i * OpSize + j]) {
14341 OpUsedElements[j] = true;
14345 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14346 : DAG.getUNDEF(OpVT));
14347 FoundSimplification |= Op == NewOps.back();
14348 OpUsedElements.reset();
14350 if (FoundSimplification)
14351 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14355 case ISD::INSERT_SUBVECTOR: {
14356 SDValue BaseV = V->getOperand(0);
14357 SDValue SubV = V->getOperand(1);
14358 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14362 int SubSize = SubV.getValueType().getVectorNumElements();
14363 int Idx = IdxN->getZExtValue();
14364 bool SubVectorUsed = false;
14365 SmallBitVector SubUsedElements(SubSize, false);
14366 for (int i = 0; i < SubSize; ++i)
14367 if (UsedElements[i + Idx]) {
14368 SubVectorUsed = true;
14369 SubUsedElements[i] = true;
14370 UsedElements[i + Idx] = false;
14373 // Now recurse on both the base and sub vectors.
14374 SDValue SimplifiedSubV =
14376 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14377 : DAG.getUNDEF(SubV.getValueType());
14378 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14379 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14380 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14381 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14387 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14388 SDValue N1, SelectionDAG &DAG) {
14389 EVT VT = SVN->getValueType(0);
14390 int NumElts = VT.getVectorNumElements();
14391 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14392 for (int M : SVN->getMask())
14393 if (M >= 0 && M < NumElts)
14394 N0UsedElements[M] = true;
14395 else if (M >= NumElts)
14396 N1UsedElements[M - NumElts] = true;
14398 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14399 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14400 if (S0 == N0 && S1 == N1)
14403 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14406 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14407 // or turn a shuffle of a single concat into simpler shuffle then concat.
14408 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14409 EVT VT = N->getValueType(0);
14410 unsigned NumElts = VT.getVectorNumElements();
14412 SDValue N0 = N->getOperand(0);
14413 SDValue N1 = N->getOperand(1);
14414 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14416 SmallVector<SDValue, 4> Ops;
14417 EVT ConcatVT = N0.getOperand(0).getValueType();
14418 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
14419 unsigned NumConcats = NumElts / NumElemsPerConcat;
14421 // Special case: shuffle(concat(A,B)) can be more efficiently represented
14422 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
14423 // half vector elements.
14424 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
14425 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
14426 SVN->getMask().end(), [](int i) { return i == -1; })) {
14427 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
14428 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
14429 N1 = DAG.getUNDEF(ConcatVT);
14430 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
14433 // Look at every vector that's inserted. We're looking for exact
14434 // subvector-sized copies from a concatenated vector
14435 for (unsigned I = 0; I != NumConcats; ++I) {
14436 // Make sure we're dealing with a copy.
14437 unsigned Begin = I * NumElemsPerConcat;
14438 bool AllUndef = true, NoUndef = true;
14439 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
14440 if (SVN->getMaskElt(J) >= 0)
14447 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
14450 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
14451 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
14454 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
14455 if (FirstElt < N0.getNumOperands())
14456 Ops.push_back(N0.getOperand(FirstElt));
14458 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
14460 } else if (AllUndef) {
14461 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
14462 } else { // Mixed with general masks and undefs, can't do optimization.
14467 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
14470 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14471 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14473 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
14474 // a simplification in some sense, but it isn't appropriate in general: some
14475 // BUILD_VECTORs are substantially cheaper than others. The general case
14476 // of a BUILD_VECTOR requires inserting each element individually (or
14477 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
14478 // all constants is a single constant pool load. A BUILD_VECTOR where each
14479 // element is identical is a splat. A BUILD_VECTOR where most of the operands
14480 // are undef lowers to a small number of element insertions.
14482 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
14483 // We don't fold shuffles where one side is a non-zero constant, and we don't
14484 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
14485 // non-constant operands. This seems to work out reasonably well in practice.
14486 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
14488 const TargetLowering &TLI) {
14489 EVT VT = SVN->getValueType(0);
14490 unsigned NumElts = VT.getVectorNumElements();
14491 SDValue N0 = SVN->getOperand(0);
14492 SDValue N1 = SVN->getOperand(1);
14494 if (!N0->hasOneUse() || !N1->hasOneUse())
14496 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
14497 // discussed above.
14498 if (!N1.isUndef()) {
14499 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
14500 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
14501 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
14503 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
14507 SmallVector<SDValue, 8> Ops;
14508 SmallSet<SDValue, 16> DuplicateOps;
14509 for (int M : SVN->getMask()) {
14510 SDValue Op = DAG.getUNDEF(VT.getScalarType());
14512 int Idx = M < (int)NumElts ? M : M - NumElts;
14513 SDValue &S = (M < (int)NumElts ? N0 : N1);
14514 if (S.getOpcode() == ISD::BUILD_VECTOR) {
14515 Op = S.getOperand(Idx);
14516 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14518 Op = S.getOperand(0);
14520 // Operand can't be combined - bail out.
14525 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
14526 // fine, but it's likely to generate low-quality code if the target can't
14527 // reconstruct an appropriate shuffle.
14528 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
14529 if (!DuplicateOps.insert(Op).second)
14534 // BUILD_VECTOR requires all inputs to be of the same type, find the
14535 // maximum type and extend them all.
14536 EVT SVT = VT.getScalarType();
14537 if (SVT.isInteger())
14538 for (SDValue &Op : Ops)
14539 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
14540 if (SVT != VT.getScalarType())
14541 for (SDValue &Op : Ops)
14542 Op = TLI.isZExtFree(Op.getValueType(), SVT)
14543 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
14544 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
14545 return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
14548 // Match shuffles that can be converted to any_vector_extend_in_reg.
14549 // This is often generated during legalization.
14550 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
14551 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
14552 SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
14554 const TargetLowering &TLI,
14555 bool LegalOperations) {
14556 EVT VT = SVN->getValueType(0);
14557 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14559 // TODO Add support for big-endian when we have a test case.
14560 if (!VT.isInteger() || IsBigEndian)
14563 unsigned NumElts = VT.getVectorNumElements();
14564 unsigned EltSizeInBits = VT.getScalarSizeInBits();
14565 ArrayRef<int> Mask = SVN->getMask();
14566 SDValue N0 = SVN->getOperand(0);
14568 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
14569 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
14570 for (unsigned i = 0; i != NumElts; ++i) {
14573 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
14580 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
14581 // power-of-2 extensions as they are the most likely.
14582 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
14583 if (!isAnyExtend(Scale))
14586 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
14587 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
14588 if (!LegalOperations ||
14589 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
14590 return DAG.getBitcast(VT,
14591 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
14597 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
14598 // each source element of a large type into the lowest elements of a smaller
14599 // destination type. This is often generated during legalization.
14600 // If the source node itself was a '*_extend_vector_inreg' node then we should
14601 // then be able to remove it.
14602 SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) {
14603 EVT VT = SVN->getValueType(0);
14604 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14606 // TODO Add support for big-endian when we have a test case.
14607 if (!VT.isInteger() || IsBigEndian)
14610 SDValue N0 = SVN->getOperand(0);
14611 while (N0.getOpcode() == ISD::BITCAST)
14612 N0 = N0.getOperand(0);
14614 unsigned Opcode = N0.getOpcode();
14615 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
14616 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
14617 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
14620 SDValue N00 = N0.getOperand(0);
14621 ArrayRef<int> Mask = SVN->getMask();
14622 unsigned NumElts = VT.getVectorNumElements();
14623 unsigned EltSizeInBits = VT.getScalarSizeInBits();
14624 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
14626 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
14627 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
14628 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
14629 auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
14630 for (unsigned i = 0; i != NumElts; ++i) {
14633 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
14640 // At the moment we just handle the case where we've truncated back to the
14641 // same size as before the extension.
14642 // TODO: handle more extension/truncation cases as cases arise.
14643 if (EltSizeInBits != ExtSrcSizeInBits)
14646 // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for
14647 // power-of-2 truncations as they are the most likely.
14648 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2)
14649 if (isTruncate(Scale))
14650 return DAG.getBitcast(VT, N00);
14655 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
14656 EVT VT = N->getValueType(0);
14657 unsigned NumElts = VT.getVectorNumElements();
14659 SDValue N0 = N->getOperand(0);
14660 SDValue N1 = N->getOperand(1);
14662 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
14664 // Canonicalize shuffle undef, undef -> undef
14665 if (N0.isUndef() && N1.isUndef())
14666 return DAG.getUNDEF(VT);
14668 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14670 // Canonicalize shuffle v, v -> v, undef
14672 SmallVector<int, 8> NewMask;
14673 for (unsigned i = 0; i != NumElts; ++i) {
14674 int Idx = SVN->getMaskElt(i);
14675 if (Idx >= (int)NumElts) Idx -= NumElts;
14676 NewMask.push_back(Idx);
14678 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
14681 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
14683 return DAG.getCommutedVectorShuffle(*SVN);
14685 // Remove references to rhs if it is undef
14686 if (N1.isUndef()) {
14687 bool Changed = false;
14688 SmallVector<int, 8> NewMask;
14689 for (unsigned i = 0; i != NumElts; ++i) {
14690 int Idx = SVN->getMaskElt(i);
14691 if (Idx >= (int)NumElts) {
14695 NewMask.push_back(Idx);
14698 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
14701 // If it is a splat, check if the argument vector is another splat or a
14703 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
14704 SDNode *V = N0.getNode();
14706 // If this is a bit convert that changes the element type of the vector but
14707 // not the number of vector elements, look through it. Be careful not to
14708 // look though conversions that change things like v4f32 to v2f64.
14709 if (V->getOpcode() == ISD::BITCAST) {
14710 SDValue ConvInput = V->getOperand(0);
14711 if (ConvInput.getValueType().isVector() &&
14712 ConvInput.getValueType().getVectorNumElements() == NumElts)
14713 V = ConvInput.getNode();
14716 if (V->getOpcode() == ISD::BUILD_VECTOR) {
14717 assert(V->getNumOperands() == NumElts &&
14718 "BUILD_VECTOR has wrong number of operands");
14720 bool AllSame = true;
14721 for (unsigned i = 0; i != NumElts; ++i) {
14722 if (!V->getOperand(i).isUndef()) {
14723 Base = V->getOperand(i);
14727 // Splat of <u, u, u, u>, return <u, u, u, u>
14728 if (!Base.getNode())
14730 for (unsigned i = 0; i != NumElts; ++i) {
14731 if (V->getOperand(i) != Base) {
14736 // Splat of <x, x, x, x>, return <x, x, x, x>
14740 // Canonicalize any other splat as a build_vector.
14741 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
14742 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
14743 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
14745 // We may have jumped through bitcasts, so the type of the
14746 // BUILD_VECTOR may not match the type of the shuffle.
14747 if (V->getValueType(0) != VT)
14748 NewBV = DAG.getBitcast(VT, NewBV);
14753 // There are various patterns used to build up a vector from smaller vectors,
14754 // subvectors, or elements. Scan chains of these and replace unused insertions
14755 // or components with undef.
14756 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
14759 // Match shuffles that can be converted to any_vector_extend_in_reg.
14760 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
14763 // Combine "truncate_vector_in_reg" style shuffles.
14764 if (SDValue V = combineTruncationShuffle(SVN, DAG))
14767 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
14768 Level < AfterLegalizeVectorOps &&
14770 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
14771 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
14772 if (SDValue V = partitionShuffleOfConcats(N, DAG))
14776 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14777 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14778 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14779 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
14782 // If this shuffle only has a single input that is a bitcasted shuffle,
14783 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
14784 // back to their original types.
14785 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
14786 N1.isUndef() && Level < AfterLegalizeVectorOps &&
14787 TLI.isTypeLegal(VT)) {
14789 // Peek through the bitcast only if there is one user.
14791 while (BC0.getOpcode() == ISD::BITCAST) {
14792 if (!BC0.hasOneUse())
14794 BC0 = BC0.getOperand(0);
14797 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
14799 return SmallVector<int, 8>(Mask.begin(), Mask.end());
14801 SmallVector<int, 8> NewMask;
14803 for (int s = 0; s != Scale; ++s)
14804 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
14808 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
14809 EVT SVT = VT.getScalarType();
14810 EVT InnerVT = BC0->getValueType(0);
14811 EVT InnerSVT = InnerVT.getScalarType();
14813 // Determine which shuffle works with the smaller scalar type.
14814 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
14815 EVT ScaleSVT = ScaleVT.getScalarType();
14817 if (TLI.isTypeLegal(ScaleVT) &&
14818 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
14819 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
14821 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14822 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14824 // Scale the shuffle masks to the smaller scalar type.
14825 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
14826 SmallVector<int, 8> InnerMask =
14827 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
14828 SmallVector<int, 8> OuterMask =
14829 ScaleShuffleMask(SVN->getMask(), OuterScale);
14831 // Merge the shuffle masks.
14832 SmallVector<int, 8> NewMask;
14833 for (int M : OuterMask)
14834 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
14836 // Test for shuffle mask legality over both commutations.
14837 SDValue SV0 = BC0->getOperand(0);
14838 SDValue SV1 = BC0->getOperand(1);
14839 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14841 std::swap(SV0, SV1);
14842 ShuffleVectorSDNode::commuteMask(NewMask);
14843 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14847 SV0 = DAG.getBitcast(ScaleVT, SV0);
14848 SV1 = DAG.getBitcast(ScaleVT, SV1);
14849 return DAG.getBitcast(
14850 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
14856 // Canonicalize shuffles according to rules:
14857 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
14858 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
14859 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
14860 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
14861 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
14862 TLI.isTypeLegal(VT)) {
14863 // The incoming shuffle must be of the same type as the result of the
14864 // current shuffle.
14865 assert(N1->getOperand(0).getValueType() == VT &&
14866 "Shuffle types don't match");
14868 SDValue SV0 = N1->getOperand(0);
14869 SDValue SV1 = N1->getOperand(1);
14870 bool HasSameOp0 = N0 == SV0;
14871 bool IsSV1Undef = SV1.isUndef();
14872 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
14873 // Commute the operands of this shuffle so that next rule
14875 return DAG.getCommutedVectorShuffle(*SVN);
14878 // Try to fold according to rules:
14879 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14880 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14881 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14882 // Don't try to fold shuffles with illegal type.
14883 // Only fold if this shuffle is the only user of the other shuffle.
14884 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14885 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14886 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14888 // Don't try to fold splats; they're likely to simplify somehow, or they
14890 if (OtherSV->isSplat())
14893 // The incoming shuffle must be of the same type as the result of the
14894 // current shuffle.
14895 assert(OtherSV->getOperand(0).getValueType() == VT &&
14896 "Shuffle types don't match");
14899 SmallVector<int, 4> Mask;
14900 // Compute the combined shuffle mask for a shuffle with SV0 as the first
14901 // operand, and SV1 as the second operand.
14902 for (unsigned i = 0; i != NumElts; ++i) {
14903 int Idx = SVN->getMaskElt(i);
14905 // Propagate Undef.
14906 Mask.push_back(Idx);
14910 SDValue CurrentVec;
14911 if (Idx < (int)NumElts) {
14912 // This shuffle index refers to the inner shuffle N0. Lookup the inner
14913 // shuffle mask to identify which vector is actually referenced.
14914 Idx = OtherSV->getMaskElt(Idx);
14916 // Propagate Undef.
14917 Mask.push_back(Idx);
14921 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14922 : OtherSV->getOperand(1);
14924 // This shuffle index references an element within N1.
14928 // Simple case where 'CurrentVec' is UNDEF.
14929 if (CurrentVec.isUndef()) {
14930 Mask.push_back(-1);
14934 // Canonicalize the shuffle index. We don't know yet if CurrentVec
14935 // will be the first or second operand of the combined shuffle.
14936 Idx = Idx % NumElts;
14937 if (!SV0.getNode() || SV0 == CurrentVec) {
14938 // Ok. CurrentVec is the left hand side.
14939 // Update the mask accordingly.
14941 Mask.push_back(Idx);
14945 // Bail out if we cannot convert the shuffle pair into a single shuffle.
14946 if (SV1.getNode() && SV1 != CurrentVec)
14949 // Ok. CurrentVec is the right hand side.
14950 // Update the mask accordingly.
14952 Mask.push_back(Idx + NumElts);
14955 // Check if all indices in Mask are Undef. In case, propagate Undef.
14956 bool isUndefMask = true;
14957 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14958 isUndefMask &= Mask[i] < 0;
14961 return DAG.getUNDEF(VT);
14963 if (!SV0.getNode())
14964 SV0 = DAG.getUNDEF(VT);
14965 if (!SV1.getNode())
14966 SV1 = DAG.getUNDEF(VT);
14968 // Avoid introducing shuffles with illegal mask.
14969 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14970 ShuffleVectorSDNode::commuteMask(Mask);
14972 if (!TLI.isShuffleMaskLegal(Mask, VT))
14975 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14976 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14977 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14978 std::swap(SV0, SV1);
14981 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14982 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14983 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14984 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14990 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14991 SDValue InVal = N->getOperand(0);
14992 EVT VT = N->getValueType(0);
14994 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14995 // with a VECTOR_SHUFFLE.
14996 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14997 SDValue InVec = InVal->getOperand(0);
14998 SDValue EltNo = InVal->getOperand(1);
15000 // FIXME: We could support implicit truncation if the shuffle can be
15001 // scaled to a smaller vector scalar type.
15002 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15003 if (C0 && VT == InVec.getValueType() &&
15004 VT.getScalarType() == InVal.getValueType()) {
15005 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15006 int Elt = C0->getZExtValue();
15009 if (TLI.isShuffleMaskLegal(NewMask, VT))
15010 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15018 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15019 EVT VT = N->getValueType(0);
15020 SDValue N0 = N->getOperand(0);
15021 SDValue N1 = N->getOperand(1);
15022 SDValue N2 = N->getOperand(2);
15024 // If inserting an UNDEF, just return the original vector.
15028 // If this is an insert of an extracted vector into an undef vector, we can
15029 // just use the input to the extract.
15030 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15031 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15032 return N1.getOperand(0);
15034 // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15035 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15036 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15037 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15038 N0.getOperand(1).getValueType() == N1.getValueType() &&
15039 N0.getOperand(2) == N2)
15040 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15043 if (!isa<ConstantSDNode>(N2))
15046 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15048 // Canonicalize insert_subvector dag nodes.
15050 // (insert_subvector (insert_subvector A, Idx0), Idx1)
15051 // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15052 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15053 N1.getValueType() == N0.getOperand(1).getValueType() &&
15054 isa<ConstantSDNode>(N0.getOperand(2))) {
15055 unsigned OtherIdx = N0.getConstantOperandVal(2);
15056 if (InsIdx < OtherIdx) {
15058 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15059 N0.getOperand(0), N1, N2);
15060 AddToWorklist(NewOp.getNode());
15061 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15062 VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15066 // If the input vector is a concatenation, and the insert replaces
15067 // one of the pieces, we can optimize into a single concat_vectors.
15068 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15069 N0.getOperand(0).getValueType() == N1.getValueType()) {
15070 unsigned Factor = N1.getValueType().getVectorNumElements();
15072 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15073 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15075 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15081 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15082 SDValue N0 = N->getOperand(0);
15084 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15085 if (N0->getOpcode() == ISD::FP16_TO_FP)
15086 return N0->getOperand(0);
15091 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15092 SDValue N0 = N->getOperand(0);
15094 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15095 if (N0->getOpcode() == ISD::AND) {
15096 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15097 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15098 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15106 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15107 /// with the destination vector and a zero vector.
15108 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15109 /// vector_shuffle V, Zero, <0, 4, 2, 4>
15110 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15111 EVT VT = N->getValueType(0);
15112 SDValue LHS = N->getOperand(0);
15113 SDValue RHS = N->getOperand(1);
15116 // Make sure we're not running after operation legalization where it
15117 // may have custom lowered the vector shuffles.
15118 if (LegalOperations)
15121 if (N->getOpcode() != ISD::AND)
15124 if (RHS.getOpcode() == ISD::BITCAST)
15125 RHS = RHS.getOperand(0);
15127 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15130 EVT RVT = RHS.getValueType();
15131 unsigned NumElts = RHS.getNumOperands();
15133 // Attempt to create a valid clear mask, splitting the mask into
15134 // sub elements and checking to see if each is
15135 // all zeros or all ones - suitable for shuffle masking.
15136 auto BuildClearMask = [&](int Split) {
15137 int NumSubElts = NumElts * Split;
15138 int NumSubBits = RVT.getScalarSizeInBits() / Split;
15140 SmallVector<int, 8> Indices;
15141 for (int i = 0; i != NumSubElts; ++i) {
15142 int EltIdx = i / Split;
15143 int SubIdx = i % Split;
15144 SDValue Elt = RHS.getOperand(EltIdx);
15145 if (Elt.isUndef()) {
15146 Indices.push_back(-1);
15151 if (isa<ConstantSDNode>(Elt))
15152 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15153 else if (isa<ConstantFPSDNode>(Elt))
15154 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15158 // Extract the sub element from the constant bit mask.
15159 if (DAG.getDataLayout().isBigEndian()) {
15160 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15162 Bits.lshrInPlace(SubIdx * NumSubBits);
15166 Bits = Bits.trunc(NumSubBits);
15168 if (Bits.isAllOnesValue())
15169 Indices.push_back(i);
15170 else if (Bits == 0)
15171 Indices.push_back(i + NumSubElts);
15176 // Let's see if the target supports this vector_shuffle.
15177 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15178 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15179 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15182 SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15183 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15184 DAG.getBitcast(ClearVT, LHS),
15188 // Determine maximum split level (byte level masking).
15190 if (RVT.getScalarSizeInBits() % 8 == 0)
15191 MaxSplit = RVT.getScalarSizeInBits() / 8;
15193 for (int Split = 1; Split <= MaxSplit; ++Split)
15194 if (RVT.getScalarSizeInBits() % Split == 0)
15195 if (SDValue S = BuildClearMask(Split))
15201 /// Visit a binary vector operation, like ADD.
15202 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15203 assert(N->getValueType(0).isVector() &&
15204 "SimplifyVBinOp only works on vectors!");
15206 SDValue LHS = N->getOperand(0);
15207 SDValue RHS = N->getOperand(1);
15208 SDValue Ops[] = {LHS, RHS};
15210 // See if we can constant fold the vector operation.
15211 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15212 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15215 // Try to convert a constant mask AND into a shuffle clear mask.
15216 if (SDValue Shuffle = XformToShuffleWithZero(N))
15219 // Type legalization might introduce new shuffles in the DAG.
15220 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15221 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
15222 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15223 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15224 LHS.getOperand(1).isUndef() &&
15225 RHS.getOperand(1).isUndef()) {
15226 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15227 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15229 if (SVN0->getMask().equals(SVN1->getMask())) {
15230 EVT VT = N->getValueType(0);
15231 SDValue UndefVector = LHS.getOperand(1);
15232 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15233 LHS.getOperand(0), RHS.getOperand(0),
15235 AddUsersToWorklist(N);
15236 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15244 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15246 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15248 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15249 cast<CondCodeSDNode>(N0.getOperand(2))->get());
15251 // If we got a simplified select_cc node back from SimplifySelectCC, then
15252 // break it down into a new SETCC node, and a new SELECT node, and then return
15253 // the SELECT node, since we were called with a SELECT node.
15254 if (SCC.getNode()) {
15255 // Check to see if we got a select_cc back (to turn into setcc/select).
15256 // Otherwise, just return whatever node we got back, like fabs.
15257 if (SCC.getOpcode() == ISD::SELECT_CC) {
15258 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15260 SCC.getOperand(0), SCC.getOperand(1),
15261 SCC.getOperand(4));
15262 AddToWorklist(SETCC.getNode());
15263 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15264 SCC.getOperand(2), SCC.getOperand(3));
15272 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15273 /// being selected between, see if we can simplify the select. Callers of this
15274 /// should assume that TheSelect is deleted if this returns true. As such, they
15275 /// should return the appropriate thing (e.g. the node) back to the top-level of
15276 /// the DAG combiner loop to avoid it being looked at.
15277 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15280 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15281 // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15282 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15283 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15284 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15285 SDValue Sqrt = RHS;
15288 const ConstantFPSDNode *Zero = nullptr;
15290 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15291 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15292 CmpLHS = TheSelect->getOperand(0);
15293 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15295 // SELECT or VSELECT
15296 SDValue Cmp = TheSelect->getOperand(0);
15297 if (Cmp.getOpcode() == ISD::SETCC) {
15298 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15299 CmpLHS = Cmp.getOperand(0);
15300 Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15303 if (Zero && Zero->isZero() &&
15304 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15305 CC == ISD::SETULT || CC == ISD::SETLT)) {
15306 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15307 CombineTo(TheSelect, Sqrt);
15312 // Cannot simplify select with vector condition
15313 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15315 // If this is a select from two identical things, try to pull the operation
15316 // through the select.
15317 if (LHS.getOpcode() != RHS.getOpcode() ||
15318 !LHS.hasOneUse() || !RHS.hasOneUse())
15321 // If this is a load and the token chain is identical, replace the select
15322 // of two loads with a load through a select of the address to load from.
15323 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15324 // constants have been dropped into the constant pool.
15325 if (LHS.getOpcode() == ISD::LOAD) {
15326 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15327 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15329 // Token chains must be identical.
15330 if (LHS.getOperand(0) != RHS.getOperand(0) ||
15331 // Do not let this transformation reduce the number of volatile loads.
15332 LLD->isVolatile() || RLD->isVolatile() ||
15333 // FIXME: If either is a pre/post inc/dec load,
15334 // we'd need to split out the address adjustment.
15335 LLD->isIndexed() || RLD->isIndexed() ||
15336 // If this is an EXTLOAD, the VT's must match.
15337 LLD->getMemoryVT() != RLD->getMemoryVT() ||
15338 // If this is an EXTLOAD, the kind of extension must match.
15339 (LLD->getExtensionType() != RLD->getExtensionType() &&
15340 // The only exception is if one of the extensions is anyext.
15341 LLD->getExtensionType() != ISD::EXTLOAD &&
15342 RLD->getExtensionType() != ISD::EXTLOAD) ||
15343 // FIXME: this discards src value information. This is
15344 // over-conservative. It would be beneficial to be able to remember
15345 // both potential memory locations. Since we are discarding
15346 // src value info, don't do the transformation if the memory
15347 // locations are not in the default address space.
15348 LLD->getPointerInfo().getAddrSpace() != 0 ||
15349 RLD->getPointerInfo().getAddrSpace() != 0 ||
15350 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
15351 LLD->getBasePtr().getValueType()))
15354 // Check that the select condition doesn't reach either load. If so,
15355 // folding this will induce a cycle into the DAG. If not, this is safe to
15356 // xform, so create a select of the addresses.
15358 if (TheSelect->getOpcode() == ISD::SELECT) {
15359 SDNode *CondNode = TheSelect->getOperand(0).getNode();
15360 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
15361 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
15363 // The loads must not depend on one another.
15364 if (LLD->isPredecessorOf(RLD) ||
15365 RLD->isPredecessorOf(LLD))
15367 Addr = DAG.getSelect(SDLoc(TheSelect),
15368 LLD->getBasePtr().getValueType(),
15369 TheSelect->getOperand(0), LLD->getBasePtr(),
15370 RLD->getBasePtr());
15371 } else { // Otherwise SELECT_CC
15372 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
15373 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
15375 if ((LLD->hasAnyUseOfValue(1) &&
15376 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
15377 (RLD->hasAnyUseOfValue(1) &&
15378 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
15381 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
15382 LLD->getBasePtr().getValueType(),
15383 TheSelect->getOperand(0),
15384 TheSelect->getOperand(1),
15385 LLD->getBasePtr(), RLD->getBasePtr(),
15386 TheSelect->getOperand(4));
15390 // It is safe to replace the two loads if they have different alignments,
15391 // but the new load must be the minimum (most restrictive) alignment of the
15393 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
15394 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
15395 if (!RLD->isInvariant())
15396 MMOFlags &= ~MachineMemOperand::MOInvariant;
15397 if (!RLD->isDereferenceable())
15398 MMOFlags &= ~MachineMemOperand::MODereferenceable;
15399 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
15400 // FIXME: Discards pointer and AA info.
15401 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
15402 LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
15405 // FIXME: Discards pointer and AA info.
15406 Load = DAG.getExtLoad(
15407 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
15408 : LLD->getExtensionType(),
15409 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
15410 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
15413 // Users of the select now use the result of the load.
15414 CombineTo(TheSelect, Load);
15416 // Users of the old loads now use the new load's chain. We know the
15417 // old-load value is dead now.
15418 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
15419 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
15426 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
15428 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
15429 SDValue N1, SDValue N2, SDValue N3,
15430 ISD::CondCode CC) {
15431 // If this is a select where the false operand is zero and the compare is a
15432 // check of the sign bit, see if we can perform the "gzip trick":
15433 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
15434 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
15435 EVT XType = N0.getValueType();
15436 EVT AType = N2.getValueType();
15437 if (!isNullConstant(N3) || !XType.bitsGE(AType))
15440 // If the comparison is testing for a positive value, we have to invert
15441 // the sign bit mask, so only do that transform if the target has a bitwise
15442 // 'and not' instruction (the invert is free).
15443 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
15444 // (X > -1) ? A : 0
15445 // (X > 0) ? X : 0 <-- This is canonical signed max.
15446 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
15448 } else if (CC == ISD::SETLT) {
15450 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
15451 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
15457 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
15459 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
15460 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15461 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
15462 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
15463 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
15464 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
15465 AddToWorklist(Shift.getNode());
15467 if (XType.bitsGT(AType)) {
15468 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15469 AddToWorklist(Shift.getNode());
15472 if (CC == ISD::SETGT)
15473 Shift = DAG.getNOT(DL, Shift, AType);
15475 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15478 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
15479 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
15480 AddToWorklist(Shift.getNode());
15482 if (XType.bitsGT(AType)) {
15483 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15484 AddToWorklist(Shift.getNode());
15487 if (CC == ISD::SETGT)
15488 Shift = DAG.getNOT(DL, Shift, AType);
15490 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15493 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
15494 /// where 'cond' is the comparison specified by CC.
15495 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
15496 SDValue N2, SDValue N3, ISD::CondCode CC,
15497 bool NotExtCompare) {
15498 // (x ? y : y) -> y.
15499 if (N2 == N3) return N2;
15501 EVT VT = N2.getValueType();
15502 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
15503 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15505 // Determine if the condition we're dealing with is constant
15506 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
15507 N0, N1, CC, DL, false);
15508 if (SCC.getNode()) AddToWorklist(SCC.getNode());
15510 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
15511 // fold select_cc true, x, y -> x
15512 // fold select_cc false, x, y -> y
15513 return !SCCC->isNullValue() ? N2 : N3;
15516 // Check to see if we can simplify the select into an fabs node
15517 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
15518 // Allow either -0.0 or 0.0
15519 if (CFP->isZero()) {
15520 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
15521 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
15522 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
15523 N2 == N3.getOperand(0))
15524 return DAG.getNode(ISD::FABS, DL, VT, N0);
15526 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
15527 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
15528 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
15529 N2.getOperand(0) == N3)
15530 return DAG.getNode(ISD::FABS, DL, VT, N3);
15534 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
15535 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
15536 // in it. This is a win when the constant is not otherwise available because
15537 // it replaces two constant pool loads with one. We only do this if the FP
15538 // type is known to be legal, because if it isn't, then we are before legalize
15539 // types an we want the other legalization to happen first (e.g. to avoid
15540 // messing with soft float) and if the ConstantFP is not legal, because if
15541 // it is legal, we may not need to store the FP constant in a constant pool.
15542 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
15543 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
15544 if (TLI.isTypeLegal(N2.getValueType()) &&
15545 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
15546 TargetLowering::Legal &&
15547 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
15548 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
15549 // If both constants have multiple uses, then we won't need to do an
15550 // extra load, they are likely around in registers for other users.
15551 (TV->hasOneUse() || FV->hasOneUse())) {
15552 Constant *Elts[] = {
15553 const_cast<ConstantFP*>(FV->getConstantFPValue()),
15554 const_cast<ConstantFP*>(TV->getConstantFPValue())
15556 Type *FPTy = Elts[0]->getType();
15557 const DataLayout &TD = DAG.getDataLayout();
15559 // Create a ConstantArray of the two constants.
15560 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
15562 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
15563 TD.getPrefTypeAlignment(FPTy));
15564 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
15566 // Get the offsets to the 0 and 1 element of the array so that we can
15567 // select between them.
15568 SDValue Zero = DAG.getIntPtrConstant(0, DL);
15569 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
15570 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
15572 SDValue Cond = DAG.getSetCC(DL,
15573 getSetCCResultType(N0.getValueType()),
15575 AddToWorklist(Cond.getNode());
15576 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
15578 AddToWorklist(CstOffset.getNode());
15579 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
15581 AddToWorklist(CPIdx.getNode());
15582 return DAG.getLoad(
15583 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
15584 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
15589 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
15592 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
15593 // where y is has a single bit set.
15594 // A plaintext description would be, we can turn the SELECT_CC into an AND
15595 // when the condition can be materialized as an all-ones register. Any
15596 // single bit-test can be materialized as an all-ones register with
15597 // shift-left and shift-right-arith.
15598 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
15599 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
15600 SDValue AndLHS = N0->getOperand(0);
15601 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
15602 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
15603 // Shift the tested bit over the sign bit.
15604 const APInt &AndMask = ConstAndRHS->getAPIntValue();
15606 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
15607 getShiftAmountTy(AndLHS.getValueType()));
15608 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
15610 // Now arithmetic right shift it all the way over, so the result is either
15611 // all-ones, or zero.
15613 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
15614 getShiftAmountTy(Shl.getValueType()));
15615 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
15617 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
15621 // fold select C, 16, 0 -> shl C, 4
15622 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
15623 TLI.getBooleanContents(N0.getValueType()) ==
15624 TargetLowering::ZeroOrOneBooleanContent) {
15626 // If the caller doesn't want us to simplify this into a zext of a compare,
15628 if (NotExtCompare && N2C->isOne())
15631 // Get a SetCC of the condition
15632 // NOTE: Don't create a SETCC if it's not legal on this target.
15633 if (!LegalOperations ||
15634 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
15636 // cast from setcc result type to select result type
15638 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
15640 if (N2.getValueType().bitsLT(SCC.getValueType()))
15641 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
15642 N2.getValueType());
15644 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15645 N2.getValueType(), SCC);
15647 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
15648 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15649 N2.getValueType(), SCC);
15652 AddToWorklist(SCC.getNode());
15653 AddToWorklist(Temp.getNode());
15658 // shl setcc result by log2 n2c
15659 return DAG.getNode(
15660 ISD::SHL, DL, N2.getValueType(), Temp,
15661 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
15662 getShiftAmountTy(Temp.getValueType())));
15666 // Check to see if this is an integer abs.
15667 // select_cc setg[te] X, 0, X, -X ->
15668 // select_cc setgt X, -1, X, -X ->
15669 // select_cc setl[te] X, 0, -X, X ->
15670 // select_cc setlt X, 1, -X, X ->
15671 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
15673 ConstantSDNode *SubC = nullptr;
15674 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
15675 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
15676 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
15677 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
15678 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
15679 (N1C->isOne() && CC == ISD::SETLT)) &&
15680 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
15681 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
15683 EVT XType = N0.getValueType();
15684 if (SubC && SubC->isNullValue() && XType.isInteger()) {
15686 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
15688 DAG.getConstant(XType.getSizeInBits() - 1, DL,
15689 getShiftAmountTy(N0.getValueType())));
15690 SDValue Add = DAG.getNode(ISD::ADD, DL,
15692 AddToWorklist(Shift.getNode());
15693 AddToWorklist(Add.getNode());
15694 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
15698 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
15699 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
15700 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
15701 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
15702 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
15703 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
15704 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
15705 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
15706 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15707 SDValue ValueOnZero = N2;
15708 SDValue Count = N3;
15709 // If the condition is NE instead of E, swap the operands.
15710 if (CC == ISD::SETNE)
15711 std::swap(ValueOnZero, Count);
15712 // Check if the value on zero is a constant equal to the bits in the type.
15713 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
15714 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
15715 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
15716 // legal, combine to just cttz.
15717 if ((Count.getOpcode() == ISD::CTTZ ||
15718 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
15719 N0 == Count.getOperand(0) &&
15720 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
15721 return DAG.getNode(ISD::CTTZ, DL, VT, N0);
15722 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
15723 // legal, combine to just ctlz.
15724 if ((Count.getOpcode() == ISD::CTLZ ||
15725 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
15726 N0 == Count.getOperand(0) &&
15727 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
15728 return DAG.getNode(ISD::CTLZ, DL, VT, N0);
15736 /// This is a stub for TargetLowering::SimplifySetCC.
15737 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
15738 ISD::CondCode Cond, const SDLoc &DL,
15739 bool foldBooleans) {
15740 TargetLowering::DAGCombinerInfo
15741 DagCombineInfo(DAG, Level, false, this);
15742 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
15745 /// Given an ISD::SDIV node expressing a divide by constant, return
15746 /// a DAG expression to select that will generate the same value by multiplying
15747 /// by a magic number.
15748 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15749 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
15750 // when optimising for minimum size, we don't want to expand a div to a mul
15752 if (DAG.getMachineFunction().getFunction()->optForMinSize())
15755 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15759 // Avoid division by zero.
15760 if (C->isNullValue())
15763 std::vector<SDNode*> Built;
15765 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15767 for (SDNode *N : Built)
15772 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
15773 /// DAG expression that will generate the same value by right shifting.
15774 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
15775 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15779 // Avoid division by zero.
15780 if (C->isNullValue())
15783 std::vector<SDNode *> Built;
15784 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
15786 for (SDNode *N : Built)
15791 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
15792 /// expression that will generate the same value by multiplying by a magic
15794 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15795 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
15796 // when optimising for minimum size, we don't want to expand a div to a mul
15798 if (DAG.getMachineFunction().getFunction()->optForMinSize())
15801 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15805 // Avoid division by zero.
15806 if (C->isNullValue())
15809 std::vector<SDNode*> Built;
15811 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15813 for (SDNode *N : Built)
15818 /// Determines the LogBase2 value for a non-null input value using the
15819 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
15820 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
15821 EVT VT = V.getValueType();
15822 unsigned EltBits = VT.getScalarSizeInBits();
15823 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
15824 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
15825 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
15829 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15830 /// For the reciprocal, we need to find the zero of the function:
15831 /// F(X) = A X - 1 [which has a zero at X = 1/A]
15833 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
15834 /// does not require additional intermediate precision]
15835 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
15836 if (Level >= AfterLegalizeDAG)
15839 // TODO: Handle half and/or extended types?
15840 EVT VT = Op.getValueType();
15841 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15844 // If estimates are explicitly disabled for this function, we're done.
15845 MachineFunction &MF = DAG.getMachineFunction();
15846 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
15847 if (Enabled == TLI.ReciprocalEstimate::Disabled)
15850 // Estimates may be explicitly enabled for this type with a custom number of
15851 // refinement steps.
15852 int Iterations = TLI.getDivRefinementSteps(VT, MF);
15853 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
15854 AddToWorklist(Est.getNode());
15857 EVT VT = Op.getValueType();
15859 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
15861 // Newton iterations: Est = Est + Est (1 - Arg * Est)
15862 for (int i = 0; i < Iterations; ++i) {
15863 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
15864 AddToWorklist(NewEst.getNode());
15866 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
15867 AddToWorklist(NewEst.getNode());
15869 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15870 AddToWorklist(NewEst.getNode());
15872 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
15873 AddToWorklist(Est.getNode());
15882 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15883 /// For the reciprocal sqrt, we need to find the zero of the function:
15884 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15886 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
15887 /// As a result, we precompute A/2 prior to the iteration loop.
15888 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
15889 unsigned Iterations,
15890 SDNodeFlags *Flags, bool Reciprocal) {
15891 EVT VT = Arg.getValueType();
15893 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
15895 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
15896 // this entire sequence requires only one FP constant.
15897 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
15898 AddToWorklist(HalfArg.getNode());
15900 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
15901 AddToWorklist(HalfArg.getNode());
15903 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
15904 for (unsigned i = 0; i < Iterations; ++i) {
15905 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
15906 AddToWorklist(NewEst.getNode());
15908 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
15909 AddToWorklist(NewEst.getNode());
15911 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
15912 AddToWorklist(NewEst.getNode());
15914 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15915 AddToWorklist(Est.getNode());
15918 // If non-reciprocal square root is requested, multiply the result by Arg.
15920 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
15921 AddToWorklist(Est.getNode());
15927 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15928 /// For the reciprocal sqrt, we need to find the zero of the function:
15929 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15931 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
15932 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
15933 unsigned Iterations,
15934 SDNodeFlags *Flags, bool Reciprocal) {
15935 EVT VT = Arg.getValueType();
15937 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
15938 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
15940 // This routine must enter the loop below to work correctly
15941 // when (Reciprocal == false).
15942 assert(Iterations > 0);
15944 // Newton iterations for reciprocal square root:
15945 // E = (E * -0.5) * ((A * E) * E + -3.0)
15946 for (unsigned i = 0; i < Iterations; ++i) {
15947 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15948 AddToWorklist(AE.getNode());
15950 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15951 AddToWorklist(AEE.getNode());
15953 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15954 AddToWorklist(RHS.getNode());
15956 // When calculating a square root at the last iteration build:
15957 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15958 // (notice a common subexpression)
15960 if (Reciprocal || (i + 1) < Iterations) {
15961 // RSQRT: LHS = (E * -0.5)
15962 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15964 // SQRT: LHS = (A * E) * -0.5
15965 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15967 AddToWorklist(LHS.getNode());
15969 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15970 AddToWorklist(Est.getNode());
15976 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15977 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15978 /// Op can be zero.
15979 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15981 if (Level >= AfterLegalizeDAG)
15984 // TODO: Handle half and/or extended types?
15985 EVT VT = Op.getValueType();
15986 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15989 // If estimates are explicitly disabled for this function, we're done.
15990 MachineFunction &MF = DAG.getMachineFunction();
15991 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
15992 if (Enabled == TLI.ReciprocalEstimate::Disabled)
15995 // Estimates may be explicitly enabled for this type with a custom number of
15996 // refinement steps.
15997 int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
15999 bool UseOneConstNR = false;
16001 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16003 AddToWorklist(Est.getNode());
16006 Est = UseOneConstNR
16007 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16008 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16011 // Unfortunately, Est is now NaN if the input was exactly 0.0.
16012 // Select out this case and force the answer to 0.0.
16013 EVT VT = Op.getValueType();
16016 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16017 EVT CCVT = getSetCCResultType(VT);
16018 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16019 AddToWorklist(ZeroCmp.getNode());
16021 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16022 ZeroCmp, FPZero, Est);
16023 AddToWorklist(Est.getNode());
16032 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
16033 return buildSqrtEstimateImpl(Op, Flags, true);
16036 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
16037 return buildSqrtEstimateImpl(Op, Flags, false);
16040 /// Return true if base is a frame index, which is known not to alias with
16041 /// anything but itself. Provides base object and offset as results.
16042 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16043 const GlobalValue *&GV, const void *&CV) {
16044 // Assume it is a primitive operation.
16045 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16047 // If it's an adding a simple constant then integrate the offset.
16048 if (Base.getOpcode() == ISD::ADD) {
16049 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16050 Base = Base.getOperand(0);
16051 Offset += C->getSExtValue();
16055 // Return the underlying GlobalValue, and update the Offset. Return false
16056 // for GlobalAddressSDNode since the same GlobalAddress may be represented
16057 // by multiple nodes with different offsets.
16058 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16059 GV = G->getGlobal();
16060 Offset += G->getOffset();
16064 // Return the underlying Constant value, and update the Offset. Return false
16065 // for ConstantSDNodes since the same constant pool entry may be represented
16066 // by multiple nodes with different offsets.
16067 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16068 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16069 : (const void *)C->getConstVal();
16070 Offset += C->getOffset();
16073 // If it's any of the following then it can't alias with anything but itself.
16074 return isa<FrameIndexSDNode>(Base);
16077 /// Return true if there is any possibility that the two addresses overlap.
16078 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16079 // If they are the same then they must be aliases.
16080 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16082 // If they are both volatile then they cannot be reordered.
16083 if (Op0->isVolatile() && Op1->isVolatile()) return true;
16085 // If one operation reads from invariant memory, and the other may store, they
16086 // cannot alias. These should really be checking the equivalent of mayWrite,
16087 // but it only matters for memory nodes other than load /store.
16088 if (Op0->isInvariant() && Op1->writeMem())
16091 if (Op1->isInvariant() && Op0->writeMem())
16094 unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16095 unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16097 // Check for BaseIndexOffset matching.
16098 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
16099 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
16100 if (BasePtr0.equalBaseIndex(BasePtr1))
16101 return !((BasePtr0.Offset + NumBytes0 <= BasePtr1.Offset) ||
16102 (BasePtr1.Offset + NumBytes1 <= BasePtr0.Offset));
16104 // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
16105 // modified to use BaseIndexOffset.
16107 // Gather base node and offset information.
16108 SDValue Base0, Base1;
16109 int64_t Offset0, Offset1;
16110 const GlobalValue *GV0, *GV1;
16111 const void *CV0, *CV1;
16112 bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16113 Base0, Offset0, GV0, CV0);
16114 bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16115 Base1, Offset1, GV1, CV1);
16117 // If they have the same base address, then check to see if they overlap.
16118 if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16119 return !((Offset0 + NumBytes0) <= Offset1 ||
16120 (Offset1 + NumBytes1) <= Offset0);
16122 // It is possible for different frame indices to alias each other, mostly
16123 // when tail call optimization reuses return address slots for arguments.
16124 // To catch this case, look up the actual index of frame indices to compute
16125 // the real alias relationship.
16126 if (IsFrameIndex0 && IsFrameIndex1) {
16127 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16128 Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16129 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16130 return !((Offset0 + NumBytes0) <= Offset1 ||
16131 (Offset1 + NumBytes1) <= Offset0);
16134 // Otherwise, if we know what the bases are, and they aren't identical, then
16135 // we know they cannot alias.
16136 if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16139 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16140 // compared to the size and offset of the access, we may be able to prove they
16141 // do not alias. This check is conservative for now to catch cases created by
16142 // splitting vector types.
16143 int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16144 int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16145 unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16146 unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16147 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16148 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16149 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16150 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16152 // There is no overlap between these relatively aligned accesses of similar
16153 // size. Return no alias.
16154 if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16155 (OffAlign1 + NumBytes1) <= OffAlign0)
16159 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16161 : DAG.getSubtarget().useAA();
16163 if (CombinerAAOnlyFunc.getNumOccurrences() &&
16164 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16169 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16170 // Use alias analysis information.
16171 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16172 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16173 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16174 AliasResult AAResult =
16175 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16176 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16177 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16178 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
16179 if (AAResult == NoAlias)
16183 // Otherwise we have to assume they alias.
16187 /// Walk up chain skipping non-aliasing memory nodes,
16188 /// looking for aliasing nodes and adding them to the Aliases vector.
16189 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16190 SmallVectorImpl<SDValue> &Aliases) {
16191 SmallVector<SDValue, 8> Chains; // List of chains to visit.
16192 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
16194 // Get alias information for node.
16195 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16198 Chains.push_back(OriginalChain);
16199 unsigned Depth = 0;
16201 // Look at each chain and determine if it is an alias. If so, add it to the
16202 // aliases list. If not, then continue up the chain looking for the next
16204 while (!Chains.empty()) {
16205 SDValue Chain = Chains.pop_back_val();
16207 // For TokenFactor nodes, look at each operand and only continue up the
16208 // chain until we reach the depth limit.
16210 // FIXME: The depth check could be made to return the last non-aliasing
16211 // chain we found before we hit a tokenfactor rather than the original
16213 if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16215 Aliases.push_back(OriginalChain);
16219 // Don't bother if we've been before.
16220 if (!Visited.insert(Chain.getNode()).second)
16223 switch (Chain.getOpcode()) {
16224 case ISD::EntryToken:
16225 // Entry token is ideal chain operand, but handled in FindBetterChain.
16230 // Get alias information for Chain.
16231 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16232 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16234 // If chain is alias then stop here.
16235 if (!(IsLoad && IsOpLoad) &&
16236 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16237 Aliases.push_back(Chain);
16239 // Look further up the chain.
16240 Chains.push_back(Chain.getOperand(0));
16246 case ISD::TokenFactor:
16247 // We have to check each of the operands of the token factor for "small"
16248 // token factors, so we queue them up. Adding the operands to the queue
16249 // (stack) in reverse order maintains the original order and increases the
16250 // likelihood that getNode will find a matching token factor (CSE.)
16251 if (Chain.getNumOperands() > 16) {
16252 Aliases.push_back(Chain);
16255 for (unsigned n = Chain.getNumOperands(); n;)
16256 Chains.push_back(Chain.getOperand(--n));
16260 case ISD::CopyFromReg:
16261 // Forward past CopyFromReg.
16262 Chains.push_back(Chain.getOperand(0));
16267 // For all other instructions we will just have to take what we can get.
16268 Aliases.push_back(Chain);
16274 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16275 /// (aliasing node.)
16276 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16277 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
16279 // Accumulate all the aliases to this node.
16280 GatherAllAliases(N, OldChain, Aliases);
16282 // If no operands then chain to entry token.
16283 if (Aliases.size() == 0)
16284 return DAG.getEntryNode();
16286 // If a single operand then chain to it. We don't need to revisit it.
16287 if (Aliases.size() == 1)
16290 // Construct a custom tailored token factor.
16291 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16294 // This function tries to collect a bunch of potentially interesting
16295 // nodes to improve the chains of, all at once. This might seem
16296 // redundant, as this function gets called when visiting every store
16297 // node, so why not let the work be done on each store as it's visited?
16299 // I believe this is mainly important because MergeConsecutiveStores
16300 // is unable to deal with merging stores of different sizes, so unless
16301 // we improve the chains of all the potential candidates up-front
16302 // before running MergeConsecutiveStores, it might only see some of
16303 // the nodes that will eventually be candidates, and then not be able
16304 // to go from a partially-merged state to the desired final
16305 // fully-merged state.
16306 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16307 // This holds the base pointer, index, and the offset in bytes from the base
16309 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16311 // We must have a base and an offset.
16312 if (!BasePtr.Base.getNode())
16315 // Do not handle stores to undef base pointers.
16316 if (BasePtr.Base.isUndef())
16319 SmallVector<StoreSDNode *, 8> ChainedStores;
16320 ChainedStores.push_back(St);
16322 // Walk up the chain and look for nodes with offsets from the same
16323 // base pointer. Stop when reaching an instruction with a different kind
16324 // or instruction which has a different base pointer.
16325 StoreSDNode *Index = St;
16327 // If the chain has more than one use, then we can't reorder the mem ops.
16328 if (Index != St && !SDValue(Index, 0)->hasOneUse())
16331 if (Index->isVolatile() || Index->isIndexed())
16334 // Find the base pointer and offset for this memory node.
16335 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
16337 // Check that the base pointer is the same as the original one.
16338 if (!Ptr.equalBaseIndex(BasePtr))
16341 // Walk up the chain to find the next store node, ignoring any
16342 // intermediate loads. Any other kind of node will halt the loop.
16343 SDNode *NextInChain = Index->getChain().getNode();
16345 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
16346 // We found a store node. Use it for the next iteration.
16347 if (STn->isVolatile() || STn->isIndexed()) {
16351 ChainedStores.push_back(STn);
16354 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
16355 NextInChain = Ldn->getChain().getNode();
16364 // At this point, ChainedStores lists all of the Store nodes
16365 // reachable by iterating up through chain nodes matching the above
16366 // conditions. For each such store identified, try to find an
16367 // earlier chain to attach the store to which won't violate the
16368 // required ordering.
16369 bool MadeChangeToSt = false;
16370 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
16372 for (StoreSDNode *ChainedStore : ChainedStores) {
16373 SDValue Chain = ChainedStore->getChain();
16374 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
16376 if (Chain != BetterChain) {
16377 if (ChainedStore == St)
16378 MadeChangeToSt = true;
16379 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
16383 // Do all replacements after finding the replacements to make to avoid making
16384 // the chains more complicated by introducing new TokenFactors.
16385 for (auto Replacement : BetterChains)
16386 replaceStoreChain(Replacement.first, Replacement.second);
16388 return MadeChangeToSt;
16391 /// This is the entry point for the file.
16392 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
16393 CodeGenOpt::Level OptLevel) {
16394 /// This is the main entry point to this class.
16395 DAGCombiner(*this, AA, OptLevel).Run(Level);