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/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.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/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitIMINMAX(SDNode *N);
249 SDValue visitAND(SDNode *N);
250 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
251 SDValue visitOR(SDNode *N);
252 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
253 SDValue visitXOR(SDNode *N);
254 SDValue SimplifyVBinOp(SDNode *N);
255 SDValue visitSHL(SDNode *N);
256 SDValue visitSRA(SDNode *N);
257 SDValue visitSRL(SDNode *N);
258 SDValue visitRotate(SDNode *N);
259 SDValue visitBSWAP(SDNode *N);
260 SDValue visitCTLZ(SDNode *N);
261 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
262 SDValue visitCTTZ(SDNode *N);
263 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
264 SDValue visitCTPOP(SDNode *N);
265 SDValue visitSELECT(SDNode *N);
266 SDValue visitVSELECT(SDNode *N);
267 SDValue visitSELECT_CC(SDNode *N);
268 SDValue visitSETCC(SDNode *N);
269 SDValue visitSIGN_EXTEND(SDNode *N);
270 SDValue visitZERO_EXTEND(SDNode *N);
271 SDValue visitANY_EXTEND(SDNode *N);
272 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
273 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
274 SDValue visitTRUNCATE(SDNode *N);
275 SDValue visitBITCAST(SDNode *N);
276 SDValue visitBUILD_PAIR(SDNode *N);
277 SDValue visitFADD(SDNode *N);
278 SDValue visitFSUB(SDNode *N);
279 SDValue visitFMUL(SDNode *N);
280 SDValue visitFMA(SDNode *N);
281 SDValue visitFDIV(SDNode *N);
282 SDValue visitFREM(SDNode *N);
283 SDValue visitFSQRT(SDNode *N);
284 SDValue visitFCOPYSIGN(SDNode *N);
285 SDValue visitSINT_TO_FP(SDNode *N);
286 SDValue visitUINT_TO_FP(SDNode *N);
287 SDValue visitFP_TO_SINT(SDNode *N);
288 SDValue visitFP_TO_UINT(SDNode *N);
289 SDValue visitFP_ROUND(SDNode *N);
290 SDValue visitFP_ROUND_INREG(SDNode *N);
291 SDValue visitFP_EXTEND(SDNode *N);
292 SDValue visitFNEG(SDNode *N);
293 SDValue visitFABS(SDNode *N);
294 SDValue visitFCEIL(SDNode *N);
295 SDValue visitFTRUNC(SDNode *N);
296 SDValue visitFFLOOR(SDNode *N);
297 SDValue visitFMINNUM(SDNode *N);
298 SDValue visitFMAXNUM(SDNode *N);
299 SDValue visitBRCOND(SDNode *N);
300 SDValue visitBR_CC(SDNode *N);
301 SDValue visitLOAD(SDNode *N);
303 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
305 SDValue visitSTORE(SDNode *N);
306 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
307 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
308 SDValue visitBUILD_VECTOR(SDNode *N);
309 SDValue visitCONCAT_VECTORS(SDNode *N);
310 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
311 SDValue visitVECTOR_SHUFFLE(SDNode *N);
312 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
313 SDValue visitINSERT_SUBVECTOR(SDNode *N);
314 SDValue visitMLOAD(SDNode *N);
315 SDValue visitMSTORE(SDNode *N);
316 SDValue visitMGATHER(SDNode *N);
317 SDValue visitMSCATTER(SDNode *N);
318 SDValue visitFP_TO_FP16(SDNode *N);
319 SDValue visitFP16_TO_FP(SDNode *N);
321 SDValue visitFADDForFMACombine(SDNode *N);
322 SDValue visitFSUBForFMACombine(SDNode *N);
324 SDValue XformToShuffleWithZero(SDNode *N);
325 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
327 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
329 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
330 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
331 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
332 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
333 SDValue N3, ISD::CondCode CC,
334 bool NotExtCompare = false);
335 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
336 SDLoc DL, bool foldBooleans = true);
338 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
340 bool isOneUseSetCC(SDValue N) const;
342 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
344 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
345 SDValue CombineExtLoad(SDNode *N);
346 SDValue combineRepeatedFPDivisors(SDNode *N);
347 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
348 SDValue BuildSDIV(SDNode *N);
349 SDValue BuildSDIVPow2(SDNode *N);
350 SDValue BuildUDIV(SDNode *N);
351 SDValue BuildReciprocalEstimate(SDValue Op);
352 SDValue BuildRsqrtEstimate(SDValue Op);
353 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
354 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
355 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
356 bool DemandHighBits = true);
357 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
358 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
359 SDValue InnerPos, SDValue InnerNeg,
360 unsigned PosOpcode, unsigned NegOpcode,
362 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
363 SDValue ReduceLoadWidth(SDNode *N);
364 SDValue ReduceLoadOpStoreWidth(SDNode *N);
365 SDValue TransformFPLoadStorePair(SDNode *N);
366 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
367 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
369 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
371 /// Walk up chain skipping non-aliasing memory nodes,
372 /// looking for aliasing nodes and adding them to the Aliases vector.
373 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
374 SmallVectorImpl<SDValue> &Aliases);
376 /// Return true if there is any possibility that the two addresses overlap.
377 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
379 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
380 /// chain (aliasing node.)
381 SDValue FindBetterChain(SDNode *N, SDValue Chain);
383 /// Do FindBetterChain for a store and any possibly adjacent stores on
384 /// consecutive chains.
385 bool findBetterNeighborChains(StoreSDNode *St);
387 /// Holds a pointer to an LSBaseSDNode as well as information on where it
388 /// is located in a sequence of memory operations connected by a chain.
390 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
391 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
392 // Ptr to the mem node.
393 LSBaseSDNode *MemNode;
394 // Offset from the base ptr.
395 int64_t OffsetFromBase;
396 // What is the sequence number of this mem node.
397 // Lowest mem operand in the DAG starts at zero.
398 unsigned SequenceNum;
401 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
402 /// constant build_vector of the stored constant values in Stores.
403 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
405 ArrayRef<MemOpLink> Stores,
408 /// This is a helper function for MergeConsecutiveStores. When the source
409 /// elements of the consecutive stores are all constants or all extracted
410 /// vector elements, try to merge them into one larger store.
411 /// \return True if a merged store was created.
412 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
413 EVT MemVT, unsigned NumStores,
414 bool IsConstantSrc, bool UseVector);
416 /// This is a helper function for MergeConsecutiveStores.
417 /// Stores that may be merged are placed in StoreNodes.
418 /// Loads that may alias with those stores are placed in AliasLoadNodes.
419 void getStoreMergeAndAliasCandidates(
420 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
421 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
423 /// Merge consecutive store operations into a wide store.
424 /// This optimization uses wide integers or vectors when possible.
425 /// \return True if some memory operations were changed.
426 bool MergeConsecutiveStores(StoreSDNode *N);
428 /// \brief Try to transform a truncation where C is a constant:
429 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
431 /// \p N needs to be a truncation and its first operand an AND. Other
432 /// requirements are checked by the function (e.g. that trunc is
433 /// single-use) and if missed an empty SDValue is returned.
434 SDValue distributeTruncateThroughAnd(SDNode *N);
437 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
438 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
439 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
440 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
443 /// Runs the dag combiner on all nodes in the work list
444 void Run(CombineLevel AtLevel);
446 SelectionDAG &getDAG() const { return DAG; }
448 /// Returns a type large enough to hold any valid shift amount - before type
449 /// legalization these can be huge.
450 EVT getShiftAmountTy(EVT LHSTy) {
451 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
452 if (LHSTy.isVector())
454 auto &DL = DAG.getDataLayout();
455 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
456 : TLI.getPointerTy(DL);
459 /// This method returns true if we are running before type legalization or
460 /// if the specified VT is legal.
461 bool isTypeLegal(const EVT &VT) {
462 if (!LegalTypes) return true;
463 return TLI.isTypeLegal(VT);
466 /// Convenience wrapper around TargetLowering::getSetCCResultType
467 EVT getSetCCResultType(EVT VT) const {
468 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
475 /// This class is a DAGUpdateListener that removes any deleted
476 /// nodes from the worklist.
477 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
480 explicit WorklistRemover(DAGCombiner &dc)
481 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
483 void NodeDeleted(SDNode *N, SDNode *E) override {
484 DC.removeFromWorklist(N);
489 //===----------------------------------------------------------------------===//
490 // TargetLowering::DAGCombinerInfo implementation
491 //===----------------------------------------------------------------------===//
493 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
494 ((DAGCombiner*)DC)->AddToWorklist(N);
497 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
498 ((DAGCombiner*)DC)->removeFromWorklist(N);
501 SDValue TargetLowering::DAGCombinerInfo::
502 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
503 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
506 SDValue TargetLowering::DAGCombinerInfo::
507 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
508 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
512 SDValue TargetLowering::DAGCombinerInfo::
513 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
514 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
517 void TargetLowering::DAGCombinerInfo::
518 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
519 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
522 //===----------------------------------------------------------------------===//
524 //===----------------------------------------------------------------------===//
526 void DAGCombiner::deleteAndRecombine(SDNode *N) {
527 removeFromWorklist(N);
529 // If the operands of this node are only used by the node, they will now be
530 // dead. Make sure to re-visit them and recursively delete dead nodes.
531 for (const SDValue &Op : N->ops())
532 // For an operand generating multiple values, one of the values may
533 // become dead allowing further simplification (e.g. split index
534 // arithmetic from an indexed load).
535 if (Op->hasOneUse() || Op->getNumValues() > 1)
536 AddToWorklist(Op.getNode());
541 /// Return 1 if we can compute the negated form of the specified expression for
542 /// the same cost as the expression itself, or 2 if we can compute the negated
543 /// form more cheaply than the expression itself.
544 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
545 const TargetLowering &TLI,
546 const TargetOptions *Options,
547 unsigned Depth = 0) {
548 // fneg is removable even if it has multiple uses.
549 if (Op.getOpcode() == ISD::FNEG) return 2;
551 // Don't allow anything with multiple uses.
552 if (!Op.hasOneUse()) return 0;
554 // Don't recurse exponentially.
555 if (Depth > 6) return 0;
557 switch (Op.getOpcode()) {
558 default: return false;
559 case ISD::ConstantFP:
560 // Don't invert constant FP values after legalize. The negated constant
561 // isn't necessarily legal.
562 return LegalOperations ? 0 : 1;
564 // FIXME: determine better conditions for this xform.
565 if (!Options->UnsafeFPMath) return 0;
567 // After operation legalization, it might not be legal to create new FSUBs.
568 if (LegalOperations &&
569 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
572 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
573 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
576 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
577 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
580 // We can't turn -(A-B) into B-A when we honor signed zeros.
581 if (!Options->UnsafeFPMath) return 0;
583 // fold (fneg (fsub A, B)) -> (fsub B, A)
588 if (Options->HonorSignDependentRoundingFPMath()) return 0;
590 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
591 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
595 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
601 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
606 /// If isNegatibleForFree returns true, return the newly negated expression.
607 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
608 bool LegalOperations, unsigned Depth = 0) {
609 const TargetOptions &Options = DAG.getTarget().Options;
610 // fneg is removable even if it has multiple uses.
611 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
613 // Don't allow anything with multiple uses.
614 assert(Op.hasOneUse() && "Unknown reuse!");
616 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
617 switch (Op.getOpcode()) {
618 default: llvm_unreachable("Unknown code");
619 case ISD::ConstantFP: {
620 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
622 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
625 // FIXME: determine better conditions for this xform.
626 assert(Options.UnsafeFPMath);
628 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
629 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
630 DAG.getTargetLoweringInfo(), &Options, Depth+1))
631 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
632 GetNegatedExpression(Op.getOperand(0), DAG,
633 LegalOperations, Depth+1),
635 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
636 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
637 GetNegatedExpression(Op.getOperand(1), DAG,
638 LegalOperations, Depth+1),
641 // We can't turn -(A-B) into B-A when we honor signed zeros.
642 assert(Options.UnsafeFPMath);
644 // fold (fneg (fsub 0, B)) -> B
645 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
647 return Op.getOperand(1);
649 // fold (fneg (fsub A, B)) -> (fsub B, A)
650 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
651 Op.getOperand(1), Op.getOperand(0));
655 assert(!Options.HonorSignDependentRoundingFPMath());
657 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
658 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
659 DAG.getTargetLoweringInfo(), &Options, Depth+1))
660 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
661 GetNegatedExpression(Op.getOperand(0), DAG,
662 LegalOperations, Depth+1),
665 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
666 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
668 GetNegatedExpression(Op.getOperand(1), DAG,
669 LegalOperations, Depth+1));
673 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
674 GetNegatedExpression(Op.getOperand(0), DAG,
675 LegalOperations, Depth+1));
677 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
678 GetNegatedExpression(Op.getOperand(0), DAG,
679 LegalOperations, Depth+1),
684 // Return true if this node is a setcc, or is a select_cc
685 // that selects between the target values used for true and false, making it
686 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
687 // the appropriate nodes based on the type of node we are checking. This
688 // simplifies life a bit for the callers.
689 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
691 if (N.getOpcode() == ISD::SETCC) {
692 LHS = N.getOperand(0);
693 RHS = N.getOperand(1);
694 CC = N.getOperand(2);
698 if (N.getOpcode() != ISD::SELECT_CC ||
699 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
700 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
703 if (TLI.getBooleanContents(N.getValueType()) ==
704 TargetLowering::UndefinedBooleanContent)
707 LHS = N.getOperand(0);
708 RHS = N.getOperand(1);
709 CC = N.getOperand(4);
713 /// Return true if this is a SetCC-equivalent operation with only one use.
714 /// If this is true, it allows the users to invert the operation for free when
715 /// it is profitable to do so.
716 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
718 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
723 /// Returns true if N is a BUILD_VECTOR node whose
724 /// elements are all the same constant or undefined.
725 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
726 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
731 unsigned SplatBitSize;
733 EVT EltVT = N->getValueType(0).getVectorElementType();
734 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
736 EltVT.getSizeInBits() >= SplatBitSize);
739 // \brief Returns the SDNode if it is a constant integer BuildVector
740 // or constant integer.
741 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
742 if (isa<ConstantSDNode>(N))
744 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
749 // \brief Returns the SDNode if it is a constant float BuildVector
750 // or constant float.
751 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
752 if (isa<ConstantFPSDNode>(N))
754 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
759 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
761 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
762 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
765 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
766 BitVector UndefElements;
767 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
769 // BuildVectors can truncate their operands. Ignore that case here.
770 // FIXME: We blindly ignore splats which include undef which is overly
772 if (CN && UndefElements.none() &&
773 CN->getValueType(0) == N.getValueType().getScalarType())
780 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
782 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
783 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
786 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
787 BitVector UndefElements;
788 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
790 if (CN && UndefElements.none())
797 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
798 SDValue N0, SDValue N1) {
799 EVT VT = N0.getValueType();
800 if (N0.getOpcode() == Opc) {
801 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
802 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
803 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
804 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
805 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
808 if (N0.hasOneUse()) {
809 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
811 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
812 if (!OpNode.getNode())
814 AddToWorklist(OpNode.getNode());
815 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
820 if (N1.getOpcode() == Opc) {
821 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
822 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
823 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
824 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
825 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
828 if (N1.hasOneUse()) {
829 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
831 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
832 if (!OpNode.getNode())
834 AddToWorklist(OpNode.getNode());
835 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
843 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
845 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
847 DEBUG(dbgs() << "\nReplacing.1 ";
849 dbgs() << "\nWith: ";
850 To[0].getNode()->dump(&DAG);
851 dbgs() << " and " << NumTo-1 << " other values\n");
852 for (unsigned i = 0, e = NumTo; i != e; ++i)
853 assert((!To[i].getNode() ||
854 N->getValueType(i) == To[i].getValueType()) &&
855 "Cannot combine value to value of different type!");
857 WorklistRemover DeadNodes(*this);
858 DAG.ReplaceAllUsesWith(N, To);
860 // Push the new nodes and any users onto the worklist
861 for (unsigned i = 0, e = NumTo; i != e; ++i) {
862 if (To[i].getNode()) {
863 AddToWorklist(To[i].getNode());
864 AddUsersToWorklist(To[i].getNode());
869 // Finally, if the node is now dead, remove it from the graph. The node
870 // may not be dead if the replacement process recursively simplified to
871 // something else needing this node.
873 deleteAndRecombine(N);
874 return SDValue(N, 0);
878 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
879 // Replace all uses. If any nodes become isomorphic to other nodes and
880 // are deleted, make sure to remove them from our worklist.
881 WorklistRemover DeadNodes(*this);
882 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
884 // Push the new node and any (possibly new) users onto the worklist.
885 AddToWorklist(TLO.New.getNode());
886 AddUsersToWorklist(TLO.New.getNode());
888 // Finally, if the node is now dead, remove it from the graph. The node
889 // may not be dead if the replacement process recursively simplified to
890 // something else needing this node.
891 if (TLO.Old.getNode()->use_empty())
892 deleteAndRecombine(TLO.Old.getNode());
895 /// Check the specified integer node value to see if it can be simplified or if
896 /// things it uses can be simplified by bit propagation. If so, return true.
897 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
898 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
899 APInt KnownZero, KnownOne;
900 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
904 AddToWorklist(Op.getNode());
906 // Replace the old value with the new one.
908 DEBUG(dbgs() << "\nReplacing.2 ";
909 TLO.Old.getNode()->dump(&DAG);
910 dbgs() << "\nWith: ";
911 TLO.New.getNode()->dump(&DAG);
914 CommitTargetLoweringOpt(TLO);
918 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
920 EVT VT = Load->getValueType(0);
921 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
923 DEBUG(dbgs() << "\nReplacing.9 ";
925 dbgs() << "\nWith: ";
926 Trunc.getNode()->dump(&DAG);
928 WorklistRemover DeadNodes(*this);
929 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
930 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
931 deleteAndRecombine(Load);
932 AddToWorklist(Trunc.getNode());
935 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
938 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
939 EVT MemVT = LD->getMemoryVT();
940 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
941 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
943 : LD->getExtensionType();
945 return DAG.getExtLoad(ExtType, dl, PVT,
946 LD->getChain(), LD->getBasePtr(),
947 MemVT, LD->getMemOperand());
950 unsigned Opc = Op.getOpcode();
953 case ISD::AssertSext:
954 return DAG.getNode(ISD::AssertSext, dl, PVT,
955 SExtPromoteOperand(Op.getOperand(0), PVT),
957 case ISD::AssertZext:
958 return DAG.getNode(ISD::AssertZext, dl, PVT,
959 ZExtPromoteOperand(Op.getOperand(0), PVT),
961 case ISD::Constant: {
963 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
964 return DAG.getNode(ExtOpc, dl, PVT, Op);
968 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
970 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
973 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
974 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
976 EVT OldVT = Op.getValueType();
978 bool Replace = false;
979 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
980 if (!NewOp.getNode())
982 AddToWorklist(NewOp.getNode());
985 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
986 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
987 DAG.getValueType(OldVT));
990 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
991 EVT OldVT = Op.getValueType();
993 bool Replace = false;
994 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
995 if (!NewOp.getNode())
997 AddToWorklist(NewOp.getNode());
1000 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1001 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1004 /// Promote the specified integer binary operation if the target indicates it is
1005 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1006 /// i32 since i16 instructions are longer.
1007 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1008 if (!LegalOperations)
1011 EVT VT = Op.getValueType();
1012 if (VT.isVector() || !VT.isInteger())
1015 // If operation type is 'undesirable', e.g. i16 on x86, consider
1017 unsigned Opc = Op.getOpcode();
1018 if (TLI.isTypeDesirableForOp(Opc, VT))
1022 // Consult target whether it is a good idea to promote this operation and
1023 // what's the right type to promote it to.
1024 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1025 assert(PVT != VT && "Don't know what type to promote to!");
1027 bool Replace0 = false;
1028 SDValue N0 = Op.getOperand(0);
1029 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1033 bool Replace1 = false;
1034 SDValue N1 = Op.getOperand(1);
1039 NN1 = PromoteOperand(N1, PVT, Replace1);
1044 AddToWorklist(NN0.getNode());
1046 AddToWorklist(NN1.getNode());
1049 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1051 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1053 DEBUG(dbgs() << "\nPromoting ";
1054 Op.getNode()->dump(&DAG));
1056 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1057 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1062 /// Promote the specified integer shift operation if the target indicates it is
1063 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1064 /// i32 since i16 instructions are longer.
1065 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1066 if (!LegalOperations)
1069 EVT VT = Op.getValueType();
1070 if (VT.isVector() || !VT.isInteger())
1073 // If operation type is 'undesirable', e.g. i16 on x86, consider
1075 unsigned Opc = Op.getOpcode();
1076 if (TLI.isTypeDesirableForOp(Opc, VT))
1080 // Consult target whether it is a good idea to promote this operation and
1081 // what's the right type to promote it to.
1082 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1083 assert(PVT != VT && "Don't know what type to promote to!");
1085 bool Replace = false;
1086 SDValue N0 = Op.getOperand(0);
1087 if (Opc == ISD::SRA)
1088 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1089 else if (Opc == ISD::SRL)
1090 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1092 N0 = PromoteOperand(N0, PVT, Replace);
1096 AddToWorklist(N0.getNode());
1098 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1100 DEBUG(dbgs() << "\nPromoting ";
1101 Op.getNode()->dump(&DAG));
1103 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1104 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1109 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1110 if (!LegalOperations)
1113 EVT VT = Op.getValueType();
1114 if (VT.isVector() || !VT.isInteger())
1117 // If operation type is 'undesirable', e.g. i16 on x86, consider
1119 unsigned Opc = Op.getOpcode();
1120 if (TLI.isTypeDesirableForOp(Opc, VT))
1124 // Consult target whether it is a good idea to promote this operation and
1125 // what's the right type to promote it to.
1126 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1127 assert(PVT != VT && "Don't know what type to promote to!");
1128 // fold (aext (aext x)) -> (aext x)
1129 // fold (aext (zext x)) -> (zext x)
1130 // fold (aext (sext x)) -> (sext x)
1131 DEBUG(dbgs() << "\nPromoting ";
1132 Op.getNode()->dump(&DAG));
1133 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1138 bool DAGCombiner::PromoteLoad(SDValue Op) {
1139 if (!LegalOperations)
1142 EVT VT = Op.getValueType();
1143 if (VT.isVector() || !VT.isInteger())
1146 // If operation type is 'undesirable', e.g. i16 on x86, consider
1148 unsigned Opc = Op.getOpcode();
1149 if (TLI.isTypeDesirableForOp(Opc, VT))
1153 // Consult target whether it is a good idea to promote this operation and
1154 // what's the right type to promote it to.
1155 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1156 assert(PVT != VT && "Don't know what type to promote to!");
1159 SDNode *N = Op.getNode();
1160 LoadSDNode *LD = cast<LoadSDNode>(N);
1161 EVT MemVT = LD->getMemoryVT();
1162 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1163 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1165 : LD->getExtensionType();
1166 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1167 LD->getChain(), LD->getBasePtr(),
1168 MemVT, LD->getMemOperand());
1169 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1171 DEBUG(dbgs() << "\nPromoting ";
1174 Result.getNode()->dump(&DAG);
1176 WorklistRemover DeadNodes(*this);
1177 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1178 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1179 deleteAndRecombine(N);
1180 AddToWorklist(Result.getNode());
1186 /// \brief Recursively delete a node which has no uses and any operands for
1187 /// which it is the only use.
1189 /// Note that this both deletes the nodes and removes them from the worklist.
1190 /// It also adds any nodes who have had a user deleted to the worklist as they
1191 /// may now have only one use and subject to other combines.
1192 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1193 if (!N->use_empty())
1196 SmallSetVector<SDNode *, 16> Nodes;
1199 N = Nodes.pop_back_val();
1203 if (N->use_empty()) {
1204 for (const SDValue &ChildN : N->op_values())
1205 Nodes.insert(ChildN.getNode());
1207 removeFromWorklist(N);
1212 } while (!Nodes.empty());
1216 //===----------------------------------------------------------------------===//
1217 // Main DAG Combiner implementation
1218 //===----------------------------------------------------------------------===//
1220 void DAGCombiner::Run(CombineLevel AtLevel) {
1221 // set the instance variables, so that the various visit routines may use it.
1223 LegalOperations = Level >= AfterLegalizeVectorOps;
1224 LegalTypes = Level >= AfterLegalizeTypes;
1226 // Add all the dag nodes to the worklist.
1227 for (SDNode &Node : DAG.allnodes())
1228 AddToWorklist(&Node);
1230 // Create a dummy node (which is not added to allnodes), that adds a reference
1231 // to the root node, preventing it from being deleted, and tracking any
1232 // changes of the root.
1233 HandleSDNode Dummy(DAG.getRoot());
1235 // while the worklist isn't empty, find a node and
1236 // try and combine it.
1237 while (!WorklistMap.empty()) {
1239 // The Worklist holds the SDNodes in order, but it may contain null entries.
1241 N = Worklist.pop_back_val();
1244 bool GoodWorklistEntry = WorklistMap.erase(N);
1245 (void)GoodWorklistEntry;
1246 assert(GoodWorklistEntry &&
1247 "Found a worklist entry without a corresponding map entry!");
1249 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1250 // N is deleted from the DAG, since they too may now be dead or may have a
1251 // reduced number of uses, allowing other xforms.
1252 if (recursivelyDeleteUnusedNodes(N))
1255 WorklistRemover DeadNodes(*this);
1257 // If this combine is running after legalizing the DAG, re-legalize any
1258 // nodes pulled off the worklist.
1259 if (Level == AfterLegalizeDAG) {
1260 SmallSetVector<SDNode *, 16> UpdatedNodes;
1261 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1263 for (SDNode *LN : UpdatedNodes) {
1265 AddUsersToWorklist(LN);
1271 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1273 // Add any operands of the new node which have not yet been combined to the
1274 // worklist as well. Because the worklist uniques things already, this
1275 // won't repeatedly process the same operand.
1276 CombinedNodes.insert(N);
1277 for (const SDValue &ChildN : N->op_values())
1278 if (!CombinedNodes.count(ChildN.getNode()))
1279 AddToWorklist(ChildN.getNode());
1281 SDValue RV = combine(N);
1288 // If we get back the same node we passed in, rather than a new node or
1289 // zero, we know that the node must have defined multiple values and
1290 // CombineTo was used. Since CombineTo takes care of the worklist
1291 // mechanics for us, we have no work to do in this case.
1292 if (RV.getNode() == N)
1295 assert(N->getOpcode() != ISD::DELETED_NODE &&
1296 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1297 "Node was deleted but visit returned new node!");
1299 DEBUG(dbgs() << " ... into: ";
1300 RV.getNode()->dump(&DAG));
1302 // Transfer debug value.
1303 DAG.TransferDbgValues(SDValue(N, 0), RV);
1304 if (N->getNumValues() == RV.getNode()->getNumValues())
1305 DAG.ReplaceAllUsesWith(N, RV.getNode());
1307 assert(N->getValueType(0) == RV.getValueType() &&
1308 N->getNumValues() == 1 && "Type mismatch");
1310 DAG.ReplaceAllUsesWith(N, &OpV);
1313 // Push the new node and any users onto the worklist
1314 AddToWorklist(RV.getNode());
1315 AddUsersToWorklist(RV.getNode());
1317 // Finally, if the node is now dead, remove it from the graph. The node
1318 // may not be dead if the replacement process recursively simplified to
1319 // something else needing this node. This will also take care of adding any
1320 // operands which have lost a user to the worklist.
1321 recursivelyDeleteUnusedNodes(N);
1324 // If the root changed (e.g. it was a dead load, update the root).
1325 DAG.setRoot(Dummy.getValue());
1326 DAG.RemoveDeadNodes();
1329 SDValue DAGCombiner::visit(SDNode *N) {
1330 switch (N->getOpcode()) {
1332 case ISD::TokenFactor: return visitTokenFactor(N);
1333 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1334 case ISD::ADD: return visitADD(N);
1335 case ISD::SUB: return visitSUB(N);
1336 case ISD::ADDC: return visitADDC(N);
1337 case ISD::SUBC: return visitSUBC(N);
1338 case ISD::ADDE: return visitADDE(N);
1339 case ISD::SUBE: return visitSUBE(N);
1340 case ISD::MUL: return visitMUL(N);
1341 case ISD::SDIV: return visitSDIV(N);
1342 case ISD::UDIV: return visitUDIV(N);
1343 case ISD::SREM: return visitSREM(N);
1344 case ISD::UREM: return visitUREM(N);
1345 case ISD::MULHU: return visitMULHU(N);
1346 case ISD::MULHS: return visitMULHS(N);
1347 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1348 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1349 case ISD::SMULO: return visitSMULO(N);
1350 case ISD::UMULO: return visitUMULO(N);
1351 case ISD::SDIVREM: return visitSDIVREM(N);
1352 case ISD::UDIVREM: return visitUDIVREM(N);
1356 case ISD::UMAX: return visitIMINMAX(N);
1357 case ISD::AND: return visitAND(N);
1358 case ISD::OR: return visitOR(N);
1359 case ISD::XOR: return visitXOR(N);
1360 case ISD::SHL: return visitSHL(N);
1361 case ISD::SRA: return visitSRA(N);
1362 case ISD::SRL: return visitSRL(N);
1364 case ISD::ROTL: return visitRotate(N);
1365 case ISD::BSWAP: return visitBSWAP(N);
1366 case ISD::CTLZ: return visitCTLZ(N);
1367 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1368 case ISD::CTTZ: return visitCTTZ(N);
1369 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1370 case ISD::CTPOP: return visitCTPOP(N);
1371 case ISD::SELECT: return visitSELECT(N);
1372 case ISD::VSELECT: return visitVSELECT(N);
1373 case ISD::SELECT_CC: return visitSELECT_CC(N);
1374 case ISD::SETCC: return visitSETCC(N);
1375 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1376 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1377 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1378 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1379 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1380 case ISD::TRUNCATE: return visitTRUNCATE(N);
1381 case ISD::BITCAST: return visitBITCAST(N);
1382 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1383 case ISD::FADD: return visitFADD(N);
1384 case ISD::FSUB: return visitFSUB(N);
1385 case ISD::FMUL: return visitFMUL(N);
1386 case ISD::FMA: return visitFMA(N);
1387 case ISD::FDIV: return visitFDIV(N);
1388 case ISD::FREM: return visitFREM(N);
1389 case ISD::FSQRT: return visitFSQRT(N);
1390 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1391 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1392 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1393 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1394 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1395 case ISD::FP_ROUND: return visitFP_ROUND(N);
1396 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1397 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1398 case ISD::FNEG: return visitFNEG(N);
1399 case ISD::FABS: return visitFABS(N);
1400 case ISD::FFLOOR: return visitFFLOOR(N);
1401 case ISD::FMINNUM: return visitFMINNUM(N);
1402 case ISD::FMAXNUM: return visitFMAXNUM(N);
1403 case ISD::FCEIL: return visitFCEIL(N);
1404 case ISD::FTRUNC: return visitFTRUNC(N);
1405 case ISD::BRCOND: return visitBRCOND(N);
1406 case ISD::BR_CC: return visitBR_CC(N);
1407 case ISD::LOAD: return visitLOAD(N);
1408 case ISD::STORE: return visitSTORE(N);
1409 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1410 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1411 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1412 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1413 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1414 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1415 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1416 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1417 case ISD::MGATHER: return visitMGATHER(N);
1418 case ISD::MLOAD: return visitMLOAD(N);
1419 case ISD::MSCATTER: return visitMSCATTER(N);
1420 case ISD::MSTORE: return visitMSTORE(N);
1421 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1422 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1427 SDValue DAGCombiner::combine(SDNode *N) {
1428 SDValue RV = visit(N);
1430 // If nothing happened, try a target-specific DAG combine.
1431 if (!RV.getNode()) {
1432 assert(N->getOpcode() != ISD::DELETED_NODE &&
1433 "Node was deleted but visit returned NULL!");
1435 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1436 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1438 // Expose the DAG combiner to the target combiner impls.
1439 TargetLowering::DAGCombinerInfo
1440 DagCombineInfo(DAG, Level, false, this);
1442 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1446 // If nothing happened still, try promoting the operation.
1447 if (!RV.getNode()) {
1448 switch (N->getOpcode()) {
1456 RV = PromoteIntBinOp(SDValue(N, 0));
1461 RV = PromoteIntShiftOp(SDValue(N, 0));
1463 case ISD::SIGN_EXTEND:
1464 case ISD::ZERO_EXTEND:
1465 case ISD::ANY_EXTEND:
1466 RV = PromoteExtend(SDValue(N, 0));
1469 if (PromoteLoad(SDValue(N, 0)))
1475 // If N is a commutative binary node, try commuting it to enable more
1477 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1478 N->getNumValues() == 1) {
1479 SDValue N0 = N->getOperand(0);
1480 SDValue N1 = N->getOperand(1);
1482 // Constant operands are canonicalized to RHS.
1483 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1484 SDValue Ops[] = {N1, N0};
1486 if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1487 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1490 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1493 return SDValue(CSENode, 0);
1500 /// Given a node, return its input chain if it has one, otherwise return a null
1502 static SDValue getInputChainForNode(SDNode *N) {
1503 if (unsigned NumOps = N->getNumOperands()) {
1504 if (N->getOperand(0).getValueType() == MVT::Other)
1505 return N->getOperand(0);
1506 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1507 return N->getOperand(NumOps-1);
1508 for (unsigned i = 1; i < NumOps-1; ++i)
1509 if (N->getOperand(i).getValueType() == MVT::Other)
1510 return N->getOperand(i);
1515 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1516 // If N has two operands, where one has an input chain equal to the other,
1517 // the 'other' chain is redundant.
1518 if (N->getNumOperands() == 2) {
1519 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1520 return N->getOperand(0);
1521 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1522 return N->getOperand(1);
1525 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1526 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1527 SmallPtrSet<SDNode*, 16> SeenOps;
1528 bool Changed = false; // If we should replace this token factor.
1530 // Start out with this token factor.
1533 // Iterate through token factors. The TFs grows when new token factors are
1535 for (unsigned i = 0; i < TFs.size(); ++i) {
1536 SDNode *TF = TFs[i];
1538 // Check each of the operands.
1539 for (const SDValue &Op : TF->op_values()) {
1541 switch (Op.getOpcode()) {
1542 case ISD::EntryToken:
1543 // Entry tokens don't need to be added to the list. They are
1548 case ISD::TokenFactor:
1549 if (Op.hasOneUse() &&
1550 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1551 // Queue up for processing.
1552 TFs.push_back(Op.getNode());
1553 // Clean up in case the token factor is removed.
1554 AddToWorklist(Op.getNode());
1561 // Only add if it isn't already in the list.
1562 if (SeenOps.insert(Op.getNode()).second)
1573 // If we've changed things around then replace token factor.
1576 // The entry token is the only possible outcome.
1577 Result = DAG.getEntryNode();
1579 // New and improved token factor.
1580 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1583 // Add users to worklist if AA is enabled, since it may introduce
1584 // a lot of new chained token factors while removing memory deps.
1585 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1586 : DAG.getSubtarget().useAA();
1587 return CombineTo(N, Result, UseAA /*add to worklist*/);
1593 /// MERGE_VALUES can always be eliminated.
1594 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1595 WorklistRemover DeadNodes(*this);
1596 // Replacing results may cause a different MERGE_VALUES to suddenly
1597 // be CSE'd with N, and carry its uses with it. Iterate until no
1598 // uses remain, to ensure that the node can be safely deleted.
1599 // First add the users of this node to the work list so that they
1600 // can be tried again once they have new operands.
1601 AddUsersToWorklist(N);
1603 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1604 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1605 } while (!N->use_empty());
1606 deleteAndRecombine(N);
1607 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1610 static bool isNullConstant(SDValue V) {
1611 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1612 return Const != nullptr && Const->isNullValue();
1615 static bool isNullFPConstant(SDValue V) {
1616 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1617 return Const != nullptr && Const->isZero() && !Const->isNegative();
1620 static bool isAllOnesConstant(SDValue V) {
1621 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1622 return Const != nullptr && Const->isAllOnesValue();
1625 static bool isOneConstant(SDValue V) {
1626 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1627 return Const != nullptr && Const->isOne();
1630 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1631 /// ContantSDNode pointer else nullptr.
1632 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1633 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1634 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1637 SDValue DAGCombiner::visitADD(SDNode *N) {
1638 SDValue N0 = N->getOperand(0);
1639 SDValue N1 = N->getOperand(1);
1640 EVT VT = N0.getValueType();
1643 if (VT.isVector()) {
1644 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1647 // fold (add x, 0) -> x, vector edition
1648 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1650 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1654 // fold (add x, undef) -> undef
1655 if (N0.getOpcode() == ISD::UNDEF)
1657 if (N1.getOpcode() == ISD::UNDEF)
1659 // fold (add c1, c2) -> c1+c2
1660 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1661 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1663 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1664 // canonicalize constant to RHS
1665 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1666 !isConstantIntBuildVectorOrConstantInt(N1))
1667 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1668 // fold (add x, 0) -> x
1669 if (isNullConstant(N1))
1671 // fold (add Sym, c) -> Sym+c
1672 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1673 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1674 GA->getOpcode() == ISD::GlobalAddress)
1675 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1677 (uint64_t)N1C->getSExtValue());
1678 // fold ((c1-A)+c2) -> (c1+c2)-A
1679 if (N1C && N0.getOpcode() == ISD::SUB)
1680 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1682 return DAG.getNode(ISD::SUB, DL, VT,
1683 DAG.getConstant(N1C->getAPIntValue()+
1684 N0C->getAPIntValue(), DL, VT),
1688 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1690 // fold ((0-A) + B) -> B-A
1691 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1692 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1693 // fold (A + (0-B)) -> A-B
1694 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1695 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1696 // fold (A+(B-A)) -> B
1697 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1698 return N1.getOperand(0);
1699 // fold ((B-A)+A) -> B
1700 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1701 return N0.getOperand(0);
1702 // fold (A+(B-(A+C))) to (B-C)
1703 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1704 N0 == N1.getOperand(1).getOperand(0))
1705 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1706 N1.getOperand(1).getOperand(1));
1707 // fold (A+(B-(C+A))) to (B-C)
1708 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1709 N0 == N1.getOperand(1).getOperand(1))
1710 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1711 N1.getOperand(1).getOperand(0));
1712 // fold (A+((B-A)+or-C)) to (B+or-C)
1713 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1714 N1.getOperand(0).getOpcode() == ISD::SUB &&
1715 N0 == N1.getOperand(0).getOperand(1))
1716 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1717 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1719 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1720 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1721 SDValue N00 = N0.getOperand(0);
1722 SDValue N01 = N0.getOperand(1);
1723 SDValue N10 = N1.getOperand(0);
1724 SDValue N11 = N1.getOperand(1);
1726 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1727 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1728 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1729 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1732 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1733 return SDValue(N, 0);
1735 // fold (a+b) -> (a|b) iff a and b share no bits.
1736 if (VT.isInteger() && !VT.isVector()) {
1737 APInt LHSZero, LHSOne;
1738 APInt RHSZero, RHSOne;
1739 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1741 if (LHSZero.getBoolValue()) {
1742 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1744 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1745 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1746 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1747 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1748 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1753 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1754 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1755 isNullConstant(N1.getOperand(0).getOperand(0)))
1756 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1757 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1758 N1.getOperand(0).getOperand(1),
1760 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1761 isNullConstant(N0.getOperand(0).getOperand(0)))
1762 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1763 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1764 N0.getOperand(0).getOperand(1),
1767 if (N1.getOpcode() == ISD::AND) {
1768 SDValue AndOp0 = N1.getOperand(0);
1769 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1770 unsigned DestBits = VT.getScalarType().getSizeInBits();
1772 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1773 // and similar xforms where the inner op is either ~0 or 0.
1774 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1776 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1780 // add (sext i1), X -> sub X, (zext i1)
1781 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1782 N0.getOperand(0).getValueType() == MVT::i1 &&
1783 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1785 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1786 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1789 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1790 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1791 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1792 if (TN->getVT() == MVT::i1) {
1794 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1795 DAG.getConstant(1, DL, VT));
1796 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1803 SDValue DAGCombiner::visitADDC(SDNode *N) {
1804 SDValue N0 = N->getOperand(0);
1805 SDValue N1 = N->getOperand(1);
1806 EVT VT = N0.getValueType();
1808 // If the flag result is dead, turn this into an ADD.
1809 if (!N->hasAnyUseOfValue(1))
1810 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1811 DAG.getNode(ISD::CARRY_FALSE,
1812 SDLoc(N), MVT::Glue));
1814 // canonicalize constant to RHS.
1815 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1816 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1818 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1820 // fold (addc x, 0) -> x + no carry out
1821 if (isNullConstant(N1))
1822 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1823 SDLoc(N), MVT::Glue));
1825 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1826 APInt LHSZero, LHSOne;
1827 APInt RHSZero, RHSOne;
1828 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1830 if (LHSZero.getBoolValue()) {
1831 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1833 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1834 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1835 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1836 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1837 DAG.getNode(ISD::CARRY_FALSE,
1838 SDLoc(N), MVT::Glue));
1844 SDValue DAGCombiner::visitADDE(SDNode *N) {
1845 SDValue N0 = N->getOperand(0);
1846 SDValue N1 = N->getOperand(1);
1847 SDValue CarryIn = N->getOperand(2);
1849 // canonicalize constant to RHS
1850 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1851 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1853 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1856 // fold (adde x, y, false) -> (addc x, y)
1857 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1858 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1863 // Since it may not be valid to emit a fold to zero for vector initializers
1864 // check if we can before folding.
1865 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1867 bool LegalOperations, bool LegalTypes) {
1869 return DAG.getConstant(0, DL, VT);
1870 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1871 return DAG.getConstant(0, DL, VT);
1875 SDValue DAGCombiner::visitSUB(SDNode *N) {
1876 SDValue N0 = N->getOperand(0);
1877 SDValue N1 = N->getOperand(1);
1878 EVT VT = N0.getValueType();
1881 if (VT.isVector()) {
1882 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1885 // fold (sub x, 0) -> x, vector edition
1886 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1890 // fold (sub x, x) -> 0
1891 // FIXME: Refactor this and xor and other similar operations together.
1893 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1894 // fold (sub c1, c2) -> c1-c2
1895 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1896 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1898 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1899 // fold (sub x, c) -> (add x, -c)
1902 return DAG.getNode(ISD::ADD, DL, VT, N0,
1903 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1905 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1906 if (isAllOnesConstant(N0))
1907 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1908 // fold A-(A-B) -> B
1909 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1910 return N1.getOperand(1);
1911 // fold (A+B)-A -> B
1912 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1913 return N0.getOperand(1);
1914 // fold (A+B)-B -> A
1915 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1916 return N0.getOperand(0);
1917 // fold C2-(A+C1) -> (C2-C1)-A
1918 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1919 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1920 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1922 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1924 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1927 // fold ((A+(B+or-C))-B) -> A+or-C
1928 if (N0.getOpcode() == ISD::ADD &&
1929 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1930 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1931 N0.getOperand(1).getOperand(0) == N1)
1932 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1933 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1934 // fold ((A+(C+B))-B) -> A+C
1935 if (N0.getOpcode() == ISD::ADD &&
1936 N0.getOperand(1).getOpcode() == ISD::ADD &&
1937 N0.getOperand(1).getOperand(1) == N1)
1938 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1939 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1940 // fold ((A-(B-C))-C) -> A-B
1941 if (N0.getOpcode() == ISD::SUB &&
1942 N0.getOperand(1).getOpcode() == ISD::SUB &&
1943 N0.getOperand(1).getOperand(1) == N1)
1944 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1945 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1947 // If either operand of a sub is undef, the result is undef
1948 if (N0.getOpcode() == ISD::UNDEF)
1950 if (N1.getOpcode() == ISD::UNDEF)
1953 // If the relocation model supports it, consider symbol offsets.
1954 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1955 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1956 // fold (sub Sym, c) -> Sym-c
1957 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1958 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1960 (uint64_t)N1C->getSExtValue());
1961 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1962 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1963 if (GA->getGlobal() == GB->getGlobal())
1964 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1968 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1969 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1970 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1971 if (TN->getVT() == MVT::i1) {
1973 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1974 DAG.getConstant(1, DL, VT));
1975 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1982 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1983 SDValue N0 = N->getOperand(0);
1984 SDValue N1 = N->getOperand(1);
1985 EVT VT = N0.getValueType();
1987 // If the flag result is dead, turn this into an SUB.
1988 if (!N->hasAnyUseOfValue(1))
1989 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1990 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1993 // fold (subc x, x) -> 0 + no borrow
1996 return CombineTo(N, DAG.getConstant(0, DL, VT),
1997 DAG.getNode(ISD::CARRY_FALSE, DL,
2001 // fold (subc x, 0) -> x + no borrow
2002 if (isNullConstant(N1))
2003 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2006 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2007 if (isAllOnesConstant(N0))
2008 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2009 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2015 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2016 SDValue N0 = N->getOperand(0);
2017 SDValue N1 = N->getOperand(1);
2018 SDValue CarryIn = N->getOperand(2);
2020 // fold (sube x, y, false) -> (subc x, y)
2021 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2022 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2027 SDValue DAGCombiner::visitMUL(SDNode *N) {
2028 SDValue N0 = N->getOperand(0);
2029 SDValue N1 = N->getOperand(1);
2030 EVT VT = N0.getValueType();
2032 // fold (mul x, undef) -> 0
2033 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2034 return DAG.getConstant(0, SDLoc(N), VT);
2036 bool N0IsConst = false;
2037 bool N1IsConst = false;
2038 bool N1IsOpaqueConst = false;
2039 bool N0IsOpaqueConst = false;
2040 APInt ConstValue0, ConstValue1;
2042 if (VT.isVector()) {
2043 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2046 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2047 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2049 N0IsConst = isa<ConstantSDNode>(N0);
2051 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2052 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2054 N1IsConst = isa<ConstantSDNode>(N1);
2056 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2057 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2061 // fold (mul c1, c2) -> c1*c2
2062 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2063 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2064 N0.getNode(), N1.getNode());
2066 // canonicalize constant to RHS (vector doesn't have to splat)
2067 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2068 !isConstantIntBuildVectorOrConstantInt(N1))
2069 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2070 // fold (mul x, 0) -> 0
2071 if (N1IsConst && ConstValue1 == 0)
2073 // We require a splat of the entire scalar bit width for non-contiguous
2076 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2077 // fold (mul x, 1) -> x
2078 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2080 // fold (mul x, -1) -> 0-x
2081 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2083 return DAG.getNode(ISD::SUB, DL, VT,
2084 DAG.getConstant(0, DL, VT), N0);
2086 // fold (mul x, (1 << c)) -> x << c
2087 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2090 return DAG.getNode(ISD::SHL, DL, VT, N0,
2091 DAG.getConstant(ConstValue1.logBase2(), DL,
2092 getShiftAmountTy(N0.getValueType())));
2094 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2095 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2097 unsigned Log2Val = (-ConstValue1).logBase2();
2099 // FIXME: If the input is something that is easily negated (e.g. a
2100 // single-use add), we should put the negate there.
2101 return DAG.getNode(ISD::SUB, DL, VT,
2102 DAG.getConstant(0, DL, VT),
2103 DAG.getNode(ISD::SHL, DL, VT, N0,
2104 DAG.getConstant(Log2Val, DL,
2105 getShiftAmountTy(N0.getValueType()))));
2109 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2110 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2111 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2112 isa<ConstantSDNode>(N0.getOperand(1)))) {
2113 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2114 N1, N0.getOperand(1));
2115 AddToWorklist(C3.getNode());
2116 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2117 N0.getOperand(0), C3);
2120 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2123 SDValue Sh(nullptr,0), Y(nullptr,0);
2124 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2125 if (N0.getOpcode() == ISD::SHL &&
2126 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2127 isa<ConstantSDNode>(N0.getOperand(1))) &&
2128 N0.getNode()->hasOneUse()) {
2130 } else if (N1.getOpcode() == ISD::SHL &&
2131 isa<ConstantSDNode>(N1.getOperand(1)) &&
2132 N1.getNode()->hasOneUse()) {
2137 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2138 Sh.getOperand(0), Y);
2139 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2140 Mul, Sh.getOperand(1));
2144 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2145 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2146 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2147 isa<ConstantSDNode>(N0.getOperand(1))))
2148 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2149 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2150 N0.getOperand(0), N1),
2151 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2152 N0.getOperand(1), N1));
2155 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2161 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2162 SDValue N0 = N->getOperand(0);
2163 SDValue N1 = N->getOperand(1);
2164 EVT VT = N->getValueType(0);
2168 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2171 // fold (sdiv c1, c2) -> c1/c2
2172 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2173 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2174 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2175 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2176 // fold (sdiv X, 1) -> X
2177 if (N1C && N1C->isOne())
2179 // fold (sdiv X, -1) -> 0-X
2180 if (N1C && N1C->isAllOnesValue()) {
2182 return DAG.getNode(ISD::SUB, DL, VT,
2183 DAG.getConstant(0, DL, VT), N0);
2185 // If we know the sign bits of both operands are zero, strength reduce to a
2186 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2187 if (!VT.isVector()) {
2188 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2189 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2193 // fold (sdiv X, pow2) -> simple ops after legalize
2194 // FIXME: We check for the exact bit here because the generic lowering gives
2195 // better results in that case. The target-specific lowering should learn how
2196 // to handle exact sdivs efficiently.
2197 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2198 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2199 (N1C->getAPIntValue().isPowerOf2() ||
2200 (-N1C->getAPIntValue()).isPowerOf2())) {
2201 // Target-specific implementation of sdiv x, pow2.
2202 if (SDValue Res = BuildSDIVPow2(N))
2205 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2208 // Splat the sign bit into the register
2210 DAG.getNode(ISD::SRA, DL, VT, N0,
2211 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2212 getShiftAmountTy(N0.getValueType())));
2213 AddToWorklist(SGN.getNode());
2215 // Add (N0 < 0) ? abs2 - 1 : 0;
2217 DAG.getNode(ISD::SRL, DL, VT, SGN,
2218 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2219 getShiftAmountTy(SGN.getValueType())));
2220 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2221 AddToWorklist(SRL.getNode());
2222 AddToWorklist(ADD.getNode()); // Divide by pow2
2223 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2224 DAG.getConstant(lg2, DL,
2225 getShiftAmountTy(ADD.getValueType())));
2227 // If we're dividing by a positive value, we're done. Otherwise, we must
2228 // negate the result.
2229 if (N1C->getAPIntValue().isNonNegative())
2232 AddToWorklist(SRA.getNode());
2233 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2236 // If integer divide is expensive and we satisfy the requirements, emit an
2237 // alternate sequence. Targets may check function attributes for size/speed
2239 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2240 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2241 if (SDValue Op = BuildSDIV(N))
2245 if (N0.getOpcode() == ISD::UNDEF)
2246 return DAG.getConstant(0, SDLoc(N), VT);
2247 // X / undef -> undef
2248 if (N1.getOpcode() == ISD::UNDEF)
2254 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2255 SDValue N0 = N->getOperand(0);
2256 SDValue N1 = N->getOperand(1);
2257 EVT VT = N->getValueType(0);
2261 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2264 // fold (udiv c1, c2) -> c1/c2
2265 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2266 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2268 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2271 // fold (udiv x, (1 << c)) -> x >>u c
2272 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2274 return DAG.getNode(ISD::SRL, DL, VT, N0,
2275 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2276 getShiftAmountTy(N0.getValueType())));
2278 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2279 if (N1.getOpcode() == ISD::SHL) {
2280 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2281 if (SHC->getAPIntValue().isPowerOf2()) {
2282 EVT ADDVT = N1.getOperand(1).getValueType();
2284 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2286 DAG.getConstant(SHC->getAPIntValue()
2289 AddToWorklist(Add.getNode());
2290 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2295 // fold (udiv x, c) -> alternate
2296 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2297 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2298 if (SDValue Op = BuildUDIV(N))
2302 if (N0.getOpcode() == ISD::UNDEF)
2303 return DAG.getConstant(0, SDLoc(N), VT);
2304 // X / undef -> undef
2305 if (N1.getOpcode() == ISD::UNDEF)
2311 SDValue DAGCombiner::visitSREM(SDNode *N) {
2312 SDValue N0 = N->getOperand(0);
2313 SDValue N1 = N->getOperand(1);
2314 EVT VT = N->getValueType(0);
2316 // fold (srem c1, c2) -> c1%c2
2317 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2318 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2320 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2323 // If we know the sign bits of both operands are zero, strength reduce to a
2324 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2325 if (!VT.isVector()) {
2326 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2327 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2330 // If X/C can be simplified by the division-by-constant logic, lower
2331 // X%C to the equivalent of X-X/C*C.
2332 if (N1C && !N1C->isNullValue()) {
2333 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2334 AddToWorklist(Div.getNode());
2335 SDValue OptimizedDiv = combine(Div.getNode());
2336 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2337 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2339 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2340 AddToWorklist(Mul.getNode());
2346 if (N0.getOpcode() == ISD::UNDEF)
2347 return DAG.getConstant(0, SDLoc(N), VT);
2348 // X % undef -> undef
2349 if (N1.getOpcode() == ISD::UNDEF)
2355 SDValue DAGCombiner::visitUREM(SDNode *N) {
2356 SDValue N0 = N->getOperand(0);
2357 SDValue N1 = N->getOperand(1);
2358 EVT VT = N->getValueType(0);
2360 // fold (urem c1, c2) -> c1%c2
2361 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2362 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2364 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2367 // fold (urem x, pow2) -> (and x, pow2-1)
2368 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2369 N1C->getAPIntValue().isPowerOf2()) {
2371 return DAG.getNode(ISD::AND, DL, VT, N0,
2372 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2374 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2375 if (N1.getOpcode() == ISD::SHL) {
2376 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2377 if (SHC->getAPIntValue().isPowerOf2()) {
2380 DAG.getNode(ISD::ADD, DL, VT, N1,
2381 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2383 AddToWorklist(Add.getNode());
2384 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2389 // If X/C can be simplified by the division-by-constant logic, lower
2390 // X%C to the equivalent of X-X/C*C.
2391 if (N1C && !N1C->isNullValue()) {
2392 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2393 AddToWorklist(Div.getNode());
2394 SDValue OptimizedDiv = combine(Div.getNode());
2395 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2396 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2398 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2399 AddToWorklist(Mul.getNode());
2405 if (N0.getOpcode() == ISD::UNDEF)
2406 return DAG.getConstant(0, SDLoc(N), VT);
2407 // X % undef -> undef
2408 if (N1.getOpcode() == ISD::UNDEF)
2414 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2415 SDValue N0 = N->getOperand(0);
2416 SDValue N1 = N->getOperand(1);
2417 EVT VT = N->getValueType(0);
2420 // fold (mulhs x, 0) -> 0
2421 if (isNullConstant(N1))
2423 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2424 if (isOneConstant(N1)) {
2426 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2427 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2429 getShiftAmountTy(N0.getValueType())));
2431 // fold (mulhs x, undef) -> 0
2432 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2433 return DAG.getConstant(0, SDLoc(N), VT);
2435 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2437 if (VT.isSimple() && !VT.isVector()) {
2438 MVT Simple = VT.getSimpleVT();
2439 unsigned SimpleSize = Simple.getSizeInBits();
2440 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2441 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2442 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2443 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2444 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2445 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2446 DAG.getConstant(SimpleSize, DL,
2447 getShiftAmountTy(N1.getValueType())));
2448 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2455 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2456 SDValue N0 = N->getOperand(0);
2457 SDValue N1 = N->getOperand(1);
2458 EVT VT = N->getValueType(0);
2461 // fold (mulhu x, 0) -> 0
2462 if (isNullConstant(N1))
2464 // fold (mulhu x, 1) -> 0
2465 if (isOneConstant(N1))
2466 return DAG.getConstant(0, DL, N0.getValueType());
2467 // fold (mulhu x, undef) -> 0
2468 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2469 return DAG.getConstant(0, DL, VT);
2471 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2473 if (VT.isSimple() && !VT.isVector()) {
2474 MVT Simple = VT.getSimpleVT();
2475 unsigned SimpleSize = Simple.getSizeInBits();
2476 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2477 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2478 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2479 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2480 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2481 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2482 DAG.getConstant(SimpleSize, DL,
2483 getShiftAmountTy(N1.getValueType())));
2484 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2491 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2492 /// give the opcodes for the two computations that are being performed. Return
2493 /// true if a simplification was made.
2494 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2496 // If the high half is not needed, just compute the low half.
2497 bool HiExists = N->hasAnyUseOfValue(1);
2499 (!LegalOperations ||
2500 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2501 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2502 return CombineTo(N, Res, Res);
2505 // If the low half is not needed, just compute the high half.
2506 bool LoExists = N->hasAnyUseOfValue(0);
2508 (!LegalOperations ||
2509 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2510 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2511 return CombineTo(N, Res, Res);
2514 // If both halves are used, return as it is.
2515 if (LoExists && HiExists)
2518 // If the two computed results can be simplified separately, separate them.
2520 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2521 AddToWorklist(Lo.getNode());
2522 SDValue LoOpt = combine(Lo.getNode());
2523 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2524 (!LegalOperations ||
2525 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2526 return CombineTo(N, LoOpt, LoOpt);
2530 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2531 AddToWorklist(Hi.getNode());
2532 SDValue HiOpt = combine(Hi.getNode());
2533 if (HiOpt.getNode() && HiOpt != Hi &&
2534 (!LegalOperations ||
2535 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2536 return CombineTo(N, HiOpt, HiOpt);
2542 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2543 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2546 EVT VT = N->getValueType(0);
2549 // If the type is twice as wide is legal, transform the mulhu to a wider
2550 // multiply plus a shift.
2551 if (VT.isSimple() && !VT.isVector()) {
2552 MVT Simple = VT.getSimpleVT();
2553 unsigned SimpleSize = Simple.getSizeInBits();
2554 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2555 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2556 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2557 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2558 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2559 // Compute the high part as N1.
2560 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2561 DAG.getConstant(SimpleSize, DL,
2562 getShiftAmountTy(Lo.getValueType())));
2563 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2564 // Compute the low part as N0.
2565 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2566 return CombineTo(N, Lo, Hi);
2573 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2574 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2577 EVT VT = N->getValueType(0);
2580 // If the type is twice as wide is legal, transform the mulhu to a wider
2581 // multiply plus a shift.
2582 if (VT.isSimple() && !VT.isVector()) {
2583 MVT Simple = VT.getSimpleVT();
2584 unsigned SimpleSize = Simple.getSizeInBits();
2585 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2586 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2587 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2588 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2589 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2590 // Compute the high part as N1.
2591 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2592 DAG.getConstant(SimpleSize, DL,
2593 getShiftAmountTy(Lo.getValueType())));
2594 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2595 // Compute the low part as N0.
2596 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2597 return CombineTo(N, Lo, Hi);
2604 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2605 // (smulo x, 2) -> (saddo x, x)
2606 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2607 if (C2->getAPIntValue() == 2)
2608 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2609 N->getOperand(0), N->getOperand(0));
2614 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2615 // (umulo x, 2) -> (uaddo x, x)
2616 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2617 if (C2->getAPIntValue() == 2)
2618 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2619 N->getOperand(0), N->getOperand(0));
2624 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2625 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2631 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2632 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2638 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2639 SDValue N0 = N->getOperand(0);
2640 SDValue N1 = N->getOperand(1);
2641 EVT VT = N0.getValueType();
2645 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2648 // fold (add c1, c2) -> c1+c2
2649 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2650 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2652 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2654 // canonicalize constant to RHS
2655 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2656 !isConstantIntBuildVectorOrConstantInt(N1))
2657 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2662 /// If this is a binary operator with two operands of the same opcode, try to
2664 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2665 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2666 EVT VT = N0.getValueType();
2667 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2669 // Bail early if none of these transforms apply.
2670 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2672 // For each of OP in AND/OR/XOR:
2673 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2674 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2675 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2676 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2677 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2679 // do not sink logical op inside of a vector extend, since it may combine
2681 EVT Op0VT = N0.getOperand(0).getValueType();
2682 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2683 N0.getOpcode() == ISD::SIGN_EXTEND ||
2684 N0.getOpcode() == ISD::BSWAP ||
2685 // Avoid infinite looping with PromoteIntBinOp.
2686 (N0.getOpcode() == ISD::ANY_EXTEND &&
2687 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2688 (N0.getOpcode() == ISD::TRUNCATE &&
2689 (!TLI.isZExtFree(VT, Op0VT) ||
2690 !TLI.isTruncateFree(Op0VT, VT)) &&
2691 TLI.isTypeLegal(Op0VT))) &&
2693 Op0VT == N1.getOperand(0).getValueType() &&
2694 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2695 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2696 N0.getOperand(0).getValueType(),
2697 N0.getOperand(0), N1.getOperand(0));
2698 AddToWorklist(ORNode.getNode());
2699 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2702 // For each of OP in SHL/SRL/SRA/AND...
2703 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2704 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2705 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2706 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2707 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2708 N0.getOperand(1) == N1.getOperand(1)) {
2709 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2710 N0.getOperand(0).getValueType(),
2711 N0.getOperand(0), N1.getOperand(0));
2712 AddToWorklist(ORNode.getNode());
2713 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2714 ORNode, N0.getOperand(1));
2717 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2718 // Only perform this optimization after type legalization and before
2719 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2720 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2721 // we don't want to undo this promotion.
2722 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2724 if ((N0.getOpcode() == ISD::BITCAST ||
2725 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2726 Level == AfterLegalizeTypes) {
2727 SDValue In0 = N0.getOperand(0);
2728 SDValue In1 = N1.getOperand(0);
2729 EVT In0Ty = In0.getValueType();
2730 EVT In1Ty = In1.getValueType();
2732 // If both incoming values are integers, and the original types are the
2734 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2735 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2736 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2737 AddToWorklist(Op.getNode());
2742 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2743 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2744 // If both shuffles use the same mask, and both shuffle within a single
2745 // vector, then it is worthwhile to move the swizzle after the operation.
2746 // The type-legalizer generates this pattern when loading illegal
2747 // vector types from memory. In many cases this allows additional shuffle
2749 // There are other cases where moving the shuffle after the xor/and/or
2750 // is profitable even if shuffles don't perform a swizzle.
2751 // If both shuffles use the same mask, and both shuffles have the same first
2752 // or second operand, then it might still be profitable to move the shuffle
2753 // after the xor/and/or operation.
2754 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2755 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2756 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2758 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2759 "Inputs to shuffles are not the same type");
2761 // Check that both shuffles use the same mask. The masks are known to be of
2762 // the same length because the result vector type is the same.
2763 // Check also that shuffles have only one use to avoid introducing extra
2765 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2766 SVN0->getMask().equals(SVN1->getMask())) {
2767 SDValue ShOp = N0->getOperand(1);
2769 // Don't try to fold this node if it requires introducing a
2770 // build vector of all zeros that might be illegal at this stage.
2771 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2773 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2778 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2779 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2780 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2781 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2782 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2783 N0->getOperand(0), N1->getOperand(0));
2784 AddToWorklist(NewNode.getNode());
2785 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2786 &SVN0->getMask()[0]);
2789 // Don't try to fold this node if it requires introducing a
2790 // build vector of all zeros that might be illegal at this stage.
2791 ShOp = N0->getOperand(0);
2792 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2794 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2799 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2800 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2801 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2802 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2803 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2804 N0->getOperand(1), N1->getOperand(1));
2805 AddToWorklist(NewNode.getNode());
2806 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2807 &SVN0->getMask()[0]);
2815 /// This contains all DAGCombine rules which reduce two values combined by
2816 /// an And operation to a single value. This makes them reusable in the context
2817 /// of visitSELECT(). Rules involving constants are not included as
2818 /// visitSELECT() already handles those cases.
2819 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2820 SDNode *LocReference) {
2821 EVT VT = N1.getValueType();
2823 // fold (and x, undef) -> 0
2824 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2825 return DAG.getConstant(0, SDLoc(LocReference), VT);
2826 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2827 SDValue LL, LR, RL, RR, CC0, CC1;
2828 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2829 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2830 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2832 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2833 LL.getValueType().isInteger()) {
2834 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2835 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2836 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2837 LR.getValueType(), LL, RL);
2838 AddToWorklist(ORNode.getNode());
2839 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2841 if (isAllOnesConstant(LR)) {
2842 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2843 if (Op1 == ISD::SETEQ) {
2844 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2845 LR.getValueType(), LL, RL);
2846 AddToWorklist(ANDNode.getNode());
2847 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2849 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2850 if (Op1 == ISD::SETGT) {
2851 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2852 LR.getValueType(), LL, RL);
2853 AddToWorklist(ORNode.getNode());
2854 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2858 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2859 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2860 Op0 == Op1 && LL.getValueType().isInteger() &&
2861 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2862 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2864 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2865 LL, DAG.getConstant(1, DL,
2866 LL.getValueType()));
2867 AddToWorklist(ADDNode.getNode());
2868 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2869 DAG.getConstant(2, DL, LL.getValueType()),
2872 // canonicalize equivalent to ll == rl
2873 if (LL == RR && LR == RL) {
2874 Op1 = ISD::getSetCCSwappedOperands(Op1);
2877 if (LL == RL && LR == RR) {
2878 bool isInteger = LL.getValueType().isInteger();
2879 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2880 if (Result != ISD::SETCC_INVALID &&
2881 (!LegalOperations ||
2882 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2883 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2884 EVT CCVT = getSetCCResultType(LL.getValueType());
2885 if (N0.getValueType() == CCVT ||
2886 (!LegalOperations && N0.getValueType() == MVT::i1))
2887 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2893 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2894 VT.getSizeInBits() <= 64) {
2895 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2896 APInt ADDC = ADDI->getAPIntValue();
2897 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2898 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2899 // immediate for an add, but it is legal if its top c2 bits are set,
2900 // transform the ADD so the immediate doesn't need to be materialized
2902 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2903 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2904 SRLI->getZExtValue());
2905 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2907 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2910 DAG.getNode(ISD::ADD, DL, VT,
2911 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2912 CombineTo(N0.getNode(), NewAdd);
2913 // Return N so it doesn't get rechecked!
2914 return SDValue(LocReference, 0);
2925 SDValue DAGCombiner::visitAND(SDNode *N) {
2926 SDValue N0 = N->getOperand(0);
2927 SDValue N1 = N->getOperand(1);
2928 EVT VT = N1.getValueType();
2931 if (VT.isVector()) {
2932 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2935 // fold (and x, 0) -> 0, vector edition
2936 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2937 // do not return N0, because undef node may exist in N0
2938 return DAG.getConstant(
2939 APInt::getNullValue(
2940 N0.getValueType().getScalarType().getSizeInBits()),
2941 SDLoc(N), N0.getValueType());
2942 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2943 // do not return N1, because undef node may exist in N1
2944 return DAG.getConstant(
2945 APInt::getNullValue(
2946 N1.getValueType().getScalarType().getSizeInBits()),
2947 SDLoc(N), N1.getValueType());
2949 // fold (and x, -1) -> x, vector edition
2950 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2952 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2956 // fold (and c1, c2) -> c1&c2
2957 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2958 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2959 if (N0C && N1C && !N1C->isOpaque())
2960 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2961 // canonicalize constant to RHS
2962 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2963 !isConstantIntBuildVectorOrConstantInt(N1))
2964 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2965 // fold (and x, -1) -> x
2966 if (isAllOnesConstant(N1))
2968 // if (and x, c) is known to be zero, return 0
2969 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2970 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2971 APInt::getAllOnesValue(BitWidth)))
2972 return DAG.getConstant(0, SDLoc(N), VT);
2974 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2976 // fold (and (or x, C), D) -> D if (C & D) == D
2977 if (N1C && N0.getOpcode() == ISD::OR)
2978 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2979 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2981 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2982 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2983 SDValue N0Op0 = N0.getOperand(0);
2984 APInt Mask = ~N1C->getAPIntValue();
2985 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2986 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2987 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2988 N0.getValueType(), N0Op0);
2990 // Replace uses of the AND with uses of the Zero extend node.
2993 // We actually want to replace all uses of the any_extend with the
2994 // zero_extend, to avoid duplicating things. This will later cause this
2995 // AND to be folded.
2996 CombineTo(N0.getNode(), Zext);
2997 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3000 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3001 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3002 // already be zero by virtue of the width of the base type of the load.
3004 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3006 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3007 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3008 N0.getOpcode() == ISD::LOAD) {
3009 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3010 N0 : N0.getOperand(0) );
3012 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3013 // This can be a pure constant or a vector splat, in which case we treat the
3014 // vector as a scalar and use the splat value.
3015 APInt Constant = APInt::getNullValue(1);
3016 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3017 Constant = C->getAPIntValue();
3018 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3019 APInt SplatValue, SplatUndef;
3020 unsigned SplatBitSize;
3022 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3023 SplatBitSize, HasAnyUndefs);
3025 // Undef bits can contribute to a possible optimisation if set, so
3027 SplatValue |= SplatUndef;
3029 // The splat value may be something like "0x00FFFFFF", which means 0 for
3030 // the first vector value and FF for the rest, repeating. We need a mask
3031 // that will apply equally to all members of the vector, so AND all the
3032 // lanes of the constant together.
3033 EVT VT = Vector->getValueType(0);
3034 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3036 // If the splat value has been compressed to a bitlength lower
3037 // than the size of the vector lane, we need to re-expand it to
3039 if (BitWidth > SplatBitSize)
3040 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3041 SplatBitSize < BitWidth;
3042 SplatBitSize = SplatBitSize * 2)
3043 SplatValue |= SplatValue.shl(SplatBitSize);
3045 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3046 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3047 if (SplatBitSize % BitWidth == 0) {
3048 Constant = APInt::getAllOnesValue(BitWidth);
3049 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3050 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3055 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3056 // actually legal and isn't going to get expanded, else this is a false
3058 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3059 Load->getValueType(0),
3060 Load->getMemoryVT());
3062 // Resize the constant to the same size as the original memory access before
3063 // extension. If it is still the AllOnesValue then this AND is completely
3066 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3069 switch (Load->getExtensionType()) {
3070 default: B = false; break;
3071 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3073 case ISD::NON_EXTLOAD: B = true; break;
3076 if (B && Constant.isAllOnesValue()) {
3077 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3078 // preserve semantics once we get rid of the AND.
3079 SDValue NewLoad(Load, 0);
3080 if (Load->getExtensionType() == ISD::EXTLOAD) {
3081 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3082 Load->getValueType(0), SDLoc(Load),
3083 Load->getChain(), Load->getBasePtr(),
3084 Load->getOffset(), Load->getMemoryVT(),
3085 Load->getMemOperand());
3086 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3087 if (Load->getNumValues() == 3) {
3088 // PRE/POST_INC loads have 3 values.
3089 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3090 NewLoad.getValue(2) };
3091 CombineTo(Load, To, 3, true);
3093 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3097 // Fold the AND away, taking care not to fold to the old load node if we
3099 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3101 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3105 // fold (and (load x), 255) -> (zextload x, i8)
3106 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3107 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3108 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3109 (N0.getOpcode() == ISD::ANY_EXTEND &&
3110 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3111 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3112 LoadSDNode *LN0 = HasAnyExt
3113 ? cast<LoadSDNode>(N0.getOperand(0))
3114 : cast<LoadSDNode>(N0);
3115 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3116 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3117 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3118 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3119 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3120 EVT LoadedVT = LN0->getMemoryVT();
3121 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3123 if (ExtVT == LoadedVT &&
3124 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3128 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3129 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3130 LN0->getMemOperand());
3132 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3133 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3136 // Do not change the width of a volatile load.
3137 // Do not generate loads of non-round integer types since these can
3138 // be expensive (and would be wrong if the type is not byte sized).
3139 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3140 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3142 EVT PtrType = LN0->getOperand(1).getValueType();
3144 unsigned Alignment = LN0->getAlignment();
3145 SDValue NewPtr = LN0->getBasePtr();
3147 // For big endian targets, we need to add an offset to the pointer
3148 // to load the correct bytes. For little endian systems, we merely
3149 // need to read fewer bytes from the same pointer.
3150 if (DAG.getDataLayout().isBigEndian()) {
3151 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3152 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3153 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3155 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3156 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3157 Alignment = MinAlign(Alignment, PtrOff);
3160 AddToWorklist(NewPtr.getNode());
3163 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3164 LN0->getChain(), NewPtr,
3165 LN0->getPointerInfo(),
3166 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3167 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3169 CombineTo(LN0, Load, Load.getValue(1));
3170 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3176 if (SDValue Combined = visitANDLike(N0, N1, N))
3179 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3180 if (N0.getOpcode() == N1.getOpcode())
3181 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3184 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3185 // fold (and (sra)) -> (and (srl)) when possible.
3186 if (!VT.isVector() &&
3187 SimplifyDemandedBits(SDValue(N, 0)))
3188 return SDValue(N, 0);
3190 // fold (zext_inreg (extload x)) -> (zextload x)
3191 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3192 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3193 EVT MemVT = LN0->getMemoryVT();
3194 // If we zero all the possible extended bits, then we can turn this into
3195 // a zextload if we are running before legalize or the operation is legal.
3196 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3197 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3198 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3199 ((!LegalOperations && !LN0->isVolatile()) ||
3200 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3201 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3202 LN0->getChain(), LN0->getBasePtr(),
3203 MemVT, LN0->getMemOperand());
3205 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3206 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3209 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3210 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3212 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3213 EVT MemVT = LN0->getMemoryVT();
3214 // If we zero all the possible extended bits, then we can turn this into
3215 // a zextload if we are running before legalize or the operation is legal.
3216 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3217 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3218 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3219 ((!LegalOperations && !LN0->isVolatile()) ||
3220 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3221 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3222 LN0->getChain(), LN0->getBasePtr(),
3223 MemVT, LN0->getMemOperand());
3225 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3226 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3229 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3230 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3231 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3232 N0.getOperand(1), false);
3233 if (BSwap.getNode())
3240 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3241 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3242 bool DemandHighBits) {
3243 if (!LegalOperations)
3246 EVT VT = N->getValueType(0);
3247 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3249 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3252 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3253 bool LookPassAnd0 = false;
3254 bool LookPassAnd1 = false;
3255 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3257 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3259 if (N0.getOpcode() == ISD::AND) {
3260 if (!N0.getNode()->hasOneUse())
3262 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3263 if (!N01C || N01C->getZExtValue() != 0xFF00)
3265 N0 = N0.getOperand(0);
3266 LookPassAnd0 = true;
3269 if (N1.getOpcode() == ISD::AND) {
3270 if (!N1.getNode()->hasOneUse())
3272 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3273 if (!N11C || N11C->getZExtValue() != 0xFF)
3275 N1 = N1.getOperand(0);
3276 LookPassAnd1 = true;
3279 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3281 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3283 if (!N0.getNode()->hasOneUse() ||
3284 !N1.getNode()->hasOneUse())
3287 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3288 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3291 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3294 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3295 SDValue N00 = N0->getOperand(0);
3296 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3297 if (!N00.getNode()->hasOneUse())
3299 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3300 if (!N001C || N001C->getZExtValue() != 0xFF)
3302 N00 = N00.getOperand(0);
3303 LookPassAnd0 = true;
3306 SDValue N10 = N1->getOperand(0);
3307 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3308 if (!N10.getNode()->hasOneUse())
3310 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3311 if (!N101C || N101C->getZExtValue() != 0xFF00)
3313 N10 = N10.getOperand(0);
3314 LookPassAnd1 = true;
3320 // Make sure everything beyond the low halfword gets set to zero since the SRL
3321 // 16 will clear the top bits.
3322 unsigned OpSizeInBits = VT.getSizeInBits();
3323 if (DemandHighBits && OpSizeInBits > 16) {
3324 // If the left-shift isn't masked out then the only way this is a bswap is
3325 // if all bits beyond the low 8 are 0. In that case the entire pattern
3326 // reduces to a left shift anyway: leave it for other parts of the combiner.
3330 // However, if the right shift isn't masked out then it might be because
3331 // it's not needed. See if we can spot that too.
3332 if (!LookPassAnd1 &&
3333 !DAG.MaskedValueIsZero(
3334 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3338 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3339 if (OpSizeInBits > 16) {
3341 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3342 DAG.getConstant(OpSizeInBits - 16, DL,
3343 getShiftAmountTy(VT)));
3348 /// Return true if the specified node is an element that makes up a 32-bit
3349 /// packed halfword byteswap.
3350 /// ((x & 0x000000ff) << 8) |
3351 /// ((x & 0x0000ff00) >> 8) |
3352 /// ((x & 0x00ff0000) << 8) |
3353 /// ((x & 0xff000000) >> 8)
3354 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3355 if (!N.getNode()->hasOneUse())
3358 unsigned Opc = N.getOpcode();
3359 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3362 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3367 switch (N1C->getZExtValue()) {
3370 case 0xFF: Num = 0; break;
3371 case 0xFF00: Num = 1; break;
3372 case 0xFF0000: Num = 2; break;
3373 case 0xFF000000: Num = 3; break;
3376 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3377 SDValue N0 = N.getOperand(0);
3378 if (Opc == ISD::AND) {
3379 if (Num == 0 || Num == 2) {
3381 // (x >> 8) & 0xff0000
3382 if (N0.getOpcode() != ISD::SRL)
3384 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3385 if (!C || C->getZExtValue() != 8)
3388 // (x << 8) & 0xff00
3389 // (x << 8) & 0xff000000
3390 if (N0.getOpcode() != ISD::SHL)
3392 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3393 if (!C || C->getZExtValue() != 8)
3396 } else if (Opc == ISD::SHL) {
3398 // (x & 0xff0000) << 8
3399 if (Num != 0 && Num != 2)
3401 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3402 if (!C || C->getZExtValue() != 8)
3404 } else { // Opc == ISD::SRL
3405 // (x & 0xff00) >> 8
3406 // (x & 0xff000000) >> 8
3407 if (Num != 1 && Num != 3)
3409 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3410 if (!C || C->getZExtValue() != 8)
3417 Parts[Num] = N0.getOperand(0).getNode();
3421 /// Match a 32-bit packed halfword bswap. That is
3422 /// ((x & 0x000000ff) << 8) |
3423 /// ((x & 0x0000ff00) >> 8) |
3424 /// ((x & 0x00ff0000) << 8) |
3425 /// ((x & 0xff000000) >> 8)
3426 /// => (rotl (bswap x), 16)
3427 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3428 if (!LegalOperations)
3431 EVT VT = N->getValueType(0);
3434 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3438 // (or (or (and), (and)), (or (and), (and)))
3439 // (or (or (or (and), (and)), (and)), (and))
3440 if (N0.getOpcode() != ISD::OR)
3442 SDValue N00 = N0.getOperand(0);
3443 SDValue N01 = N0.getOperand(1);
3444 SDNode *Parts[4] = {};
3446 if (N1.getOpcode() == ISD::OR &&
3447 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3448 // (or (or (and), (and)), (or (and), (and)))
3449 SDValue N000 = N00.getOperand(0);
3450 if (!isBSwapHWordElement(N000, Parts))
3453 SDValue N001 = N00.getOperand(1);
3454 if (!isBSwapHWordElement(N001, Parts))
3456 SDValue N010 = N01.getOperand(0);
3457 if (!isBSwapHWordElement(N010, Parts))
3459 SDValue N011 = N01.getOperand(1);
3460 if (!isBSwapHWordElement(N011, Parts))
3463 // (or (or (or (and), (and)), (and)), (and))
3464 if (!isBSwapHWordElement(N1, Parts))
3466 if (!isBSwapHWordElement(N01, Parts))
3468 if (N00.getOpcode() != ISD::OR)
3470 SDValue N000 = N00.getOperand(0);
3471 if (!isBSwapHWordElement(N000, Parts))
3473 SDValue N001 = N00.getOperand(1);
3474 if (!isBSwapHWordElement(N001, Parts))
3478 // Make sure the parts are all coming from the same node.
3479 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3483 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3484 SDValue(Parts[0], 0));
3486 // Result of the bswap should be rotated by 16. If it's not legal, then
3487 // do (x << 16) | (x >> 16).
3488 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3489 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3490 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3491 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3492 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3493 return DAG.getNode(ISD::OR, DL, VT,
3494 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3495 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3498 /// This contains all DAGCombine rules which reduce two values combined by
3499 /// an Or operation to a single value \see visitANDLike().
3500 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3501 EVT VT = N1.getValueType();
3502 // fold (or x, undef) -> -1
3503 if (!LegalOperations &&
3504 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3505 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3506 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3507 SDLoc(LocReference), VT);
3509 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3510 SDValue LL, LR, RL, RR, CC0, CC1;
3511 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3512 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3513 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3515 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3516 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3517 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3518 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3519 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3520 LR.getValueType(), LL, RL);
3521 AddToWorklist(ORNode.getNode());
3522 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3524 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3525 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3526 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3527 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3528 LR.getValueType(), LL, RL);
3529 AddToWorklist(ANDNode.getNode());
3530 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3533 // canonicalize equivalent to ll == rl
3534 if (LL == RR && LR == RL) {
3535 Op1 = ISD::getSetCCSwappedOperands(Op1);
3538 if (LL == RL && LR == RR) {
3539 bool isInteger = LL.getValueType().isInteger();
3540 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3541 if (Result != ISD::SETCC_INVALID &&
3542 (!LegalOperations ||
3543 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3544 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3545 EVT CCVT = getSetCCResultType(LL.getValueType());
3546 if (N0.getValueType() == CCVT ||
3547 (!LegalOperations && N0.getValueType() == MVT::i1))
3548 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3554 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3555 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3556 // Don't increase # computations.
3557 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3558 // We can only do this xform if we know that bits from X that are set in C2
3559 // but not in C1 are already zero. Likewise for Y.
3560 if (const ConstantSDNode *N0O1C =
3561 getAsNonOpaqueConstant(N0.getOperand(1))) {
3562 if (const ConstantSDNode *N1O1C =
3563 getAsNonOpaqueConstant(N1.getOperand(1))) {
3564 // We can only do this xform if we know that bits from X that are set in
3565 // C2 but not in C1 are already zero. Likewise for Y.
3566 const APInt &LHSMask = N0O1C->getAPIntValue();
3567 const APInt &RHSMask = N1O1C->getAPIntValue();
3569 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3570 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3571 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3572 N0.getOperand(0), N1.getOperand(0));
3573 SDLoc DL(LocReference);
3574 return DAG.getNode(ISD::AND, DL, VT, X,
3575 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3581 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3582 if (N0.getOpcode() == ISD::AND &&
3583 N1.getOpcode() == ISD::AND &&
3584 N0.getOperand(0) == N1.getOperand(0) &&
3585 // Don't increase # computations.
3586 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3587 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3588 N0.getOperand(1), N1.getOperand(1));
3589 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3595 SDValue DAGCombiner::visitOR(SDNode *N) {
3596 SDValue N0 = N->getOperand(0);
3597 SDValue N1 = N->getOperand(1);
3598 EVT VT = N1.getValueType();
3601 if (VT.isVector()) {
3602 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3605 // fold (or x, 0) -> x, vector edition
3606 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3608 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3611 // fold (or x, -1) -> -1, vector edition
3612 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3613 // do not return N0, because undef node may exist in N0
3614 return DAG.getConstant(
3615 APInt::getAllOnesValue(
3616 N0.getValueType().getScalarType().getSizeInBits()),
3617 SDLoc(N), N0.getValueType());
3618 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3619 // do not return N1, because undef node may exist in N1
3620 return DAG.getConstant(
3621 APInt::getAllOnesValue(
3622 N1.getValueType().getScalarType().getSizeInBits()),
3623 SDLoc(N), N1.getValueType());
3625 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3626 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3627 // Do this only if the resulting shuffle is legal.
3628 if (isa<ShuffleVectorSDNode>(N0) &&
3629 isa<ShuffleVectorSDNode>(N1) &&
3630 // Avoid folding a node with illegal type.
3631 TLI.isTypeLegal(VT) &&
3632 N0->getOperand(1) == N1->getOperand(1) &&
3633 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3634 bool CanFold = true;
3635 unsigned NumElts = VT.getVectorNumElements();
3636 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3637 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3638 // We construct two shuffle masks:
3639 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3640 // and N1 as the second operand.
3641 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3642 // and N0 as the second operand.
3643 // We do this because OR is commutable and therefore there might be
3644 // two ways to fold this node into a shuffle.
3645 SmallVector<int,4> Mask1;
3646 SmallVector<int,4> Mask2;
3648 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3649 int M0 = SV0->getMaskElt(i);
3650 int M1 = SV1->getMaskElt(i);
3652 // Both shuffle indexes are undef. Propagate Undef.
3653 if (M0 < 0 && M1 < 0) {
3654 Mask1.push_back(M0);
3655 Mask2.push_back(M0);
3659 if (M0 < 0 || M1 < 0 ||
3660 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3661 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3666 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3667 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3671 // Fold this sequence only if the resulting shuffle is 'legal'.
3672 if (TLI.isShuffleMaskLegal(Mask1, VT))
3673 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3674 N1->getOperand(0), &Mask1[0]);
3675 if (TLI.isShuffleMaskLegal(Mask2, VT))
3676 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3677 N0->getOperand(0), &Mask2[0]);
3682 // fold (or c1, c2) -> c1|c2
3683 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3684 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3685 if (N0C && N1C && !N1C->isOpaque())
3686 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3687 // canonicalize constant to RHS
3688 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3689 !isConstantIntBuildVectorOrConstantInt(N1))
3690 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3691 // fold (or x, 0) -> x
3692 if (isNullConstant(N1))
3694 // fold (or x, -1) -> -1
3695 if (isAllOnesConstant(N1))
3697 // fold (or x, c) -> c iff (x & ~c) == 0
3698 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3701 if (SDValue Combined = visitORLike(N0, N1, N))
3704 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3705 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3707 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3711 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3713 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3714 // iff (c1 & c2) == 0.
3715 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3716 isa<ConstantSDNode>(N0.getOperand(1))) {
3717 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3718 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3719 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3722 ISD::AND, SDLoc(N), VT,
3723 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3727 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3728 if (N0.getOpcode() == N1.getOpcode())
3729 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3732 // See if this is some rotate idiom.
3733 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3734 return SDValue(Rot, 0);
3736 // Simplify the operands using demanded-bits information.
3737 if (!VT.isVector() &&
3738 SimplifyDemandedBits(SDValue(N, 0)))
3739 return SDValue(N, 0);
3744 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3745 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3746 if (Op.getOpcode() == ISD::AND) {
3747 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3748 Mask = Op.getOperand(1);
3749 Op = Op.getOperand(0);
3755 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3763 // Return true if we can prove that, whenever Neg and Pos are both in the
3764 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3765 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3767 // (or (shift1 X, Neg), (shift2 X, Pos))
3769 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3770 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3771 // to consider shift amounts with defined behavior.
3772 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3773 // If OpSize is a power of 2 then:
3775 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3776 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3778 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3779 // for the stronger condition:
3781 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3783 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3784 // we can just replace Neg with Neg' for the rest of the function.
3786 // In other cases we check for the even stronger condition:
3788 // Neg == OpSize - Pos [B]
3790 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3791 // behavior if Pos == 0 (and consequently Neg == OpSize).
3793 // We could actually use [A] whenever OpSize is a power of 2, but the
3794 // only extra cases that it would match are those uninteresting ones
3795 // where Neg and Pos are never in range at the same time. E.g. for
3796 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3797 // as well as (sub 32, Pos), but:
3799 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3801 // always invokes undefined behavior for 32-bit X.
3803 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3804 unsigned MaskLoBits = 0;
3805 if (Neg.getOpcode() == ISD::AND &&
3806 isPowerOf2_64(OpSize) &&
3807 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3808 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3809 Neg = Neg.getOperand(0);
3810 MaskLoBits = Log2_64(OpSize);
3813 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3814 if (Neg.getOpcode() != ISD::SUB)
3816 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3819 SDValue NegOp1 = Neg.getOperand(1);
3821 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3822 // Pos'. The truncation is redundant for the purpose of the equality.
3824 Pos.getOpcode() == ISD::AND &&
3825 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3826 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3827 Pos = Pos.getOperand(0);
3829 // The condition we need is now:
3831 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3833 // If NegOp1 == Pos then we need:
3835 // OpSize & Mask == NegC & Mask
3837 // (because "x & Mask" is a truncation and distributes through subtraction).
3840 Width = NegC->getAPIntValue();
3841 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3842 // Then the condition we want to prove becomes:
3844 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3846 // which, again because "x & Mask" is a truncation, becomes:
3848 // NegC & Mask == (OpSize - PosC) & Mask
3849 // OpSize & Mask == (NegC + PosC) & Mask
3850 else if (Pos.getOpcode() == ISD::ADD &&
3851 Pos.getOperand(0) == NegOp1 &&
3852 Pos.getOperand(1).getOpcode() == ISD::Constant)
3853 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3854 NegC->getAPIntValue());
3858 // Now we just need to check that OpSize & Mask == Width & Mask.
3860 // Opsize & Mask is 0 since Mask is Opsize - 1.
3861 return Width.getLoBits(MaskLoBits) == 0;
3862 return Width == OpSize;
3865 // A subroutine of MatchRotate used once we have found an OR of two opposite
3866 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3867 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3868 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3869 // Neg with outer conversions stripped away.
3870 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3871 SDValue Neg, SDValue InnerPos,
3872 SDValue InnerNeg, unsigned PosOpcode,
3873 unsigned NegOpcode, SDLoc DL) {
3874 // fold (or (shl x, (*ext y)),
3875 // (srl x, (*ext (sub 32, y)))) ->
3876 // (rotl x, y) or (rotr x, (sub 32, y))
3878 // fold (or (shl x, (*ext (sub 32, y))),
3879 // (srl x, (*ext y))) ->
3880 // (rotr x, y) or (rotl x, (sub 32, y))
3881 EVT VT = Shifted.getValueType();
3882 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3883 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3884 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3885 HasPos ? Pos : Neg).getNode();
3891 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3892 // idioms for rotate, and if the target supports rotation instructions, generate
3894 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3895 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3896 EVT VT = LHS.getValueType();
3897 if (!TLI.isTypeLegal(VT)) return nullptr;
3899 // The target must have at least one rotate flavor.
3900 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3901 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3902 if (!HasROTL && !HasROTR) return nullptr;
3904 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3905 SDValue LHSShift; // The shift.
3906 SDValue LHSMask; // AND value if any.
3907 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3908 return nullptr; // Not part of a rotate.
3910 SDValue RHSShift; // The shift.
3911 SDValue RHSMask; // AND value if any.
3912 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3913 return nullptr; // Not part of a rotate.
3915 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3916 return nullptr; // Not shifting the same value.
3918 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3919 return nullptr; // Shifts must disagree.
3921 // Canonicalize shl to left side in a shl/srl pair.
3922 if (RHSShift.getOpcode() == ISD::SHL) {
3923 std::swap(LHS, RHS);
3924 std::swap(LHSShift, RHSShift);
3925 std::swap(LHSMask , RHSMask );
3928 unsigned OpSizeInBits = VT.getSizeInBits();
3929 SDValue LHSShiftArg = LHSShift.getOperand(0);
3930 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3931 SDValue RHSShiftArg = RHSShift.getOperand(0);
3932 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3934 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3935 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3936 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3937 RHSShiftAmt.getOpcode() == ISD::Constant) {
3938 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3939 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3940 if ((LShVal + RShVal) != OpSizeInBits)
3943 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3944 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3946 // If there is an AND of either shifted operand, apply it to the result.
3947 if (LHSMask.getNode() || RHSMask.getNode()) {
3948 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3950 if (LHSMask.getNode()) {
3951 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3952 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3954 if (RHSMask.getNode()) {
3955 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3956 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3959 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3962 return Rot.getNode();
3965 // If there is a mask here, and we have a variable shift, we can't be sure
3966 // that we're masking out the right stuff.
3967 if (LHSMask.getNode() || RHSMask.getNode())
3970 // If the shift amount is sign/zext/any-extended just peel it off.
3971 SDValue LExtOp0 = LHSShiftAmt;
3972 SDValue RExtOp0 = RHSShiftAmt;
3973 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3974 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3975 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3976 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3977 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3978 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3979 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3980 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3981 LExtOp0 = LHSShiftAmt.getOperand(0);
3982 RExtOp0 = RHSShiftAmt.getOperand(0);
3985 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3986 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3990 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3991 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3998 SDValue DAGCombiner::visitXOR(SDNode *N) {
3999 SDValue N0 = N->getOperand(0);
4000 SDValue N1 = N->getOperand(1);
4001 EVT VT = N0.getValueType();
4004 if (VT.isVector()) {
4005 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4008 // fold (xor x, 0) -> x, vector edition
4009 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4011 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4015 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4016 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4017 return DAG.getConstant(0, SDLoc(N), VT);
4018 // fold (xor x, undef) -> undef
4019 if (N0.getOpcode() == ISD::UNDEF)
4021 if (N1.getOpcode() == ISD::UNDEF)
4023 // fold (xor c1, c2) -> c1^c2
4024 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4025 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4027 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4028 // canonicalize constant to RHS
4029 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4030 !isConstantIntBuildVectorOrConstantInt(N1))
4031 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4032 // fold (xor x, 0) -> x
4033 if (isNullConstant(N1))
4036 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4039 // fold !(x cc y) -> (x !cc y)
4040 SDValue LHS, RHS, CC;
4041 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4042 bool isInt = LHS.getValueType().isInteger();
4043 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4046 if (!LegalOperations ||
4047 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4048 switch (N0.getOpcode()) {
4050 llvm_unreachable("Unhandled SetCC Equivalent!");
4052 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4053 case ISD::SELECT_CC:
4054 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4055 N0.getOperand(3), NotCC);
4060 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4061 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4062 N0.getNode()->hasOneUse() &&
4063 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4064 SDValue V = N0.getOperand(0);
4066 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4067 DAG.getConstant(1, DL, V.getValueType()));
4068 AddToWorklist(V.getNode());
4069 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4072 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4073 if (isOneConstant(N1) && VT == MVT::i1 &&
4074 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4075 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4076 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4077 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4078 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4079 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4080 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4081 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4084 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4085 if (isAllOnesConstant(N1) &&
4086 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4087 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4088 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4089 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4090 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4091 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4092 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4093 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4096 // fold (xor (and x, y), y) -> (and (not x), y)
4097 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4098 N0->getOperand(1) == N1) {
4099 SDValue X = N0->getOperand(0);
4100 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4101 AddToWorklist(NotX.getNode());
4102 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4104 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4105 if (N1C && N0.getOpcode() == ISD::XOR) {
4106 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4108 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4109 DAG.getConstant(N1C->getAPIntValue() ^
4110 N00C->getAPIntValue(), DL, VT));
4112 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4114 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4115 DAG.getConstant(N1C->getAPIntValue() ^
4116 N01C->getAPIntValue(), DL, VT));
4119 // fold (xor x, x) -> 0
4121 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4123 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4124 // Here is a concrete example of this equivalence:
4126 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4127 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4131 // i16 ~1 == 0b1111111111111110
4132 // i16 rol(~1, 14) == 0b1011111111111111
4134 // Some additional tips to help conceptualize this transform:
4135 // - Try to see the operation as placing a single zero in a value of all ones.
4136 // - There exists no value for x which would allow the result to contain zero.
4137 // - Values of x larger than the bitwidth are undefined and do not require a
4138 // consistent result.
4139 // - Pushing the zero left requires shifting one bits in from the right.
4140 // A rotate left of ~1 is a nice way of achieving the desired result.
4141 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4142 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4144 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4148 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4149 if (N0.getOpcode() == N1.getOpcode())
4150 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4153 // Simplify the expression using non-local knowledge.
4154 if (!VT.isVector() &&
4155 SimplifyDemandedBits(SDValue(N, 0)))
4156 return SDValue(N, 0);
4161 /// Handle transforms common to the three shifts, when the shift amount is a
4163 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4164 SDNode *LHS = N->getOperand(0).getNode();
4165 if (!LHS->hasOneUse()) return SDValue();
4167 // We want to pull some binops through shifts, so that we have (and (shift))
4168 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4169 // thing happens with address calculations, so it's important to canonicalize
4171 bool HighBitSet = false; // Can we transform this if the high bit is set?
4173 switch (LHS->getOpcode()) {
4174 default: return SDValue();
4177 HighBitSet = false; // We can only transform sra if the high bit is clear.
4180 HighBitSet = true; // We can only transform sra if the high bit is set.
4183 if (N->getOpcode() != ISD::SHL)
4184 return SDValue(); // only shl(add) not sr[al](add).
4185 HighBitSet = false; // We can only transform sra if the high bit is clear.
4189 // We require the RHS of the binop to be a constant and not opaque as well.
4190 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4191 if (!BinOpCst) return SDValue();
4193 // FIXME: disable this unless the input to the binop is a shift by a constant.
4194 // If it is not a shift, it pessimizes some common cases like:
4196 // void foo(int *X, int i) { X[i & 1235] = 1; }
4197 // int bar(int *X, int i) { return X[i & 255]; }
4198 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4199 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4200 BinOpLHSVal->getOpcode() != ISD::SRA &&
4201 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4202 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4205 EVT VT = N->getValueType(0);
4207 // If this is a signed shift right, and the high bit is modified by the
4208 // logical operation, do not perform the transformation. The highBitSet
4209 // boolean indicates the value of the high bit of the constant which would
4210 // cause it to be modified for this operation.
4211 if (N->getOpcode() == ISD::SRA) {
4212 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4213 if (BinOpRHSSignSet != HighBitSet)
4217 if (!TLI.isDesirableToCommuteWithShift(LHS))
4220 // Fold the constants, shifting the binop RHS by the shift amount.
4221 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4223 LHS->getOperand(1), N->getOperand(1));
4224 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4226 // Create the new shift.
4227 SDValue NewShift = DAG.getNode(N->getOpcode(),
4228 SDLoc(LHS->getOperand(0)),
4229 VT, LHS->getOperand(0), N->getOperand(1));
4231 // Create the new binop.
4232 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4235 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4236 assert(N->getOpcode() == ISD::TRUNCATE);
4237 assert(N->getOperand(0).getOpcode() == ISD::AND);
4239 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4240 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4241 SDValue N01 = N->getOperand(0).getOperand(1);
4243 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4244 if (!N01C->isOpaque()) {
4245 EVT TruncVT = N->getValueType(0);
4246 SDValue N00 = N->getOperand(0).getOperand(0);
4247 APInt TruncC = N01C->getAPIntValue();
4248 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4251 return DAG.getNode(ISD::AND, DL, TruncVT,
4252 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4253 DAG.getConstant(TruncC, DL, TruncVT));
4261 SDValue DAGCombiner::visitRotate(SDNode *N) {
4262 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4263 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4264 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4265 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4266 if (NewOp1.getNode())
4267 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4268 N->getOperand(0), NewOp1);
4273 SDValue DAGCombiner::visitSHL(SDNode *N) {
4274 SDValue N0 = N->getOperand(0);
4275 SDValue N1 = N->getOperand(1);
4276 EVT VT = N0.getValueType();
4277 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4280 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4281 if (VT.isVector()) {
4282 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4285 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4286 // If setcc produces all-one true value then:
4287 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4288 if (N1CV && N1CV->isConstant()) {
4289 if (N0.getOpcode() == ISD::AND) {
4290 SDValue N00 = N0->getOperand(0);
4291 SDValue N01 = N0->getOperand(1);
4292 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4294 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4295 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4296 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4297 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4299 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4302 N1C = isConstOrConstSplat(N1);
4307 // fold (shl c1, c2) -> c1<<c2
4308 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4309 if (N0C && N1C && !N1C->isOpaque())
4310 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4311 // fold (shl 0, x) -> 0
4312 if (isNullConstant(N0))
4314 // fold (shl x, c >= size(x)) -> undef
4315 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4316 return DAG.getUNDEF(VT);
4317 // fold (shl x, 0) -> x
4318 if (N1C && N1C->isNullValue())
4320 // fold (shl undef, x) -> 0
4321 if (N0.getOpcode() == ISD::UNDEF)
4322 return DAG.getConstant(0, SDLoc(N), VT);
4323 // if (shl x, c) is known to be zero, return 0
4324 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4325 APInt::getAllOnesValue(OpSizeInBits)))
4326 return DAG.getConstant(0, SDLoc(N), VT);
4327 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4328 if (N1.getOpcode() == ISD::TRUNCATE &&
4329 N1.getOperand(0).getOpcode() == ISD::AND) {
4330 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4331 if (NewOp1.getNode())
4332 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4335 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4336 return SDValue(N, 0);
4338 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4339 if (N1C && N0.getOpcode() == ISD::SHL) {
4340 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4341 uint64_t c1 = N0C1->getZExtValue();
4342 uint64_t c2 = N1C->getZExtValue();
4344 if (c1 + c2 >= OpSizeInBits)
4345 return DAG.getConstant(0, DL, VT);
4346 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4347 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4351 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4352 // For this to be valid, the second form must not preserve any of the bits
4353 // that are shifted out by the inner shift in the first form. This means
4354 // the outer shift size must be >= the number of bits added by the ext.
4355 // As a corollary, we don't care what kind of ext it is.
4356 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4357 N0.getOpcode() == ISD::ANY_EXTEND ||
4358 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4359 N0.getOperand(0).getOpcode() == ISD::SHL) {
4360 SDValue N0Op0 = N0.getOperand(0);
4361 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4362 uint64_t c1 = N0Op0C1->getZExtValue();
4363 uint64_t c2 = N1C->getZExtValue();
4364 EVT InnerShiftVT = N0Op0.getValueType();
4365 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4366 if (c2 >= OpSizeInBits - InnerShiftSize) {
4368 if (c1 + c2 >= OpSizeInBits)
4369 return DAG.getConstant(0, DL, VT);
4370 return DAG.getNode(ISD::SHL, DL, VT,
4371 DAG.getNode(N0.getOpcode(), DL, VT,
4372 N0Op0->getOperand(0)),
4373 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4378 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4379 // Only fold this if the inner zext has no other uses to avoid increasing
4380 // the total number of instructions.
4381 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4382 N0.getOperand(0).getOpcode() == ISD::SRL) {
4383 SDValue N0Op0 = N0.getOperand(0);
4384 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4385 uint64_t c1 = N0Op0C1->getZExtValue();
4386 if (c1 < VT.getScalarSizeInBits()) {
4387 uint64_t c2 = N1C->getZExtValue();
4389 SDValue NewOp0 = N0.getOperand(0);
4390 EVT CountVT = NewOp0.getOperand(1).getValueType();
4392 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4394 DAG.getConstant(c2, DL, CountVT));
4395 AddToWorklist(NewSHL.getNode());
4396 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4402 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4403 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4404 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4405 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4406 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4407 uint64_t C1 = N0C1->getZExtValue();
4408 uint64_t C2 = N1C->getZExtValue();
4411 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4412 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4413 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4414 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4418 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4419 // (and (srl x, (sub c1, c2), MASK)
4420 // Only fold this if the inner shift has no other uses -- if it does, folding
4421 // this will increase the total number of instructions.
4422 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4423 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4424 uint64_t c1 = N0C1->getZExtValue();
4425 if (c1 < OpSizeInBits) {
4426 uint64_t c2 = N1C->getZExtValue();
4427 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4430 Mask = Mask.shl(c2 - c1);
4432 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4433 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4435 Mask = Mask.lshr(c1 - c2);
4437 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4438 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4441 return DAG.getNode(ISD::AND, DL, VT, Shift,
4442 DAG.getConstant(Mask, DL, VT));
4446 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4447 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4448 unsigned BitSize = VT.getScalarSizeInBits();
4450 SDValue HiBitsMask =
4451 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4452 BitSize - N1C->getZExtValue()),
4454 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4458 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4459 // Variant of version done on multiply, except mul by a power of 2 is turned
4462 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4463 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4464 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4465 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4466 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4467 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4470 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4471 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4472 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4473 if (SDValue Folded =
4474 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4475 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4479 if (N1C && !N1C->isOpaque())
4480 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4486 SDValue DAGCombiner::visitSRA(SDNode *N) {
4487 SDValue N0 = N->getOperand(0);
4488 SDValue N1 = N->getOperand(1);
4489 EVT VT = N0.getValueType();
4490 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4493 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4494 if (VT.isVector()) {
4495 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4498 N1C = isConstOrConstSplat(N1);
4501 // fold (sra c1, c2) -> (sra c1, c2)
4502 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4503 if (N0C && N1C && !N1C->isOpaque())
4504 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4505 // fold (sra 0, x) -> 0
4506 if (isNullConstant(N0))
4508 // fold (sra -1, x) -> -1
4509 if (isAllOnesConstant(N0))
4511 // fold (sra x, (setge c, size(x))) -> undef
4512 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4513 return DAG.getUNDEF(VT);
4514 // fold (sra x, 0) -> x
4515 if (N1C && N1C->isNullValue())
4517 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4519 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4520 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4521 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4523 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4524 ExtVT, VT.getVectorNumElements());
4525 if ((!LegalOperations ||
4526 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4527 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4528 N0.getOperand(0), DAG.getValueType(ExtVT));
4531 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4532 if (N1C && N0.getOpcode() == ISD::SRA) {
4533 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4534 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4535 if (Sum >= OpSizeInBits)
4536 Sum = OpSizeInBits - 1;
4538 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4539 DAG.getConstant(Sum, DL, N1.getValueType()));
4543 // fold (sra (shl X, m), (sub result_size, n))
4544 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4545 // result_size - n != m.
4546 // If truncate is free for the target sext(shl) is likely to result in better
4548 if (N0.getOpcode() == ISD::SHL && N1C) {
4549 // Get the two constanst of the shifts, CN0 = m, CN = n.
4550 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4552 LLVMContext &Ctx = *DAG.getContext();
4553 // Determine what the truncate's result bitsize and type would be.
4554 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4557 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4559 // Determine the residual right-shift amount.
4560 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4562 // If the shift is not a no-op (in which case this should be just a sign
4563 // extend already), the truncated to type is legal, sign_extend is legal
4564 // on that type, and the truncate to that type is both legal and free,
4565 // perform the transform.
4566 if ((ShiftAmt > 0) &&
4567 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4568 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4569 TLI.isTruncateFree(VT, TruncVT)) {
4572 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4573 getShiftAmountTy(N0.getOperand(0).getValueType()));
4574 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4575 N0.getOperand(0), Amt);
4576 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4578 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4579 N->getValueType(0), Trunc);
4584 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4585 if (N1.getOpcode() == ISD::TRUNCATE &&
4586 N1.getOperand(0).getOpcode() == ISD::AND) {
4587 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4588 if (NewOp1.getNode())
4589 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4592 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4593 // if c1 is equal to the number of bits the trunc removes
4594 if (N0.getOpcode() == ISD::TRUNCATE &&
4595 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4596 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4597 N0.getOperand(0).hasOneUse() &&
4598 N0.getOperand(0).getOperand(1).hasOneUse() &&
4600 SDValue N0Op0 = N0.getOperand(0);
4601 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4602 unsigned LargeShiftVal = LargeShift->getZExtValue();
4603 EVT LargeVT = N0Op0.getValueType();
4605 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4608 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4609 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4610 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4611 N0Op0.getOperand(0), Amt);
4612 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4617 // Simplify, based on bits shifted out of the LHS.
4618 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4619 return SDValue(N, 0);
4622 // If the sign bit is known to be zero, switch this to a SRL.
4623 if (DAG.SignBitIsZero(N0))
4624 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4626 if (N1C && !N1C->isOpaque())
4627 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4633 SDValue DAGCombiner::visitSRL(SDNode *N) {
4634 SDValue N0 = N->getOperand(0);
4635 SDValue N1 = N->getOperand(1);
4636 EVT VT = N0.getValueType();
4637 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4640 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4641 if (VT.isVector()) {
4642 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4645 N1C = isConstOrConstSplat(N1);
4648 // fold (srl c1, c2) -> c1 >>u c2
4649 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4650 if (N0C && N1C && !N1C->isOpaque())
4651 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4652 // fold (srl 0, x) -> 0
4653 if (isNullConstant(N0))
4655 // fold (srl x, c >= size(x)) -> undef
4656 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4657 return DAG.getUNDEF(VT);
4658 // fold (srl x, 0) -> x
4659 if (N1C && N1C->isNullValue())
4661 // if (srl x, c) is known to be zero, return 0
4662 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4663 APInt::getAllOnesValue(OpSizeInBits)))
4664 return DAG.getConstant(0, SDLoc(N), VT);
4666 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4667 if (N1C && N0.getOpcode() == ISD::SRL) {
4668 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4669 uint64_t c1 = N01C->getZExtValue();
4670 uint64_t c2 = N1C->getZExtValue();
4672 if (c1 + c2 >= OpSizeInBits)
4673 return DAG.getConstant(0, DL, VT);
4674 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4675 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4679 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4680 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4681 N0.getOperand(0).getOpcode() == ISD::SRL &&
4682 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4684 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4685 uint64_t c2 = N1C->getZExtValue();
4686 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4687 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4688 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4689 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4690 if (c1 + OpSizeInBits == InnerShiftSize) {
4692 if (c1 + c2 >= InnerShiftSize)
4693 return DAG.getConstant(0, DL, VT);
4694 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4695 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4696 N0.getOperand(0)->getOperand(0),
4697 DAG.getConstant(c1 + c2, DL,
4702 // fold (srl (shl x, c), c) -> (and x, cst2)
4703 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4704 unsigned BitSize = N0.getScalarValueSizeInBits();
4705 if (BitSize <= 64) {
4706 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4708 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4709 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4713 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4714 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4715 // Shifting in all undef bits?
4716 EVT SmallVT = N0.getOperand(0).getValueType();
4717 unsigned BitSize = SmallVT.getScalarSizeInBits();
4718 if (N1C->getZExtValue() >= BitSize)
4719 return DAG.getUNDEF(VT);
4721 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4722 uint64_t ShiftAmt = N1C->getZExtValue();
4724 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4726 DAG.getConstant(ShiftAmt, DL0,
4727 getShiftAmountTy(SmallVT)));
4728 AddToWorklist(SmallShift.getNode());
4729 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4731 return DAG.getNode(ISD::AND, DL, VT,
4732 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4733 DAG.getConstant(Mask, DL, VT));
4737 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4738 // bit, which is unmodified by sra.
4739 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4740 if (N0.getOpcode() == ISD::SRA)
4741 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4744 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4745 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4746 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4747 APInt KnownZero, KnownOne;
4748 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4750 // If any of the input bits are KnownOne, then the input couldn't be all
4751 // zeros, thus the result of the srl will always be zero.
4752 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4754 // If all of the bits input the to ctlz node are known to be zero, then
4755 // the result of the ctlz is "32" and the result of the shift is one.
4756 APInt UnknownBits = ~KnownZero;
4757 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4759 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4760 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4761 // Okay, we know that only that the single bit specified by UnknownBits
4762 // could be set on input to the CTLZ node. If this bit is set, the SRL
4763 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4764 // to an SRL/XOR pair, which is likely to simplify more.
4765 unsigned ShAmt = UnknownBits.countTrailingZeros();
4766 SDValue Op = N0.getOperand(0);
4770 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4771 DAG.getConstant(ShAmt, DL,
4772 getShiftAmountTy(Op.getValueType())));
4773 AddToWorklist(Op.getNode());
4777 return DAG.getNode(ISD::XOR, DL, VT,
4778 Op, DAG.getConstant(1, DL, VT));
4782 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4783 if (N1.getOpcode() == ISD::TRUNCATE &&
4784 N1.getOperand(0).getOpcode() == ISD::AND) {
4785 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4786 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4789 // fold operands of srl based on knowledge that the low bits are not
4791 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4792 return SDValue(N, 0);
4794 if (N1C && !N1C->isOpaque())
4795 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4798 // Attempt to convert a srl of a load into a narrower zero-extending load.
4799 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4802 // Here is a common situation. We want to optimize:
4805 // %b = and i32 %a, 2
4806 // %c = srl i32 %b, 1
4807 // brcond i32 %c ...
4813 // %c = setcc eq %b, 0
4816 // However when after the source operand of SRL is optimized into AND, the SRL
4817 // itself may not be optimized further. Look for it and add the BRCOND into
4819 if (N->hasOneUse()) {
4820 SDNode *Use = *N->use_begin();
4821 if (Use->getOpcode() == ISD::BRCOND)
4823 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4824 // Also look pass the truncate.
4825 Use = *Use->use_begin();
4826 if (Use->getOpcode() == ISD::BRCOND)
4834 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4835 SDValue N0 = N->getOperand(0);
4836 EVT VT = N->getValueType(0);
4838 // fold (bswap c1) -> c2
4839 if (isConstantIntBuildVectorOrConstantInt(N0))
4840 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4841 // fold (bswap (bswap x)) -> x
4842 if (N0.getOpcode() == ISD::BSWAP)
4843 return N0->getOperand(0);
4847 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4848 SDValue N0 = N->getOperand(0);
4849 EVT VT = N->getValueType(0);
4851 // fold (ctlz c1) -> c2
4852 if (isConstantIntBuildVectorOrConstantInt(N0))
4853 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4857 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4858 SDValue N0 = N->getOperand(0);
4859 EVT VT = N->getValueType(0);
4861 // fold (ctlz_zero_undef c1) -> c2
4862 if (isConstantIntBuildVectorOrConstantInt(N0))
4863 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4867 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4868 SDValue N0 = N->getOperand(0);
4869 EVT VT = N->getValueType(0);
4871 // fold (cttz c1) -> c2
4872 if (isConstantIntBuildVectorOrConstantInt(N0))
4873 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4877 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4878 SDValue N0 = N->getOperand(0);
4879 EVT VT = N->getValueType(0);
4881 // fold (cttz_zero_undef c1) -> c2
4882 if (isConstantIntBuildVectorOrConstantInt(N0))
4883 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4887 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4888 SDValue N0 = N->getOperand(0);
4889 EVT VT = N->getValueType(0);
4891 // fold (ctpop c1) -> c2
4892 if (isConstantIntBuildVectorOrConstantInt(N0))
4893 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4898 /// \brief Generate Min/Max node
4899 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4900 SDValue True, SDValue False,
4901 ISD::CondCode CC, const TargetLowering &TLI,
4902 SelectionDAG &DAG) {
4903 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4913 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4914 if (TLI.isOperationLegal(Opcode, VT))
4915 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4924 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4925 if (TLI.isOperationLegal(Opcode, VT))
4926 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4934 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4935 SDValue N0 = N->getOperand(0);
4936 SDValue N1 = N->getOperand(1);
4937 SDValue N2 = N->getOperand(2);
4938 EVT VT = N->getValueType(0);
4939 EVT VT0 = N0.getValueType();
4941 // fold (select C, X, X) -> X
4944 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4945 // fold (select true, X, Y) -> X
4946 // fold (select false, X, Y) -> Y
4947 return !N0C->isNullValue() ? N1 : N2;
4949 // fold (select C, 1, X) -> (or C, X)
4950 if (VT == MVT::i1 && isOneConstant(N1))
4951 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4952 // fold (select C, 0, 1) -> (xor C, 1)
4953 // We can't do this reliably if integer based booleans have different contents
4954 // to floating point based booleans. This is because we can't tell whether we
4955 // have an integer-based boolean or a floating-point-based boolean unless we
4956 // can find the SETCC that produced it and inspect its operands. This is
4957 // fairly easy if C is the SETCC node, but it can potentially be
4958 // undiscoverable (or not reasonably discoverable). For example, it could be
4959 // in another basic block or it could require searching a complicated
4961 if (VT.isInteger() &&
4962 (VT0 == MVT::i1 || (VT0.isInteger() &&
4963 TLI.getBooleanContents(false, false) ==
4964 TLI.getBooleanContents(false, true) &&
4965 TLI.getBooleanContents(false, false) ==
4966 TargetLowering::ZeroOrOneBooleanContent)) &&
4967 isNullConstant(N1) && isOneConstant(N2)) {
4971 return DAG.getNode(ISD::XOR, DL, VT0,
4972 N0, DAG.getConstant(1, DL, VT0));
4975 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4976 N0, DAG.getConstant(1, DL0, VT0));
4977 AddToWorklist(XORNode.getNode());
4979 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4980 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4982 // fold (select C, 0, X) -> (and (not C), X)
4983 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4984 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4985 AddToWorklist(NOTNode.getNode());
4986 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4988 // fold (select C, X, 1) -> (or (not C), X)
4989 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4990 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4991 AddToWorklist(NOTNode.getNode());
4992 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4994 // fold (select C, X, 0) -> (and C, X)
4995 if (VT == MVT::i1 && isNullConstant(N2))
4996 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4997 // fold (select X, X, Y) -> (or X, Y)
4998 // fold (select X, 1, Y) -> (or X, Y)
4999 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5000 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5001 // fold (select X, Y, X) -> (and X, Y)
5002 // fold (select X, Y, 0) -> (and X, Y)
5003 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5004 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5006 // If we can fold this based on the true/false value, do so.
5007 if (SimplifySelectOps(N, N1, N2))
5008 return SDValue(N, 0); // Don't revisit N.
5010 if (VT0 == MVT::i1) {
5011 // The code in this block deals with the following 2 equivalences:
5012 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5013 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5014 // The target can specify its prefered form with the
5015 // shouldNormalizeToSelectSequence() callback. However we always transform
5016 // to the right anyway if we find the inner select exists in the DAG anyway
5017 // and we always transform to the left side if we know that we can further
5018 // optimize the combination of the conditions.
5019 bool normalizeToSequence
5020 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5021 // select (and Cond0, Cond1), X, Y
5022 // -> select Cond0, (select Cond1, X, Y), Y
5023 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5024 SDValue Cond0 = N0->getOperand(0);
5025 SDValue Cond1 = N0->getOperand(1);
5026 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5027 N1.getValueType(), Cond1, N1, N2);
5028 if (normalizeToSequence || !InnerSelect.use_empty())
5029 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5032 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5033 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5034 SDValue Cond0 = N0->getOperand(0);
5035 SDValue Cond1 = N0->getOperand(1);
5036 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5037 N1.getValueType(), Cond1, N1, N2);
5038 if (normalizeToSequence || !InnerSelect.use_empty())
5039 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5043 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5044 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5045 SDValue N1_0 = N1->getOperand(0);
5046 SDValue N1_1 = N1->getOperand(1);
5047 SDValue N1_2 = N1->getOperand(2);
5048 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5049 // Create the actual and node if we can generate good code for it.
5050 if (!normalizeToSequence) {
5051 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5053 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5056 // Otherwise see if we can optimize the "and" to a better pattern.
5057 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5058 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5062 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5063 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5064 SDValue N2_0 = N2->getOperand(0);
5065 SDValue N2_1 = N2->getOperand(1);
5066 SDValue N2_2 = N2->getOperand(2);
5067 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5068 // Create the actual or node if we can generate good code for it.
5069 if (!normalizeToSequence) {
5070 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5072 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5075 // Otherwise see if we can optimize to a better pattern.
5076 if (SDValue Combined = visitORLike(N0, N2_0, N))
5077 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5083 // fold selects based on a setcc into other things, such as min/max/abs
5084 if (N0.getOpcode() == ISD::SETCC) {
5085 // select x, y (fcmp lt x, y) -> fminnum x, y
5086 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5088 // This is OK if we don't care about what happens if either operand is a
5092 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5093 // no signed zeros as well as no nans.
5094 const TargetOptions &Options = DAG.getTarget().Options;
5095 if (Options.UnsafeFPMath &&
5096 VT.isFloatingPoint() && N0.hasOneUse() &&
5097 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5098 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5100 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5101 N0.getOperand(1), N1, N2, CC,
5106 if ((!LegalOperations &&
5107 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5108 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5109 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5110 N0.getOperand(0), N0.getOperand(1),
5111 N1, N2, N0.getOperand(2));
5112 return SimplifySelect(SDLoc(N), N0, N1, N2);
5119 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5122 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5124 // Split the inputs.
5125 SDValue Lo, Hi, LL, LH, RL, RH;
5126 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5127 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5129 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5130 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5132 return std::make_pair(Lo, Hi);
5135 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5136 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5137 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5139 SDValue Cond = N->getOperand(0);
5140 SDValue LHS = N->getOperand(1);
5141 SDValue RHS = N->getOperand(2);
5142 EVT VT = N->getValueType(0);
5143 int NumElems = VT.getVectorNumElements();
5144 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5145 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5146 Cond.getOpcode() == ISD::BUILD_VECTOR);
5148 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5149 // binary ones here.
5150 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5153 // We're sure we have an even number of elements due to the
5154 // concat_vectors we have as arguments to vselect.
5155 // Skip BV elements until we find one that's not an UNDEF
5156 // After we find an UNDEF element, keep looping until we get to half the
5157 // length of the BV and see if all the non-undef nodes are the same.
5158 ConstantSDNode *BottomHalf = nullptr;
5159 for (int i = 0; i < NumElems / 2; ++i) {
5160 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5163 if (BottomHalf == nullptr)
5164 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5165 else if (Cond->getOperand(i).getNode() != BottomHalf)
5169 // Do the same for the second half of the BuildVector
5170 ConstantSDNode *TopHalf = nullptr;
5171 for (int i = NumElems / 2; i < NumElems; ++i) {
5172 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5175 if (TopHalf == nullptr)
5176 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5177 else if (Cond->getOperand(i).getNode() != TopHalf)
5181 assert(TopHalf && BottomHalf &&
5182 "One half of the selector was all UNDEFs and the other was all the "
5183 "same value. This should have been addressed before this function.");
5185 ISD::CONCAT_VECTORS, dl, VT,
5186 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5187 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5190 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5192 if (Level >= AfterLegalizeTypes)
5195 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5196 SDValue Mask = MSC->getMask();
5197 SDValue Data = MSC->getValue();
5200 // If the MSCATTER data type requires splitting and the mask is provided by a
5201 // SETCC, then split both nodes and its operands before legalization. This
5202 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5203 // and enables future optimizations (e.g. min/max pattern matching on X86).
5204 if (Mask.getOpcode() != ISD::SETCC)
5207 // Check if any splitting is required.
5208 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5209 TargetLowering::TypeSplitVector)
5211 SDValue MaskLo, MaskHi, Lo, Hi;
5212 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5215 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5217 SDValue Chain = MSC->getChain();
5219 EVT MemoryVT = MSC->getMemoryVT();
5220 unsigned Alignment = MSC->getOriginalAlignment();
5222 EVT LoMemVT, HiMemVT;
5223 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5225 SDValue DataLo, DataHi;
5226 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5228 SDValue BasePtr = MSC->getBasePtr();
5229 SDValue IndexLo, IndexHi;
5230 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5232 MachineMemOperand *MMO = DAG.getMachineFunction().
5233 getMachineMemOperand(MSC->getPointerInfo(),
5234 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5235 Alignment, MSC->getAAInfo(), MSC->getRanges());
5237 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5238 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5241 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5242 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5245 AddToWorklist(Lo.getNode());
5246 AddToWorklist(Hi.getNode());
5248 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5251 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5253 if (Level >= AfterLegalizeTypes)
5256 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5257 SDValue Mask = MST->getMask();
5258 SDValue Data = MST->getValue();
5261 // If the MSTORE data type requires splitting and the mask is provided by a
5262 // SETCC, then split both nodes and its operands before legalization. This
5263 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5264 // and enables future optimizations (e.g. min/max pattern matching on X86).
5265 if (Mask.getOpcode() == ISD::SETCC) {
5267 // Check if any splitting is required.
5268 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5269 TargetLowering::TypeSplitVector)
5272 SDValue MaskLo, MaskHi, Lo, Hi;
5273 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5276 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5278 SDValue Chain = MST->getChain();
5279 SDValue Ptr = MST->getBasePtr();
5281 EVT MemoryVT = MST->getMemoryVT();
5282 unsigned Alignment = MST->getOriginalAlignment();
5284 // if Alignment is equal to the vector size,
5285 // take the half of it for the second part
5286 unsigned SecondHalfAlignment =
5287 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5288 Alignment/2 : Alignment;
5290 EVT LoMemVT, HiMemVT;
5291 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5293 SDValue DataLo, DataHi;
5294 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5296 MachineMemOperand *MMO = DAG.getMachineFunction().
5297 getMachineMemOperand(MST->getPointerInfo(),
5298 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5299 Alignment, MST->getAAInfo(), MST->getRanges());
5301 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5302 MST->isTruncatingStore());
5304 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5305 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5306 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5308 MMO = DAG.getMachineFunction().
5309 getMachineMemOperand(MST->getPointerInfo(),
5310 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5311 SecondHalfAlignment, MST->getAAInfo(),
5314 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5315 MST->isTruncatingStore());
5317 AddToWorklist(Lo.getNode());
5318 AddToWorklist(Hi.getNode());
5320 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5325 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5327 if (Level >= AfterLegalizeTypes)
5330 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5331 SDValue Mask = MGT->getMask();
5334 // If the MGATHER result requires splitting and the mask is provided by a
5335 // SETCC, then split both nodes and its operands before legalization. This
5336 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5337 // and enables future optimizations (e.g. min/max pattern matching on X86).
5339 if (Mask.getOpcode() != ISD::SETCC)
5342 EVT VT = N->getValueType(0);
5344 // Check if any splitting is required.
5345 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5346 TargetLowering::TypeSplitVector)
5349 SDValue MaskLo, MaskHi, Lo, Hi;
5350 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5352 SDValue Src0 = MGT->getValue();
5353 SDValue Src0Lo, Src0Hi;
5354 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5357 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5359 SDValue Chain = MGT->getChain();
5360 EVT MemoryVT = MGT->getMemoryVT();
5361 unsigned Alignment = MGT->getOriginalAlignment();
5363 EVT LoMemVT, HiMemVT;
5364 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5366 SDValue BasePtr = MGT->getBasePtr();
5367 SDValue Index = MGT->getIndex();
5368 SDValue IndexLo, IndexHi;
5369 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5371 MachineMemOperand *MMO = DAG.getMachineFunction().
5372 getMachineMemOperand(MGT->getPointerInfo(),
5373 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5374 Alignment, MGT->getAAInfo(), MGT->getRanges());
5376 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5377 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5380 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5381 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5384 AddToWorklist(Lo.getNode());
5385 AddToWorklist(Hi.getNode());
5387 // Build a factor node to remember that this load is independent of the
5389 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5392 // Legalized the chain result - switch anything that used the old chain to
5394 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5396 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5398 SDValue RetOps[] = { GatherRes, Chain };
5399 return DAG.getMergeValues(RetOps, DL);
5402 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5404 if (Level >= AfterLegalizeTypes)
5407 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5408 SDValue Mask = MLD->getMask();
5411 // If the MLOAD result requires splitting and the mask is provided by a
5412 // SETCC, then split both nodes and its operands before legalization. This
5413 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5414 // and enables future optimizations (e.g. min/max pattern matching on X86).
5416 if (Mask.getOpcode() == ISD::SETCC) {
5417 EVT VT = N->getValueType(0);
5419 // Check if any splitting is required.
5420 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5421 TargetLowering::TypeSplitVector)
5424 SDValue MaskLo, MaskHi, Lo, Hi;
5425 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5427 SDValue Src0 = MLD->getSrc0();
5428 SDValue Src0Lo, Src0Hi;
5429 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5432 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5434 SDValue Chain = MLD->getChain();
5435 SDValue Ptr = MLD->getBasePtr();
5436 EVT MemoryVT = MLD->getMemoryVT();
5437 unsigned Alignment = MLD->getOriginalAlignment();
5439 // if Alignment is equal to the vector size,
5440 // take the half of it for the second part
5441 unsigned SecondHalfAlignment =
5442 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5443 Alignment/2 : Alignment;
5445 EVT LoMemVT, HiMemVT;
5446 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5448 MachineMemOperand *MMO = DAG.getMachineFunction().
5449 getMachineMemOperand(MLD->getPointerInfo(),
5450 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5451 Alignment, MLD->getAAInfo(), MLD->getRanges());
5453 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5456 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5457 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5458 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5460 MMO = DAG.getMachineFunction().
5461 getMachineMemOperand(MLD->getPointerInfo(),
5462 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5463 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5465 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5468 AddToWorklist(Lo.getNode());
5469 AddToWorklist(Hi.getNode());
5471 // Build a factor node to remember that this load is independent of the
5473 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5476 // Legalized the chain result - switch anything that used the old chain to
5478 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5480 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5482 SDValue RetOps[] = { LoadRes, Chain };
5483 return DAG.getMergeValues(RetOps, DL);
5488 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5489 SDValue N0 = N->getOperand(0);
5490 SDValue N1 = N->getOperand(1);
5491 SDValue N2 = N->getOperand(2);
5494 // Canonicalize integer abs.
5495 // vselect (setg[te] X, 0), X, -X ->
5496 // vselect (setgt X, -1), X, -X ->
5497 // vselect (setl[te] X, 0), -X, X ->
5498 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5499 if (N0.getOpcode() == ISD::SETCC) {
5500 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5501 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5503 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5505 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5506 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5507 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5508 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5509 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5510 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5511 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5514 EVT VT = LHS.getValueType();
5515 SDValue Shift = DAG.getNode(
5516 ISD::SRA, DL, VT, LHS,
5517 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5518 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5519 AddToWorklist(Shift.getNode());
5520 AddToWorklist(Add.getNode());
5521 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5525 if (SimplifySelectOps(N, N1, N2))
5526 return SDValue(N, 0); // Don't revisit N.
5528 // If the VSELECT result requires splitting and the mask is provided by a
5529 // SETCC, then split both nodes and its operands before legalization. This
5530 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5531 // and enables future optimizations (e.g. min/max pattern matching on X86).
5532 if (N0.getOpcode() == ISD::SETCC) {
5533 EVT VT = N->getValueType(0);
5535 // Check if any splitting is required.
5536 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5537 TargetLowering::TypeSplitVector)
5540 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5541 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5542 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5543 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5545 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5546 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5548 // Add the new VSELECT nodes to the work list in case they need to be split
5550 AddToWorklist(Lo.getNode());
5551 AddToWorklist(Hi.getNode());
5553 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5556 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5557 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5559 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5560 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5563 // The ConvertSelectToConcatVector function is assuming both the above
5564 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5566 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5567 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5568 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5569 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5576 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5577 SDValue N0 = N->getOperand(0);
5578 SDValue N1 = N->getOperand(1);
5579 SDValue N2 = N->getOperand(2);
5580 SDValue N3 = N->getOperand(3);
5581 SDValue N4 = N->getOperand(4);
5582 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5584 // fold select_cc lhs, rhs, x, x, cc -> x
5588 // Determine if the condition we're dealing with is constant
5589 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5590 N0, N1, CC, SDLoc(N), false);
5591 if (SCC.getNode()) {
5592 AddToWorklist(SCC.getNode());
5594 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5595 if (!SCCC->isNullValue())
5596 return N2; // cond always true -> true val
5598 return N3; // cond always false -> false val
5599 } else if (SCC->getOpcode() == ISD::UNDEF) {
5600 // When the condition is UNDEF, just return the first operand. This is
5601 // coherent the DAG creation, no setcc node is created in this case
5603 } else if (SCC.getOpcode() == ISD::SETCC) {
5604 // Fold to a simpler select_cc
5605 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5606 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5611 // If we can fold this based on the true/false value, do so.
5612 if (SimplifySelectOps(N, N2, N3))
5613 return SDValue(N, 0); // Don't revisit N.
5615 // fold select_cc into other things, such as min/max/abs
5616 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5619 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5620 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5621 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5625 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5626 /// a build_vector of constants.
5627 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5628 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5629 /// Vector extends are not folded if operations are legal; this is to
5630 /// avoid introducing illegal build_vector dag nodes.
5631 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5632 SelectionDAG &DAG, bool LegalTypes,
5633 bool LegalOperations) {
5634 unsigned Opcode = N->getOpcode();
5635 SDValue N0 = N->getOperand(0);
5636 EVT VT = N->getValueType(0);
5638 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5639 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5640 && "Expected EXTEND dag node in input!");
5642 // fold (sext c1) -> c1
5643 // fold (zext c1) -> c1
5644 // fold (aext c1) -> c1
5645 if (isa<ConstantSDNode>(N0))
5646 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5648 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5649 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5650 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5651 EVT SVT = VT.getScalarType();
5652 if (!(VT.isVector() &&
5653 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5654 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5657 // We can fold this node into a build_vector.
5658 unsigned VTBits = SVT.getSizeInBits();
5659 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5660 SmallVector<SDValue, 8> Elts;
5661 unsigned NumElts = VT.getVectorNumElements();
5664 for (unsigned i=0; i != NumElts; ++i) {
5665 SDValue Op = N0->getOperand(i);
5666 if (Op->getOpcode() == ISD::UNDEF) {
5667 Elts.push_back(DAG.getUNDEF(SVT));
5672 // Get the constant value and if needed trunc it to the size of the type.
5673 // Nodes like build_vector might have constants wider than the scalar type.
5674 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5675 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5676 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5678 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5681 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5684 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5685 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5686 // transformation. Returns true if extension are possible and the above
5687 // mentioned transformation is profitable.
5688 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5690 SmallVectorImpl<SDNode *> &ExtendNodes,
5691 const TargetLowering &TLI) {
5692 bool HasCopyToRegUses = false;
5693 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5694 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5695 UE = N0.getNode()->use_end();
5700 if (UI.getUse().getResNo() != N0.getResNo())
5702 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5703 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5704 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5705 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5706 // Sign bits will be lost after a zext.
5709 for (unsigned i = 0; i != 2; ++i) {
5710 SDValue UseOp = User->getOperand(i);
5713 if (!isa<ConstantSDNode>(UseOp))
5718 ExtendNodes.push_back(User);
5721 // If truncates aren't free and there are users we can't
5722 // extend, it isn't worthwhile.
5725 // Remember if this value is live-out.
5726 if (User->getOpcode() == ISD::CopyToReg)
5727 HasCopyToRegUses = true;
5730 if (HasCopyToRegUses) {
5731 bool BothLiveOut = false;
5732 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5734 SDUse &Use = UI.getUse();
5735 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5741 // Both unextended and extended values are live out. There had better be
5742 // a good reason for the transformation.
5743 return ExtendNodes.size();
5748 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5749 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5750 ISD::NodeType ExtType) {
5751 // Extend SetCC uses if necessary.
5752 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5753 SDNode *SetCC = SetCCs[i];
5754 SmallVector<SDValue, 4> Ops;
5756 for (unsigned j = 0; j != 2; ++j) {
5757 SDValue SOp = SetCC->getOperand(j);
5759 Ops.push_back(ExtLoad);
5761 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5764 Ops.push_back(SetCC->getOperand(2));
5765 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5769 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5770 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5771 SDValue N0 = N->getOperand(0);
5772 EVT DstVT = N->getValueType(0);
5773 EVT SrcVT = N0.getValueType();
5775 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5776 N->getOpcode() == ISD::ZERO_EXTEND) &&
5777 "Unexpected node type (not an extend)!");
5779 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5780 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5781 // (v8i32 (sext (v8i16 (load x))))
5783 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5784 // (v4i32 (sextload (x + 16)))))
5785 // Where uses of the original load, i.e.:
5787 // are replaced with:
5789 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5790 // (v4i32 (sextload (x + 16)))))))
5792 // This combine is only applicable to illegal, but splittable, vectors.
5793 // All legal types, and illegal non-vector types, are handled elsewhere.
5794 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5796 if (N0->getOpcode() != ISD::LOAD)
5799 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5801 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5802 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5803 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5806 SmallVector<SDNode *, 4> SetCCs;
5807 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5810 ISD::LoadExtType ExtType =
5811 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5813 // Try to split the vector types to get down to legal types.
5814 EVT SplitSrcVT = SrcVT;
5815 EVT SplitDstVT = DstVT;
5816 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5817 SplitSrcVT.getVectorNumElements() > 1) {
5818 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5819 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5822 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5826 const unsigned NumSplits =
5827 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5828 const unsigned Stride = SplitSrcVT.getStoreSize();
5829 SmallVector<SDValue, 4> Loads;
5830 SmallVector<SDValue, 4> Chains;
5832 SDValue BasePtr = LN0->getBasePtr();
5833 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5834 const unsigned Offset = Idx * Stride;
5835 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5837 SDValue SplitLoad = DAG.getExtLoad(
5838 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5839 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5840 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5841 Align, LN0->getAAInfo());
5843 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5844 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5846 Loads.push_back(SplitLoad.getValue(0));
5847 Chains.push_back(SplitLoad.getValue(1));
5850 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5851 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5853 CombineTo(N, NewValue);
5855 // Replace uses of the original load (before extension)
5856 // with a truncate of the concatenated sextloaded vectors.
5858 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5859 CombineTo(N0.getNode(), Trunc, NewChain);
5860 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5861 (ISD::NodeType)N->getOpcode());
5862 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5865 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5866 SDValue N0 = N->getOperand(0);
5867 EVT VT = N->getValueType(0);
5869 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5871 return SDValue(Res, 0);
5873 // fold (sext (sext x)) -> (sext x)
5874 // fold (sext (aext x)) -> (sext x)
5875 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5876 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5879 if (N0.getOpcode() == ISD::TRUNCATE) {
5880 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5881 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5882 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5883 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5884 if (NarrowLoad.getNode() != N0.getNode()) {
5885 CombineTo(N0.getNode(), NarrowLoad);
5886 // CombineTo deleted the truncate, if needed, but not what's under it.
5889 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5892 // See if the value being truncated is already sign extended. If so, just
5893 // eliminate the trunc/sext pair.
5894 SDValue Op = N0.getOperand(0);
5895 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5896 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5897 unsigned DestBits = VT.getScalarType().getSizeInBits();
5898 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5900 if (OpBits == DestBits) {
5901 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5902 // bits, it is already ready.
5903 if (NumSignBits > DestBits-MidBits)
5905 } else if (OpBits < DestBits) {
5906 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5907 // bits, just sext from i32.
5908 if (NumSignBits > OpBits-MidBits)
5909 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5911 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5912 // bits, just truncate to i32.
5913 if (NumSignBits > OpBits-MidBits)
5914 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5917 // fold (sext (truncate x)) -> (sextinreg x).
5918 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5919 N0.getValueType())) {
5920 if (OpBits < DestBits)
5921 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5922 else if (OpBits > DestBits)
5923 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5924 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5925 DAG.getValueType(N0.getValueType()));
5929 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5930 // Only generate vector extloads when 1) they're legal, and 2) they are
5931 // deemed desirable by the target.
5932 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5933 ((!LegalOperations && !VT.isVector() &&
5934 !cast<LoadSDNode>(N0)->isVolatile()) ||
5935 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5936 bool DoXform = true;
5937 SmallVector<SDNode*, 4> SetCCs;
5938 if (!N0.hasOneUse())
5939 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5941 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5943 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5944 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5946 LN0->getBasePtr(), N0.getValueType(),
5947 LN0->getMemOperand());
5948 CombineTo(N, ExtLoad);
5949 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5950 N0.getValueType(), ExtLoad);
5951 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5952 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5954 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5958 // fold (sext (load x)) to multiple smaller sextloads.
5959 // Only on illegal but splittable vectors.
5960 if (SDValue ExtLoad = CombineExtLoad(N))
5963 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5964 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5965 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5966 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5967 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5968 EVT MemVT = LN0->getMemoryVT();
5969 if ((!LegalOperations && !LN0->isVolatile()) ||
5970 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5971 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5973 LN0->getBasePtr(), MemVT,
5974 LN0->getMemOperand());
5975 CombineTo(N, ExtLoad);
5976 CombineTo(N0.getNode(),
5977 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5978 N0.getValueType(), ExtLoad),
5979 ExtLoad.getValue(1));
5980 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5984 // fold (sext (and/or/xor (load x), cst)) ->
5985 // (and/or/xor (sextload x), (sext cst))
5986 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5987 N0.getOpcode() == ISD::XOR) &&
5988 isa<LoadSDNode>(N0.getOperand(0)) &&
5989 N0.getOperand(1).getOpcode() == ISD::Constant &&
5990 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5991 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5992 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5993 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5994 bool DoXform = true;
5995 SmallVector<SDNode*, 4> SetCCs;
5996 if (!N0.hasOneUse())
5997 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6000 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6001 LN0->getChain(), LN0->getBasePtr(),
6003 LN0->getMemOperand());
6004 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6005 Mask = Mask.sext(VT.getSizeInBits());
6007 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6008 ExtLoad, DAG.getConstant(Mask, DL, VT));
6009 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6010 SDLoc(N0.getOperand(0)),
6011 N0.getOperand(0).getValueType(), ExtLoad);
6013 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6014 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6016 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6021 if (N0.getOpcode() == ISD::SETCC) {
6022 EVT N0VT = N0.getOperand(0).getValueType();
6023 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6024 // Only do this before legalize for now.
6025 if (VT.isVector() && !LegalOperations &&
6026 TLI.getBooleanContents(N0VT) ==
6027 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6028 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6029 // of the same size as the compared operands. Only optimize sext(setcc())
6030 // if this is the case.
6031 EVT SVT = getSetCCResultType(N0VT);
6033 // We know that the # elements of the results is the same as the
6034 // # elements of the compare (and the # elements of the compare result
6035 // for that matter). Check to see that they are the same size. If so,
6036 // we know that the element size of the sext'd result matches the
6037 // element size of the compare operands.
6038 if (VT.getSizeInBits() == SVT.getSizeInBits())
6039 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6041 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6043 // If the desired elements are smaller or larger than the source
6044 // elements we can use a matching integer vector type and then
6045 // truncate/sign extend
6046 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6047 if (SVT == MatchingVectorType) {
6048 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6049 N0.getOperand(0), N0.getOperand(1),
6050 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6051 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6055 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6056 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6059 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6061 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6062 NegOne, DAG.getConstant(0, DL, VT),
6063 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6064 if (SCC.getNode()) return SCC;
6066 if (!VT.isVector()) {
6067 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6068 if (!LegalOperations ||
6069 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6071 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6072 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6073 N0.getOperand(0), N0.getOperand(1), CC);
6074 return DAG.getSelect(DL, VT, SetCC,
6075 NegOne, DAG.getConstant(0, DL, VT));
6080 // fold (sext x) -> (zext x) if the sign bit is known zero.
6081 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6082 DAG.SignBitIsZero(N0))
6083 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6088 // isTruncateOf - If N is a truncate of some other value, return true, record
6089 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6090 // This function computes KnownZero to avoid a duplicated call to
6091 // computeKnownBits in the caller.
6092 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6095 if (N->getOpcode() == ISD::TRUNCATE) {
6096 Op = N->getOperand(0);
6097 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6101 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6102 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6105 SDValue Op0 = N->getOperand(0);
6106 SDValue Op1 = N->getOperand(1);
6107 assert(Op0.getValueType() == Op1.getValueType());
6109 if (isNullConstant(Op0))
6111 else if (isNullConstant(Op1))
6116 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6118 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6124 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6125 SDValue N0 = N->getOperand(0);
6126 EVT VT = N->getValueType(0);
6128 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6130 return SDValue(Res, 0);
6132 // fold (zext (zext x)) -> (zext x)
6133 // fold (zext (aext x)) -> (zext x)
6134 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6135 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6138 // fold (zext (truncate x)) -> (zext x) or
6139 // (zext (truncate x)) -> (truncate x)
6140 // This is valid when the truncated bits of x are already zero.
6141 // FIXME: We should extend this to work for vectors too.
6144 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6145 APInt TruncatedBits =
6146 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6147 APInt(Op.getValueSizeInBits(), 0) :
6148 APInt::getBitsSet(Op.getValueSizeInBits(),
6149 N0.getValueSizeInBits(),
6150 std::min(Op.getValueSizeInBits(),
6151 VT.getSizeInBits()));
6152 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6153 if (VT.bitsGT(Op.getValueType()))
6154 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6155 if (VT.bitsLT(Op.getValueType()))
6156 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6162 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6163 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6164 if (N0.getOpcode() == ISD::TRUNCATE) {
6165 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6166 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6167 if (NarrowLoad.getNode() != N0.getNode()) {
6168 CombineTo(N0.getNode(), NarrowLoad);
6169 // CombineTo deleted the truncate, if needed, but not what's under it.
6172 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6176 // fold (zext (truncate x)) -> (and x, mask)
6177 if (N0.getOpcode() == ISD::TRUNCATE) {
6178 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6179 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6180 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6181 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6182 if (NarrowLoad.getNode() != N0.getNode()) {
6183 CombineTo(N0.getNode(), NarrowLoad);
6184 // CombineTo deleted the truncate, if needed, but not what's under it.
6187 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6190 EVT SrcVT = N0.getOperand(0).getValueType();
6191 EVT MinVT = N0.getValueType();
6193 // Try to mask before the extension to avoid having to generate a larger mask,
6194 // possibly over several sub-vectors.
6195 if (SrcVT.bitsLT(VT)) {
6196 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6197 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6198 SDValue Op = N0.getOperand(0);
6199 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6200 AddToWorklist(Op.getNode());
6201 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6205 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6206 SDValue Op = N0.getOperand(0);
6207 if (SrcVT.bitsLT(VT)) {
6208 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6209 AddToWorklist(Op.getNode());
6210 } else if (SrcVT.bitsGT(VT)) {
6211 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6212 AddToWorklist(Op.getNode());
6214 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6218 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6219 // if either of the casts is not free.
6220 if (N0.getOpcode() == ISD::AND &&
6221 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6222 N0.getOperand(1).getOpcode() == ISD::Constant &&
6223 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6224 N0.getValueType()) ||
6225 !TLI.isZExtFree(N0.getValueType(), VT))) {
6226 SDValue X = N0.getOperand(0).getOperand(0);
6227 if (X.getValueType().bitsLT(VT)) {
6228 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6229 } else if (X.getValueType().bitsGT(VT)) {
6230 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6232 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6233 Mask = Mask.zext(VT.getSizeInBits());
6235 return DAG.getNode(ISD::AND, DL, VT,
6236 X, DAG.getConstant(Mask, DL, VT));
6239 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6240 // Only generate vector extloads when 1) they're legal, and 2) they are
6241 // deemed desirable by the target.
6242 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6243 ((!LegalOperations && !VT.isVector() &&
6244 !cast<LoadSDNode>(N0)->isVolatile()) ||
6245 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6246 bool DoXform = true;
6247 SmallVector<SDNode*, 4> SetCCs;
6248 if (!N0.hasOneUse())
6249 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6251 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6253 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6254 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6256 LN0->getBasePtr(), N0.getValueType(),
6257 LN0->getMemOperand());
6258 CombineTo(N, ExtLoad);
6259 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6260 N0.getValueType(), ExtLoad);
6261 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6263 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6265 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6269 // fold (zext (load x)) to multiple smaller zextloads.
6270 // Only on illegal but splittable vectors.
6271 if (SDValue ExtLoad = CombineExtLoad(N))
6274 // fold (zext (and/or/xor (load x), cst)) ->
6275 // (and/or/xor (zextload x), (zext cst))
6276 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6277 N0.getOpcode() == ISD::XOR) &&
6278 isa<LoadSDNode>(N0.getOperand(0)) &&
6279 N0.getOperand(1).getOpcode() == ISD::Constant &&
6280 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6281 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6282 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6283 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6284 bool DoXform = true;
6285 SmallVector<SDNode*, 4> SetCCs;
6286 if (!N0.hasOneUse())
6287 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6290 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6291 LN0->getChain(), LN0->getBasePtr(),
6293 LN0->getMemOperand());
6294 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6295 Mask = Mask.zext(VT.getSizeInBits());
6297 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6298 ExtLoad, DAG.getConstant(Mask, DL, VT));
6299 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6300 SDLoc(N0.getOperand(0)),
6301 N0.getOperand(0).getValueType(), ExtLoad);
6303 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6304 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6306 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6311 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6312 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6313 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6314 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6315 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6316 EVT MemVT = LN0->getMemoryVT();
6317 if ((!LegalOperations && !LN0->isVolatile()) ||
6318 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6319 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6321 LN0->getBasePtr(), MemVT,
6322 LN0->getMemOperand());
6323 CombineTo(N, ExtLoad);
6324 CombineTo(N0.getNode(),
6325 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6327 ExtLoad.getValue(1));
6328 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6332 if (N0.getOpcode() == ISD::SETCC) {
6333 if (!LegalOperations && VT.isVector() &&
6334 N0.getValueType().getVectorElementType() == MVT::i1) {
6335 EVT N0VT = N0.getOperand(0).getValueType();
6336 if (getSetCCResultType(N0VT) == N0.getValueType())
6339 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6340 // Only do this before legalize for now.
6341 EVT EltVT = VT.getVectorElementType();
6343 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6344 DAG.getConstant(1, DL, EltVT));
6345 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6346 // We know that the # elements of the results is the same as the
6347 // # elements of the compare (and the # elements of the compare result
6348 // for that matter). Check to see that they are the same size. If so,
6349 // we know that the element size of the sext'd result matches the
6350 // element size of the compare operands.
6351 return DAG.getNode(ISD::AND, DL, VT,
6352 DAG.getSetCC(DL, VT, N0.getOperand(0),
6354 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6355 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6358 // If the desired elements are smaller or larger than the source
6359 // elements we can use a matching integer vector type and then
6360 // truncate/sign extend
6361 EVT MatchingElementType =
6362 EVT::getIntegerVT(*DAG.getContext(),
6363 N0VT.getScalarType().getSizeInBits());
6364 EVT MatchingVectorType =
6365 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6366 N0VT.getVectorNumElements());
6368 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6370 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6371 return DAG.getNode(ISD::AND, DL, VT,
6372 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6373 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6376 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6379 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6380 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6381 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6382 if (SCC.getNode()) return SCC;
6385 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6386 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6387 isa<ConstantSDNode>(N0.getOperand(1)) &&
6388 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6390 SDValue ShAmt = N0.getOperand(1);
6391 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6392 if (N0.getOpcode() == ISD::SHL) {
6393 SDValue InnerZExt = N0.getOperand(0);
6394 // If the original shl may be shifting out bits, do not perform this
6396 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6397 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6398 if (ShAmtVal > KnownZeroBits)
6404 // Ensure that the shift amount is wide enough for the shifted value.
6405 if (VT.getSizeInBits() >= 256)
6406 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6408 return DAG.getNode(N0.getOpcode(), DL, VT,
6409 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6416 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6417 SDValue N0 = N->getOperand(0);
6418 EVT VT = N->getValueType(0);
6420 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6422 return SDValue(Res, 0);
6424 // fold (aext (aext x)) -> (aext x)
6425 // fold (aext (zext x)) -> (zext x)
6426 // fold (aext (sext x)) -> (sext x)
6427 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6428 N0.getOpcode() == ISD::ZERO_EXTEND ||
6429 N0.getOpcode() == ISD::SIGN_EXTEND)
6430 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6432 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6433 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6434 if (N0.getOpcode() == ISD::TRUNCATE) {
6435 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6436 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6437 if (NarrowLoad.getNode() != N0.getNode()) {
6438 CombineTo(N0.getNode(), NarrowLoad);
6439 // CombineTo deleted the truncate, if needed, but not what's under it.
6442 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6446 // fold (aext (truncate x))
6447 if (N0.getOpcode() == ISD::TRUNCATE) {
6448 SDValue TruncOp = N0.getOperand(0);
6449 if (TruncOp.getValueType() == VT)
6450 return TruncOp; // x iff x size == zext size.
6451 if (TruncOp.getValueType().bitsGT(VT))
6452 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6453 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6456 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6457 // if the trunc is not free.
6458 if (N0.getOpcode() == ISD::AND &&
6459 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6460 N0.getOperand(1).getOpcode() == ISD::Constant &&
6461 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6462 N0.getValueType())) {
6463 SDValue X = N0.getOperand(0).getOperand(0);
6464 if (X.getValueType().bitsLT(VT)) {
6465 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6466 } else if (X.getValueType().bitsGT(VT)) {
6467 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6469 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6470 Mask = Mask.zext(VT.getSizeInBits());
6472 return DAG.getNode(ISD::AND, DL, VT,
6473 X, DAG.getConstant(Mask, DL, VT));
6476 // fold (aext (load x)) -> (aext (truncate (extload x)))
6477 // None of the supported targets knows how to perform load and any_ext
6478 // on vectors in one instruction. We only perform this transformation on
6480 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6481 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6482 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6483 bool DoXform = true;
6484 SmallVector<SDNode*, 4> SetCCs;
6485 if (!N0.hasOneUse())
6486 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6488 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6489 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6491 LN0->getBasePtr(), N0.getValueType(),
6492 LN0->getMemOperand());
6493 CombineTo(N, ExtLoad);
6494 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6495 N0.getValueType(), ExtLoad);
6496 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6497 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6499 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6503 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6504 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6505 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6506 if (N0.getOpcode() == ISD::LOAD &&
6507 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6509 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6510 ISD::LoadExtType ExtType = LN0->getExtensionType();
6511 EVT MemVT = LN0->getMemoryVT();
6512 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6513 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6514 VT, LN0->getChain(), LN0->getBasePtr(),
6515 MemVT, LN0->getMemOperand());
6516 CombineTo(N, ExtLoad);
6517 CombineTo(N0.getNode(),
6518 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6519 N0.getValueType(), ExtLoad),
6520 ExtLoad.getValue(1));
6521 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6525 if (N0.getOpcode() == ISD::SETCC) {
6527 // aext(setcc) -> vsetcc
6528 // aext(setcc) -> truncate(vsetcc)
6529 // aext(setcc) -> aext(vsetcc)
6530 // Only do this before legalize for now.
6531 if (VT.isVector() && !LegalOperations) {
6532 EVT N0VT = N0.getOperand(0).getValueType();
6533 // We know that the # elements of the results is the same as the
6534 // # elements of the compare (and the # elements of the compare result
6535 // for that matter). Check to see that they are the same size. If so,
6536 // we know that the element size of the sext'd result matches the
6537 // element size of the compare operands.
6538 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6539 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6541 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6542 // If the desired elements are smaller or larger than the source
6543 // elements we can use a matching integer vector type and then
6544 // truncate/any extend
6546 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6548 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6550 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6551 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6555 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6558 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6559 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6560 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6568 /// See if the specified operand can be simplified with the knowledge that only
6569 /// the bits specified by Mask are used. If so, return the simpler operand,
6570 /// otherwise return a null SDValue.
6571 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6572 switch (V.getOpcode()) {
6574 case ISD::Constant: {
6575 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6576 assert(CV && "Const value should be ConstSDNode.");
6577 const APInt &CVal = CV->getAPIntValue();
6578 APInt NewVal = CVal & Mask;
6580 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6585 // If the LHS or RHS don't contribute bits to the or, drop them.
6586 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6587 return V.getOperand(1);
6588 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6589 return V.getOperand(0);
6592 // Only look at single-use SRLs.
6593 if (!V.getNode()->hasOneUse())
6595 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6596 // See if we can recursively simplify the LHS.
6597 unsigned Amt = RHSC->getZExtValue();
6599 // Watch out for shift count overflow though.
6600 if (Amt >= Mask.getBitWidth()) break;
6601 APInt NewMask = Mask << Amt;
6602 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6603 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6604 SimplifyLHS, V.getOperand(1));
6610 /// If the result of a wider load is shifted to right of N bits and then
6611 /// truncated to a narrower type and where N is a multiple of number of bits of
6612 /// the narrower type, transform it to a narrower load from address + N / num of
6613 /// bits of new type. If the result is to be extended, also fold the extension
6614 /// to form a extending load.
6615 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6616 unsigned Opc = N->getOpcode();
6618 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6619 SDValue N0 = N->getOperand(0);
6620 EVT VT = N->getValueType(0);
6623 // This transformation isn't valid for vector loads.
6627 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6629 if (Opc == ISD::SIGN_EXTEND_INREG) {
6630 ExtType = ISD::SEXTLOAD;
6631 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6632 } else if (Opc == ISD::SRL) {
6633 // Another special-case: SRL is basically zero-extending a narrower value.
6634 ExtType = ISD::ZEXTLOAD;
6636 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6637 if (!N01) return SDValue();
6638 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6639 VT.getSizeInBits() - N01->getZExtValue());
6641 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6644 unsigned EVTBits = ExtVT.getSizeInBits();
6646 // Do not generate loads of non-round integer types since these can
6647 // be expensive (and would be wrong if the type is not byte sized).
6648 if (!ExtVT.isRound())
6652 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6653 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6654 ShAmt = N01->getZExtValue();
6655 // Is the shift amount a multiple of size of VT?
6656 if ((ShAmt & (EVTBits-1)) == 0) {
6657 N0 = N0.getOperand(0);
6658 // Is the load width a multiple of size of VT?
6659 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6663 // At this point, we must have a load or else we can't do the transform.
6664 if (!isa<LoadSDNode>(N0)) return SDValue();
6666 // Because a SRL must be assumed to *need* to zero-extend the high bits
6667 // (as opposed to anyext the high bits), we can't combine the zextload
6668 // lowering of SRL and an sextload.
6669 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6672 // If the shift amount is larger than the input type then we're not
6673 // accessing any of the loaded bytes. If the load was a zextload/extload
6674 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6675 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6680 // If the load is shifted left (and the result isn't shifted back right),
6681 // we can fold the truncate through the shift.
6682 unsigned ShLeftAmt = 0;
6683 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6684 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6685 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6686 ShLeftAmt = N01->getZExtValue();
6687 N0 = N0.getOperand(0);
6691 // If we haven't found a load, we can't narrow it. Don't transform one with
6692 // multiple uses, this would require adding a new load.
6693 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6696 // Don't change the width of a volatile load.
6697 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6698 if (LN0->isVolatile())
6701 // Verify that we are actually reducing a load width here.
6702 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6705 // For the transform to be legal, the load must produce only two values
6706 // (the value loaded and the chain). Don't transform a pre-increment
6707 // load, for example, which produces an extra value. Otherwise the
6708 // transformation is not equivalent, and the downstream logic to replace
6709 // uses gets things wrong.
6710 if (LN0->getNumValues() > 2)
6713 // If the load that we're shrinking is an extload and we're not just
6714 // discarding the extension we can't simply shrink the load. Bail.
6715 // TODO: It would be possible to merge the extensions in some cases.
6716 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6717 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6720 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6723 EVT PtrType = N0.getOperand(1).getValueType();
6725 if (PtrType == MVT::Untyped || PtrType.isExtended())
6726 // It's not possible to generate a constant of extended or untyped type.
6729 // For big endian targets, we need to adjust the offset to the pointer to
6730 // load the correct bytes.
6731 if (DAG.getDataLayout().isBigEndian()) {
6732 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6733 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6734 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6737 uint64_t PtrOff = ShAmt / 8;
6738 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6740 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6741 PtrType, LN0->getBasePtr(),
6742 DAG.getConstant(PtrOff, DL, PtrType));
6743 AddToWorklist(NewPtr.getNode());
6746 if (ExtType == ISD::NON_EXTLOAD)
6747 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6748 LN0->getPointerInfo().getWithOffset(PtrOff),
6749 LN0->isVolatile(), LN0->isNonTemporal(),
6750 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6752 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6753 LN0->getPointerInfo().getWithOffset(PtrOff),
6754 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6755 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6757 // Replace the old load's chain with the new load's chain.
6758 WorklistRemover DeadNodes(*this);
6759 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6761 // Shift the result left, if we've swallowed a left shift.
6762 SDValue Result = Load;
6763 if (ShLeftAmt != 0) {
6764 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6765 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6767 // If the shift amount is as large as the result size (but, presumably,
6768 // no larger than the source) then the useful bits of the result are
6769 // zero; we can't simply return the shortened shift, because the result
6770 // of that operation is undefined.
6772 if (ShLeftAmt >= VT.getSizeInBits())
6773 Result = DAG.getConstant(0, DL, VT);
6775 Result = DAG.getNode(ISD::SHL, DL, VT,
6776 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6779 // Return the new loaded value.
6783 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6784 SDValue N0 = N->getOperand(0);
6785 SDValue N1 = N->getOperand(1);
6786 EVT VT = N->getValueType(0);
6787 EVT EVT = cast<VTSDNode>(N1)->getVT();
6788 unsigned VTBits = VT.getScalarType().getSizeInBits();
6789 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6791 // fold (sext_in_reg c1) -> c1
6792 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6793 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6795 // If the input is already sign extended, just drop the extension.
6796 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6799 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6800 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6801 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6802 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6803 N0.getOperand(0), N1);
6805 // fold (sext_in_reg (sext x)) -> (sext x)
6806 // fold (sext_in_reg (aext x)) -> (sext x)
6807 // if x is small enough.
6808 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6809 SDValue N00 = N0.getOperand(0);
6810 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6811 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6812 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6815 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6816 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6817 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6819 // fold operands of sext_in_reg based on knowledge that the top bits are not
6821 if (SimplifyDemandedBits(SDValue(N, 0)))
6822 return SDValue(N, 0);
6824 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6825 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6826 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6829 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6830 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6831 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6832 if (N0.getOpcode() == ISD::SRL) {
6833 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6834 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6835 // We can turn this into an SRA iff the input to the SRL is already sign
6837 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6838 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6839 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6840 N0.getOperand(0), N0.getOperand(1));
6844 // fold (sext_inreg (extload x)) -> (sextload x)
6845 if (ISD::isEXTLoad(N0.getNode()) &&
6846 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6847 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6848 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6849 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6850 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6851 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6853 LN0->getBasePtr(), EVT,
6854 LN0->getMemOperand());
6855 CombineTo(N, ExtLoad);
6856 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6857 AddToWorklist(ExtLoad.getNode());
6858 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6860 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6861 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6863 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6864 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6865 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6866 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6867 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6869 LN0->getBasePtr(), EVT,
6870 LN0->getMemOperand());
6871 CombineTo(N, ExtLoad);
6872 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6873 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6876 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6877 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6878 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6879 N0.getOperand(1), false);
6880 if (BSwap.getNode())
6881 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6885 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6886 // into a build_vector.
6887 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6888 SmallVector<SDValue, 8> Elts;
6889 unsigned NumElts = N0->getNumOperands();
6890 unsigned ShAmt = VTBits - EVTBits;
6892 for (unsigned i = 0; i != NumElts; ++i) {
6893 SDValue Op = N0->getOperand(i);
6894 if (Op->getOpcode() == ISD::UNDEF) {
6899 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6900 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6901 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6902 SDLoc(Op), Op.getValueType()));
6905 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6911 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6912 SDValue N0 = N->getOperand(0);
6913 EVT VT = N->getValueType(0);
6915 if (N0.getOpcode() == ISD::UNDEF)
6916 return DAG.getUNDEF(VT);
6918 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6920 return SDValue(Res, 0);
6925 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6926 SDValue N0 = N->getOperand(0);
6927 EVT VT = N->getValueType(0);
6928 bool isLE = DAG.getDataLayout().isLittleEndian();
6931 if (N0.getValueType() == N->getValueType(0))
6933 // fold (truncate c1) -> c1
6934 if (isConstantIntBuildVectorOrConstantInt(N0))
6935 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6936 // fold (truncate (truncate x)) -> (truncate x)
6937 if (N0.getOpcode() == ISD::TRUNCATE)
6938 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6939 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6940 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6941 N0.getOpcode() == ISD::SIGN_EXTEND ||
6942 N0.getOpcode() == ISD::ANY_EXTEND) {
6943 if (N0.getOperand(0).getValueType().bitsLT(VT))
6944 // if the source is smaller than the dest, we still need an extend
6945 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6947 if (N0.getOperand(0).getValueType().bitsGT(VT))
6948 // if the source is larger than the dest, than we just need the truncate
6949 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6950 // if the source and dest are the same type, we can drop both the extend
6951 // and the truncate.
6952 return N0.getOperand(0);
6955 // Fold extract-and-trunc into a narrow extract. For example:
6956 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6957 // i32 y = TRUNCATE(i64 x)
6959 // v16i8 b = BITCAST (v2i64 val)
6960 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6962 // Note: We only run this optimization after type legalization (which often
6963 // creates this pattern) and before operation legalization after which
6964 // we need to be more careful about the vector instructions that we generate.
6965 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6966 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6968 EVT VecTy = N0.getOperand(0).getValueType();
6969 EVT ExTy = N0.getValueType();
6970 EVT TrTy = N->getValueType(0);
6972 unsigned NumElem = VecTy.getVectorNumElements();
6973 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6975 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6976 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6978 SDValue EltNo = N0->getOperand(1);
6979 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6980 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6981 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6982 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6984 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6985 NVT, N0.getOperand(0));
6988 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6990 DAG.getConstant(Index, DL, IndexTy));
6994 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6995 if (N0.getOpcode() == ISD::SELECT) {
6996 EVT SrcVT = N0.getValueType();
6997 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6998 TLI.isTruncateFree(SrcVT, VT)) {
7000 SDValue Cond = N0.getOperand(0);
7001 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7002 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7003 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7007 // Fold a series of buildvector, bitcast, and truncate if possible.
7009 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7010 // (2xi32 (buildvector x, y)).
7011 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7012 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7013 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7014 N0.getOperand(0).hasOneUse()) {
7016 SDValue BuildVect = N0.getOperand(0);
7017 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7018 EVT TruncVecEltTy = VT.getVectorElementType();
7020 // Check that the element types match.
7021 if (BuildVectEltTy == TruncVecEltTy) {
7022 // Now we only need to compute the offset of the truncated elements.
7023 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7024 unsigned TruncVecNumElts = VT.getVectorNumElements();
7025 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7027 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7028 "Invalid number of elements");
7030 SmallVector<SDValue, 8> Opnds;
7031 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7032 Opnds.push_back(BuildVect.getOperand(i));
7034 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7038 // See if we can simplify the input to this truncate through knowledge that
7039 // only the low bits are being used.
7040 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7041 // Currently we only perform this optimization on scalars because vectors
7042 // may have different active low bits.
7043 if (!VT.isVector()) {
7045 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7046 VT.getSizeInBits()));
7047 if (Shorter.getNode())
7048 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7050 // fold (truncate (load x)) -> (smaller load x)
7051 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7052 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7053 if (SDValue Reduced = ReduceLoadWidth(N))
7056 // Handle the case where the load remains an extending load even
7057 // after truncation.
7058 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7059 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7060 if (!LN0->isVolatile() &&
7061 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7062 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7063 VT, LN0->getChain(), LN0->getBasePtr(),
7065 LN0->getMemOperand());
7066 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7071 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7072 // where ... are all 'undef'.
7073 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7074 SmallVector<EVT, 8> VTs;
7077 unsigned NumDefs = 0;
7079 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7080 SDValue X = N0.getOperand(i);
7081 if (X.getOpcode() != ISD::UNDEF) {
7086 // Stop if more than one members are non-undef.
7089 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7090 VT.getVectorElementType(),
7091 X.getValueType().getVectorNumElements()));
7095 return DAG.getUNDEF(VT);
7098 assert(V.getNode() && "The single defined operand is empty!");
7099 SmallVector<SDValue, 8> Opnds;
7100 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7102 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7105 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7106 AddToWorklist(NV.getNode());
7107 Opnds.push_back(NV);
7109 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7113 // Simplify the operands using demanded-bits information.
7114 if (!VT.isVector() &&
7115 SimplifyDemandedBits(SDValue(N, 0)))
7116 return SDValue(N, 0);
7121 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7122 SDValue Elt = N->getOperand(i);
7123 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7124 return Elt.getNode();
7125 return Elt.getOperand(Elt.getResNo()).getNode();
7128 /// build_pair (load, load) -> load
7129 /// if load locations are consecutive.
7130 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7131 assert(N->getOpcode() == ISD::BUILD_PAIR);
7133 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7134 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7135 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7136 LD1->getAddressSpace() != LD2->getAddressSpace())
7138 EVT LD1VT = LD1->getValueType(0);
7140 if (ISD::isNON_EXTLoad(LD2) &&
7142 // If both are volatile this would reduce the number of volatile loads.
7143 // If one is volatile it might be ok, but play conservative and bail out.
7144 !LD1->isVolatile() &&
7145 !LD2->isVolatile() &&
7146 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7147 unsigned Align = LD1->getAlignment();
7148 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7149 VT.getTypeForEVT(*DAG.getContext()));
7151 if (NewAlign <= Align &&
7152 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7153 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7154 LD1->getBasePtr(), LD1->getPointerInfo(),
7155 false, false, false, Align);
7161 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7162 SDValue N0 = N->getOperand(0);
7163 EVT VT = N->getValueType(0);
7165 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7166 // Only do this before legalize, since afterward the target may be depending
7167 // on the bitconvert.
7168 // First check to see if this is all constant.
7170 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7172 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7174 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7175 assert(!DestEltVT.isVector() &&
7176 "Element type of vector ValueType must not be vector!");
7178 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7181 // If the input is a constant, let getNode fold it.
7182 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7183 // If we can't allow illegal operations, we need to check that this is just
7184 // a fp -> int or int -> conversion and that the resulting operation will
7186 if (!LegalOperations ||
7187 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7188 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7189 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7190 TLI.isOperationLegal(ISD::Constant, VT)))
7191 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7194 // (conv (conv x, t1), t2) -> (conv x, t2)
7195 if (N0.getOpcode() == ISD::BITCAST)
7196 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7199 // fold (conv (load x)) -> (load (conv*)x)
7200 // If the resultant load doesn't need a higher alignment than the original!
7201 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7202 // Do not change the width of a volatile load.
7203 !cast<LoadSDNode>(N0)->isVolatile() &&
7204 // Do not remove the cast if the types differ in endian layout.
7205 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7206 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7207 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7208 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7209 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7210 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7211 VT.getTypeForEVT(*DAG.getContext()));
7212 unsigned OrigAlign = LN0->getAlignment();
7214 if (Align <= OrigAlign) {
7215 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7216 LN0->getBasePtr(), LN0->getPointerInfo(),
7217 LN0->isVolatile(), LN0->isNonTemporal(),
7218 LN0->isInvariant(), OrigAlign,
7220 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7225 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7226 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7227 // This often reduces constant pool loads.
7228 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7229 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7230 N0.getNode()->hasOneUse() && VT.isInteger() &&
7231 !VT.isVector() && !N0.getValueType().isVector()) {
7232 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7234 AddToWorklist(NewConv.getNode());
7237 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7238 if (N0.getOpcode() == ISD::FNEG)
7239 return DAG.getNode(ISD::XOR, DL, VT,
7240 NewConv, DAG.getConstant(SignBit, DL, VT));
7241 assert(N0.getOpcode() == ISD::FABS);
7242 return DAG.getNode(ISD::AND, DL, VT,
7243 NewConv, DAG.getConstant(~SignBit, DL, VT));
7246 // fold (bitconvert (fcopysign cst, x)) ->
7247 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7248 // Note that we don't handle (copysign x, cst) because this can always be
7249 // folded to an fneg or fabs.
7250 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7251 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7252 VT.isInteger() && !VT.isVector()) {
7253 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7254 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7255 if (isTypeLegal(IntXVT)) {
7256 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7257 IntXVT, N0.getOperand(1));
7258 AddToWorklist(X.getNode());
7260 // If X has a different width than the result/lhs, sext it or truncate it.
7261 unsigned VTWidth = VT.getSizeInBits();
7262 if (OrigXWidth < VTWidth) {
7263 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7264 AddToWorklist(X.getNode());
7265 } else if (OrigXWidth > VTWidth) {
7266 // To get the sign bit in the right place, we have to shift it right
7267 // before truncating.
7269 X = DAG.getNode(ISD::SRL, DL,
7270 X.getValueType(), X,
7271 DAG.getConstant(OrigXWidth-VTWidth, DL,
7273 AddToWorklist(X.getNode());
7274 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7275 AddToWorklist(X.getNode());
7278 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7279 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7280 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7281 AddToWorklist(X.getNode());
7283 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7284 VT, N0.getOperand(0));
7285 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7286 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7287 AddToWorklist(Cst.getNode());
7289 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7293 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7294 if (N0.getOpcode() == ISD::BUILD_PAIR)
7295 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7298 // Remove double bitcasts from shuffles - this is often a legacy of
7299 // XformToShuffleWithZero being used to combine bitmaskings (of
7300 // float vectors bitcast to integer vectors) into shuffles.
7301 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7302 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7303 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7304 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7305 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7306 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7308 // If operands are a bitcast, peek through if it casts the original VT.
7309 // If operands are a constant, just bitcast back to original VT.
7310 auto PeekThroughBitcast = [&](SDValue Op) {
7311 if (Op.getOpcode() == ISD::BITCAST &&
7312 Op.getOperand(0).getValueType() == VT)
7313 return SDValue(Op.getOperand(0));
7314 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7315 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7316 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7320 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7321 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7326 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7327 SmallVector<int, 8> NewMask;
7328 for (int M : SVN->getMask())
7329 for (int i = 0; i != MaskScale; ++i)
7330 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7332 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7334 std::swap(SV0, SV1);
7335 ShuffleVectorSDNode::commuteMask(NewMask);
7336 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7340 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7346 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7347 EVT VT = N->getValueType(0);
7348 return CombineConsecutiveLoads(N, VT);
7351 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7352 /// operands. DstEltVT indicates the destination element value type.
7353 SDValue DAGCombiner::
7354 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7355 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7357 // If this is already the right type, we're done.
7358 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7360 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7361 unsigned DstBitSize = DstEltVT.getSizeInBits();
7363 // If this is a conversion of N elements of one type to N elements of another
7364 // type, convert each element. This handles FP<->INT cases.
7365 if (SrcBitSize == DstBitSize) {
7366 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7367 BV->getValueType(0).getVectorNumElements());
7369 // Due to the FP element handling below calling this routine recursively,
7370 // we can end up with a scalar-to-vector node here.
7371 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7372 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7373 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7374 DstEltVT, BV->getOperand(0)));
7376 SmallVector<SDValue, 8> Ops;
7377 for (SDValue Op : BV->op_values()) {
7378 // If the vector element type is not legal, the BUILD_VECTOR operands
7379 // are promoted and implicitly truncated. Make that explicit here.
7380 if (Op.getValueType() != SrcEltVT)
7381 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7382 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7384 AddToWorklist(Ops.back().getNode());
7386 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7389 // Otherwise, we're growing or shrinking the elements. To avoid having to
7390 // handle annoying details of growing/shrinking FP values, we convert them to
7392 if (SrcEltVT.isFloatingPoint()) {
7393 // Convert the input float vector to a int vector where the elements are the
7395 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7396 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7400 // Now we know the input is an integer vector. If the output is a FP type,
7401 // convert to integer first, then to FP of the right size.
7402 if (DstEltVT.isFloatingPoint()) {
7403 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7404 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7406 // Next, convert to FP elements of the same size.
7407 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7412 // Okay, we know the src/dst types are both integers of differing types.
7413 // Handling growing first.
7414 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7415 if (SrcBitSize < DstBitSize) {
7416 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7418 SmallVector<SDValue, 8> Ops;
7419 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7420 i += NumInputsPerOutput) {
7421 bool isLE = DAG.getDataLayout().isLittleEndian();
7422 APInt NewBits = APInt(DstBitSize, 0);
7423 bool EltIsUndef = true;
7424 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7425 // Shift the previously computed bits over.
7426 NewBits <<= SrcBitSize;
7427 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7428 if (Op.getOpcode() == ISD::UNDEF) continue;
7431 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7432 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7436 Ops.push_back(DAG.getUNDEF(DstEltVT));
7438 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7441 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7442 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7445 // Finally, this must be the case where we are shrinking elements: each input
7446 // turns into multiple outputs.
7447 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7448 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7449 NumOutputsPerInput*BV->getNumOperands());
7450 SmallVector<SDValue, 8> Ops;
7452 for (const SDValue &Op : BV->op_values()) {
7453 if (Op.getOpcode() == ISD::UNDEF) {
7454 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7458 APInt OpVal = cast<ConstantSDNode>(Op)->
7459 getAPIntValue().zextOrTrunc(SrcBitSize);
7461 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7462 APInt ThisVal = OpVal.trunc(DstBitSize);
7463 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7464 OpVal = OpVal.lshr(DstBitSize);
7467 // For big endian targets, swap the order of the pieces of each element.
7468 if (DAG.getDataLayout().isBigEndian())
7469 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7472 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7475 /// Try to perform FMA combining on a given FADD node.
7476 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7477 SDValue N0 = N->getOperand(0);
7478 SDValue N1 = N->getOperand(1);
7479 EVT VT = N->getValueType(0);
7482 const TargetOptions &Options = DAG.getTarget().Options;
7483 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7484 Options.UnsafeFPMath);
7486 // Floating-point multiply-add with intermediate rounding.
7487 bool HasFMAD = (LegalOperations &&
7488 TLI.isOperationLegal(ISD::FMAD, VT));
7490 // Floating-point multiply-add without intermediate rounding.
7491 bool HasFMA = ((!LegalOperations ||
7492 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7493 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7496 // No valid opcode, do not combine.
7497 if (!HasFMAD && !HasFMA)
7500 // Always prefer FMAD to FMA for precision.
7501 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7502 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7503 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7505 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7506 // prefer to fold the multiply with fewer uses.
7507 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7508 N1.getOpcode() == ISD::FMUL) {
7509 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7513 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7514 if (N0.getOpcode() == ISD::FMUL &&
7515 (Aggressive || N0->hasOneUse())) {
7516 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7517 N0.getOperand(0), N0.getOperand(1), N1);
7520 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7521 // Note: Commutes FADD operands.
7522 if (N1.getOpcode() == ISD::FMUL &&
7523 (Aggressive || N1->hasOneUse())) {
7524 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7525 N1.getOperand(0), N1.getOperand(1), N0);
7528 // Look through FP_EXTEND nodes to do more combining.
7529 if (UnsafeFPMath && LookThroughFPExt) {
7530 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7531 if (N0.getOpcode() == ISD::FP_EXTEND) {
7532 SDValue N00 = N0.getOperand(0);
7533 if (N00.getOpcode() == ISD::FMUL)
7534 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7535 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7537 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7538 N00.getOperand(1)), N1);
7541 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7542 // Note: Commutes FADD operands.
7543 if (N1.getOpcode() == ISD::FP_EXTEND) {
7544 SDValue N10 = N1.getOperand(0);
7545 if (N10.getOpcode() == ISD::FMUL)
7546 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7547 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7549 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7550 N10.getOperand(1)), N0);
7554 // More folding opportunities when target permits.
7555 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7556 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7557 if (N0.getOpcode() == PreferredFusedOpcode &&
7558 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7559 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7560 N0.getOperand(0), N0.getOperand(1),
7561 DAG.getNode(PreferredFusedOpcode, SL, VT,
7562 N0.getOperand(2).getOperand(0),
7563 N0.getOperand(2).getOperand(1),
7567 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7568 if (N1->getOpcode() == PreferredFusedOpcode &&
7569 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7570 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7571 N1.getOperand(0), N1.getOperand(1),
7572 DAG.getNode(PreferredFusedOpcode, SL, VT,
7573 N1.getOperand(2).getOperand(0),
7574 N1.getOperand(2).getOperand(1),
7578 if (UnsafeFPMath && LookThroughFPExt) {
7579 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7580 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7581 auto FoldFAddFMAFPExtFMul = [&] (
7582 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7583 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7584 DAG.getNode(PreferredFusedOpcode, SL, VT,
7585 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7586 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7589 if (N0.getOpcode() == PreferredFusedOpcode) {
7590 SDValue N02 = N0.getOperand(2);
7591 if (N02.getOpcode() == ISD::FP_EXTEND) {
7592 SDValue N020 = N02.getOperand(0);
7593 if (N020.getOpcode() == ISD::FMUL)
7594 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7595 N020.getOperand(0), N020.getOperand(1),
7600 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7601 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7602 // FIXME: This turns two single-precision and one double-precision
7603 // operation into two double-precision operations, which might not be
7604 // interesting for all targets, especially GPUs.
7605 auto FoldFAddFPExtFMAFMul = [&] (
7606 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7607 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7608 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7609 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7610 DAG.getNode(PreferredFusedOpcode, SL, VT,
7611 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7612 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7615 if (N0.getOpcode() == ISD::FP_EXTEND) {
7616 SDValue N00 = N0.getOperand(0);
7617 if (N00.getOpcode() == PreferredFusedOpcode) {
7618 SDValue N002 = N00.getOperand(2);
7619 if (N002.getOpcode() == ISD::FMUL)
7620 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7621 N002.getOperand(0), N002.getOperand(1),
7626 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7627 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7628 if (N1.getOpcode() == PreferredFusedOpcode) {
7629 SDValue N12 = N1.getOperand(2);
7630 if (N12.getOpcode() == ISD::FP_EXTEND) {
7631 SDValue N120 = N12.getOperand(0);
7632 if (N120.getOpcode() == ISD::FMUL)
7633 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7634 N120.getOperand(0), N120.getOperand(1),
7639 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7640 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7641 // FIXME: This turns two single-precision and one double-precision
7642 // operation into two double-precision operations, which might not be
7643 // interesting for all targets, especially GPUs.
7644 if (N1.getOpcode() == ISD::FP_EXTEND) {
7645 SDValue N10 = N1.getOperand(0);
7646 if (N10.getOpcode() == PreferredFusedOpcode) {
7647 SDValue N102 = N10.getOperand(2);
7648 if (N102.getOpcode() == ISD::FMUL)
7649 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7650 N102.getOperand(0), N102.getOperand(1),
7660 /// Try to perform FMA combining on a given FSUB node.
7661 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7662 SDValue N0 = N->getOperand(0);
7663 SDValue N1 = N->getOperand(1);
7664 EVT VT = N->getValueType(0);
7667 const TargetOptions &Options = DAG.getTarget().Options;
7668 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7669 Options.UnsafeFPMath);
7671 // Floating-point multiply-add with intermediate rounding.
7672 bool HasFMAD = (LegalOperations &&
7673 TLI.isOperationLegal(ISD::FMAD, VT));
7675 // Floating-point multiply-add without intermediate rounding.
7676 bool HasFMA = ((!LegalOperations ||
7677 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7678 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7681 // No valid opcode, do not combine.
7682 if (!HasFMAD && !HasFMA)
7685 // Always prefer FMAD to FMA for precision.
7686 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7687 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7688 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7690 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7691 if (N0.getOpcode() == ISD::FMUL &&
7692 (Aggressive || N0->hasOneUse())) {
7693 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7694 N0.getOperand(0), N0.getOperand(1),
7695 DAG.getNode(ISD::FNEG, SL, VT, N1));
7698 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7699 // Note: Commutes FSUB operands.
7700 if (N1.getOpcode() == ISD::FMUL &&
7701 (Aggressive || N1->hasOneUse()))
7702 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7703 DAG.getNode(ISD::FNEG, SL, VT,
7705 N1.getOperand(1), N0);
7707 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7708 if (N0.getOpcode() == ISD::FNEG &&
7709 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7710 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7711 SDValue N00 = N0.getOperand(0).getOperand(0);
7712 SDValue N01 = N0.getOperand(0).getOperand(1);
7713 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7714 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7715 DAG.getNode(ISD::FNEG, SL, VT, N1));
7718 // Look through FP_EXTEND nodes to do more combining.
7719 if (UnsafeFPMath && LookThroughFPExt) {
7720 // fold (fsub (fpext (fmul x, y)), z)
7721 // -> (fma (fpext x), (fpext y), (fneg z))
7722 if (N0.getOpcode() == ISD::FP_EXTEND) {
7723 SDValue N00 = N0.getOperand(0);
7724 if (N00.getOpcode() == ISD::FMUL)
7725 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7726 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7728 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7730 DAG.getNode(ISD::FNEG, SL, VT, N1));
7733 // fold (fsub x, (fpext (fmul y, z)))
7734 // -> (fma (fneg (fpext y)), (fpext z), x)
7735 // Note: Commutes FSUB operands.
7736 if (N1.getOpcode() == ISD::FP_EXTEND) {
7737 SDValue N10 = N1.getOperand(0);
7738 if (N10.getOpcode() == ISD::FMUL)
7739 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7740 DAG.getNode(ISD::FNEG, SL, VT,
7741 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7742 N10.getOperand(0))),
7743 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7748 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7749 // -> (fneg (fma (fpext x), (fpext y), z))
7750 // Note: This could be removed with appropriate canonicalization of the
7751 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7752 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7753 // from implementing the canonicalization in visitFSUB.
7754 if (N0.getOpcode() == ISD::FP_EXTEND) {
7755 SDValue N00 = N0.getOperand(0);
7756 if (N00.getOpcode() == ISD::FNEG) {
7757 SDValue N000 = N00.getOperand(0);
7758 if (N000.getOpcode() == ISD::FMUL) {
7759 return DAG.getNode(ISD::FNEG, SL, VT,
7760 DAG.getNode(PreferredFusedOpcode, SL, VT,
7761 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7762 N000.getOperand(0)),
7763 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7764 N000.getOperand(1)),
7770 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7771 // -> (fneg (fma (fpext x)), (fpext y), z)
7772 // Note: This could be removed with appropriate canonicalization of the
7773 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7774 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7775 // from implementing the canonicalization in visitFSUB.
7776 if (N0.getOpcode() == ISD::FNEG) {
7777 SDValue N00 = N0.getOperand(0);
7778 if (N00.getOpcode() == ISD::FP_EXTEND) {
7779 SDValue N000 = N00.getOperand(0);
7780 if (N000.getOpcode() == ISD::FMUL) {
7781 return DAG.getNode(ISD::FNEG, SL, VT,
7782 DAG.getNode(PreferredFusedOpcode, SL, VT,
7783 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7784 N000.getOperand(0)),
7785 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7786 N000.getOperand(1)),
7794 // More folding opportunities when target permits.
7795 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7796 // fold (fsub (fma x, y, (fmul u, v)), z)
7797 // -> (fma x, y (fma u, v, (fneg z)))
7798 if (N0.getOpcode() == PreferredFusedOpcode &&
7799 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7800 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7801 N0.getOperand(0), N0.getOperand(1),
7802 DAG.getNode(PreferredFusedOpcode, SL, VT,
7803 N0.getOperand(2).getOperand(0),
7804 N0.getOperand(2).getOperand(1),
7805 DAG.getNode(ISD::FNEG, SL, VT,
7809 // fold (fsub x, (fma y, z, (fmul u, v)))
7810 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7811 if (N1.getOpcode() == PreferredFusedOpcode &&
7812 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7813 SDValue N20 = N1.getOperand(2).getOperand(0);
7814 SDValue N21 = N1.getOperand(2).getOperand(1);
7815 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7816 DAG.getNode(ISD::FNEG, SL, VT,
7819 DAG.getNode(PreferredFusedOpcode, SL, VT,
7820 DAG.getNode(ISD::FNEG, SL, VT, N20),
7825 if (UnsafeFPMath && LookThroughFPExt) {
7826 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7827 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7828 if (N0.getOpcode() == PreferredFusedOpcode) {
7829 SDValue N02 = N0.getOperand(2);
7830 if (N02.getOpcode() == ISD::FP_EXTEND) {
7831 SDValue N020 = N02.getOperand(0);
7832 if (N020.getOpcode() == ISD::FMUL)
7833 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7834 N0.getOperand(0), N0.getOperand(1),
7835 DAG.getNode(PreferredFusedOpcode, SL, VT,
7836 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7837 N020.getOperand(0)),
7838 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7839 N020.getOperand(1)),
7840 DAG.getNode(ISD::FNEG, SL, VT,
7845 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7846 // -> (fma (fpext x), (fpext y),
7847 // (fma (fpext u), (fpext v), (fneg z)))
7848 // FIXME: This turns two single-precision and one double-precision
7849 // operation into two double-precision operations, which might not be
7850 // interesting for all targets, especially GPUs.
7851 if (N0.getOpcode() == ISD::FP_EXTEND) {
7852 SDValue N00 = N0.getOperand(0);
7853 if (N00.getOpcode() == PreferredFusedOpcode) {
7854 SDValue N002 = N00.getOperand(2);
7855 if (N002.getOpcode() == ISD::FMUL)
7856 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7857 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7859 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7861 DAG.getNode(PreferredFusedOpcode, SL, VT,
7862 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7863 N002.getOperand(0)),
7864 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7865 N002.getOperand(1)),
7866 DAG.getNode(ISD::FNEG, SL, VT,
7871 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7872 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7873 if (N1.getOpcode() == PreferredFusedOpcode &&
7874 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7875 SDValue N120 = N1.getOperand(2).getOperand(0);
7876 if (N120.getOpcode() == ISD::FMUL) {
7877 SDValue N1200 = N120.getOperand(0);
7878 SDValue N1201 = N120.getOperand(1);
7879 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7880 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7882 DAG.getNode(PreferredFusedOpcode, SL, VT,
7883 DAG.getNode(ISD::FNEG, SL, VT,
7884 DAG.getNode(ISD::FP_EXTEND, SL,
7886 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7892 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7893 // -> (fma (fneg (fpext y)), (fpext z),
7894 // (fma (fneg (fpext u)), (fpext v), x))
7895 // FIXME: This turns two single-precision and one double-precision
7896 // operation into two double-precision operations, which might not be
7897 // interesting for all targets, especially GPUs.
7898 if (N1.getOpcode() == ISD::FP_EXTEND &&
7899 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7900 SDValue N100 = N1.getOperand(0).getOperand(0);
7901 SDValue N101 = N1.getOperand(0).getOperand(1);
7902 SDValue N102 = N1.getOperand(0).getOperand(2);
7903 if (N102.getOpcode() == ISD::FMUL) {
7904 SDValue N1020 = N102.getOperand(0);
7905 SDValue N1021 = N102.getOperand(1);
7906 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7907 DAG.getNode(ISD::FNEG, SL, VT,
7908 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7910 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7911 DAG.getNode(PreferredFusedOpcode, SL, VT,
7912 DAG.getNode(ISD::FNEG, SL, VT,
7913 DAG.getNode(ISD::FP_EXTEND, SL,
7915 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7926 SDValue DAGCombiner::visitFADD(SDNode *N) {
7927 SDValue N0 = N->getOperand(0);
7928 SDValue N1 = N->getOperand(1);
7929 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7930 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7931 EVT VT = N->getValueType(0);
7933 const TargetOptions &Options = DAG.getTarget().Options;
7937 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7940 // fold (fadd c1, c2) -> c1 + c2
7942 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7944 // canonicalize constant to RHS
7945 if (N0CFP && !N1CFP)
7946 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7948 // fold (fadd A, (fneg B)) -> (fsub A, B)
7949 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7950 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7951 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7952 GetNegatedExpression(N1, DAG, LegalOperations));
7954 // fold (fadd (fneg A), B) -> (fsub B, A)
7955 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7956 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7957 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7958 GetNegatedExpression(N0, DAG, LegalOperations));
7960 // If 'unsafe math' is enabled, fold lots of things.
7961 if (Options.UnsafeFPMath) {
7962 // No FP constant should be created after legalization as Instruction
7963 // Selection pass has a hard time dealing with FP constants.
7964 bool AllowNewConst = (Level < AfterLegalizeDAG);
7966 // fold (fadd A, 0) -> A
7967 if (N1CFP && N1CFP->isZero())
7970 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7971 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7972 isa<ConstantFPSDNode>(N0.getOperand(1)))
7973 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7974 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7976 // If allowed, fold (fadd (fneg x), x) -> 0.0
7977 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7978 return DAG.getConstantFP(0.0, DL, VT);
7980 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7981 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7982 return DAG.getConstantFP(0.0, DL, VT);
7984 // We can fold chains of FADD's of the same value into multiplications.
7985 // This transform is not safe in general because we are reducing the number
7986 // of rounding steps.
7987 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7988 if (N0.getOpcode() == ISD::FMUL) {
7989 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7990 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7992 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7993 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7994 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7995 DAG.getConstantFP(1.0, DL, VT));
7996 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7999 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8000 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8001 N1.getOperand(0) == N1.getOperand(1) &&
8002 N0.getOperand(0) == N1.getOperand(0)) {
8003 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
8004 DAG.getConstantFP(2.0, DL, VT));
8005 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
8009 if (N1.getOpcode() == ISD::FMUL) {
8010 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8011 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
8013 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8014 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8015 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8016 DAG.getConstantFP(1.0, DL, VT));
8017 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
8020 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8021 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8022 N0.getOperand(0) == N0.getOperand(1) &&
8023 N1.getOperand(0) == N0.getOperand(0)) {
8024 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8025 DAG.getConstantFP(2.0, DL, VT));
8026 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
8030 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8031 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8032 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8033 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
8034 (N0.getOperand(0) == N1)) {
8035 return DAG.getNode(ISD::FMUL, DL, VT,
8036 N1, DAG.getConstantFP(3.0, DL, VT));
8040 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8041 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8042 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8043 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8044 N1.getOperand(0) == N0) {
8045 return DAG.getNode(ISD::FMUL, DL, VT,
8046 N0, DAG.getConstantFP(3.0, DL, VT));
8050 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8051 if (AllowNewConst &&
8052 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8053 N0.getOperand(0) == N0.getOperand(1) &&
8054 N1.getOperand(0) == N1.getOperand(1) &&
8055 N0.getOperand(0) == N1.getOperand(0)) {
8056 return DAG.getNode(ISD::FMUL, DL, VT,
8057 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
8060 } // enable-unsafe-fp-math
8062 // FADD -> FMA combines:
8063 if (SDValue Fused = visitFADDForFMACombine(N)) {
8064 AddToWorklist(Fused.getNode());
8071 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8072 SDValue N0 = N->getOperand(0);
8073 SDValue N1 = N->getOperand(1);
8074 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8075 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8076 EVT VT = N->getValueType(0);
8078 const TargetOptions &Options = DAG.getTarget().Options;
8082 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8085 // fold (fsub c1, c2) -> c1-c2
8087 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8089 // fold (fsub A, (fneg B)) -> (fadd A, B)
8090 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8091 return DAG.getNode(ISD::FADD, dl, VT, N0,
8092 GetNegatedExpression(N1, DAG, LegalOperations));
8094 // If 'unsafe math' is enabled, fold lots of things.
8095 if (Options.UnsafeFPMath) {
8097 if (N1CFP && N1CFP->isZero())
8100 // (fsub 0, B) -> -B
8101 if (N0CFP && N0CFP->isZero()) {
8102 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8103 return GetNegatedExpression(N1, DAG, LegalOperations);
8104 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8105 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8108 // (fsub x, x) -> 0.0
8110 return DAG.getConstantFP(0.0f, dl, VT);
8112 // (fsub x, (fadd x, y)) -> (fneg y)
8113 // (fsub x, (fadd y, x)) -> (fneg y)
8114 if (N1.getOpcode() == ISD::FADD) {
8115 SDValue N10 = N1->getOperand(0);
8116 SDValue N11 = N1->getOperand(1);
8118 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8119 return GetNegatedExpression(N11, DAG, LegalOperations);
8121 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8122 return GetNegatedExpression(N10, DAG, LegalOperations);
8126 // FSUB -> FMA combines:
8127 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8128 AddToWorklist(Fused.getNode());
8135 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8136 SDValue N0 = N->getOperand(0);
8137 SDValue N1 = N->getOperand(1);
8138 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8139 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8140 EVT VT = N->getValueType(0);
8142 const TargetOptions &Options = DAG.getTarget().Options;
8145 if (VT.isVector()) {
8146 // This just handles C1 * C2 for vectors. Other vector folds are below.
8147 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8151 // fold (fmul c1, c2) -> c1*c2
8153 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8155 // canonicalize constant to RHS
8156 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8157 !isConstantFPBuildVectorOrConstantFP(N1))
8158 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8160 // fold (fmul A, 1.0) -> A
8161 if (N1CFP && N1CFP->isExactlyValue(1.0))
8164 if (Options.UnsafeFPMath) {
8165 // fold (fmul A, 0) -> 0
8166 if (N1CFP && N1CFP->isZero())
8169 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8170 if (N0.getOpcode() == ISD::FMUL) {
8171 // Fold scalars or any vector constants (not just splats).
8172 // This fold is done in general by InstCombine, but extra fmul insts
8173 // may have been generated during lowering.
8174 SDValue N00 = N0.getOperand(0);
8175 SDValue N01 = N0.getOperand(1);
8176 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8177 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8178 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8180 // Check 1: Make sure that the first operand of the inner multiply is NOT
8181 // a constant. Otherwise, we may induce infinite looping.
8182 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8183 // Check 2: Make sure that the second operand of the inner multiply and
8184 // the second operand of the outer multiply are constants.
8185 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8186 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8187 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8188 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8193 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8194 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8195 // during an early run of DAGCombiner can prevent folding with fmuls
8196 // inserted during lowering.
8197 if (N0.getOpcode() == ISD::FADD &&
8198 (N0.getOperand(0) == N0.getOperand(1)) &&
8200 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8201 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8202 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8206 // fold (fmul X, 2.0) -> (fadd X, X)
8207 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8208 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8210 // fold (fmul X, -1.0) -> (fneg X)
8211 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8212 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8213 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8215 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8216 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8217 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8218 // Both can be negated for free, check to see if at least one is cheaper
8220 if (LHSNeg == 2 || RHSNeg == 2)
8221 return DAG.getNode(ISD::FMUL, DL, VT,
8222 GetNegatedExpression(N0, DAG, LegalOperations),
8223 GetNegatedExpression(N1, DAG, LegalOperations));
8230 SDValue DAGCombiner::visitFMA(SDNode *N) {
8231 SDValue N0 = N->getOperand(0);
8232 SDValue N1 = N->getOperand(1);
8233 SDValue N2 = N->getOperand(2);
8234 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8235 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8236 EVT VT = N->getValueType(0);
8238 const TargetOptions &Options = DAG.getTarget().Options;
8240 // Constant fold FMA.
8241 if (isa<ConstantFPSDNode>(N0) &&
8242 isa<ConstantFPSDNode>(N1) &&
8243 isa<ConstantFPSDNode>(N2)) {
8244 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8247 if (Options.UnsafeFPMath) {
8248 if (N0CFP && N0CFP->isZero())
8250 if (N1CFP && N1CFP->isZero())
8253 if (N0CFP && N0CFP->isExactlyValue(1.0))
8254 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8255 if (N1CFP && N1CFP->isExactlyValue(1.0))
8256 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8258 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8259 if (N0CFP && !N1CFP)
8260 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8262 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8263 if (Options.UnsafeFPMath && N1CFP &&
8264 N2.getOpcode() == ISD::FMUL &&
8265 N0 == N2.getOperand(0) &&
8266 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8267 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8268 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8272 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8273 if (Options.UnsafeFPMath &&
8274 N0.getOpcode() == ISD::FMUL && N1CFP &&
8275 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8276 return DAG.getNode(ISD::FMA, dl, VT,
8278 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8282 // (fma x, 1, y) -> (fadd x, y)
8283 // (fma x, -1, y) -> (fadd (fneg x), y)
8285 if (N1CFP->isExactlyValue(1.0))
8286 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8288 if (N1CFP->isExactlyValue(-1.0) &&
8289 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8290 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8291 AddToWorklist(RHSNeg.getNode());
8292 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8296 // (fma x, c, x) -> (fmul x, (c+1))
8297 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8298 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8299 DAG.getNode(ISD::FADD, dl, VT,
8300 N1, DAG.getConstantFP(1.0, dl, VT)));
8302 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8303 if (Options.UnsafeFPMath && N1CFP &&
8304 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8305 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8306 DAG.getNode(ISD::FADD, dl, VT,
8307 N1, DAG.getConstantFP(-1.0, dl, VT)));
8313 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8315 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8316 // Notice that this is not always beneficial. One reason is different target
8317 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8318 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8319 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8320 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8321 if (!DAG.getTarget().Options.UnsafeFPMath)
8324 // Skip if current node is a reciprocal.
8325 SDValue N0 = N->getOperand(0);
8326 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8327 if (N0CFP && N0CFP->isExactlyValue(1.0))
8330 // Exit early if the target does not want this transform or if there can't
8331 // possibly be enough uses of the divisor to make the transform worthwhile.
8332 SDValue N1 = N->getOperand(1);
8333 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8334 if (!MinUses || N1->use_size() < MinUses)
8337 // Find all FDIV users of the same divisor.
8338 // Use a set because duplicates may be present in the user list.
8339 SetVector<SDNode *> Users;
8340 for (auto *U : N1->uses())
8341 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8344 // Now that we have the actual number of divisor uses, make sure it meets
8345 // the minimum threshold specified by the target.
8346 if (Users.size() < MinUses)
8349 EVT VT = N->getValueType(0);
8351 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8352 // FIXME: This optimization requires some level of fast-math, so the
8353 // created reciprocal node should at least have the 'allowReciprocal'
8354 // fast-math-flag set.
8355 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8357 // Dividend / Divisor -> Dividend * Reciprocal
8358 for (auto *U : Users) {
8359 SDValue Dividend = U->getOperand(0);
8360 if (Dividend != FPOne) {
8361 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8363 CombineTo(U, NewNode);
8364 } else if (U != Reciprocal.getNode()) {
8365 // In the absence of fast-math-flags, this user node is always the
8366 // same node as Reciprocal, but with FMF they may be different nodes.
8367 CombineTo(U, Reciprocal);
8370 return SDValue(N, 0); // N was replaced.
8373 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8374 SDValue N0 = N->getOperand(0);
8375 SDValue N1 = N->getOperand(1);
8376 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8377 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8378 EVT VT = N->getValueType(0);
8380 const TargetOptions &Options = DAG.getTarget().Options;
8384 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8387 // fold (fdiv c1, c2) -> c1/c2
8389 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8391 if (Options.UnsafeFPMath) {
8392 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8394 // Compute the reciprocal 1.0 / c2.
8395 APFloat N1APF = N1CFP->getValueAPF();
8396 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8397 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8398 // Only do the transform if the reciprocal is a legal fp immediate that
8399 // isn't too nasty (eg NaN, denormal, ...).
8400 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8401 (!LegalOperations ||
8402 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8403 // backend)... we should handle this gracefully after Legalize.
8404 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8405 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8406 TLI.isFPImmLegal(Recip, VT)))
8407 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8408 DAG.getConstantFP(Recip, DL, VT));
8411 // If this FDIV is part of a reciprocal square root, it may be folded
8412 // into a target-specific square root estimate instruction.
8413 if (N1.getOpcode() == ISD::FSQRT) {
8414 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8415 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8417 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8418 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8419 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8420 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8421 AddToWorklist(RV.getNode());
8422 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8424 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8425 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8426 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8427 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8428 AddToWorklist(RV.getNode());
8429 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8431 } else if (N1.getOpcode() == ISD::FMUL) {
8432 // Look through an FMUL. Even though this won't remove the FDIV directly,
8433 // it's still worthwhile to get rid of the FSQRT if possible.
8436 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8437 SqrtOp = N1.getOperand(0);
8438 OtherOp = N1.getOperand(1);
8439 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8440 SqrtOp = N1.getOperand(1);
8441 OtherOp = N1.getOperand(0);
8443 if (SqrtOp.getNode()) {
8444 // We found a FSQRT, so try to make this fold:
8445 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8446 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8447 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8448 AddToWorklist(RV.getNode());
8449 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8454 // Fold into a reciprocal estimate and multiply instead of a real divide.
8455 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8456 AddToWorklist(RV.getNode());
8457 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8461 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8462 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8463 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8464 // Both can be negated for free, check to see if at least one is cheaper
8466 if (LHSNeg == 2 || RHSNeg == 2)
8467 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8468 GetNegatedExpression(N0, DAG, LegalOperations),
8469 GetNegatedExpression(N1, DAG, LegalOperations));
8473 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8474 return CombineRepeatedDivisors;
8479 SDValue DAGCombiner::visitFREM(SDNode *N) {
8480 SDValue N0 = N->getOperand(0);
8481 SDValue N1 = N->getOperand(1);
8482 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8483 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8484 EVT VT = N->getValueType(0);
8486 // fold (frem c1, c2) -> fmod(c1,c2)
8488 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8493 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8494 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8497 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8498 SDValue RV = BuildRsqrtEstimate(N->getOperand(0));
8502 EVT VT = RV.getValueType();
8504 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8505 AddToWorklist(RV.getNode());
8507 // Unfortunately, RV is now NaN if the input was exactly 0.
8508 // Select out this case and force the answer to 0.
8509 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8510 EVT CCVT = getSetCCResultType(VT);
8511 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8512 AddToWorklist(ZeroCmp.getNode());
8513 AddToWorklist(RV.getNode());
8515 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8519 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8520 SDValue N0 = N->getOperand(0);
8521 SDValue N1 = N->getOperand(1);
8522 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8523 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8524 EVT VT = N->getValueType(0);
8526 if (N0CFP && N1CFP) // Constant fold
8527 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8530 const APFloat& V = N1CFP->getValueAPF();
8531 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8532 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8533 if (!V.isNegative()) {
8534 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8535 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8537 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8538 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8539 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8543 // copysign(fabs(x), y) -> copysign(x, y)
8544 // copysign(fneg(x), y) -> copysign(x, y)
8545 // copysign(copysign(x,z), y) -> copysign(x, y)
8546 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8547 N0.getOpcode() == ISD::FCOPYSIGN)
8548 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8549 N0.getOperand(0), N1);
8551 // copysign(x, abs(y)) -> abs(x)
8552 if (N1.getOpcode() == ISD::FABS)
8553 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8555 // copysign(x, copysign(y,z)) -> copysign(x, z)
8556 if (N1.getOpcode() == ISD::FCOPYSIGN)
8557 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8558 N0, N1.getOperand(1));
8560 // copysign(x, fp_extend(y)) -> copysign(x, y)
8561 // copysign(x, fp_round(y)) -> copysign(x, y)
8562 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8563 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8564 N0, N1.getOperand(0));
8569 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8570 SDValue N0 = N->getOperand(0);
8571 EVT VT = N->getValueType(0);
8572 EVT OpVT = N0.getValueType();
8574 // fold (sint_to_fp c1) -> c1fp
8575 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8576 // ...but only if the target supports immediate floating-point values
8577 (!LegalOperations ||
8578 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8579 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8581 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8582 // but UINT_TO_FP is legal on this target, try to convert.
8583 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8584 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8585 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8586 if (DAG.SignBitIsZero(N0))
8587 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8590 // The next optimizations are desirable only if SELECT_CC can be lowered.
8591 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8592 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8593 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8595 (!LegalOperations ||
8596 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8599 { N0.getOperand(0), N0.getOperand(1),
8600 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8602 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8605 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8606 // (select_cc x, y, 1.0, 0.0,, cc)
8607 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8608 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8609 (!LegalOperations ||
8610 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8613 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8614 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8615 N0.getOperand(0).getOperand(2) };
8616 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8623 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8624 SDValue N0 = N->getOperand(0);
8625 EVT VT = N->getValueType(0);
8626 EVT OpVT = N0.getValueType();
8628 // fold (uint_to_fp c1) -> c1fp
8629 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8630 // ...but only if the target supports immediate floating-point values
8631 (!LegalOperations ||
8632 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8633 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8635 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8636 // but SINT_TO_FP is legal on this target, try to convert.
8637 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8638 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8639 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8640 if (DAG.SignBitIsZero(N0))
8641 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8644 // The next optimizations are desirable only if SELECT_CC can be lowered.
8645 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8646 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8648 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8649 (!LegalOperations ||
8650 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8653 { N0.getOperand(0), N0.getOperand(1),
8654 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8656 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8663 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8664 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8665 SDValue N0 = N->getOperand(0);
8666 EVT VT = N->getValueType(0);
8668 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8671 SDValue Src = N0.getOperand(0);
8672 EVT SrcVT = Src.getValueType();
8673 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8674 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8676 // We can safely assume the conversion won't overflow the output range,
8677 // because (for example) (uint8_t)18293.f is undefined behavior.
8679 // Since we can assume the conversion won't overflow, our decision as to
8680 // whether the input will fit in the float should depend on the minimum
8681 // of the input range and output range.
8683 // This means this is also safe for a signed input and unsigned output, since
8684 // a negative input would lead to undefined behavior.
8685 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8686 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8687 unsigned ActualSize = std::min(InputSize, OutputSize);
8688 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8690 // We can only fold away the float conversion if the input range can be
8691 // represented exactly in the float range.
8692 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8693 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8694 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8696 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8698 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8699 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8702 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8707 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8708 SDValue N0 = N->getOperand(0);
8709 EVT VT = N->getValueType(0);
8711 // fold (fp_to_sint c1fp) -> c1
8712 if (isConstantFPBuildVectorOrConstantFP(N0))
8713 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8715 return FoldIntToFPToInt(N, DAG);
8718 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8719 SDValue N0 = N->getOperand(0);
8720 EVT VT = N->getValueType(0);
8722 // fold (fp_to_uint c1fp) -> c1
8723 if (isConstantFPBuildVectorOrConstantFP(N0))
8724 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8726 return FoldIntToFPToInt(N, DAG);
8729 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8730 SDValue N0 = N->getOperand(0);
8731 SDValue N1 = N->getOperand(1);
8732 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8733 EVT VT = N->getValueType(0);
8735 // fold (fp_round c1fp) -> c1fp
8737 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8739 // fold (fp_round (fp_extend x)) -> x
8740 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8741 return N0.getOperand(0);
8743 // fold (fp_round (fp_round x)) -> (fp_round x)
8744 if (N0.getOpcode() == ISD::FP_ROUND) {
8745 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8746 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8747 // If the first fp_round isn't a value preserving truncation, it might
8748 // introduce a tie in the second fp_round, that wouldn't occur in the
8749 // single-step fp_round we want to fold to.
8750 // In other words, double rounding isn't the same as rounding.
8751 // Also, this is a value preserving truncation iff both fp_round's are.
8752 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8754 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8755 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8759 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8760 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8761 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8762 N0.getOperand(0), N1);
8763 AddToWorklist(Tmp.getNode());
8764 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8765 Tmp, N0.getOperand(1));
8771 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8772 SDValue N0 = N->getOperand(0);
8773 EVT VT = N->getValueType(0);
8774 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8775 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8777 // fold (fp_round_inreg c1fp) -> c1fp
8778 if (N0CFP && isTypeLegal(EVT)) {
8780 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8781 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8787 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8788 SDValue N0 = N->getOperand(0);
8789 EVT VT = N->getValueType(0);
8791 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8792 if (N->hasOneUse() &&
8793 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8796 // fold (fp_extend c1fp) -> c1fp
8797 if (isConstantFPBuildVectorOrConstantFP(N0))
8798 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8800 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8801 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8802 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8803 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8805 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8807 if (N0.getOpcode() == ISD::FP_ROUND
8808 && N0.getNode()->getConstantOperandVal(1) == 1) {
8809 SDValue In = N0.getOperand(0);
8810 if (In.getValueType() == VT) return In;
8811 if (VT.bitsLT(In.getValueType()))
8812 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8813 In, N0.getOperand(1));
8814 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8817 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8818 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8819 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8820 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8821 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8823 LN0->getBasePtr(), N0.getValueType(),
8824 LN0->getMemOperand());
8825 CombineTo(N, ExtLoad);
8826 CombineTo(N0.getNode(),
8827 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8828 N0.getValueType(), ExtLoad,
8829 DAG.getIntPtrConstant(1, SDLoc(N0))),
8830 ExtLoad.getValue(1));
8831 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8837 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8838 SDValue N0 = N->getOperand(0);
8839 EVT VT = N->getValueType(0);
8841 // fold (fceil c1) -> fceil(c1)
8842 if (isConstantFPBuildVectorOrConstantFP(N0))
8843 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8848 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8849 SDValue N0 = N->getOperand(0);
8850 EVT VT = N->getValueType(0);
8852 // fold (ftrunc c1) -> ftrunc(c1)
8853 if (isConstantFPBuildVectorOrConstantFP(N0))
8854 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8859 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8860 SDValue N0 = N->getOperand(0);
8861 EVT VT = N->getValueType(0);
8863 // fold (ffloor c1) -> ffloor(c1)
8864 if (isConstantFPBuildVectorOrConstantFP(N0))
8865 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8870 // FIXME: FNEG and FABS have a lot in common; refactor.
8871 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8872 SDValue N0 = N->getOperand(0);
8873 EVT VT = N->getValueType(0);
8875 // Constant fold FNEG.
8876 if (isConstantFPBuildVectorOrConstantFP(N0))
8877 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8879 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8880 &DAG.getTarget().Options))
8881 return GetNegatedExpression(N0, DAG, LegalOperations);
8883 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8884 // constant pool values.
8885 if (!TLI.isFNegFree(VT) &&
8886 N0.getOpcode() == ISD::BITCAST &&
8887 N0.getNode()->hasOneUse()) {
8888 SDValue Int = N0.getOperand(0);
8889 EVT IntVT = Int.getValueType();
8890 if (IntVT.isInteger() && !IntVT.isVector()) {
8892 if (N0.getValueType().isVector()) {
8893 // For a vector, get a mask such as 0x80... per scalar element
8895 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8896 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8898 // For a scalar, just generate 0x80...
8899 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8902 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8903 DAG.getConstant(SignMask, DL0, IntVT));
8904 AddToWorklist(Int.getNode());
8905 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8909 // (fneg (fmul c, x)) -> (fmul -c, x)
8910 if (N0.getOpcode() == ISD::FMUL &&
8911 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8912 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8914 APFloat CVal = CFP1->getValueAPF();
8916 if (Level >= AfterLegalizeDAG &&
8917 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8918 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8920 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8921 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8928 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8929 SDValue N0 = N->getOperand(0);
8930 SDValue N1 = N->getOperand(1);
8931 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8932 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8934 if (N0CFP && N1CFP) {
8935 const APFloat &C0 = N0CFP->getValueAPF();
8936 const APFloat &C1 = N1CFP->getValueAPF();
8937 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8941 EVT VT = N->getValueType(0);
8942 // Canonicalize to constant on RHS.
8943 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8949 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8950 SDValue N0 = N->getOperand(0);
8951 SDValue N1 = N->getOperand(1);
8952 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8953 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8955 if (N0CFP && N1CFP) {
8956 const APFloat &C0 = N0CFP->getValueAPF();
8957 const APFloat &C1 = N1CFP->getValueAPF();
8958 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8962 EVT VT = N->getValueType(0);
8963 // Canonicalize to constant on RHS.
8964 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8970 SDValue DAGCombiner::visitFABS(SDNode *N) {
8971 SDValue N0 = N->getOperand(0);
8972 EVT VT = N->getValueType(0);
8974 // fold (fabs c1) -> fabs(c1)
8975 if (isConstantFPBuildVectorOrConstantFP(N0))
8976 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8978 // fold (fabs (fabs x)) -> (fabs x)
8979 if (N0.getOpcode() == ISD::FABS)
8980 return N->getOperand(0);
8982 // fold (fabs (fneg x)) -> (fabs x)
8983 // fold (fabs (fcopysign x, y)) -> (fabs x)
8984 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8985 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8987 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8988 // constant pool values.
8989 if (!TLI.isFAbsFree(VT) &&
8990 N0.getOpcode() == ISD::BITCAST &&
8991 N0.getNode()->hasOneUse()) {
8992 SDValue Int = N0.getOperand(0);
8993 EVT IntVT = Int.getValueType();
8994 if (IntVT.isInteger() && !IntVT.isVector()) {
8996 if (N0.getValueType().isVector()) {
8997 // For a vector, get a mask such as 0x7f... per scalar element
8999 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9000 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9002 // For a scalar, just generate 0x7f...
9003 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9006 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9007 DAG.getConstant(SignMask, DL, IntVT));
9008 AddToWorklist(Int.getNode());
9009 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9016 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9017 SDValue Chain = N->getOperand(0);
9018 SDValue N1 = N->getOperand(1);
9019 SDValue N2 = N->getOperand(2);
9021 // If N is a constant we could fold this into a fallthrough or unconditional
9022 // branch. However that doesn't happen very often in normal code, because
9023 // Instcombine/SimplifyCFG should have handled the available opportunities.
9024 // If we did this folding here, it would be necessary to update the
9025 // MachineBasicBlock CFG, which is awkward.
9027 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9029 if (N1.getOpcode() == ISD::SETCC &&
9030 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9031 N1.getOperand(0).getValueType())) {
9032 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9033 Chain, N1.getOperand(2),
9034 N1.getOperand(0), N1.getOperand(1), N2);
9037 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9038 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9039 (N1.getOperand(0).hasOneUse() &&
9040 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9041 SDNode *Trunc = nullptr;
9042 if (N1.getOpcode() == ISD::TRUNCATE) {
9043 // Look pass the truncate.
9044 Trunc = N1.getNode();
9045 N1 = N1.getOperand(0);
9048 // Match this pattern so that we can generate simpler code:
9051 // %b = and i32 %a, 2
9052 // %c = srl i32 %b, 1
9053 // brcond i32 %c ...
9058 // %b = and i32 %a, 2
9059 // %c = setcc eq %b, 0
9062 // This applies only when the AND constant value has one bit set and the
9063 // SRL constant is equal to the log2 of the AND constant. The back-end is
9064 // smart enough to convert the result into a TEST/JMP sequence.
9065 SDValue Op0 = N1.getOperand(0);
9066 SDValue Op1 = N1.getOperand(1);
9068 if (Op0.getOpcode() == ISD::AND &&
9069 Op1.getOpcode() == ISD::Constant) {
9070 SDValue AndOp1 = Op0.getOperand(1);
9072 if (AndOp1.getOpcode() == ISD::Constant) {
9073 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9075 if (AndConst.isPowerOf2() &&
9076 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9080 getSetCCResultType(Op0.getValueType()),
9081 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9084 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9085 MVT::Other, Chain, SetCC, N2);
9086 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9087 // will convert it back to (X & C1) >> C2.
9088 CombineTo(N, NewBRCond, false);
9089 // Truncate is dead.
9091 deleteAndRecombine(Trunc);
9092 // Replace the uses of SRL with SETCC
9093 WorklistRemover DeadNodes(*this);
9094 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9095 deleteAndRecombine(N1.getNode());
9096 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9102 // Restore N1 if the above transformation doesn't match.
9103 N1 = N->getOperand(1);
9106 // Transform br(xor(x, y)) -> br(x != y)
9107 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9108 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9109 SDNode *TheXor = N1.getNode();
9110 SDValue Op0 = TheXor->getOperand(0);
9111 SDValue Op1 = TheXor->getOperand(1);
9112 if (Op0.getOpcode() == Op1.getOpcode()) {
9113 // Avoid missing important xor optimizations.
9114 if (SDValue Tmp = visitXOR(TheXor)) {
9115 if (Tmp.getNode() != TheXor) {
9116 DEBUG(dbgs() << "\nReplacing.8 ";
9118 dbgs() << "\nWith: ";
9119 Tmp.getNode()->dump(&DAG);
9121 WorklistRemover DeadNodes(*this);
9122 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9123 deleteAndRecombine(TheXor);
9124 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9125 MVT::Other, Chain, Tmp, N2);
9128 // visitXOR has changed XOR's operands or replaced the XOR completely,
9130 return SDValue(N, 0);
9134 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9136 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9137 Op0.getOpcode() == ISD::XOR) {
9138 TheXor = Op0.getNode();
9142 EVT SetCCVT = N1.getValueType();
9144 SetCCVT = getSetCCResultType(SetCCVT);
9145 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9148 Equal ? ISD::SETEQ : ISD::SETNE);
9149 // Replace the uses of XOR with SETCC
9150 WorklistRemover DeadNodes(*this);
9151 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9152 deleteAndRecombine(N1.getNode());
9153 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9154 MVT::Other, Chain, SetCC, N2);
9161 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9163 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9164 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9165 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9167 // If N is a constant we could fold this into a fallthrough or unconditional
9168 // branch. However that doesn't happen very often in normal code, because
9169 // Instcombine/SimplifyCFG should have handled the available opportunities.
9170 // If we did this folding here, it would be necessary to update the
9171 // MachineBasicBlock CFG, which is awkward.
9173 // Use SimplifySetCC to simplify SETCC's.
9174 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9175 CondLHS, CondRHS, CC->get(), SDLoc(N),
9177 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9179 // fold to a simpler setcc
9180 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9181 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9182 N->getOperand(0), Simp.getOperand(2),
9183 Simp.getOperand(0), Simp.getOperand(1),
9189 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9190 /// and that N may be folded in the load / store addressing mode.
9191 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9193 const TargetLowering &TLI) {
9197 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9198 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9200 VT = LD->getMemoryVT();
9201 AS = LD->getAddressSpace();
9202 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9203 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9205 VT = ST->getMemoryVT();
9206 AS = ST->getAddressSpace();
9210 TargetLowering::AddrMode AM;
9211 if (N->getOpcode() == ISD::ADD) {
9212 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9215 AM.BaseOffs = Offset->getSExtValue();
9219 } else if (N->getOpcode() == ISD::SUB) {
9220 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9223 AM.BaseOffs = -Offset->getSExtValue();
9230 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9231 VT.getTypeForEVT(*DAG.getContext()), AS);
9234 /// Try turning a load/store into a pre-indexed load/store when the base
9235 /// pointer is an add or subtract and it has other uses besides the load/store.
9236 /// After the transformation, the new indexed load/store has effectively folded
9237 /// the add/subtract in and all of its other uses are redirected to the
9239 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9240 if (Level < AfterLegalizeDAG)
9246 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9247 if (LD->isIndexed())
9249 VT = LD->getMemoryVT();
9250 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9251 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9253 Ptr = LD->getBasePtr();
9254 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9255 if (ST->isIndexed())
9257 VT = ST->getMemoryVT();
9258 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9259 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9261 Ptr = ST->getBasePtr();
9267 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9268 // out. There is no reason to make this a preinc/predec.
9269 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9270 Ptr.getNode()->hasOneUse())
9273 // Ask the target to do addressing mode selection.
9276 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9277 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9280 // Backends without true r+i pre-indexed forms may need to pass a
9281 // constant base with a variable offset so that constant coercion
9282 // will work with the patterns in canonical form.
9283 bool Swapped = false;
9284 if (isa<ConstantSDNode>(BasePtr)) {
9285 std::swap(BasePtr, Offset);
9289 // Don't create a indexed load / store with zero offset.
9290 if (isNullConstant(Offset))
9293 // Try turning it into a pre-indexed load / store except when:
9294 // 1) The new base ptr is a frame index.
9295 // 2) If N is a store and the new base ptr is either the same as or is a
9296 // predecessor of the value being stored.
9297 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9298 // that would create a cycle.
9299 // 4) All uses are load / store ops that use it as old base ptr.
9301 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9302 // (plus the implicit offset) to a register to preinc anyway.
9303 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9308 SDValue Val = cast<StoreSDNode>(N)->getValue();
9309 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9313 // If the offset is a constant, there may be other adds of constants that
9314 // can be folded with this one. We should do this to avoid having to keep
9315 // a copy of the original base pointer.
9316 SmallVector<SDNode *, 16> OtherUses;
9317 if (isa<ConstantSDNode>(Offset))
9318 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9319 UE = BasePtr.getNode()->use_end();
9321 SDUse &Use = UI.getUse();
9322 // Skip the use that is Ptr and uses of other results from BasePtr's
9323 // node (important for nodes that return multiple results).
9324 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9327 if (Use.getUser()->isPredecessorOf(N))
9330 if (Use.getUser()->getOpcode() != ISD::ADD &&
9331 Use.getUser()->getOpcode() != ISD::SUB) {
9336 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9337 if (!isa<ConstantSDNode>(Op1)) {
9342 // FIXME: In some cases, we can be smarter about this.
9343 if (Op1.getValueType() != Offset.getValueType()) {
9348 OtherUses.push_back(Use.getUser());
9352 std::swap(BasePtr, Offset);
9354 // Now check for #3 and #4.
9355 bool RealUse = false;
9357 // Caches for hasPredecessorHelper
9358 SmallPtrSet<const SDNode *, 32> Visited;
9359 SmallVector<const SDNode *, 16> Worklist;
9361 for (SDNode *Use : Ptr.getNode()->uses()) {
9364 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9367 // If Ptr may be folded in addressing mode of other use, then it's
9368 // not profitable to do this transformation.
9369 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9378 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9379 BasePtr, Offset, AM);
9381 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9382 BasePtr, Offset, AM);
9385 DEBUG(dbgs() << "\nReplacing.4 ";
9387 dbgs() << "\nWith: ";
9388 Result.getNode()->dump(&DAG);
9390 WorklistRemover DeadNodes(*this);
9392 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9393 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9395 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9398 // Finally, since the node is now dead, remove it from the graph.
9399 deleteAndRecombine(N);
9402 std::swap(BasePtr, Offset);
9404 // Replace other uses of BasePtr that can be updated to use Ptr
9405 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9406 unsigned OffsetIdx = 1;
9407 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9409 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9410 BasePtr.getNode() && "Expected BasePtr operand");
9412 // We need to replace ptr0 in the following expression:
9413 // x0 * offset0 + y0 * ptr0 = t0
9415 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9417 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9418 // indexed load/store and the expresion that needs to be re-written.
9420 // Therefore, we have:
9421 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9423 ConstantSDNode *CN =
9424 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9426 APInt Offset0 = CN->getAPIntValue();
9427 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9429 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9430 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9431 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9432 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9434 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9436 APInt CNV = Offset0;
9437 if (X0 < 0) CNV = -CNV;
9438 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9439 else CNV = CNV - Offset1;
9441 SDLoc DL(OtherUses[i]);
9443 // We can now generate the new expression.
9444 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9445 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9447 SDValue NewUse = DAG.getNode(Opcode,
9449 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9450 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9451 deleteAndRecombine(OtherUses[i]);
9454 // Replace the uses of Ptr with uses of the updated base value.
9455 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9456 deleteAndRecombine(Ptr.getNode());
9461 /// Try to combine a load/store with a add/sub of the base pointer node into a
9462 /// post-indexed load/store. The transformation folded the add/subtract into the
9463 /// new indexed load/store effectively and all of its uses are redirected to the
9465 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9466 if (Level < AfterLegalizeDAG)
9472 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9473 if (LD->isIndexed())
9475 VT = LD->getMemoryVT();
9476 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9477 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9479 Ptr = LD->getBasePtr();
9480 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9481 if (ST->isIndexed())
9483 VT = ST->getMemoryVT();
9484 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9485 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9487 Ptr = ST->getBasePtr();
9493 if (Ptr.getNode()->hasOneUse())
9496 for (SDNode *Op : Ptr.getNode()->uses()) {
9498 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9503 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9504 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9505 // Don't create a indexed load / store with zero offset.
9506 if (isNullConstant(Offset))
9509 // Try turning it into a post-indexed load / store except when
9510 // 1) All uses are load / store ops that use it as base ptr (and
9511 // it may be folded as addressing mmode).
9512 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9513 // nor a successor of N. Otherwise, if Op is folded that would
9516 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9520 bool TryNext = false;
9521 for (SDNode *Use : BasePtr.getNode()->uses()) {
9522 if (Use == Ptr.getNode())
9525 // If all the uses are load / store addresses, then don't do the
9527 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9528 bool RealUse = false;
9529 for (SDNode *UseUse : Use->uses()) {
9530 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9545 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9546 SDValue Result = isLoad
9547 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9548 BasePtr, Offset, AM)
9549 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9550 BasePtr, Offset, AM);
9553 DEBUG(dbgs() << "\nReplacing.5 ";
9555 dbgs() << "\nWith: ";
9556 Result.getNode()->dump(&DAG);
9558 WorklistRemover DeadNodes(*this);
9560 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9561 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9563 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9566 // Finally, since the node is now dead, remove it from the graph.
9567 deleteAndRecombine(N);
9569 // Replace the uses of Use with uses of the updated base value.
9570 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9571 Result.getValue(isLoad ? 1 : 0));
9572 deleteAndRecombine(Op);
9581 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9582 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9583 ISD::MemIndexedMode AM = LD->getAddressingMode();
9584 assert(AM != ISD::UNINDEXED);
9585 SDValue BP = LD->getOperand(1);
9586 SDValue Inc = LD->getOperand(2);
9588 // Some backends use TargetConstants for load offsets, but don't expect
9589 // TargetConstants in general ADD nodes. We can convert these constants into
9590 // regular Constants (if the constant is not opaque).
9591 assert((Inc.getOpcode() != ISD::TargetConstant ||
9592 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9593 "Cannot split out indexing using opaque target constants");
9594 if (Inc.getOpcode() == ISD::TargetConstant) {
9595 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9596 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9597 ConstInc->getValueType(0));
9601 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9602 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9605 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9606 LoadSDNode *LD = cast<LoadSDNode>(N);
9607 SDValue Chain = LD->getChain();
9608 SDValue Ptr = LD->getBasePtr();
9610 // If load is not volatile and there are no uses of the loaded value (and
9611 // the updated indexed value in case of indexed loads), change uses of the
9612 // chain value into uses of the chain input (i.e. delete the dead load).
9613 if (!LD->isVolatile()) {
9614 if (N->getValueType(1) == MVT::Other) {
9616 if (!N->hasAnyUseOfValue(0)) {
9617 // It's not safe to use the two value CombineTo variant here. e.g.
9618 // v1, chain2 = load chain1, loc
9619 // v2, chain3 = load chain2, loc
9621 // Now we replace use of chain2 with chain1. This makes the second load
9622 // isomorphic to the one we are deleting, and thus makes this load live.
9623 DEBUG(dbgs() << "\nReplacing.6 ";
9625 dbgs() << "\nWith chain: ";
9626 Chain.getNode()->dump(&DAG);
9628 WorklistRemover DeadNodes(*this);
9629 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9632 deleteAndRecombine(N);
9634 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9638 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9640 // If this load has an opaque TargetConstant offset, then we cannot split
9641 // the indexing into an add/sub directly (that TargetConstant may not be
9642 // valid for a different type of node, and we cannot convert an opaque
9643 // target constant into a regular constant).
9644 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9645 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9647 if (!N->hasAnyUseOfValue(0) &&
9648 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9649 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9651 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9652 Index = SplitIndexingFromLoad(LD);
9653 // Try to fold the base pointer arithmetic into subsequent loads and
9655 AddUsersToWorklist(N);
9657 Index = DAG.getUNDEF(N->getValueType(1));
9658 DEBUG(dbgs() << "\nReplacing.7 ";
9660 dbgs() << "\nWith: ";
9661 Undef.getNode()->dump(&DAG);
9662 dbgs() << " and 2 other values\n");
9663 WorklistRemover DeadNodes(*this);
9664 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9665 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9666 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9667 deleteAndRecombine(N);
9668 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9673 // If this load is directly stored, replace the load value with the stored
9675 // TODO: Handle store large -> read small portion.
9676 // TODO: Handle TRUNCSTORE/LOADEXT
9677 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9678 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9679 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9680 if (PrevST->getBasePtr() == Ptr &&
9681 PrevST->getValue().getValueType() == N->getValueType(0))
9682 return CombineTo(N, Chain.getOperand(1), Chain);
9686 // Try to infer better alignment information than the load already has.
9687 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9688 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9689 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9691 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9692 LD->getValueType(0),
9693 Chain, Ptr, LD->getPointerInfo(),
9695 LD->isVolatile(), LD->isNonTemporal(),
9696 LD->isInvariant(), Align, LD->getAAInfo());
9697 if (NewLoad.getNode() != N)
9698 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9703 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9704 : DAG.getSubtarget().useAA();
9706 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9707 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9710 if (UseAA && LD->isUnindexed()) {
9711 // Walk up chain skipping non-aliasing memory nodes.
9712 SDValue BetterChain = FindBetterChain(N, Chain);
9714 // If there is a better chain.
9715 if (Chain != BetterChain) {
9718 // Replace the chain to void dependency.
9719 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9720 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9721 BetterChain, Ptr, LD->getMemOperand());
9723 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9724 LD->getValueType(0),
9725 BetterChain, Ptr, LD->getMemoryVT(),
9726 LD->getMemOperand());
9729 // Create token factor to keep old chain connected.
9730 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9731 MVT::Other, Chain, ReplLoad.getValue(1));
9733 // Make sure the new and old chains are cleaned up.
9734 AddToWorklist(Token.getNode());
9736 // Replace uses with load result and token factor. Don't add users
9738 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9742 // Try transforming N to an indexed load.
9743 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9744 return SDValue(N, 0);
9746 // Try to slice up N to more direct loads if the slices are mapped to
9747 // different register banks or pairing can take place.
9749 return SDValue(N, 0);
9755 /// \brief Helper structure used to slice a load in smaller loads.
9756 /// Basically a slice is obtained from the following sequence:
9757 /// Origin = load Ty1, Base
9758 /// Shift = srl Ty1 Origin, CstTy Amount
9759 /// Inst = trunc Shift to Ty2
9761 /// Then, it will be rewriten into:
9762 /// Slice = load SliceTy, Base + SliceOffset
9763 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9765 /// SliceTy is deduced from the number of bits that are actually used to
9767 struct LoadedSlice {
9768 /// \brief Helper structure used to compute the cost of a slice.
9770 /// Are we optimizing for code size.
9775 unsigned CrossRegisterBanksCopies;
9779 Cost(bool ForCodeSize = false)
9780 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9781 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9783 /// \brief Get the cost of one isolated slice.
9784 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9785 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9786 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9787 EVT TruncType = LS.Inst->getValueType(0);
9788 EVT LoadedType = LS.getLoadedType();
9789 if (TruncType != LoadedType &&
9790 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9794 /// \brief Account for slicing gain in the current cost.
9795 /// Slicing provide a few gains like removing a shift or a
9796 /// truncate. This method allows to grow the cost of the original
9797 /// load with the gain from this slice.
9798 void addSliceGain(const LoadedSlice &LS) {
9799 // Each slice saves a truncate.
9800 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9801 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9802 LS.Inst->getValueType(0)))
9804 // If there is a shift amount, this slice gets rid of it.
9807 // If this slice can merge a cross register bank copy, account for it.
9808 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9809 ++CrossRegisterBanksCopies;
9812 Cost &operator+=(const Cost &RHS) {
9814 Truncates += RHS.Truncates;
9815 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9821 bool operator==(const Cost &RHS) const {
9822 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9823 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9824 ZExts == RHS.ZExts && Shift == RHS.Shift;
9827 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9829 bool operator<(const Cost &RHS) const {
9830 // Assume cross register banks copies are as expensive as loads.
9831 // FIXME: Do we want some more target hooks?
9832 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9833 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9834 // Unless we are optimizing for code size, consider the
9835 // expensive operation first.
9836 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9837 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9838 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9839 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9842 bool operator>(const Cost &RHS) const { return RHS < *this; }
9844 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9846 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9848 // The last instruction that represent the slice. This should be a
9849 // truncate instruction.
9851 // The original load instruction.
9853 // The right shift amount in bits from the original load.
9855 // The DAG from which Origin came from.
9856 // This is used to get some contextual information about legal types, etc.
9859 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9860 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9861 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9863 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9864 /// \return Result is \p BitWidth and has used bits set to 1 and
9865 /// not used bits set to 0.
9866 APInt getUsedBits() const {
9867 // Reproduce the trunc(lshr) sequence:
9868 // - Start from the truncated value.
9869 // - Zero extend to the desired bit width.
9871 assert(Origin && "No original load to compare against.");
9872 unsigned BitWidth = Origin->getValueSizeInBits(0);
9873 assert(Inst && "This slice is not bound to an instruction");
9874 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9875 "Extracted slice is bigger than the whole type!");
9876 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9877 UsedBits.setAllBits();
9878 UsedBits = UsedBits.zext(BitWidth);
9883 /// \brief Get the size of the slice to be loaded in bytes.
9884 unsigned getLoadedSize() const {
9885 unsigned SliceSize = getUsedBits().countPopulation();
9886 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9887 return SliceSize / 8;
9890 /// \brief Get the type that will be loaded for this slice.
9891 /// Note: This may not be the final type for the slice.
9892 EVT getLoadedType() const {
9893 assert(DAG && "Missing context");
9894 LLVMContext &Ctxt = *DAG->getContext();
9895 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9898 /// \brief Get the alignment of the load used for this slice.
9899 unsigned getAlignment() const {
9900 unsigned Alignment = Origin->getAlignment();
9901 unsigned Offset = getOffsetFromBase();
9903 Alignment = MinAlign(Alignment, Alignment + Offset);
9907 /// \brief Check if this slice can be rewritten with legal operations.
9908 bool isLegal() const {
9909 // An invalid slice is not legal.
9910 if (!Origin || !Inst || !DAG)
9913 // Offsets are for indexed load only, we do not handle that.
9914 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9917 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9919 // Check that the type is legal.
9920 EVT SliceType = getLoadedType();
9921 if (!TLI.isTypeLegal(SliceType))
9924 // Check that the load is legal for this type.
9925 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9928 // Check that the offset can be computed.
9929 // 1. Check its type.
9930 EVT PtrType = Origin->getBasePtr().getValueType();
9931 if (PtrType == MVT::Untyped || PtrType.isExtended())
9934 // 2. Check that it fits in the immediate.
9935 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9938 // 3. Check that the computation is legal.
9939 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9942 // Check that the zext is legal if it needs one.
9943 EVT TruncateType = Inst->getValueType(0);
9944 if (TruncateType != SliceType &&
9945 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9951 /// \brief Get the offset in bytes of this slice in the original chunk of
9953 /// \pre DAG != nullptr.
9954 uint64_t getOffsetFromBase() const {
9955 assert(DAG && "Missing context.");
9956 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9957 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9958 uint64_t Offset = Shift / 8;
9959 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9960 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9961 "The size of the original loaded type is not a multiple of a"
9963 // If Offset is bigger than TySizeInBytes, it means we are loading all
9964 // zeros. This should have been optimized before in the process.
9965 assert(TySizeInBytes > Offset &&
9966 "Invalid shift amount for given loaded size");
9968 Offset = TySizeInBytes - Offset - getLoadedSize();
9972 /// \brief Generate the sequence of instructions to load the slice
9973 /// represented by this object and redirect the uses of this slice to
9974 /// this new sequence of instructions.
9975 /// \pre this->Inst && this->Origin are valid Instructions and this
9976 /// object passed the legal check: LoadedSlice::isLegal returned true.
9977 /// \return The last instruction of the sequence used to load the slice.
9978 SDValue loadSlice() const {
9979 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9980 const SDValue &OldBaseAddr = Origin->getBasePtr();
9981 SDValue BaseAddr = OldBaseAddr;
9982 // Get the offset in that chunk of bytes w.r.t. the endianess.
9983 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9984 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9986 // BaseAddr = BaseAddr + Offset.
9987 EVT ArithType = BaseAddr.getValueType();
9989 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9990 DAG->getConstant(Offset, DL, ArithType));
9993 // Create the type of the loaded slice according to its size.
9994 EVT SliceType = getLoadedType();
9996 // Create the load for the slice.
9997 SDValue LastInst = DAG->getLoad(
9998 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9999 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10000 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10001 // If the final type is not the same as the loaded type, this means that
10002 // we have to pad with zero. Create a zero extend for that.
10003 EVT FinalType = Inst->getValueType(0);
10004 if (SliceType != FinalType)
10006 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10010 /// \brief Check if this slice can be merged with an expensive cross register
10011 /// bank copy. E.g.,
10013 /// f = bitcast i32 i to float
10014 bool canMergeExpensiveCrossRegisterBankCopy() const {
10015 if (!Inst || !Inst->hasOneUse())
10017 SDNode *Use = *Inst->use_begin();
10018 if (Use->getOpcode() != ISD::BITCAST)
10020 assert(DAG && "Missing context");
10021 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10022 EVT ResVT = Use->getValueType(0);
10023 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10024 const TargetRegisterClass *ArgRC =
10025 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10026 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10029 // At this point, we know that we perform a cross-register-bank copy.
10030 // Check if it is expensive.
10031 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10032 // Assume bitcasts are cheap, unless both register classes do not
10033 // explicitly share a common sub class.
10034 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10037 // Check if it will be merged with the load.
10038 // 1. Check the alignment constraint.
10039 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10040 ResVT.getTypeForEVT(*DAG->getContext()));
10042 if (RequiredAlignment > getAlignment())
10045 // 2. Check that the load is a legal operation for that type.
10046 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10049 // 3. Check that we do not have a zext in the way.
10050 if (Inst->getValueType(0) != getLoadedType())
10058 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10059 /// \p UsedBits looks like 0..0 1..1 0..0.
10060 static bool areUsedBitsDense(const APInt &UsedBits) {
10061 // If all the bits are one, this is dense!
10062 if (UsedBits.isAllOnesValue())
10065 // Get rid of the unused bits on the right.
10066 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10067 // Get rid of the unused bits on the left.
10068 if (NarrowedUsedBits.countLeadingZeros())
10069 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10070 // Check that the chunk of bits is completely used.
10071 return NarrowedUsedBits.isAllOnesValue();
10074 /// \brief Check whether or not \p First and \p Second are next to each other
10075 /// in memory. This means that there is no hole between the bits loaded
10076 /// by \p First and the bits loaded by \p Second.
10077 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10078 const LoadedSlice &Second) {
10079 assert(First.Origin == Second.Origin && First.Origin &&
10080 "Unable to match different memory origins.");
10081 APInt UsedBits = First.getUsedBits();
10082 assert((UsedBits & Second.getUsedBits()) == 0 &&
10083 "Slices are not supposed to overlap.");
10084 UsedBits |= Second.getUsedBits();
10085 return areUsedBitsDense(UsedBits);
10088 /// \brief Adjust the \p GlobalLSCost according to the target
10089 /// paring capabilities and the layout of the slices.
10090 /// \pre \p GlobalLSCost should account for at least as many loads as
10091 /// there is in the slices in \p LoadedSlices.
10092 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10093 LoadedSlice::Cost &GlobalLSCost) {
10094 unsigned NumberOfSlices = LoadedSlices.size();
10095 // If there is less than 2 elements, no pairing is possible.
10096 if (NumberOfSlices < 2)
10099 // Sort the slices so that elements that are likely to be next to each
10100 // other in memory are next to each other in the list.
10101 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10102 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10103 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10104 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10106 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10107 // First (resp. Second) is the first (resp. Second) potentially candidate
10108 // to be placed in a paired load.
10109 const LoadedSlice *First = nullptr;
10110 const LoadedSlice *Second = nullptr;
10111 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10112 // Set the beginning of the pair.
10115 Second = &LoadedSlices[CurrSlice];
10117 // If First is NULL, it means we start a new pair.
10118 // Get to the next slice.
10122 EVT LoadedType = First->getLoadedType();
10124 // If the types of the slices are different, we cannot pair them.
10125 if (LoadedType != Second->getLoadedType())
10128 // Check if the target supplies paired loads for this type.
10129 unsigned RequiredAlignment = 0;
10130 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10131 // move to the next pair, this type is hopeless.
10135 // Check if we meet the alignment requirement.
10136 if (RequiredAlignment > First->getAlignment())
10139 // Check that both loads are next to each other in memory.
10140 if (!areSlicesNextToEachOther(*First, *Second))
10143 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10144 --GlobalLSCost.Loads;
10145 // Move to the next pair.
10150 /// \brief Check the profitability of all involved LoadedSlice.
10151 /// Currently, it is considered profitable if there is exactly two
10152 /// involved slices (1) which are (2) next to each other in memory, and
10153 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10155 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10156 /// the elements themselves.
10158 /// FIXME: When the cost model will be mature enough, we can relax
10159 /// constraints (1) and (2).
10160 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10161 const APInt &UsedBits, bool ForCodeSize) {
10162 unsigned NumberOfSlices = LoadedSlices.size();
10163 if (StressLoadSlicing)
10164 return NumberOfSlices > 1;
10167 if (NumberOfSlices != 2)
10171 if (!areUsedBitsDense(UsedBits))
10175 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10176 // The original code has one big load.
10177 OrigCost.Loads = 1;
10178 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10179 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10180 // Accumulate the cost of all the slices.
10181 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10182 GlobalSlicingCost += SliceCost;
10184 // Account as cost in the original configuration the gain obtained
10185 // with the current slices.
10186 OrigCost.addSliceGain(LS);
10189 // If the target supports paired load, adjust the cost accordingly.
10190 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10191 return OrigCost > GlobalSlicingCost;
10194 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10195 /// operations, split it in the various pieces being extracted.
10197 /// This sort of thing is introduced by SROA.
10198 /// This slicing takes care not to insert overlapping loads.
10199 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10200 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10201 if (Level < AfterLegalizeDAG)
10204 LoadSDNode *LD = cast<LoadSDNode>(N);
10205 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10206 !LD->getValueType(0).isInteger())
10209 // Keep track of already used bits to detect overlapping values.
10210 // In that case, we will just abort the transformation.
10211 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10213 SmallVector<LoadedSlice, 4> LoadedSlices;
10215 // Check if this load is used as several smaller chunks of bits.
10216 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10217 // of computation for each trunc.
10218 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10219 UI != UIEnd; ++UI) {
10220 // Skip the uses of the chain.
10221 if (UI.getUse().getResNo() != 0)
10224 SDNode *User = *UI;
10225 unsigned Shift = 0;
10227 // Check if this is a trunc(lshr).
10228 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10229 isa<ConstantSDNode>(User->getOperand(1))) {
10230 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10231 User = *User->use_begin();
10234 // At this point, User is a Truncate, iff we encountered, trunc or
10236 if (User->getOpcode() != ISD::TRUNCATE)
10239 // The width of the type must be a power of 2 and greater than 8-bits.
10240 // Otherwise the load cannot be represented in LLVM IR.
10241 // Moreover, if we shifted with a non-8-bits multiple, the slice
10242 // will be across several bytes. We do not support that.
10243 unsigned Width = User->getValueSizeInBits(0);
10244 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10247 // Build the slice for this chain of computations.
10248 LoadedSlice LS(User, LD, Shift, &DAG);
10249 APInt CurrentUsedBits = LS.getUsedBits();
10251 // Check if this slice overlaps with another.
10252 if ((CurrentUsedBits & UsedBits) != 0)
10254 // Update the bits used globally.
10255 UsedBits |= CurrentUsedBits;
10257 // Check if the new slice would be legal.
10261 // Record the slice.
10262 LoadedSlices.push_back(LS);
10265 // Abort slicing if it does not seem to be profitable.
10266 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10271 // Rewrite each chain to use an independent load.
10272 // By construction, each chain can be represented by a unique load.
10274 // Prepare the argument for the new token factor for all the slices.
10275 SmallVector<SDValue, 8> ArgChains;
10276 for (SmallVectorImpl<LoadedSlice>::const_iterator
10277 LSIt = LoadedSlices.begin(),
10278 LSItEnd = LoadedSlices.end();
10279 LSIt != LSItEnd; ++LSIt) {
10280 SDValue SliceInst = LSIt->loadSlice();
10281 CombineTo(LSIt->Inst, SliceInst, true);
10282 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10283 SliceInst = SliceInst.getOperand(0);
10284 assert(SliceInst->getOpcode() == ISD::LOAD &&
10285 "It takes more than a zext to get to the loaded slice!!");
10286 ArgChains.push_back(SliceInst.getValue(1));
10289 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10291 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10295 /// Check to see if V is (and load (ptr), imm), where the load is having
10296 /// specific bytes cleared out. If so, return the byte size being masked out
10297 /// and the shift amount.
10298 static std::pair<unsigned, unsigned>
10299 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10300 std::pair<unsigned, unsigned> Result(0, 0);
10302 // Check for the structure we're looking for.
10303 if (V->getOpcode() != ISD::AND ||
10304 !isa<ConstantSDNode>(V->getOperand(1)) ||
10305 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10308 // Check the chain and pointer.
10309 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10310 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10312 // The store should be chained directly to the load or be an operand of a
10314 if (LD == Chain.getNode())
10316 else if (Chain->getOpcode() != ISD::TokenFactor)
10317 return Result; // Fail.
10320 for (const SDValue &ChainOp : Chain->op_values())
10321 if (ChainOp.getNode() == LD) {
10325 if (!isOk) return Result;
10328 // This only handles simple types.
10329 if (V.getValueType() != MVT::i16 &&
10330 V.getValueType() != MVT::i32 &&
10331 V.getValueType() != MVT::i64)
10334 // Check the constant mask. Invert it so that the bits being masked out are
10335 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10336 // follow the sign bit for uniformity.
10337 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10338 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10339 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10340 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10341 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10342 if (NotMaskLZ == 64) return Result; // All zero mask.
10344 // See if we have a continuous run of bits. If so, we have 0*1+0*
10345 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10348 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10349 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10350 NotMaskLZ -= 64-V.getValueSizeInBits();
10352 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10353 switch (MaskedBytes) {
10357 default: return Result; // All one mask, or 5-byte mask.
10360 // Verify that the first bit starts at a multiple of mask so that the access
10361 // is aligned the same as the access width.
10362 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10364 Result.first = MaskedBytes;
10365 Result.second = NotMaskTZ/8;
10370 /// Check to see if IVal is something that provides a value as specified by
10371 /// MaskInfo. If so, replace the specified store with a narrower store of
10372 /// truncated IVal.
10374 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10375 SDValue IVal, StoreSDNode *St,
10377 unsigned NumBytes = MaskInfo.first;
10378 unsigned ByteShift = MaskInfo.second;
10379 SelectionDAG &DAG = DC->getDAG();
10381 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10382 // that uses this. If not, this is not a replacement.
10383 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10384 ByteShift*8, (ByteShift+NumBytes)*8);
10385 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10387 // Check that it is legal on the target to do this. It is legal if the new
10388 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10390 MVT VT = MVT::getIntegerVT(NumBytes*8);
10391 if (!DC->isTypeLegal(VT))
10394 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10395 // shifted by ByteShift and truncated down to NumBytes.
10398 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10399 DAG.getConstant(ByteShift*8, DL,
10400 DC->getShiftAmountTy(IVal.getValueType())));
10403 // Figure out the offset for the store and the alignment of the access.
10405 unsigned NewAlign = St->getAlignment();
10407 if (DAG.getDataLayout().isLittleEndian())
10408 StOffset = ByteShift;
10410 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10412 SDValue Ptr = St->getBasePtr();
10415 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10416 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10417 NewAlign = MinAlign(NewAlign, StOffset);
10420 // Truncate down to the new size.
10421 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10424 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10425 St->getPointerInfo().getWithOffset(StOffset),
10426 false, false, NewAlign).getNode();
10430 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10431 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10432 /// narrowing the load and store if it would end up being a win for performance
10434 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10435 StoreSDNode *ST = cast<StoreSDNode>(N);
10436 if (ST->isVolatile())
10439 SDValue Chain = ST->getChain();
10440 SDValue Value = ST->getValue();
10441 SDValue Ptr = ST->getBasePtr();
10442 EVT VT = Value.getValueType();
10444 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10447 unsigned Opc = Value.getOpcode();
10449 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10450 // is a byte mask indicating a consecutive number of bytes, check to see if
10451 // Y is known to provide just those bytes. If so, we try to replace the
10452 // load + replace + store sequence with a single (narrower) store, which makes
10454 if (Opc == ISD::OR) {
10455 std::pair<unsigned, unsigned> MaskedLoad;
10456 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10457 if (MaskedLoad.first)
10458 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10459 Value.getOperand(1), ST,this))
10460 return SDValue(NewST, 0);
10462 // Or is commutative, so try swapping X and Y.
10463 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10464 if (MaskedLoad.first)
10465 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10466 Value.getOperand(0), ST,this))
10467 return SDValue(NewST, 0);
10470 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10471 Value.getOperand(1).getOpcode() != ISD::Constant)
10474 SDValue N0 = Value.getOperand(0);
10475 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10476 Chain == SDValue(N0.getNode(), 1)) {
10477 LoadSDNode *LD = cast<LoadSDNode>(N0);
10478 if (LD->getBasePtr() != Ptr ||
10479 LD->getPointerInfo().getAddrSpace() !=
10480 ST->getPointerInfo().getAddrSpace())
10483 // Find the type to narrow it the load / op / store to.
10484 SDValue N1 = Value.getOperand(1);
10485 unsigned BitWidth = N1.getValueSizeInBits();
10486 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10487 if (Opc == ISD::AND)
10488 Imm ^= APInt::getAllOnesValue(BitWidth);
10489 if (Imm == 0 || Imm.isAllOnesValue())
10491 unsigned ShAmt = Imm.countTrailingZeros();
10492 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10493 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10494 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10495 // The narrowing should be profitable, the load/store operation should be
10496 // legal (or custom) and the store size should be equal to the NewVT width.
10497 while (NewBW < BitWidth &&
10498 (NewVT.getStoreSizeInBits() != NewBW ||
10499 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10500 !TLI.isNarrowingProfitable(VT, NewVT))) {
10501 NewBW = NextPowerOf2(NewBW);
10502 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10504 if (NewBW >= BitWidth)
10507 // If the lsb changed does not start at the type bitwidth boundary,
10508 // start at the previous one.
10510 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10511 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10512 std::min(BitWidth, ShAmt + NewBW));
10513 if ((Imm & Mask) == Imm) {
10514 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10515 if (Opc == ISD::AND)
10516 NewImm ^= APInt::getAllOnesValue(NewBW);
10517 uint64_t PtrOff = ShAmt / 8;
10518 // For big endian targets, we need to adjust the offset to the pointer to
10519 // load the correct bytes.
10520 if (DAG.getDataLayout().isBigEndian())
10521 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10523 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10524 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10525 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10528 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10529 Ptr.getValueType(), Ptr,
10530 DAG.getConstant(PtrOff, SDLoc(LD),
10531 Ptr.getValueType()));
10532 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10533 LD->getChain(), NewPtr,
10534 LD->getPointerInfo().getWithOffset(PtrOff),
10535 LD->isVolatile(), LD->isNonTemporal(),
10536 LD->isInvariant(), NewAlign,
10538 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10539 DAG.getConstant(NewImm, SDLoc(Value),
10541 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10543 ST->getPointerInfo().getWithOffset(PtrOff),
10544 false, false, NewAlign);
10546 AddToWorklist(NewPtr.getNode());
10547 AddToWorklist(NewLD.getNode());
10548 AddToWorklist(NewVal.getNode());
10549 WorklistRemover DeadNodes(*this);
10550 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10559 /// For a given floating point load / store pair, if the load value isn't used
10560 /// by any other operations, then consider transforming the pair to integer
10561 /// load / store operations if the target deems the transformation profitable.
10562 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10563 StoreSDNode *ST = cast<StoreSDNode>(N);
10564 SDValue Chain = ST->getChain();
10565 SDValue Value = ST->getValue();
10566 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10567 Value.hasOneUse() &&
10568 Chain == SDValue(Value.getNode(), 1)) {
10569 LoadSDNode *LD = cast<LoadSDNode>(Value);
10570 EVT VT = LD->getMemoryVT();
10571 if (!VT.isFloatingPoint() ||
10572 VT != ST->getMemoryVT() ||
10573 LD->isNonTemporal() ||
10574 ST->isNonTemporal() ||
10575 LD->getPointerInfo().getAddrSpace() != 0 ||
10576 ST->getPointerInfo().getAddrSpace() != 0)
10579 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10580 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10581 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10582 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10583 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10586 unsigned LDAlign = LD->getAlignment();
10587 unsigned STAlign = ST->getAlignment();
10588 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10589 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10590 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10593 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10594 LD->getChain(), LD->getBasePtr(),
10595 LD->getPointerInfo(),
10596 false, false, false, LDAlign);
10598 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10599 NewLD, ST->getBasePtr(),
10600 ST->getPointerInfo(),
10601 false, false, STAlign);
10603 AddToWorklist(NewLD.getNode());
10604 AddToWorklist(NewST.getNode());
10605 WorklistRemover DeadNodes(*this);
10606 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10615 /// Helper struct to parse and store a memory address as base + index + offset.
10616 /// We ignore sign extensions when it is safe to do so.
10617 /// The following two expressions are not equivalent. To differentiate we need
10618 /// to store whether there was a sign extension involved in the index
10620 /// (load (i64 add (i64 copyfromreg %c)
10621 /// (i64 signextend (add (i8 load %index)
10625 /// (load (i64 add (i64 copyfromreg %c)
10626 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10628 struct BaseIndexOffset {
10632 bool IsIndexSignExt;
10634 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10636 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10637 bool IsIndexSignExt) :
10638 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10640 bool equalBaseIndex(const BaseIndexOffset &Other) {
10641 return Other.Base == Base && Other.Index == Index &&
10642 Other.IsIndexSignExt == IsIndexSignExt;
10645 /// Parses tree in Ptr for base, index, offset addresses.
10646 static BaseIndexOffset match(SDValue Ptr) {
10647 bool IsIndexSignExt = false;
10649 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10650 // instruction, then it could be just the BASE or everything else we don't
10651 // know how to handle. Just use Ptr as BASE and give up.
10652 if (Ptr->getOpcode() != ISD::ADD)
10653 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10655 // We know that we have at least an ADD instruction. Try to pattern match
10656 // the simple case of BASE + OFFSET.
10657 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10658 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10659 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10663 // Inside a loop the current BASE pointer is calculated using an ADD and a
10664 // MUL instruction. In this case Ptr is the actual BASE pointer.
10665 // (i64 add (i64 %array_ptr)
10666 // (i64 mul (i64 %induction_var)
10667 // (i64 %element_size)))
10668 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10669 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10671 // Look at Base + Index + Offset cases.
10672 SDValue Base = Ptr->getOperand(0);
10673 SDValue IndexOffset = Ptr->getOperand(1);
10675 // Skip signextends.
10676 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10677 IndexOffset = IndexOffset->getOperand(0);
10678 IsIndexSignExt = true;
10681 // Either the case of Base + Index (no offset) or something else.
10682 if (IndexOffset->getOpcode() != ISD::ADD)
10683 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10685 // Now we have the case of Base + Index + offset.
10686 SDValue Index = IndexOffset->getOperand(0);
10687 SDValue Offset = IndexOffset->getOperand(1);
10689 if (!isa<ConstantSDNode>(Offset))
10690 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10692 // Ignore signextends.
10693 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10694 Index = Index->getOperand(0);
10695 IsIndexSignExt = true;
10696 } else IsIndexSignExt = false;
10698 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10699 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10704 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10706 ArrayRef<MemOpLink> Stores,
10708 SmallVector<SDValue, 8> BuildVector;
10710 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10711 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10713 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10716 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10717 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10718 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10719 // Make sure we have something to merge.
10723 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10724 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10725 unsigned LatestNodeUsed = 0;
10727 for (unsigned i=0; i < NumStores; ++i) {
10728 // Find a chain for the new wide-store operand. Notice that some
10729 // of the store nodes that we found may not be selected for inclusion
10730 // in the wide store. The chain we use needs to be the chain of the
10731 // latest store node which is *used* and replaced by the wide store.
10732 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10733 LatestNodeUsed = i;
10736 // The latest Node in the DAG.
10737 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10738 SDLoc DL(StoreNodes[0].MemNode);
10742 bool IsVec = MemVT.isVector();
10743 unsigned Elts = NumStores;
10745 // When merging vector stores, get the total number of elements.
10746 Elts *= MemVT.getVectorNumElements();
10748 // Get the type for the merged vector store.
10749 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10750 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10752 if (IsConstantSrc) {
10753 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10755 SmallVector<SDValue, 8> Ops;
10756 for (unsigned i = 0; i < NumStores; ++i) {
10757 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10758 SDValue Val = St->getValue();
10759 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10760 if (Val.getValueType() != MemVT)
10762 Ops.push_back(Val);
10765 // Build the extracted vector elements back into a vector.
10766 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10769 // We should always use a vector store when merging extracted vector
10770 // elements, so this path implies a store of constants.
10771 assert(IsConstantSrc && "Merged vector elements should use vector store");
10773 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10774 APInt StoreInt(SizeInBits, 0);
10776 // Construct a single integer constant which is made of the smaller
10777 // constant inputs.
10778 bool IsLE = DAG.getDataLayout().isLittleEndian();
10779 for (unsigned i = 0; i < NumStores; ++i) {
10780 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10781 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10782 SDValue Val = St->getValue();
10783 StoreInt <<= ElementSizeBytes * 8;
10784 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10785 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10786 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10787 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10789 llvm_unreachable("Invalid constant element type");
10793 // Create the new Load and Store operations.
10794 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10795 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10798 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10799 FirstInChain->getBasePtr(),
10800 FirstInChain->getPointerInfo(),
10802 FirstInChain->getAlignment());
10804 // Replace the last store with the new store
10805 CombineTo(LatestOp, NewStore);
10806 // Erase all other stores.
10807 for (unsigned i = 0; i < NumStores; ++i) {
10808 if (StoreNodes[i].MemNode == LatestOp)
10810 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10811 // ReplaceAllUsesWith will replace all uses that existed when it was
10812 // called, but graph optimizations may cause new ones to appear. For
10813 // example, the case in pr14333 looks like
10815 // St's chain -> St -> another store -> X
10817 // And the only difference from St to the other store is the chain.
10818 // When we change it's chain to be St's chain they become identical,
10819 // get CSEed and the net result is that X is now a use of St.
10820 // Since we know that St is redundant, just iterate.
10821 while (!St->use_empty())
10822 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10823 deleteAndRecombine(St);
10829 void DAGCombiner::getStoreMergeAndAliasCandidates(
10830 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10831 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10832 // This holds the base pointer, index, and the offset in bytes from the base
10834 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10836 // We must have a base and an offset.
10837 if (!BasePtr.Base.getNode())
10840 // Do not handle stores to undef base pointers.
10841 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10844 // Walk up the chain and look for nodes with offsets from the same
10845 // base pointer. Stop when reaching an instruction with a different kind
10846 // or instruction which has a different base pointer.
10847 EVT MemVT = St->getMemoryVT();
10849 StoreSDNode *Index = St;
10852 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10853 : DAG.getSubtarget().useAA();
10856 // Look at other users of the same chain. Stores on the same chain do not
10857 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10858 // to be on the same chain, so don't bother looking at adjacent chains.
10860 SDValue Chain = St->getChain();
10861 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10862 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10864 if (OtherST->isVolatile() || OtherST->isIndexed())
10867 if (OtherST->getMemoryVT() != MemVT)
10870 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10872 if (Ptr.equalBaseIndex(BasePtr))
10873 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
10881 // If the chain has more than one use, then we can't reorder the mem ops.
10882 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10885 // Find the base pointer and offset for this memory node.
10886 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10888 // Check that the base pointer is the same as the original one.
10889 if (!Ptr.equalBaseIndex(BasePtr))
10892 // The memory operands must not be volatile.
10893 if (Index->isVolatile() || Index->isIndexed())
10897 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10898 if (St->isTruncatingStore())
10901 // The stored memory type must be the same.
10902 if (Index->getMemoryVT() != MemVT)
10905 // We found a potential memory operand to merge.
10906 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10908 // Find the next memory operand in the chain. If the next operand in the
10909 // chain is a store then move up and continue the scan with the next
10910 // memory operand. If the next operand is a load save it and use alias
10911 // information to check if it interferes with anything.
10912 SDNode *NextInChain = Index->getChain().getNode();
10914 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10915 // We found a store node. Use it for the next iteration.
10918 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10919 if (Ldn->isVolatile()) {
10924 // Save the load node for later. Continue the scan.
10925 AliasLoadNodes.push_back(Ldn);
10926 NextInChain = Ldn->getChain().getNode();
10936 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10937 if (OptLevel == CodeGenOpt::None)
10940 EVT MemVT = St->getMemoryVT();
10941 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10942 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10943 Attribute::NoImplicitFloat);
10945 // This function cannot currently deal with non-byte-sized memory sizes.
10946 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10949 // Don't merge vectors into wider inputs.
10950 if (MemVT.isVector() || !MemVT.isSimple())
10953 // Perform an early exit check. Do not bother looking at stored values that
10954 // are not constants, loads, or extracted vector elements.
10955 SDValue StoredVal = St->getValue();
10956 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10957 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10958 isa<ConstantFPSDNode>(StoredVal);
10959 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10961 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10964 // Only look at ends of store sequences.
10965 SDValue Chain = SDValue(St, 0);
10966 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10969 // Save the LoadSDNodes that we find in the chain.
10970 // We need to make sure that these nodes do not interfere with
10971 // any of the store nodes.
10972 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10974 // Save the StoreSDNodes that we find in the chain.
10975 SmallVector<MemOpLink, 8> StoreNodes;
10977 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10979 // Check if there is anything to merge.
10980 if (StoreNodes.size() < 2)
10983 // Sort the memory operands according to their distance from the base pointer.
10984 std::sort(StoreNodes.begin(), StoreNodes.end(),
10985 [](MemOpLink LHS, MemOpLink RHS) {
10986 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10987 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10988 LHS.SequenceNum > RHS.SequenceNum);
10991 // Scan the memory operations on the chain and find the first non-consecutive
10992 // store memory address.
10993 unsigned LastConsecutiveStore = 0;
10994 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10995 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10997 // Check that the addresses are consecutive starting from the second
10998 // element in the list of stores.
11000 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11001 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11005 bool Alias = false;
11006 // Check if this store interferes with any of the loads that we found.
11007 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11008 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11012 // We found a load that alias with this store. Stop the sequence.
11016 // Mark this node as useful.
11017 LastConsecutiveStore = i;
11020 // The node with the lowest store address.
11021 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11022 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11023 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11024 LLVMContext &Context = *DAG.getContext();
11025 const DataLayout &DL = DAG.getDataLayout();
11027 // Store the constants into memory as one consecutive store.
11028 if (IsConstantSrc) {
11029 unsigned LastLegalType = 0;
11030 unsigned LastLegalVectorType = 0;
11031 bool NonZero = false;
11032 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11033 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11034 SDValue StoredVal = St->getValue();
11036 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11037 NonZero |= !C->isNullValue();
11038 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11039 NonZero |= !C->getConstantFPValue()->isNullValue();
11045 // Find a legal type for the constant store.
11046 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11047 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11049 if (TLI.isTypeLegal(StoreTy) &&
11050 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11051 FirstStoreAlign, &IsFast) && IsFast) {
11052 LastLegalType = i+1;
11053 // Or check whether a truncstore is legal.
11054 } else if (TLI.getTypeAction(Context, StoreTy) ==
11055 TargetLowering::TypePromoteInteger) {
11056 EVT LegalizedStoredValueTy =
11057 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11058 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11059 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11060 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11062 LastLegalType = i + 1;
11066 // We only use vectors if the constant is known to be zero or the target
11067 // allows it and the function is not marked with the noimplicitfloat
11069 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11072 // Find a legal type for the vector store.
11073 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11074 if (TLI.isTypeLegal(Ty) &&
11075 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11076 FirstStoreAlign, &IsFast) && IsFast)
11077 LastLegalVectorType = i + 1;
11081 // Check if we found a legal integer type to store.
11082 if (LastLegalType == 0 && LastLegalVectorType == 0)
11085 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11086 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11088 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11092 // When extracting multiple vector elements, try to store them
11093 // in one vector store rather than a sequence of scalar stores.
11094 if (IsExtractVecEltSrc) {
11095 unsigned NumElem = 0;
11096 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11097 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11098 SDValue StoredVal = St->getValue();
11099 // This restriction could be loosened.
11100 // Bail out if any stored values are not elements extracted from a vector.
11101 // It should be possible to handle mixed sources, but load sources need
11102 // more careful handling (see the block of code below that handles
11103 // consecutive loads).
11104 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11107 // Find a legal type for the vector store.
11108 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11110 if (TLI.isTypeLegal(Ty) &&
11111 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11112 FirstStoreAlign, &IsFast) && IsFast)
11116 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11120 // Below we handle the case of multiple consecutive stores that
11121 // come from multiple consecutive loads. We merge them into a single
11122 // wide load and a single wide store.
11124 // Look for load nodes which are used by the stored values.
11125 SmallVector<MemOpLink, 8> LoadNodes;
11127 // Find acceptable loads. Loads need to have the same chain (token factor),
11128 // must not be zext, volatile, indexed, and they must be consecutive.
11129 BaseIndexOffset LdBasePtr;
11130 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11131 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11132 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11135 // Loads must only have one use.
11136 if (!Ld->hasNUsesOfValue(1, 0))
11139 // The memory operands must not be volatile.
11140 if (Ld->isVolatile() || Ld->isIndexed())
11143 // We do not accept ext loads.
11144 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11147 // The stored memory type must be the same.
11148 if (Ld->getMemoryVT() != MemVT)
11151 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11152 // If this is not the first ptr that we check.
11153 if (LdBasePtr.Base.getNode()) {
11154 // The base ptr must be the same.
11155 if (!LdPtr.equalBaseIndex(LdBasePtr))
11158 // Check that all other base pointers are the same as this one.
11162 // We found a potential memory operand to merge.
11163 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11166 if (LoadNodes.size() < 2)
11169 // If we have load/store pair instructions and we only have two values,
11171 unsigned RequiredAlignment;
11172 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11173 St->getAlignment() >= RequiredAlignment)
11176 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11177 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11178 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11180 // Scan the memory operations on the chain and find the first non-consecutive
11181 // load memory address. These variables hold the index in the store node
11183 unsigned LastConsecutiveLoad = 0;
11184 // This variable refers to the size and not index in the array.
11185 unsigned LastLegalVectorType = 0;
11186 unsigned LastLegalIntegerType = 0;
11187 StartAddress = LoadNodes[0].OffsetFromBase;
11188 SDValue FirstChain = FirstLoad->getChain();
11189 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11190 // All loads much share the same chain.
11191 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11194 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11195 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11197 LastConsecutiveLoad = i;
11198 // Find a legal type for the vector store.
11199 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11200 bool IsFastSt, IsFastLd;
11201 if (TLI.isTypeLegal(StoreTy) &&
11202 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11203 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11204 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11205 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11206 LastLegalVectorType = i + 1;
11209 // Find a legal type for the integer store.
11210 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11211 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11212 if (TLI.isTypeLegal(StoreTy) &&
11213 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11214 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11215 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11216 FirstLoadAlign, &IsFastLd) && IsFastLd)
11217 LastLegalIntegerType = i + 1;
11218 // Or check whether a truncstore and extload is legal.
11219 else if (TLI.getTypeAction(Context, StoreTy) ==
11220 TargetLowering::TypePromoteInteger) {
11221 EVT LegalizedStoredValueTy =
11222 TLI.getTypeToTransformTo(Context, StoreTy);
11223 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11224 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11225 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11226 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11227 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11228 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11230 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11231 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11233 LastLegalIntegerType = i+1;
11237 // Only use vector types if the vector type is larger than the integer type.
11238 // If they are the same, use integers.
11239 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11240 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11242 // We add +1 here because the LastXXX variables refer to location while
11243 // the NumElem refers to array/index size.
11244 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11245 NumElem = std::min(LastLegalType, NumElem);
11250 // The latest Node in the DAG.
11251 unsigned LatestNodeUsed = 0;
11252 for (unsigned i=1; i<NumElem; ++i) {
11253 // Find a chain for the new wide-store operand. Notice that some
11254 // of the store nodes that we found may not be selected for inclusion
11255 // in the wide store. The chain we use needs to be the chain of the
11256 // latest store node which is *used* and replaced by the wide store.
11257 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11258 LatestNodeUsed = i;
11261 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11263 // Find if it is better to use vectors or integers to load and store
11267 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11269 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11270 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11273 SDLoc LoadDL(LoadNodes[0].MemNode);
11274 SDLoc StoreDL(StoreNodes[0].MemNode);
11276 SDValue NewLoad = DAG.getLoad(
11277 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11278 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11280 SDValue NewStore = DAG.getStore(
11281 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11282 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11284 // Replace one of the loads with the new load.
11285 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11286 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11287 SDValue(NewLoad.getNode(), 1));
11289 // Remove the rest of the load chains.
11290 for (unsigned i = 1; i < NumElem ; ++i) {
11291 // Replace all chain users of the old load nodes with the chain of the new
11293 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11294 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11297 // Replace the last store with the new store.
11298 CombineTo(LatestOp, NewStore);
11299 // Erase all other stores.
11300 for (unsigned i = 0; i < NumElem ; ++i) {
11301 // Remove all Store nodes.
11302 if (StoreNodes[i].MemNode == LatestOp)
11304 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11305 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11306 deleteAndRecombine(St);
11312 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11316 // Replace the chain to avoid dependency.
11317 if (ST->isTruncatingStore()) {
11318 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11319 ST->getBasePtr(), ST->getMemoryVT(),
11320 ST->getMemOperand());
11322 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11323 ST->getMemOperand());
11326 // Create token to keep both nodes around.
11327 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11328 MVT::Other, ST->getChain(), ReplStore);
11330 // Make sure the new and old chains are cleaned up.
11331 AddToWorklist(Token.getNode());
11333 // Don't add users to work list.
11334 return CombineTo(ST, Token, false);
11337 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11338 StoreSDNode *ST = cast<StoreSDNode>(N);
11339 SDValue Chain = ST->getChain();
11340 SDValue Value = ST->getValue();
11341 SDValue Ptr = ST->getBasePtr();
11343 // If this is a store of a bit convert, store the input value if the
11344 // resultant store does not need a higher alignment than the original.
11345 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11346 ST->isUnindexed()) {
11347 unsigned OrigAlign = ST->getAlignment();
11348 EVT SVT = Value.getOperand(0).getValueType();
11349 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11350 SVT.getTypeForEVT(*DAG.getContext()));
11351 if (Align <= OrigAlign &&
11352 ((!LegalOperations && !ST->isVolatile()) ||
11353 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11354 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11355 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11356 ST->isNonTemporal(), OrigAlign,
11360 // Turn 'store undef, Ptr' -> nothing.
11361 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11364 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11365 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11366 // NOTE: If the original store is volatile, this transform must not increase
11367 // the number of stores. For example, on x86-32 an f64 can be stored in one
11368 // processor operation but an i64 (which is not legal) requires two. So the
11369 // transform should not be done in this case.
11370 if (Value.getOpcode() != ISD::TargetConstantFP) {
11372 switch (CFP->getSimpleValueType(0).SimpleTy) {
11373 default: llvm_unreachable("Unknown FP type");
11374 case MVT::f16: // We don't do this for these yet.
11380 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11381 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11383 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11384 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11386 return DAG.getStore(Chain, SDLoc(N), Tmp,
11387 Ptr, ST->getMemOperand());
11391 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11392 !ST->isVolatile()) ||
11393 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11395 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11396 getZExtValue(), SDLoc(CFP), MVT::i64);
11397 return DAG.getStore(Chain, SDLoc(N), Tmp,
11398 Ptr, ST->getMemOperand());
11401 if (!ST->isVolatile() &&
11402 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11403 // Many FP stores are not made apparent until after legalize, e.g. for
11404 // argument passing. Since this is so common, custom legalize the
11405 // 64-bit integer store into two 32-bit stores.
11406 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11407 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11408 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11409 if (DAG.getDataLayout().isBigEndian())
11412 unsigned Alignment = ST->getAlignment();
11413 bool isVolatile = ST->isVolatile();
11414 bool isNonTemporal = ST->isNonTemporal();
11415 AAMDNodes AAInfo = ST->getAAInfo();
11419 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11420 Ptr, ST->getPointerInfo(),
11421 isVolatile, isNonTemporal,
11422 ST->getAlignment(), AAInfo);
11423 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11424 DAG.getConstant(4, DL, Ptr.getValueType()));
11425 Alignment = MinAlign(Alignment, 4U);
11426 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11427 Ptr, ST->getPointerInfo().getWithOffset(4),
11428 isVolatile, isNonTemporal,
11429 Alignment, AAInfo);
11430 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11439 // Try to infer better alignment information than the store already has.
11440 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11441 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11442 if (Align > ST->getAlignment()) {
11444 DAG.getTruncStore(Chain, SDLoc(N), Value,
11445 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11446 ST->isVolatile(), ST->isNonTemporal(), Align,
11448 if (NewStore.getNode() != N)
11449 return CombineTo(ST, NewStore, true);
11454 // Try transforming a pair floating point load / store ops to integer
11455 // load / store ops.
11456 if (SDValue NewST = TransformFPLoadStorePair(N))
11459 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11460 : DAG.getSubtarget().useAA();
11462 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11463 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11466 if (UseAA && ST->isUnindexed()) {
11467 // FIXME: We should do this even without AA enabled. AA will just allow
11468 // FindBetterChain to work in more situations. The problem with this is that
11469 // any combine that expects memory operations to be on consecutive chains
11470 // first needs to be updated to look for users of the same chain.
11472 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11473 // adjacent stores.
11474 if (findBetterNeighborChains(ST)) {
11475 // replaceStoreChain uses CombineTo, which handled all of the worklist
11476 // manipulation. Return the original node to not do anything else.
11477 return SDValue(ST, 0);
11481 // Try transforming N to an indexed store.
11482 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11483 return SDValue(N, 0);
11485 // FIXME: is there such a thing as a truncating indexed store?
11486 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11487 Value.getValueType().isInteger()) {
11488 // See if we can simplify the input to this truncstore with knowledge that
11489 // only the low bits are being used. For example:
11490 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11492 GetDemandedBits(Value,
11493 APInt::getLowBitsSet(
11494 Value.getValueType().getScalarType().getSizeInBits(),
11495 ST->getMemoryVT().getScalarType().getSizeInBits()));
11496 AddToWorklist(Value.getNode());
11497 if (Shorter.getNode())
11498 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11499 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11501 // Otherwise, see if we can simplify the operation with
11502 // SimplifyDemandedBits, which only works if the value has a single use.
11503 if (SimplifyDemandedBits(Value,
11504 APInt::getLowBitsSet(
11505 Value.getValueType().getScalarType().getSizeInBits(),
11506 ST->getMemoryVT().getScalarType().getSizeInBits())))
11507 return SDValue(N, 0);
11510 // If this is a load followed by a store to the same location, then the store
11512 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11513 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11514 ST->isUnindexed() && !ST->isVolatile() &&
11515 // There can't be any side effects between the load and store, such as
11516 // a call or store.
11517 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11518 // The store is dead, remove it.
11523 // If this is a store followed by a store with the same value to the same
11524 // location, then the store is dead/noop.
11525 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11526 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11527 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11528 ST1->isUnindexed() && !ST1->isVolatile()) {
11529 // The store is dead, remove it.
11534 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11535 // truncating store. We can do this even if this is already a truncstore.
11536 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11537 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11538 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11539 ST->getMemoryVT())) {
11540 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11541 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11544 // Only perform this optimization before the types are legal, because we
11545 // don't want to perform this optimization on every DAGCombine invocation.
11547 bool EverChanged = false;
11550 // There can be multiple store sequences on the same chain.
11551 // Keep trying to merge store sequences until we are unable to do so
11552 // or until we merge the last store on the chain.
11553 bool Changed = MergeConsecutiveStores(ST);
11554 EverChanged |= Changed;
11555 if (!Changed) break;
11556 } while (ST->getOpcode() != ISD::DELETED_NODE);
11559 return SDValue(N, 0);
11562 return ReduceLoadOpStoreWidth(N);
11565 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11566 SDValue InVec = N->getOperand(0);
11567 SDValue InVal = N->getOperand(1);
11568 SDValue EltNo = N->getOperand(2);
11571 // If the inserted element is an UNDEF, just use the input vector.
11572 if (InVal.getOpcode() == ISD::UNDEF)
11575 EVT VT = InVec.getValueType();
11577 // If we can't generate a legal BUILD_VECTOR, exit
11578 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11581 // Check that we know which element is being inserted
11582 if (!isa<ConstantSDNode>(EltNo))
11584 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11586 // Canonicalize insert_vector_elt dag nodes.
11588 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11589 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11591 // Do this only if the child insert_vector node has one use; also
11592 // do this only if indices are both constants and Idx1 < Idx0.
11593 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11594 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11595 unsigned OtherElt =
11596 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11597 if (Elt < OtherElt) {
11599 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11600 InVec.getOperand(0), InVal, EltNo);
11601 AddToWorklist(NewOp.getNode());
11602 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11603 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11607 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11608 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11609 // vector elements.
11610 SmallVector<SDValue, 8> Ops;
11611 // Do not combine these two vectors if the output vector will not replace
11612 // the input vector.
11613 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11614 Ops.append(InVec.getNode()->op_begin(),
11615 InVec.getNode()->op_end());
11616 } else if (InVec.getOpcode() == ISD::UNDEF) {
11617 unsigned NElts = VT.getVectorNumElements();
11618 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11623 // Insert the element
11624 if (Elt < Ops.size()) {
11625 // All the operands of BUILD_VECTOR must have the same type;
11626 // we enforce that here.
11627 EVT OpVT = Ops[0].getValueType();
11628 if (InVal.getValueType() != OpVT)
11629 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11630 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11631 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11635 // Return the new vector
11636 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11639 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11640 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11641 EVT ResultVT = EVE->getValueType(0);
11642 EVT VecEltVT = InVecVT.getVectorElementType();
11643 unsigned Align = OriginalLoad->getAlignment();
11644 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11645 VecEltVT.getTypeForEVT(*DAG.getContext()));
11647 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11652 SDValue NewPtr = OriginalLoad->getBasePtr();
11654 EVT PtrType = NewPtr.getValueType();
11655 MachinePointerInfo MPI;
11657 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11658 int Elt = ConstEltNo->getZExtValue();
11659 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11660 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11661 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11663 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11664 Offset = DAG.getNode(
11665 ISD::MUL, DL, PtrType, Offset,
11666 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11667 MPI = OriginalLoad->getPointerInfo();
11669 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11671 // The replacement we need to do here is a little tricky: we need to
11672 // replace an extractelement of a load with a load.
11673 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11674 // Note that this replacement assumes that the extractvalue is the only
11675 // use of the load; that's okay because we don't want to perform this
11676 // transformation in other cases anyway.
11679 if (ResultVT.bitsGT(VecEltVT)) {
11680 // If the result type of vextract is wider than the load, then issue an
11681 // extending load instead.
11682 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11686 Load = DAG.getExtLoad(
11687 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11688 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11689 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11690 Chain = Load.getValue(1);
11692 Load = DAG.getLoad(
11693 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11694 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11695 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11696 Chain = Load.getValue(1);
11697 if (ResultVT.bitsLT(VecEltVT))
11698 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11700 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11702 WorklistRemover DeadNodes(*this);
11703 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11704 SDValue To[] = { Load, Chain };
11705 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11706 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11707 // worklist explicitly as well.
11708 AddToWorklist(Load.getNode());
11709 AddUsersToWorklist(Load.getNode()); // Add users too
11710 // Make sure to revisit this node to clean it up; it will usually be dead.
11711 AddToWorklist(EVE);
11713 return SDValue(EVE, 0);
11716 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11717 // (vextract (scalar_to_vector val, 0) -> val
11718 SDValue InVec = N->getOperand(0);
11719 EVT VT = InVec.getValueType();
11720 EVT NVT = N->getValueType(0);
11722 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11723 // Check if the result type doesn't match the inserted element type. A
11724 // SCALAR_TO_VECTOR may truncate the inserted element and the
11725 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11726 SDValue InOp = InVec.getOperand(0);
11727 if (InOp.getValueType() != NVT) {
11728 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11729 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11734 SDValue EltNo = N->getOperand(1);
11735 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11737 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11738 // We only perform this optimization before the op legalization phase because
11739 // we may introduce new vector instructions which are not backed by TD
11740 // patterns. For example on AVX, extracting elements from a wide vector
11741 // without using extract_subvector. However, if we can find an underlying
11742 // scalar value, then we can always use that.
11743 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11745 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11746 int NumElem = VT.getVectorNumElements();
11747 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11748 // Find the new index to extract from.
11749 int OrigElt = SVOp->getMaskElt(Elt);
11751 // Extracting an undef index is undef.
11753 return DAG.getUNDEF(NVT);
11755 // Select the right vector half to extract from.
11757 if (OrigElt < NumElem) {
11758 SVInVec = InVec->getOperand(0);
11760 SVInVec = InVec->getOperand(1);
11761 OrigElt -= NumElem;
11764 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11765 SDValue InOp = SVInVec.getOperand(OrigElt);
11766 if (InOp.getValueType() != NVT) {
11767 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11768 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11774 // FIXME: We should handle recursing on other vector shuffles and
11775 // scalar_to_vector here as well.
11777 if (!LegalOperations) {
11778 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11779 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11780 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11784 bool BCNumEltsChanged = false;
11785 EVT ExtVT = VT.getVectorElementType();
11788 // If the result of load has to be truncated, then it's not necessarily
11790 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11793 if (InVec.getOpcode() == ISD::BITCAST) {
11794 // Don't duplicate a load with other uses.
11795 if (!InVec.hasOneUse())
11798 EVT BCVT = InVec.getOperand(0).getValueType();
11799 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11801 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11802 BCNumEltsChanged = true;
11803 InVec = InVec.getOperand(0);
11804 ExtVT = BCVT.getVectorElementType();
11807 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11808 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11809 ISD::isNormalLoad(InVec.getNode()) &&
11810 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11811 SDValue Index = N->getOperand(1);
11812 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11813 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11817 // Perform only after legalization to ensure build_vector / vector_shuffle
11818 // optimizations have already been done.
11819 if (!LegalOperations) return SDValue();
11821 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11822 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11823 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11826 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11828 LoadSDNode *LN0 = nullptr;
11829 const ShuffleVectorSDNode *SVN = nullptr;
11830 if (ISD::isNormalLoad(InVec.getNode())) {
11831 LN0 = cast<LoadSDNode>(InVec);
11832 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11833 InVec.getOperand(0).getValueType() == ExtVT &&
11834 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11835 // Don't duplicate a load with other uses.
11836 if (!InVec.hasOneUse())
11839 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11840 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11841 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11843 // (load $addr+1*size)
11845 // Don't duplicate a load with other uses.
11846 if (!InVec.hasOneUse())
11849 // If the bit convert changed the number of elements, it is unsafe
11850 // to examine the mask.
11851 if (BCNumEltsChanged)
11854 // Select the input vector, guarding against out of range extract vector.
11855 unsigned NumElems = VT.getVectorNumElements();
11856 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11857 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11859 if (InVec.getOpcode() == ISD::BITCAST) {
11860 // Don't duplicate a load with other uses.
11861 if (!InVec.hasOneUse())
11864 InVec = InVec.getOperand(0);
11866 if (ISD::isNormalLoad(InVec.getNode())) {
11867 LN0 = cast<LoadSDNode>(InVec);
11868 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11869 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11873 // Make sure we found a non-volatile load and the extractelement is
11875 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11878 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11880 return DAG.getUNDEF(LVT);
11882 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11888 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11889 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11890 // We perform this optimization post type-legalization because
11891 // the type-legalizer often scalarizes integer-promoted vectors.
11892 // Performing this optimization before may create bit-casts which
11893 // will be type-legalized to complex code sequences.
11894 // We perform this optimization only before the operation legalizer because we
11895 // may introduce illegal operations.
11896 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11899 unsigned NumInScalars = N->getNumOperands();
11901 EVT VT = N->getValueType(0);
11903 // Check to see if this is a BUILD_VECTOR of a bunch of values
11904 // which come from any_extend or zero_extend nodes. If so, we can create
11905 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11906 // optimizations. We do not handle sign-extend because we can't fill the sign
11908 EVT SourceType = MVT::Other;
11909 bool AllAnyExt = true;
11911 for (unsigned i = 0; i != NumInScalars; ++i) {
11912 SDValue In = N->getOperand(i);
11913 // Ignore undef inputs.
11914 if (In.getOpcode() == ISD::UNDEF) continue;
11916 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11917 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11919 // Abort if the element is not an extension.
11920 if (!ZeroExt && !AnyExt) {
11921 SourceType = MVT::Other;
11925 // The input is a ZeroExt or AnyExt. Check the original type.
11926 EVT InTy = In.getOperand(0).getValueType();
11928 // Check that all of the widened source types are the same.
11929 if (SourceType == MVT::Other)
11932 else if (InTy != SourceType) {
11933 // Multiple income types. Abort.
11934 SourceType = MVT::Other;
11938 // Check if all of the extends are ANY_EXTENDs.
11939 AllAnyExt &= AnyExt;
11942 // In order to have valid types, all of the inputs must be extended from the
11943 // same source type and all of the inputs must be any or zero extend.
11944 // Scalar sizes must be a power of two.
11945 EVT OutScalarTy = VT.getScalarType();
11946 bool ValidTypes = SourceType != MVT::Other &&
11947 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11948 isPowerOf2_32(SourceType.getSizeInBits());
11950 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11951 // turn into a single shuffle instruction.
11955 bool isLE = DAG.getDataLayout().isLittleEndian();
11956 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11957 assert(ElemRatio > 1 && "Invalid element size ratio");
11958 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11959 DAG.getConstant(0, SDLoc(N), SourceType);
11961 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11962 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11964 // Populate the new build_vector
11965 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11966 SDValue Cast = N->getOperand(i);
11967 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11968 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11969 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11971 if (Cast.getOpcode() == ISD::UNDEF)
11972 In = DAG.getUNDEF(SourceType);
11974 In = Cast->getOperand(0);
11975 unsigned Index = isLE ? (i * ElemRatio) :
11976 (i * ElemRatio + (ElemRatio - 1));
11978 assert(Index < Ops.size() && "Invalid index");
11982 // The type of the new BUILD_VECTOR node.
11983 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11984 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11985 "Invalid vector size");
11986 // Check if the new vector type is legal.
11987 if (!isTypeLegal(VecVT)) return SDValue();
11989 // Make the new BUILD_VECTOR.
11990 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11992 // The new BUILD_VECTOR node has the potential to be further optimized.
11993 AddToWorklist(BV.getNode());
11994 // Bitcast to the desired type.
11995 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11998 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11999 EVT VT = N->getValueType(0);
12001 unsigned NumInScalars = N->getNumOperands();
12004 EVT SrcVT = MVT::Other;
12005 unsigned Opcode = ISD::DELETED_NODE;
12006 unsigned NumDefs = 0;
12008 for (unsigned i = 0; i != NumInScalars; ++i) {
12009 SDValue In = N->getOperand(i);
12010 unsigned Opc = In.getOpcode();
12012 if (Opc == ISD::UNDEF)
12015 // If all scalar values are floats and converted from integers.
12016 if (Opcode == ISD::DELETED_NODE &&
12017 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12024 EVT InVT = In.getOperand(0).getValueType();
12026 // If all scalar values are typed differently, bail out. It's chosen to
12027 // simplify BUILD_VECTOR of integer types.
12028 if (SrcVT == MVT::Other)
12035 // If the vector has just one element defined, it's not worth to fold it into
12036 // a vectorized one.
12040 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12041 && "Should only handle conversion from integer to float.");
12042 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12044 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12046 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12049 // Just because the floating-point vector type is legal does not necessarily
12050 // mean that the corresponding integer vector type is.
12051 if (!isTypeLegal(NVT))
12054 SmallVector<SDValue, 8> Opnds;
12055 for (unsigned i = 0; i != NumInScalars; ++i) {
12056 SDValue In = N->getOperand(i);
12058 if (In.getOpcode() == ISD::UNDEF)
12059 Opnds.push_back(DAG.getUNDEF(SrcVT));
12061 Opnds.push_back(In.getOperand(0));
12063 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12064 AddToWorklist(BV.getNode());
12066 return DAG.getNode(Opcode, dl, VT, BV);
12069 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12070 unsigned NumInScalars = N->getNumOperands();
12072 EVT VT = N->getValueType(0);
12074 // A vector built entirely of undefs is undef.
12075 if (ISD::allOperandsUndef(N))
12076 return DAG.getUNDEF(VT);
12078 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12081 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12084 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12085 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12086 // at most two distinct vectors, turn this into a shuffle node.
12088 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12089 if (!isTypeLegal(VT))
12092 // May only combine to shuffle after legalize if shuffle is legal.
12093 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12096 SDValue VecIn1, VecIn2;
12097 bool UsesZeroVector = false;
12098 for (unsigned i = 0; i != NumInScalars; ++i) {
12099 SDValue Op = N->getOperand(i);
12100 // Ignore undef inputs.
12101 if (Op.getOpcode() == ISD::UNDEF) continue;
12103 // See if we can combine this build_vector into a blend with a zero vector.
12104 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12105 UsesZeroVector = true;
12109 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12110 // constant index, bail out.
12111 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12112 !isa<ConstantSDNode>(Op.getOperand(1))) {
12113 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12117 // We allow up to two distinct input vectors.
12118 SDValue ExtractedFromVec = Op.getOperand(0);
12119 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12122 if (!VecIn1.getNode()) {
12123 VecIn1 = ExtractedFromVec;
12124 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12125 VecIn2 = ExtractedFromVec;
12127 // Too many inputs.
12128 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12133 // If everything is good, we can make a shuffle operation.
12134 if (VecIn1.getNode()) {
12135 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12136 SmallVector<int, 8> Mask;
12137 for (unsigned i = 0; i != NumInScalars; ++i) {
12138 unsigned Opcode = N->getOperand(i).getOpcode();
12139 if (Opcode == ISD::UNDEF) {
12140 Mask.push_back(-1);
12144 // Operands can also be zero.
12145 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12146 assert(UsesZeroVector &&
12147 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12148 "Unexpected node found!");
12149 Mask.push_back(NumInScalars+i);
12153 // If extracting from the first vector, just use the index directly.
12154 SDValue Extract = N->getOperand(i);
12155 SDValue ExtVal = Extract.getOperand(1);
12156 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12157 if (Extract.getOperand(0) == VecIn1) {
12158 Mask.push_back(ExtIndex);
12162 // Otherwise, use InIdx + InputVecSize
12163 Mask.push_back(InNumElements + ExtIndex);
12166 // Avoid introducing illegal shuffles with zero.
12167 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12170 // We can't generate a shuffle node with mismatched input and output types.
12171 // Attempt to transform a single input vector to the correct type.
12172 if ((VT != VecIn1.getValueType())) {
12173 // If the input vector type has a different base type to the output
12174 // vector type, bail out.
12175 EVT VTElemType = VT.getVectorElementType();
12176 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12177 (VecIn2.getNode() &&
12178 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12181 // If the input vector is too small, widen it.
12182 // We only support widening of vectors which are half the size of the
12183 // output registers. For example XMM->YMM widening on X86 with AVX.
12184 EVT VecInT = VecIn1.getValueType();
12185 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12186 // If we only have one small input, widen it by adding undef values.
12187 if (!VecIn2.getNode())
12188 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12189 DAG.getUNDEF(VecIn1.getValueType()));
12190 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12191 // If we have two small inputs of the same type, try to concat them.
12192 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12193 VecIn2 = SDValue(nullptr, 0);
12196 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12197 // If the input vector is too large, try to split it.
12198 // We don't support having two input vectors that are too large.
12199 // If the zero vector was used, we can not split the vector,
12200 // since we'd need 3 inputs.
12201 if (UsesZeroVector || VecIn2.getNode())
12204 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12207 // Try to replace VecIn1 with two extract_subvectors
12208 // No need to update the masks, they should still be correct.
12209 VecIn2 = DAG.getNode(
12210 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12211 DAG.getConstant(VT.getVectorNumElements(), dl,
12212 TLI.getVectorIdxTy(DAG.getDataLayout())));
12213 VecIn1 = DAG.getNode(
12214 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12215 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12220 if (UsesZeroVector)
12221 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12222 DAG.getConstantFP(0.0, dl, VT);
12224 // If VecIn2 is unused then change it to undef.
12225 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12227 // Check that we were able to transform all incoming values to the same
12229 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12230 VecIn1.getValueType() != VT)
12233 // Return the new VECTOR_SHUFFLE node.
12237 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12243 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12244 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12245 EVT OpVT = N->getOperand(0).getValueType();
12247 // If the operands are legal vectors, leave them alone.
12248 if (TLI.isTypeLegal(OpVT))
12252 EVT VT = N->getValueType(0);
12253 SmallVector<SDValue, 8> Ops;
12255 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12256 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12258 // Keep track of what we encounter.
12259 bool AnyInteger = false;
12260 bool AnyFP = false;
12261 for (const SDValue &Op : N->ops()) {
12262 if (ISD::BITCAST == Op.getOpcode() &&
12263 !Op.getOperand(0).getValueType().isVector())
12264 Ops.push_back(Op.getOperand(0));
12265 else if (ISD::UNDEF == Op.getOpcode())
12266 Ops.push_back(ScalarUndef);
12270 // Note whether we encounter an integer or floating point scalar.
12271 // If it's neither, bail out, it could be something weird like x86mmx.
12272 EVT LastOpVT = Ops.back().getValueType();
12273 if (LastOpVT.isFloatingPoint())
12275 else if (LastOpVT.isInteger())
12281 // If any of the operands is a floating point scalar bitcast to a vector,
12282 // use floating point types throughout, and bitcast everything.
12283 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12285 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12286 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12288 for (SDValue &Op : Ops) {
12289 if (Op.getValueType() == SVT)
12291 if (Op.getOpcode() == ISD::UNDEF)
12294 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12299 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12300 VT.getSizeInBits() / SVT.getSizeInBits());
12301 return DAG.getNode(ISD::BITCAST, DL, VT,
12302 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12305 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12306 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12307 // most two distinct vectors the same size as the result, attempt to turn this
12308 // into a legal shuffle.
12309 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12310 EVT VT = N->getValueType(0);
12311 EVT OpVT = N->getOperand(0).getValueType();
12312 int NumElts = VT.getVectorNumElements();
12313 int NumOpElts = OpVT.getVectorNumElements();
12315 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12316 SmallVector<int, 8> Mask;
12318 for (SDValue Op : N->ops()) {
12319 // Peek through any bitcast.
12320 while (Op.getOpcode() == ISD::BITCAST)
12321 Op = Op.getOperand(0);
12323 // UNDEF nodes convert to UNDEF shuffle mask values.
12324 if (Op.getOpcode() == ISD::UNDEF) {
12325 Mask.append((unsigned)NumOpElts, -1);
12329 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12332 // What vector are we extracting the subvector from and at what index?
12333 SDValue ExtVec = Op.getOperand(0);
12335 // We want the EVT of the original extraction to correctly scale the
12336 // extraction index.
12337 EVT ExtVT = ExtVec.getValueType();
12339 // Peek through any bitcast.
12340 while (ExtVec.getOpcode() == ISD::BITCAST)
12341 ExtVec = ExtVec.getOperand(0);
12343 // UNDEF nodes convert to UNDEF shuffle mask values.
12344 if (ExtVec.getOpcode() == ISD::UNDEF) {
12345 Mask.append((unsigned)NumOpElts, -1);
12349 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12351 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12353 // Ensure that we are extracting a subvector from a vector the same
12354 // size as the result.
12355 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12358 // Scale the subvector index to account for any bitcast.
12359 int NumExtElts = ExtVT.getVectorNumElements();
12360 if (0 == (NumExtElts % NumElts))
12361 ExtIdx /= (NumExtElts / NumElts);
12362 else if (0 == (NumElts % NumExtElts))
12363 ExtIdx *= (NumElts / NumExtElts);
12367 // At most we can reference 2 inputs in the final shuffle.
12368 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12370 for (int i = 0; i != NumOpElts; ++i)
12371 Mask.push_back(i + ExtIdx);
12372 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12374 for (int i = 0; i != NumOpElts; ++i)
12375 Mask.push_back(i + ExtIdx + NumElts);
12381 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12384 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12385 DAG.getBitcast(VT, SV1), Mask);
12388 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12389 // If we only have one input vector, we don't need to do any concatenation.
12390 if (N->getNumOperands() == 1)
12391 return N->getOperand(0);
12393 // Check if all of the operands are undefs.
12394 EVT VT = N->getValueType(0);
12395 if (ISD::allOperandsUndef(N))
12396 return DAG.getUNDEF(VT);
12398 // Optimize concat_vectors where all but the first of the vectors are undef.
12399 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12400 return Op.getOpcode() == ISD::UNDEF;
12402 SDValue In = N->getOperand(0);
12403 assert(In.getValueType().isVector() && "Must concat vectors");
12405 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12406 if (In->getOpcode() == ISD::BITCAST &&
12407 !In->getOperand(0)->getValueType(0).isVector()) {
12408 SDValue Scalar = In->getOperand(0);
12410 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12411 // look through the trunc so we can still do the transform:
12412 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12413 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12414 !TLI.isTypeLegal(Scalar.getValueType()) &&
12415 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12416 Scalar = Scalar->getOperand(0);
12418 EVT SclTy = Scalar->getValueType(0);
12420 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12423 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12424 VT.getSizeInBits() / SclTy.getSizeInBits());
12425 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12428 SDLoc dl = SDLoc(N);
12429 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12430 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12434 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12435 // We have already tested above for an UNDEF only concatenation.
12436 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12437 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12438 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12439 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12441 bool AllBuildVectorsOrUndefs =
12442 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12443 if (AllBuildVectorsOrUndefs) {
12444 SmallVector<SDValue, 8> Opnds;
12445 EVT SVT = VT.getScalarType();
12448 if (!SVT.isFloatingPoint()) {
12449 // If BUILD_VECTOR are from built from integer, they may have different
12450 // operand types. Get the smallest type and truncate all operands to it.
12451 bool FoundMinVT = false;
12452 for (const SDValue &Op : N->ops())
12453 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12454 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12455 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12458 assert(FoundMinVT && "Concat vector type mismatch");
12461 for (const SDValue &Op : N->ops()) {
12462 EVT OpVT = Op.getValueType();
12463 unsigned NumElts = OpVT.getVectorNumElements();
12465 if (ISD::UNDEF == Op.getOpcode())
12466 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12468 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12469 if (SVT.isFloatingPoint()) {
12470 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12471 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12473 for (unsigned i = 0; i != NumElts; ++i)
12475 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12480 assert(VT.getVectorNumElements() == Opnds.size() &&
12481 "Concat vector type mismatch");
12482 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12485 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12486 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12489 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12490 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12491 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12494 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12495 // nodes often generate nop CONCAT_VECTOR nodes.
12496 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12497 // place the incoming vectors at the exact same location.
12498 SDValue SingleSource = SDValue();
12499 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12501 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12502 SDValue Op = N->getOperand(i);
12504 if (Op.getOpcode() == ISD::UNDEF)
12507 // Check if this is the identity extract:
12508 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12511 // Find the single incoming vector for the extract_subvector.
12512 if (SingleSource.getNode()) {
12513 if (Op.getOperand(0) != SingleSource)
12516 SingleSource = Op.getOperand(0);
12518 // Check the source type is the same as the type of the result.
12519 // If not, this concat may extend the vector, so we can not
12520 // optimize it away.
12521 if (SingleSource.getValueType() != N->getValueType(0))
12525 unsigned IdentityIndex = i * PartNumElem;
12526 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12527 // The extract index must be constant.
12531 // Check that we are reading from the identity index.
12532 if (CS->getZExtValue() != IdentityIndex)
12536 if (SingleSource.getNode())
12537 return SingleSource;
12542 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12543 EVT NVT = N->getValueType(0);
12544 SDValue V = N->getOperand(0);
12546 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12548 // (extract_subvec (concat V1, V2, ...), i)
12551 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12553 if (V->getOperand(0).getValueType() != NVT)
12555 unsigned Idx = N->getConstantOperandVal(1);
12556 unsigned NumElems = NVT.getVectorNumElements();
12557 assert((Idx % NumElems) == 0 &&
12558 "IDX in concat is not a multiple of the result vector length.");
12559 return V->getOperand(Idx / NumElems);
12563 if (V->getOpcode() == ISD::BITCAST)
12564 V = V.getOperand(0);
12566 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12568 // Handle only simple case where vector being inserted and vector
12569 // being extracted are of same type, and are half size of larger vectors.
12570 EVT BigVT = V->getOperand(0).getValueType();
12571 EVT SmallVT = V->getOperand(1).getValueType();
12572 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12575 // Only handle cases where both indexes are constants with the same type.
12576 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12577 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12579 if (InsIdx && ExtIdx &&
12580 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12581 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12583 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12585 // indices are equal or bit offsets are equal => V1
12586 // otherwise => (extract_subvec V1, ExtIdx)
12587 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12588 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12589 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12590 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12591 DAG.getNode(ISD::BITCAST, dl,
12592 N->getOperand(0).getValueType(),
12593 V->getOperand(0)), N->getOperand(1));
12600 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12601 SDValue V, SelectionDAG &DAG) {
12603 EVT VT = V.getValueType();
12605 switch (V.getOpcode()) {
12609 case ISD::CONCAT_VECTORS: {
12610 EVT OpVT = V->getOperand(0).getValueType();
12611 int OpSize = OpVT.getVectorNumElements();
12612 SmallBitVector OpUsedElements(OpSize, false);
12613 bool FoundSimplification = false;
12614 SmallVector<SDValue, 4> NewOps;
12615 NewOps.reserve(V->getNumOperands());
12616 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12617 SDValue Op = V->getOperand(i);
12618 bool OpUsed = false;
12619 for (int j = 0; j < OpSize; ++j)
12620 if (UsedElements[i * OpSize + j]) {
12621 OpUsedElements[j] = true;
12625 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12626 : DAG.getUNDEF(OpVT));
12627 FoundSimplification |= Op == NewOps.back();
12628 OpUsedElements.reset();
12630 if (FoundSimplification)
12631 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12635 case ISD::INSERT_SUBVECTOR: {
12636 SDValue BaseV = V->getOperand(0);
12637 SDValue SubV = V->getOperand(1);
12638 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12642 int SubSize = SubV.getValueType().getVectorNumElements();
12643 int Idx = IdxN->getZExtValue();
12644 bool SubVectorUsed = false;
12645 SmallBitVector SubUsedElements(SubSize, false);
12646 for (int i = 0; i < SubSize; ++i)
12647 if (UsedElements[i + Idx]) {
12648 SubVectorUsed = true;
12649 SubUsedElements[i] = true;
12650 UsedElements[i + Idx] = false;
12653 // Now recurse on both the base and sub vectors.
12654 SDValue SimplifiedSubV =
12656 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12657 : DAG.getUNDEF(SubV.getValueType());
12658 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12659 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12660 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12661 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12667 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12668 SDValue N1, SelectionDAG &DAG) {
12669 EVT VT = SVN->getValueType(0);
12670 int NumElts = VT.getVectorNumElements();
12671 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12672 for (int M : SVN->getMask())
12673 if (M >= 0 && M < NumElts)
12674 N0UsedElements[M] = true;
12675 else if (M >= NumElts)
12676 N1UsedElements[M - NumElts] = true;
12678 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12679 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12680 if (S0 == N0 && S1 == N1)
12683 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12686 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12687 // or turn a shuffle of a single concat into simpler shuffle then concat.
12688 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12689 EVT VT = N->getValueType(0);
12690 unsigned NumElts = VT.getVectorNumElements();
12692 SDValue N0 = N->getOperand(0);
12693 SDValue N1 = N->getOperand(1);
12694 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12696 SmallVector<SDValue, 4> Ops;
12697 EVT ConcatVT = N0.getOperand(0).getValueType();
12698 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12699 unsigned NumConcats = NumElts / NumElemsPerConcat;
12701 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12702 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12703 // half vector elements.
12704 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12705 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12706 SVN->getMask().end(), [](int i) { return i == -1; })) {
12707 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12708 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12709 N1 = DAG.getUNDEF(ConcatVT);
12710 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12713 // Look at every vector that's inserted. We're looking for exact
12714 // subvector-sized copies from a concatenated vector
12715 for (unsigned I = 0; I != NumConcats; ++I) {
12716 // Make sure we're dealing with a copy.
12717 unsigned Begin = I * NumElemsPerConcat;
12718 bool AllUndef = true, NoUndef = true;
12719 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12720 if (SVN->getMaskElt(J) >= 0)
12727 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12730 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12731 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12734 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12735 if (FirstElt < N0.getNumOperands())
12736 Ops.push_back(N0.getOperand(FirstElt));
12738 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12740 } else if (AllUndef) {
12741 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12742 } else { // Mixed with general masks and undefs, can't do optimization.
12747 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12750 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12751 EVT VT = N->getValueType(0);
12752 unsigned NumElts = VT.getVectorNumElements();
12754 SDValue N0 = N->getOperand(0);
12755 SDValue N1 = N->getOperand(1);
12757 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12759 // Canonicalize shuffle undef, undef -> undef
12760 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12761 return DAG.getUNDEF(VT);
12763 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12765 // Canonicalize shuffle v, v -> v, undef
12767 SmallVector<int, 8> NewMask;
12768 for (unsigned i = 0; i != NumElts; ++i) {
12769 int Idx = SVN->getMaskElt(i);
12770 if (Idx >= (int)NumElts) Idx -= NumElts;
12771 NewMask.push_back(Idx);
12773 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12777 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12778 if (N0.getOpcode() == ISD::UNDEF) {
12779 SmallVector<int, 8> NewMask;
12780 for (unsigned i = 0; i != NumElts; ++i) {
12781 int Idx = SVN->getMaskElt(i);
12783 if (Idx >= (int)NumElts)
12786 Idx = -1; // remove reference to lhs
12788 NewMask.push_back(Idx);
12790 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12794 // Remove references to rhs if it is undef
12795 if (N1.getOpcode() == ISD::UNDEF) {
12796 bool Changed = false;
12797 SmallVector<int, 8> NewMask;
12798 for (unsigned i = 0; i != NumElts; ++i) {
12799 int Idx = SVN->getMaskElt(i);
12800 if (Idx >= (int)NumElts) {
12804 NewMask.push_back(Idx);
12807 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12810 // If it is a splat, check if the argument vector is another splat or a
12812 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12813 SDNode *V = N0.getNode();
12815 // If this is a bit convert that changes the element type of the vector but
12816 // not the number of vector elements, look through it. Be careful not to
12817 // look though conversions that change things like v4f32 to v2f64.
12818 if (V->getOpcode() == ISD::BITCAST) {
12819 SDValue ConvInput = V->getOperand(0);
12820 if (ConvInput.getValueType().isVector() &&
12821 ConvInput.getValueType().getVectorNumElements() == NumElts)
12822 V = ConvInput.getNode();
12825 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12826 assert(V->getNumOperands() == NumElts &&
12827 "BUILD_VECTOR has wrong number of operands");
12829 bool AllSame = true;
12830 for (unsigned i = 0; i != NumElts; ++i) {
12831 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12832 Base = V->getOperand(i);
12836 // Splat of <u, u, u, u>, return <u, u, u, u>
12837 if (!Base.getNode())
12839 for (unsigned i = 0; i != NumElts; ++i) {
12840 if (V->getOperand(i) != Base) {
12845 // Splat of <x, x, x, x>, return <x, x, x, x>
12849 // Canonicalize any other splat as a build_vector.
12850 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12851 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12852 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12853 V->getValueType(0), Ops);
12855 // We may have jumped through bitcasts, so the type of the
12856 // BUILD_VECTOR may not match the type of the shuffle.
12857 if (V->getValueType(0) != VT)
12858 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12863 // There are various patterns used to build up a vector from smaller vectors,
12864 // subvectors, or elements. Scan chains of these and replace unused insertions
12865 // or components with undef.
12866 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12869 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12870 Level < AfterLegalizeVectorOps &&
12871 (N1.getOpcode() == ISD::UNDEF ||
12872 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12873 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12874 SDValue V = partitionShuffleOfConcats(N, DAG);
12880 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12881 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12882 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12883 SmallVector<SDValue, 8> Ops;
12884 for (int M : SVN->getMask()) {
12885 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12887 int Idx = M % NumElts;
12888 SDValue &S = (M < (int)NumElts ? N0 : N1);
12889 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12890 Op = S.getOperand(Idx);
12891 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12893 Op = S.getOperand(0);
12895 // Operand can't be combined - bail out.
12901 if (Ops.size() == VT.getVectorNumElements()) {
12902 // BUILD_VECTOR requires all inputs to be of the same type, find the
12903 // maximum type and extend them all.
12904 EVT SVT = VT.getScalarType();
12905 if (SVT.isInteger())
12906 for (SDValue &Op : Ops)
12907 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12908 if (SVT != VT.getScalarType())
12909 for (SDValue &Op : Ops)
12910 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12911 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12912 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12913 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12917 // If this shuffle only has a single input that is a bitcasted shuffle,
12918 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12919 // back to their original types.
12920 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12921 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12922 TLI.isTypeLegal(VT)) {
12924 // Peek through the bitcast only if there is one user.
12926 while (BC0.getOpcode() == ISD::BITCAST) {
12927 if (!BC0.hasOneUse())
12929 BC0 = BC0.getOperand(0);
12932 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12934 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12936 SmallVector<int, 8> NewMask;
12938 for (int s = 0; s != Scale; ++s)
12939 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12943 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12944 EVT SVT = VT.getScalarType();
12945 EVT InnerVT = BC0->getValueType(0);
12946 EVT InnerSVT = InnerVT.getScalarType();
12948 // Determine which shuffle works with the smaller scalar type.
12949 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12950 EVT ScaleSVT = ScaleVT.getScalarType();
12952 if (TLI.isTypeLegal(ScaleVT) &&
12953 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12954 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12956 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12957 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12959 // Scale the shuffle masks to the smaller scalar type.
12960 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12961 SmallVector<int, 8> InnerMask =
12962 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12963 SmallVector<int, 8> OuterMask =
12964 ScaleShuffleMask(SVN->getMask(), OuterScale);
12966 // Merge the shuffle masks.
12967 SmallVector<int, 8> NewMask;
12968 for (int M : OuterMask)
12969 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12971 // Test for shuffle mask legality over both commutations.
12972 SDValue SV0 = BC0->getOperand(0);
12973 SDValue SV1 = BC0->getOperand(1);
12974 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12976 std::swap(SV0, SV1);
12977 ShuffleVectorSDNode::commuteMask(NewMask);
12978 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12982 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12983 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12984 return DAG.getNode(
12985 ISD::BITCAST, SDLoc(N), VT,
12986 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12992 // Canonicalize shuffles according to rules:
12993 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12994 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12995 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12996 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12997 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12998 TLI.isTypeLegal(VT)) {
12999 // The incoming shuffle must be of the same type as the result of the
13000 // current shuffle.
13001 assert(N1->getOperand(0).getValueType() == VT &&
13002 "Shuffle types don't match");
13004 SDValue SV0 = N1->getOperand(0);
13005 SDValue SV1 = N1->getOperand(1);
13006 bool HasSameOp0 = N0 == SV0;
13007 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13008 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13009 // Commute the operands of this shuffle so that next rule
13011 return DAG.getCommutedVectorShuffle(*SVN);
13014 // Try to fold according to rules:
13015 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13016 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13017 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13018 // Don't try to fold shuffles with illegal type.
13019 // Only fold if this shuffle is the only user of the other shuffle.
13020 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13021 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13022 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13024 // The incoming shuffle must be of the same type as the result of the
13025 // current shuffle.
13026 assert(OtherSV->getOperand(0).getValueType() == VT &&
13027 "Shuffle types don't match");
13030 SmallVector<int, 4> Mask;
13031 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13032 // operand, and SV1 as the second operand.
13033 for (unsigned i = 0; i != NumElts; ++i) {
13034 int Idx = SVN->getMaskElt(i);
13036 // Propagate Undef.
13037 Mask.push_back(Idx);
13041 SDValue CurrentVec;
13042 if (Idx < (int)NumElts) {
13043 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13044 // shuffle mask to identify which vector is actually referenced.
13045 Idx = OtherSV->getMaskElt(Idx);
13047 // Propagate Undef.
13048 Mask.push_back(Idx);
13052 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13053 : OtherSV->getOperand(1);
13055 // This shuffle index references an element within N1.
13059 // Simple case where 'CurrentVec' is UNDEF.
13060 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13061 Mask.push_back(-1);
13065 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13066 // will be the first or second operand of the combined shuffle.
13067 Idx = Idx % NumElts;
13068 if (!SV0.getNode() || SV0 == CurrentVec) {
13069 // Ok. CurrentVec is the left hand side.
13070 // Update the mask accordingly.
13072 Mask.push_back(Idx);
13076 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13077 if (SV1.getNode() && SV1 != CurrentVec)
13080 // Ok. CurrentVec is the right hand side.
13081 // Update the mask accordingly.
13083 Mask.push_back(Idx + NumElts);
13086 // Check if all indices in Mask are Undef. In case, propagate Undef.
13087 bool isUndefMask = true;
13088 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13089 isUndefMask &= Mask[i] < 0;
13092 return DAG.getUNDEF(VT);
13094 if (!SV0.getNode())
13095 SV0 = DAG.getUNDEF(VT);
13096 if (!SV1.getNode())
13097 SV1 = DAG.getUNDEF(VT);
13099 // Avoid introducing shuffles with illegal mask.
13100 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13101 ShuffleVectorSDNode::commuteMask(Mask);
13103 if (!TLI.isShuffleMaskLegal(Mask, VT))
13106 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13107 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13108 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13109 std::swap(SV0, SV1);
13112 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13113 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13114 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13115 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13121 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13122 SDValue InVal = N->getOperand(0);
13123 EVT VT = N->getValueType(0);
13125 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13126 // with a VECTOR_SHUFFLE.
13127 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13128 SDValue InVec = InVal->getOperand(0);
13129 SDValue EltNo = InVal->getOperand(1);
13131 // FIXME: We could support implicit truncation if the shuffle can be
13132 // scaled to a smaller vector scalar type.
13133 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13134 if (C0 && VT == InVec.getValueType() &&
13135 VT.getScalarType() == InVal.getValueType()) {
13136 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13137 int Elt = C0->getZExtValue();
13140 if (TLI.isShuffleMaskLegal(NewMask, VT))
13141 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13149 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13150 SDValue N0 = N->getOperand(0);
13151 SDValue N2 = N->getOperand(2);
13153 // If the input vector is a concatenation, and the insert replaces
13154 // one of the halves, we can optimize into a single concat_vectors.
13155 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13156 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13157 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13158 EVT VT = N->getValueType(0);
13160 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13161 // (concat_vectors Z, Y)
13163 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13164 N->getOperand(1), N0.getOperand(1));
13166 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13167 // (concat_vectors X, Z)
13168 if (InsIdx == VT.getVectorNumElements()/2)
13169 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13170 N0.getOperand(0), N->getOperand(1));
13176 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13177 SDValue N0 = N->getOperand(0);
13179 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13180 if (N0->getOpcode() == ISD::FP16_TO_FP)
13181 return N0->getOperand(0);
13186 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13187 SDValue N0 = N->getOperand(0);
13189 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13190 if (N0->getOpcode() == ISD::AND) {
13191 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13192 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13193 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13201 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13202 /// with the destination vector and a zero vector.
13203 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13204 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13205 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13206 EVT VT = N->getValueType(0);
13207 SDValue LHS = N->getOperand(0);
13208 SDValue RHS = N->getOperand(1);
13211 // Make sure we're not running after operation legalization where it
13212 // may have custom lowered the vector shuffles.
13213 if (LegalOperations)
13216 if (N->getOpcode() != ISD::AND)
13219 if (RHS.getOpcode() == ISD::BITCAST)
13220 RHS = RHS.getOperand(0);
13222 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13225 EVT RVT = RHS.getValueType();
13226 unsigned NumElts = RHS.getNumOperands();
13228 // Attempt to create a valid clear mask, splitting the mask into
13229 // sub elements and checking to see if each is
13230 // all zeros or all ones - suitable for shuffle masking.
13231 auto BuildClearMask = [&](int Split) {
13232 int NumSubElts = NumElts * Split;
13233 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13235 SmallVector<int, 8> Indices;
13236 for (int i = 0; i != NumSubElts; ++i) {
13237 int EltIdx = i / Split;
13238 int SubIdx = i % Split;
13239 SDValue Elt = RHS.getOperand(EltIdx);
13240 if (Elt.getOpcode() == ISD::UNDEF) {
13241 Indices.push_back(-1);
13246 if (isa<ConstantSDNode>(Elt))
13247 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13248 else if (isa<ConstantFPSDNode>(Elt))
13249 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13253 // Extract the sub element from the constant bit mask.
13254 if (DAG.getDataLayout().isBigEndian()) {
13255 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13257 Bits = Bits.lshr(SubIdx * NumSubBits);
13261 Bits = Bits.trunc(NumSubBits);
13263 if (Bits.isAllOnesValue())
13264 Indices.push_back(i);
13265 else if (Bits == 0)
13266 Indices.push_back(i + NumSubElts);
13271 // Let's see if the target supports this vector_shuffle.
13272 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13273 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13274 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13277 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13278 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13279 DAG.getBitcast(ClearVT, LHS),
13280 Zero, &Indices[0]));
13283 // Determine maximum split level (byte level masking).
13285 if (RVT.getScalarSizeInBits() % 8 == 0)
13286 MaxSplit = RVT.getScalarSizeInBits() / 8;
13288 for (int Split = 1; Split <= MaxSplit; ++Split)
13289 if (RVT.getScalarSizeInBits() % Split == 0)
13290 if (SDValue S = BuildClearMask(Split))
13296 /// Visit a binary vector operation, like ADD.
13297 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13298 assert(N->getValueType(0).isVector() &&
13299 "SimplifyVBinOp only works on vectors!");
13301 SDValue LHS = N->getOperand(0);
13302 SDValue RHS = N->getOperand(1);
13304 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13306 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13307 RHS.getOpcode() == ISD::BUILD_VECTOR) {
13308 // Check if both vectors are constants. If not bail out.
13309 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13310 cast<BuildVectorSDNode>(RHS)->isConstant()))
13313 SmallVector<SDValue, 8> Ops;
13314 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13315 SDValue LHSOp = LHS.getOperand(i);
13316 SDValue RHSOp = RHS.getOperand(i);
13318 // Can't fold divide by zero.
13319 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13320 N->getOpcode() == ISD::FDIV) {
13321 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13322 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13326 EVT VT = LHSOp.getValueType();
13327 EVT RVT = RHSOp.getValueType();
13329 // Integer BUILD_VECTOR operands may have types larger than the element
13330 // size (e.g., when the element type is not legal). Prior to type
13331 // legalization, the types may not match between the two BUILD_VECTORS.
13332 // Truncate one of the operands to make them match.
13333 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13334 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13336 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13340 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13342 if (FoldOp.getOpcode() != ISD::UNDEF &&
13343 FoldOp.getOpcode() != ISD::Constant &&
13344 FoldOp.getOpcode() != ISD::ConstantFP)
13346 Ops.push_back(FoldOp);
13347 AddToWorklist(FoldOp.getNode());
13350 if (Ops.size() == LHS.getNumOperands())
13351 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13354 // Try to convert a constant mask AND into a shuffle clear mask.
13355 if (SDValue Shuffle = XformToShuffleWithZero(N))
13358 // Type legalization might introduce new shuffles in the DAG.
13359 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13360 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13361 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13362 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13363 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13364 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13365 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13366 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13368 if (SVN0->getMask().equals(SVN1->getMask())) {
13369 EVT VT = N->getValueType(0);
13370 SDValue UndefVector = LHS.getOperand(1);
13371 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13372 LHS.getOperand(0), RHS.getOperand(0));
13373 AddUsersToWorklist(N);
13374 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13375 &SVN0->getMask()[0]);
13382 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13383 SDValue N1, SDValue N2){
13384 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13386 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13387 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13389 // If we got a simplified select_cc node back from SimplifySelectCC, then
13390 // break it down into a new SETCC node, and a new SELECT node, and then return
13391 // the SELECT node, since we were called with a SELECT node.
13392 if (SCC.getNode()) {
13393 // Check to see if we got a select_cc back (to turn into setcc/select).
13394 // Otherwise, just return whatever node we got back, like fabs.
13395 if (SCC.getOpcode() == ISD::SELECT_CC) {
13396 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13398 SCC.getOperand(0), SCC.getOperand(1),
13399 SCC.getOperand(4));
13400 AddToWorklist(SETCC.getNode());
13401 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13402 SCC.getOperand(2), SCC.getOperand(3));
13410 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13411 /// being selected between, see if we can simplify the select. Callers of this
13412 /// should assume that TheSelect is deleted if this returns true. As such, they
13413 /// should return the appropriate thing (e.g. the node) back to the top-level of
13414 /// the DAG combiner loop to avoid it being looked at.
13415 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13418 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13419 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13420 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13421 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13422 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13423 SDValue Sqrt = RHS;
13426 const ConstantFPSDNode *NegZero = nullptr;
13428 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13429 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13430 CmpLHS = TheSelect->getOperand(0);
13431 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13433 // SELECT or VSELECT
13434 SDValue Cmp = TheSelect->getOperand(0);
13435 if (Cmp.getOpcode() == ISD::SETCC) {
13436 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13437 CmpLHS = Cmp.getOperand(0);
13438 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13441 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13442 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13443 CC == ISD::SETULT || CC == ISD::SETLT)) {
13444 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13445 CombineTo(TheSelect, Sqrt);
13450 // Cannot simplify select with vector condition
13451 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13453 // If this is a select from two identical things, try to pull the operation
13454 // through the select.
13455 if (LHS.getOpcode() != RHS.getOpcode() ||
13456 !LHS.hasOneUse() || !RHS.hasOneUse())
13459 // If this is a load and the token chain is identical, replace the select
13460 // of two loads with a load through a select of the address to load from.
13461 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13462 // constants have been dropped into the constant pool.
13463 if (LHS.getOpcode() == ISD::LOAD) {
13464 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13465 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13467 // Token chains must be identical.
13468 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13469 // Do not let this transformation reduce the number of volatile loads.
13470 LLD->isVolatile() || RLD->isVolatile() ||
13471 // FIXME: If either is a pre/post inc/dec load,
13472 // we'd need to split out the address adjustment.
13473 LLD->isIndexed() || RLD->isIndexed() ||
13474 // If this is an EXTLOAD, the VT's must match.
13475 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13476 // If this is an EXTLOAD, the kind of extension must match.
13477 (LLD->getExtensionType() != RLD->getExtensionType() &&
13478 // The only exception is if one of the extensions is anyext.
13479 LLD->getExtensionType() != ISD::EXTLOAD &&
13480 RLD->getExtensionType() != ISD::EXTLOAD) ||
13481 // FIXME: this discards src value information. This is
13482 // over-conservative. It would be beneficial to be able to remember
13483 // both potential memory locations. Since we are discarding
13484 // src value info, don't do the transformation if the memory
13485 // locations are not in the default address space.
13486 LLD->getPointerInfo().getAddrSpace() != 0 ||
13487 RLD->getPointerInfo().getAddrSpace() != 0 ||
13488 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13489 LLD->getBasePtr().getValueType()))
13492 // Check that the select condition doesn't reach either load. If so,
13493 // folding this will induce a cycle into the DAG. If not, this is safe to
13494 // xform, so create a select of the addresses.
13496 if (TheSelect->getOpcode() == ISD::SELECT) {
13497 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13498 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13499 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13501 // The loads must not depend on one another.
13502 if (LLD->isPredecessorOf(RLD) ||
13503 RLD->isPredecessorOf(LLD))
13505 Addr = DAG.getSelect(SDLoc(TheSelect),
13506 LLD->getBasePtr().getValueType(),
13507 TheSelect->getOperand(0), LLD->getBasePtr(),
13508 RLD->getBasePtr());
13509 } else { // Otherwise SELECT_CC
13510 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13511 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13513 if ((LLD->hasAnyUseOfValue(1) &&
13514 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13515 (RLD->hasAnyUseOfValue(1) &&
13516 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13519 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13520 LLD->getBasePtr().getValueType(),
13521 TheSelect->getOperand(0),
13522 TheSelect->getOperand(1),
13523 LLD->getBasePtr(), RLD->getBasePtr(),
13524 TheSelect->getOperand(4));
13528 // It is safe to replace the two loads if they have different alignments,
13529 // but the new load must be the minimum (most restrictive) alignment of the
13531 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13532 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13533 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13534 Load = DAG.getLoad(TheSelect->getValueType(0),
13536 // FIXME: Discards pointer and AA info.
13537 LLD->getChain(), Addr, MachinePointerInfo(),
13538 LLD->isVolatile(), LLD->isNonTemporal(),
13539 isInvariant, Alignment);
13541 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13542 RLD->getExtensionType() : LLD->getExtensionType(),
13544 TheSelect->getValueType(0),
13545 // FIXME: Discards pointer and AA info.
13546 LLD->getChain(), Addr, MachinePointerInfo(),
13547 LLD->getMemoryVT(), LLD->isVolatile(),
13548 LLD->isNonTemporal(), isInvariant, Alignment);
13551 // Users of the select now use the result of the load.
13552 CombineTo(TheSelect, Load);
13554 // Users of the old loads now use the new load's chain. We know the
13555 // old-load value is dead now.
13556 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13557 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13564 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13565 /// where 'cond' is the comparison specified by CC.
13566 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13567 SDValue N2, SDValue N3,
13568 ISD::CondCode CC, bool NotExtCompare) {
13569 // (x ? y : y) -> y.
13570 if (N2 == N3) return N2;
13572 EVT VT = N2.getValueType();
13573 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13574 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13576 // Determine if the condition we're dealing with is constant
13577 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13578 N0, N1, CC, DL, false);
13579 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13581 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13582 // fold select_cc true, x, y -> x
13583 // fold select_cc false, x, y -> y
13584 return !SCCC->isNullValue() ? N2 : N3;
13587 // Check to see if we can simplify the select into an fabs node
13588 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13589 // Allow either -0.0 or 0.0
13590 if (CFP->isZero()) {
13591 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13592 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13593 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13594 N2 == N3.getOperand(0))
13595 return DAG.getNode(ISD::FABS, DL, VT, N0);
13597 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13598 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13599 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13600 N2.getOperand(0) == N3)
13601 return DAG.getNode(ISD::FABS, DL, VT, N3);
13605 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13606 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13607 // in it. This is a win when the constant is not otherwise available because
13608 // it replaces two constant pool loads with one. We only do this if the FP
13609 // type is known to be legal, because if it isn't, then we are before legalize
13610 // types an we want the other legalization to happen first (e.g. to avoid
13611 // messing with soft float) and if the ConstantFP is not legal, because if
13612 // it is legal, we may not need to store the FP constant in a constant pool.
13613 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13614 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13615 if (TLI.isTypeLegal(N2.getValueType()) &&
13616 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13617 TargetLowering::Legal &&
13618 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13619 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13620 // If both constants have multiple uses, then we won't need to do an
13621 // extra load, they are likely around in registers for other users.
13622 (TV->hasOneUse() || FV->hasOneUse())) {
13623 Constant *Elts[] = {
13624 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13625 const_cast<ConstantFP*>(TV->getConstantFPValue())
13627 Type *FPTy = Elts[0]->getType();
13628 const DataLayout &TD = DAG.getDataLayout();
13630 // Create a ConstantArray of the two constants.
13631 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13633 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13634 TD.getPrefTypeAlignment(FPTy));
13635 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13637 // Get the offsets to the 0 and 1 element of the array so that we can
13638 // select between them.
13639 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13640 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13641 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13643 SDValue Cond = DAG.getSetCC(DL,
13644 getSetCCResultType(N0.getValueType()),
13646 AddToWorklist(Cond.getNode());
13647 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13649 AddToWorklist(CstOffset.getNode());
13650 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13652 AddToWorklist(CPIdx.getNode());
13653 return DAG.getLoad(
13654 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13655 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13656 false, false, false, Alignment);
13660 // Check to see if we can perform the "gzip trick", transforming
13661 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13662 if (isNullConstant(N3) && CC == ISD::SETLT &&
13663 (isNullConstant(N1) || // (a < 0) ? b : 0
13664 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13665 EVT XType = N0.getValueType();
13666 EVT AType = N2.getValueType();
13667 if (XType.bitsGE(AType)) {
13668 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13669 // single-bit constant.
13670 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13671 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13672 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13673 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13674 getShiftAmountTy(N0.getValueType()));
13675 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13677 AddToWorklist(Shift.getNode());
13679 if (XType.bitsGT(AType)) {
13680 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13681 AddToWorklist(Shift.getNode());
13684 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13687 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13689 DAG.getConstant(XType.getSizeInBits() - 1,
13691 getShiftAmountTy(N0.getValueType())));
13692 AddToWorklist(Shift.getNode());
13694 if (XType.bitsGT(AType)) {
13695 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13696 AddToWorklist(Shift.getNode());
13699 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13703 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13704 // where y is has a single bit set.
13705 // A plaintext description would be, we can turn the SELECT_CC into an AND
13706 // when the condition can be materialized as an all-ones register. Any
13707 // single bit-test can be materialized as an all-ones register with
13708 // shift-left and shift-right-arith.
13709 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13710 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13711 SDValue AndLHS = N0->getOperand(0);
13712 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13713 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13714 // Shift the tested bit over the sign bit.
13715 APInt AndMask = ConstAndRHS->getAPIntValue();
13717 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13718 getShiftAmountTy(AndLHS.getValueType()));
13719 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13721 // Now arithmetic right shift it all the way over, so the result is either
13722 // all-ones, or zero.
13724 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13725 getShiftAmountTy(Shl.getValueType()));
13726 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13728 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13732 // fold select C, 16, 0 -> shl C, 4
13733 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13734 TLI.getBooleanContents(N0.getValueType()) ==
13735 TargetLowering::ZeroOrOneBooleanContent) {
13737 // If the caller doesn't want us to simplify this into a zext of a compare,
13739 if (NotExtCompare && N2C->isOne())
13742 // Get a SetCC of the condition
13743 // NOTE: Don't create a SETCC if it's not legal on this target.
13744 if (!LegalOperations ||
13745 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13747 // cast from setcc result type to select result type
13749 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13751 if (N2.getValueType().bitsLT(SCC.getValueType()))
13752 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13753 N2.getValueType());
13755 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13756 N2.getValueType(), SCC);
13758 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13759 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13760 N2.getValueType(), SCC);
13763 AddToWorklist(SCC.getNode());
13764 AddToWorklist(Temp.getNode());
13769 // shl setcc result by log2 n2c
13770 return DAG.getNode(
13771 ISD::SHL, DL, N2.getValueType(), Temp,
13772 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13773 getShiftAmountTy(Temp.getValueType())));
13777 // Check to see if this is an integer abs.
13778 // select_cc setg[te] X, 0, X, -X ->
13779 // select_cc setgt X, -1, X, -X ->
13780 // select_cc setl[te] X, 0, -X, X ->
13781 // select_cc setlt X, 1, -X, X ->
13782 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13784 ConstantSDNode *SubC = nullptr;
13785 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13786 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13787 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13788 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13789 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13790 (N1C->isOne() && CC == ISD::SETLT)) &&
13791 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13792 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13794 EVT XType = N0.getValueType();
13795 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13797 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13799 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13800 getShiftAmountTy(N0.getValueType())));
13801 SDValue Add = DAG.getNode(ISD::ADD, DL,
13803 AddToWorklist(Shift.getNode());
13804 AddToWorklist(Add.getNode());
13805 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13812 /// This is a stub for TargetLowering::SimplifySetCC.
13813 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13814 SDValue N1, ISD::CondCode Cond,
13815 SDLoc DL, bool foldBooleans) {
13816 TargetLowering::DAGCombinerInfo
13817 DagCombineInfo(DAG, Level, false, this);
13818 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13821 /// Given an ISD::SDIV node expressing a divide by constant, return
13822 /// a DAG expression to select that will generate the same value by multiplying
13823 /// by a magic number.
13824 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13825 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13826 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13830 // Avoid division by zero.
13831 if (C->isNullValue())
13834 std::vector<SDNode*> Built;
13836 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13838 for (SDNode *N : Built)
13843 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13844 /// DAG expression that will generate the same value by right shifting.
13845 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13846 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13850 // Avoid division by zero.
13851 if (C->isNullValue())
13854 std::vector<SDNode *> Built;
13855 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13857 for (SDNode *N : Built)
13862 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13863 /// expression that will generate the same value by multiplying by a magic
13865 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13866 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13867 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13871 // Avoid division by zero.
13872 if (C->isNullValue())
13875 std::vector<SDNode*> Built;
13877 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13879 for (SDNode *N : Built)
13884 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13885 if (Level >= AfterLegalizeDAG)
13888 // Expose the DAG combiner to the target combiner implementations.
13889 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13891 unsigned Iterations = 0;
13892 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13894 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13895 // For the reciprocal, we need to find the zero of the function:
13896 // F(X) = A X - 1 [which has a zero at X = 1/A]
13898 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13899 // does not require additional intermediate precision]
13900 EVT VT = Op.getValueType();
13902 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13904 AddToWorklist(Est.getNode());
13906 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13907 for (unsigned i = 0; i < Iterations; ++i) {
13908 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13909 AddToWorklist(NewEst.getNode());
13911 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13912 AddToWorklist(NewEst.getNode());
13914 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13915 AddToWorklist(NewEst.getNode());
13917 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13918 AddToWorklist(Est.getNode());
13927 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13928 /// For the reciprocal sqrt, we need to find the zero of the function:
13929 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13931 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13932 /// As a result, we precompute A/2 prior to the iteration loop.
13933 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13934 unsigned Iterations) {
13935 EVT VT = Arg.getValueType();
13937 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13939 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13940 // this entire sequence requires only one FP constant.
13941 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13942 AddToWorklist(HalfArg.getNode());
13944 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13945 AddToWorklist(HalfArg.getNode());
13947 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13948 for (unsigned i = 0; i < Iterations; ++i) {
13949 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13950 AddToWorklist(NewEst.getNode());
13952 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13953 AddToWorklist(NewEst.getNode());
13955 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13956 AddToWorklist(NewEst.getNode());
13958 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13959 AddToWorklist(Est.getNode());
13964 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13965 /// For the reciprocal sqrt, we need to find the zero of the function:
13966 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13968 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13969 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13970 unsigned Iterations) {
13971 EVT VT = Arg.getValueType();
13973 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13974 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13976 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13977 for (unsigned i = 0; i < Iterations; ++i) {
13978 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13979 AddToWorklist(HalfEst.getNode());
13981 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13982 AddToWorklist(Est.getNode());
13984 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13985 AddToWorklist(Est.getNode());
13987 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13988 AddToWorklist(Est.getNode());
13990 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13991 AddToWorklist(Est.getNode());
13996 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13997 if (Level >= AfterLegalizeDAG)
14000 // Expose the DAG combiner to the target combiner implementations.
14001 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14002 unsigned Iterations = 0;
14003 bool UseOneConstNR = false;
14004 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14005 AddToWorklist(Est.getNode());
14007 Est = UseOneConstNR ?
14008 BuildRsqrtNROneConst(Op, Est, Iterations) :
14009 BuildRsqrtNRTwoConst(Op, Est, Iterations);
14017 /// Return true if base is a frame index, which is known not to alias with
14018 /// anything but itself. Provides base object and offset as results.
14019 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14020 const GlobalValue *&GV, const void *&CV) {
14021 // Assume it is a primitive operation.
14022 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14024 // If it's an adding a simple constant then integrate the offset.
14025 if (Base.getOpcode() == ISD::ADD) {
14026 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14027 Base = Base.getOperand(0);
14028 Offset += C->getZExtValue();
14032 // Return the underlying GlobalValue, and update the Offset. Return false
14033 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14034 // by multiple nodes with different offsets.
14035 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14036 GV = G->getGlobal();
14037 Offset += G->getOffset();
14041 // Return the underlying Constant value, and update the Offset. Return false
14042 // for ConstantSDNodes since the same constant pool entry may be represented
14043 // by multiple nodes with different offsets.
14044 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14045 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14046 : (const void *)C->getConstVal();
14047 Offset += C->getOffset();
14050 // If it's any of the following then it can't alias with anything but itself.
14051 return isa<FrameIndexSDNode>(Base);
14054 /// Return true if there is any possibility that the two addresses overlap.
14055 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14056 // If they are the same then they must be aliases.
14057 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14059 // If they are both volatile then they cannot be reordered.
14060 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14062 // If one operation reads from invariant memory, and the other may store, they
14063 // cannot alias. These should really be checking the equivalent of mayWrite,
14064 // but it only matters for memory nodes other than load /store.
14065 if (Op0->isInvariant() && Op1->writeMem())
14068 if (Op1->isInvariant() && Op0->writeMem())
14071 // Gather base node and offset information.
14072 SDValue Base1, Base2;
14073 int64_t Offset1, Offset2;
14074 const GlobalValue *GV1, *GV2;
14075 const void *CV1, *CV2;
14076 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14077 Base1, Offset1, GV1, CV1);
14078 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14079 Base2, Offset2, GV2, CV2);
14081 // If they have a same base address then check to see if they overlap.
14082 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14083 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14084 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14086 // It is possible for different frame indices to alias each other, mostly
14087 // when tail call optimization reuses return address slots for arguments.
14088 // To catch this case, look up the actual index of frame indices to compute
14089 // the real alias relationship.
14090 if (isFrameIndex1 && isFrameIndex2) {
14091 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14092 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14093 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14094 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14095 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14098 // Otherwise, if we know what the bases are, and they aren't identical, then
14099 // we know they cannot alias.
14100 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14103 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14104 // compared to the size and offset of the access, we may be able to prove they
14105 // do not alias. This check is conservative for now to catch cases created by
14106 // splitting vector types.
14107 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14108 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14109 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14110 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14111 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14112 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14113 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14115 // There is no overlap between these relatively aligned accesses of similar
14116 // size, return no alias.
14117 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14118 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14122 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14124 : DAG.getSubtarget().useAA();
14126 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14127 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14131 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14132 // Use alias analysis information.
14133 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14134 Op1->getSrcValueOffset());
14135 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14136 Op0->getSrcValueOffset() - MinOffset;
14137 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14138 Op1->getSrcValueOffset() - MinOffset;
14139 AliasResult AAResult =
14140 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14141 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14142 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14143 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14144 if (AAResult == NoAlias)
14148 // Otherwise we have to assume they alias.
14152 /// Walk up chain skipping non-aliasing memory nodes,
14153 /// looking for aliasing nodes and adding them to the Aliases vector.
14154 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14155 SmallVectorImpl<SDValue> &Aliases) {
14156 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14157 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14159 // Get alias information for node.
14160 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14163 Chains.push_back(OriginalChain);
14164 unsigned Depth = 0;
14166 // Look at each chain and determine if it is an alias. If so, add it to the
14167 // aliases list. If not, then continue up the chain looking for the next
14169 while (!Chains.empty()) {
14170 SDValue Chain = Chains.pop_back_val();
14172 // For TokenFactor nodes, look at each operand and only continue up the
14173 // chain until we find two aliases. If we've seen two aliases, assume we'll
14174 // find more and revert to original chain since the xform is unlikely to be
14177 // FIXME: The depth check could be made to return the last non-aliasing
14178 // chain we found before we hit a tokenfactor rather than the original
14180 if (Depth > 6 || Aliases.size() == 2) {
14182 Aliases.push_back(OriginalChain);
14186 // Don't bother if we've been before.
14187 if (!Visited.insert(Chain.getNode()).second)
14190 switch (Chain.getOpcode()) {
14191 case ISD::EntryToken:
14192 // Entry token is ideal chain operand, but handled in FindBetterChain.
14197 // Get alias information for Chain.
14198 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14199 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14201 // If chain is alias then stop here.
14202 if (!(IsLoad && IsOpLoad) &&
14203 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14204 Aliases.push_back(Chain);
14206 // Look further up the chain.
14207 Chains.push_back(Chain.getOperand(0));
14213 case ISD::TokenFactor:
14214 // We have to check each of the operands of the token factor for "small"
14215 // token factors, so we queue them up. Adding the operands to the queue
14216 // (stack) in reverse order maintains the original order and increases the
14217 // likelihood that getNode will find a matching token factor (CSE.)
14218 if (Chain.getNumOperands() > 16) {
14219 Aliases.push_back(Chain);
14222 for (unsigned n = Chain.getNumOperands(); n;)
14223 Chains.push_back(Chain.getOperand(--n));
14228 // For all other instructions we will just have to take what we can get.
14229 Aliases.push_back(Chain);
14234 // We need to be careful here to also search for aliases through the
14235 // value operand of a store, etc. Consider the following situation:
14237 // L1 = load Token1, %52
14238 // S1 = store Token1, L1, %51
14239 // L2 = load Token1, %52+8
14240 // S2 = store Token1, L2, %51+8
14241 // Token2 = Token(S1, S2)
14242 // L3 = load Token2, %53
14243 // S3 = store Token2, L3, %52
14244 // L4 = load Token2, %53+8
14245 // S4 = store Token2, L4, %52+8
14246 // If we search for aliases of S3 (which loads address %52), and we look
14247 // only through the chain, then we'll miss the trivial dependence on L1
14248 // (which also loads from %52). We then might change all loads and
14249 // stores to use Token1 as their chain operand, which could result in
14250 // copying %53 into %52 before copying %52 into %51 (which should
14253 // The problem is, however, that searching for such data dependencies
14254 // can become expensive, and the cost is not directly related to the
14255 // chain depth. Instead, we'll rule out such configurations here by
14256 // insisting that we've visited all chain users (except for users
14257 // of the original chain, which is not necessary). When doing this,
14258 // we need to look through nodes we don't care about (otherwise, things
14259 // like register copies will interfere with trivial cases).
14261 SmallVector<const SDNode *, 16> Worklist;
14262 for (const SDNode *N : Visited)
14263 if (N != OriginalChain.getNode())
14264 Worklist.push_back(N);
14266 while (!Worklist.empty()) {
14267 const SDNode *M = Worklist.pop_back_val();
14269 // We have already visited M, and want to make sure we've visited any uses
14270 // of M that we care about. For uses that we've not visisted, and don't
14271 // care about, queue them to the worklist.
14273 for (SDNode::use_iterator UI = M->use_begin(),
14274 UIE = M->use_end(); UI != UIE; ++UI)
14275 if (UI.getUse().getValueType() == MVT::Other &&
14276 Visited.insert(*UI).second) {
14277 if (isa<MemSDNode>(*UI)) {
14278 // We've not visited this use, and we care about it (it could have an
14279 // ordering dependency with the original node).
14281 Aliases.push_back(OriginalChain);
14285 // We've not visited this use, but we don't care about it. Mark it as
14286 // visited and enqueue it to the worklist.
14287 Worklist.push_back(*UI);
14292 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14293 /// (aliasing node.)
14294 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14295 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14297 // Accumulate all the aliases to this node.
14298 GatherAllAliases(N, OldChain, Aliases);
14300 // If no operands then chain to entry token.
14301 if (Aliases.size() == 0)
14302 return DAG.getEntryNode();
14304 // If a single operand then chain to it. We don't need to revisit it.
14305 if (Aliases.size() == 1)
14308 // Construct a custom tailored token factor.
14309 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14312 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14313 // This holds the base pointer, index, and the offset in bytes from the base
14315 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14317 // We must have a base and an offset.
14318 if (!BasePtr.Base.getNode())
14321 // Do not handle stores to undef base pointers.
14322 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14325 SmallVector<StoreSDNode *, 8> ChainedStores;
14326 ChainedStores.push_back(St);
14328 // Walk up the chain and look for nodes with offsets from the same
14329 // base pointer. Stop when reaching an instruction with a different kind
14330 // or instruction which has a different base pointer.
14331 StoreSDNode *Index = St;
14333 // If the chain has more than one use, then we can't reorder the mem ops.
14334 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14337 // Find the base pointer and offset for this memory node.
14338 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14340 // Check that the base pointer is the same as the original one.
14341 if (!Ptr.equalBaseIndex(BasePtr))
14344 if (Index->isVolatile() || Index->isIndexed())
14347 // Find the next memory operand in the chain. If the next operand in the
14348 // chain is a store then move up and continue the scan with the next
14349 // memory operand. If the next operand is a load save it and use alias
14350 // information to check if it interferes with anything.
14351 SDNode *NextInChain = Index->getChain().getNode();
14353 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14354 // We found a store node. Use it for the next iteration.
14355 ChainedStores.push_back(STn);
14358 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14359 NextInChain = Ldn->getChain().getNode();
14368 bool MadeChange = false;
14369 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14371 for (StoreSDNode *ChainedStore : ChainedStores) {
14372 SDValue Chain = ChainedStore->getChain();
14373 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14375 if (Chain != BetterChain) {
14377 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14381 // Do all replacements after finding the replacements to make to avoid making
14382 // the chains more complicated by introducing new TokenFactors.
14383 for (auto Replacement : BetterChains)
14384 replaceStoreChain(Replacement.first, Replacement.second);
14389 /// This is the entry point for the file.
14390 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14391 CodeGenOpt::Level OptLevel) {
14392 /// This is the main entry point to this class.
14393 DAGCombiner(*this, AA, OptLevel).Run(Level);