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 visitAND(SDNode *N);
249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250 SDValue visitOR(SDNode *N);
251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
254 SDValue visitSHL(SDNode *N);
255 SDValue visitSRA(SDNode *N);
256 SDValue visitSRL(SDNode *N);
257 SDValue visitRotate(SDNode *N);
258 SDValue visitCTLZ(SDNode *N);
259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260 SDValue visitCTTZ(SDNode *N);
261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262 SDValue visitCTPOP(SDNode *N);
263 SDValue visitSELECT(SDNode *N);
264 SDValue visitVSELECT(SDNode *N);
265 SDValue visitSELECT_CC(SDNode *N);
266 SDValue visitSETCC(SDNode *N);
267 SDValue visitSIGN_EXTEND(SDNode *N);
268 SDValue visitZERO_EXTEND(SDNode *N);
269 SDValue visitANY_EXTEND(SDNode *N);
270 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271 SDValue visitTRUNCATE(SDNode *N);
272 SDValue visitBITCAST(SDNode *N);
273 SDValue visitBUILD_PAIR(SDNode *N);
274 SDValue visitFADD(SDNode *N);
275 SDValue visitFSUB(SDNode *N);
276 SDValue visitFMUL(SDNode *N);
277 SDValue visitFMA(SDNode *N);
278 SDValue visitFDIV(SDNode *N);
279 SDValue visitFREM(SDNode *N);
280 SDValue visitFSQRT(SDNode *N);
281 SDValue visitFCOPYSIGN(SDNode *N);
282 SDValue visitSINT_TO_FP(SDNode *N);
283 SDValue visitUINT_TO_FP(SDNode *N);
284 SDValue visitFP_TO_SINT(SDNode *N);
285 SDValue visitFP_TO_UINT(SDNode *N);
286 SDValue visitFP_ROUND(SDNode *N);
287 SDValue visitFP_ROUND_INREG(SDNode *N);
288 SDValue visitFP_EXTEND(SDNode *N);
289 SDValue visitFNEG(SDNode *N);
290 SDValue visitFABS(SDNode *N);
291 SDValue visitFCEIL(SDNode *N);
292 SDValue visitFTRUNC(SDNode *N);
293 SDValue visitFFLOOR(SDNode *N);
294 SDValue visitFMINNUM(SDNode *N);
295 SDValue visitFMAXNUM(SDNode *N);
296 SDValue visitBRCOND(SDNode *N);
297 SDValue visitBR_CC(SDNode *N);
298 SDValue visitLOAD(SDNode *N);
299 SDValue visitSTORE(SDNode *N);
300 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302 SDValue visitBUILD_VECTOR(SDNode *N);
303 SDValue visitCONCAT_VECTORS(SDNode *N);
304 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305 SDValue visitVECTOR_SHUFFLE(SDNode *N);
306 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307 SDValue visitINSERT_SUBVECTOR(SDNode *N);
308 SDValue visitMLOAD(SDNode *N);
309 SDValue visitMSTORE(SDNode *N);
310 SDValue visitFP_TO_FP16(SDNode *N);
312 SDValue visitFADDForFMACombine(SDNode *N);
313 SDValue visitFSUBForFMACombine(SDNode *N);
315 SDValue XformToShuffleWithZero(SDNode *N);
316 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
318 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
320 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
321 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
322 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
323 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
324 SDValue N3, ISD::CondCode CC,
325 bool NotExtCompare = false);
326 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
327 SDLoc DL, bool foldBooleans = true);
329 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
331 bool isOneUseSetCC(SDValue N) const;
333 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
335 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
336 SDValue CombineExtLoad(SDNode *N);
337 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
338 SDValue BuildSDIV(SDNode *N);
339 SDValue BuildSDIVPow2(SDNode *N);
340 SDValue BuildUDIV(SDNode *N);
341 SDValue BuildReciprocalEstimate(SDValue Op);
342 SDValue BuildRsqrtEstimate(SDValue Op);
343 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
344 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
345 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
346 bool DemandHighBits = true);
347 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
348 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
349 SDValue InnerPos, SDValue InnerNeg,
350 unsigned PosOpcode, unsigned NegOpcode,
352 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
353 SDValue ReduceLoadWidth(SDNode *N);
354 SDValue ReduceLoadOpStoreWidth(SDNode *N);
355 SDValue TransformFPLoadStorePair(SDNode *N);
356 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
357 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
359 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
361 /// Walk up chain skipping non-aliasing memory nodes,
362 /// looking for aliasing nodes and adding them to the Aliases vector.
363 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
364 SmallVectorImpl<SDValue> &Aliases);
366 /// Return true if there is any possibility that the two addresses overlap.
367 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
369 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
370 /// chain (aliasing node.)
371 SDValue FindBetterChain(SDNode *N, SDValue Chain);
373 /// Holds a pointer to an LSBaseSDNode as well as information on where it
374 /// is located in a sequence of memory operations connected by a chain.
376 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
377 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
378 // Ptr to the mem node.
379 LSBaseSDNode *MemNode;
380 // Offset from the base ptr.
381 int64_t OffsetFromBase;
382 // What is the sequence number of this mem node.
383 // Lowest mem operand in the DAG starts at zero.
384 unsigned SequenceNum;
387 /// This is a helper function for MergeConsecutiveStores. When the source
388 /// elements of the consecutive stores are all constants or all extracted
389 /// vector elements, try to merge them into one larger store.
390 /// \return True if a merged store was created.
391 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
392 EVT MemVT, unsigned NumElem,
393 bool IsConstantSrc, bool UseVector);
395 /// Merge consecutive store operations into a wide store.
396 /// This optimization uses wide integers or vectors when possible.
397 /// \return True if some memory operations were changed.
398 bool MergeConsecutiveStores(StoreSDNode *N);
400 /// \brief Try to transform a truncation where C is a constant:
401 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
403 /// \p N needs to be a truncation and its first operand an AND. Other
404 /// requirements are checked by the function (e.g. that trunc is
405 /// single-use) and if missed an empty SDValue is returned.
406 SDValue distributeTruncateThroughAnd(SDNode *N);
409 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
410 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
411 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
412 auto *F = DAG.getMachineFunction().getFunction();
413 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
414 F->hasFnAttribute(Attribute::MinSize);
417 /// Runs the dag combiner on all nodes in the work list
418 void Run(CombineLevel AtLevel);
420 SelectionDAG &getDAG() const { return DAG; }
422 /// Returns a type large enough to hold any valid shift amount - before type
423 /// legalization these can be huge.
424 EVT getShiftAmountTy(EVT LHSTy) {
425 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
426 if (LHSTy.isVector())
428 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
429 : TLI.getPointerTy();
432 /// This method returns true if we are running before type legalization or
433 /// if the specified VT is legal.
434 bool isTypeLegal(const EVT &VT) {
435 if (!LegalTypes) return true;
436 return TLI.isTypeLegal(VT);
439 /// Convenience wrapper around TargetLowering::getSetCCResultType
440 EVT getSetCCResultType(EVT VT) const {
441 return TLI.getSetCCResultType(*DAG.getContext(), VT);
448 /// This class is a DAGUpdateListener that removes any deleted
449 /// nodes from the worklist.
450 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
453 explicit WorklistRemover(DAGCombiner &dc)
454 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
456 void NodeDeleted(SDNode *N, SDNode *E) override {
457 DC.removeFromWorklist(N);
462 //===----------------------------------------------------------------------===//
463 // TargetLowering::DAGCombinerInfo implementation
464 //===----------------------------------------------------------------------===//
466 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
467 ((DAGCombiner*)DC)->AddToWorklist(N);
470 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
471 ((DAGCombiner*)DC)->removeFromWorklist(N);
474 SDValue TargetLowering::DAGCombinerInfo::
475 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
476 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
479 SDValue TargetLowering::DAGCombinerInfo::
480 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
481 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
485 SDValue TargetLowering::DAGCombinerInfo::
486 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
487 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
490 void TargetLowering::DAGCombinerInfo::
491 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
492 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
495 //===----------------------------------------------------------------------===//
497 //===----------------------------------------------------------------------===//
499 void DAGCombiner::deleteAndRecombine(SDNode *N) {
500 removeFromWorklist(N);
502 // If the operands of this node are only used by the node, they will now be
503 // dead. Make sure to re-visit them and recursively delete dead nodes.
504 for (const SDValue &Op : N->ops())
505 // For an operand generating multiple values, one of the values may
506 // become dead allowing further simplification (e.g. split index
507 // arithmetic from an indexed load).
508 if (Op->hasOneUse() || Op->getNumValues() > 1)
509 AddToWorklist(Op.getNode());
514 /// Return 1 if we can compute the negated form of the specified expression for
515 /// the same cost as the expression itself, or 2 if we can compute the negated
516 /// form more cheaply than the expression itself.
517 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
518 const TargetLowering &TLI,
519 const TargetOptions *Options,
520 unsigned Depth = 0) {
521 // fneg is removable even if it has multiple uses.
522 if (Op.getOpcode() == ISD::FNEG) return 2;
524 // Don't allow anything with multiple uses.
525 if (!Op.hasOneUse()) return 0;
527 // Don't recurse exponentially.
528 if (Depth > 6) return 0;
530 switch (Op.getOpcode()) {
531 default: return false;
532 case ISD::ConstantFP:
533 // Don't invert constant FP values after legalize. The negated constant
534 // isn't necessarily legal.
535 return LegalOperations ? 0 : 1;
537 // FIXME: determine better conditions for this xform.
538 if (!Options->UnsafeFPMath) return 0;
540 // After operation legalization, it might not be legal to create new FSUBs.
541 if (LegalOperations &&
542 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
545 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
546 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
549 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
553 // We can't turn -(A-B) into B-A when we honor signed zeros.
554 if (!Options->UnsafeFPMath) return 0;
556 // fold (fneg (fsub A, B)) -> (fsub B, A)
561 if (Options->HonorSignDependentRoundingFPMath()) return 0;
563 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
564 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
568 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
574 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
579 /// If isNegatibleForFree returns true, return the newly negated expression.
580 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
581 bool LegalOperations, unsigned Depth = 0) {
582 const TargetOptions &Options = DAG.getTarget().Options;
583 // fneg is removable even if it has multiple uses.
584 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
586 // Don't allow anything with multiple uses.
587 assert(Op.hasOneUse() && "Unknown reuse!");
589 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
590 switch (Op.getOpcode()) {
591 default: llvm_unreachable("Unknown code");
592 case ISD::ConstantFP: {
593 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
595 return DAG.getConstantFP(V, Op.getValueType());
598 // FIXME: determine better conditions for this xform.
599 assert(Options.UnsafeFPMath);
601 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
602 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
603 DAG.getTargetLoweringInfo(), &Options, Depth+1))
604 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
605 GetNegatedExpression(Op.getOperand(0), DAG,
606 LegalOperations, Depth+1),
608 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
609 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
610 GetNegatedExpression(Op.getOperand(1), DAG,
611 LegalOperations, Depth+1),
614 // We can't turn -(A-B) into B-A when we honor signed zeros.
615 assert(Options.UnsafeFPMath);
617 // fold (fneg (fsub 0, B)) -> B
618 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
619 if (N0CFP->getValueAPF().isZero())
620 return Op.getOperand(1);
622 // fold (fneg (fsub A, B)) -> (fsub B, A)
623 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
624 Op.getOperand(1), Op.getOperand(0));
628 assert(!Options.HonorSignDependentRoundingFPMath());
630 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
631 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
632 DAG.getTargetLoweringInfo(), &Options, Depth+1))
633 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
634 GetNegatedExpression(Op.getOperand(0), DAG,
635 LegalOperations, Depth+1),
638 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
639 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
641 GetNegatedExpression(Op.getOperand(1), DAG,
642 LegalOperations, Depth+1));
646 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
647 GetNegatedExpression(Op.getOperand(0), DAG,
648 LegalOperations, Depth+1));
650 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
651 GetNegatedExpression(Op.getOperand(0), DAG,
652 LegalOperations, Depth+1),
657 // Return true if this node is a setcc, or is a select_cc
658 // that selects between the target values used for true and false, making it
659 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
660 // the appropriate nodes based on the type of node we are checking. This
661 // simplifies life a bit for the callers.
662 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
664 if (N.getOpcode() == ISD::SETCC) {
665 LHS = N.getOperand(0);
666 RHS = N.getOperand(1);
667 CC = N.getOperand(2);
671 if (N.getOpcode() != ISD::SELECT_CC ||
672 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
673 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
676 if (TLI.getBooleanContents(N.getValueType()) ==
677 TargetLowering::UndefinedBooleanContent)
680 LHS = N.getOperand(0);
681 RHS = N.getOperand(1);
682 CC = N.getOperand(4);
686 /// Return true if this is a SetCC-equivalent operation with only one use.
687 /// If this is true, it allows the users to invert the operation for free when
688 /// it is profitable to do so.
689 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
691 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
696 /// Returns true if N is a BUILD_VECTOR node whose
697 /// elements are all the same constant or undefined.
698 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
699 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
704 unsigned SplatBitSize;
706 EVT EltVT = N->getValueType(0).getVectorElementType();
707 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
709 EltVT.getSizeInBits() >= SplatBitSize);
712 // \brief Returns the SDNode if it is a constant integer BuildVector
713 // or constant integer.
714 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
715 if (isa<ConstantSDNode>(N))
717 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
722 // \brief Returns the SDNode if it is a constant float BuildVector
723 // or constant float.
724 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
725 if (isa<ConstantFPSDNode>(N))
727 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
732 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
734 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
735 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
738 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
739 BitVector UndefElements;
740 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
742 // BuildVectors can truncate their operands. Ignore that case here.
743 // FIXME: We blindly ignore splats which include undef which is overly
745 if (CN && UndefElements.none() &&
746 CN->getValueType(0) == N.getValueType().getScalarType())
753 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
755 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
756 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
759 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
760 BitVector UndefElements;
761 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
763 if (CN && UndefElements.none())
770 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
771 SDValue N0, SDValue N1) {
772 EVT VT = N0.getValueType();
773 if (N0.getOpcode() == Opc) {
774 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
775 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
776 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
777 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
778 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
781 if (N0.hasOneUse()) {
782 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
784 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
785 if (!OpNode.getNode())
787 AddToWorklist(OpNode.getNode());
788 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
793 if (N1.getOpcode() == Opc) {
794 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
795 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
796 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
797 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
798 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
801 if (N1.hasOneUse()) {
802 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
804 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
805 if (!OpNode.getNode())
807 AddToWorklist(OpNode.getNode());
808 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
816 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
818 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
820 DEBUG(dbgs() << "\nReplacing.1 ";
822 dbgs() << "\nWith: ";
823 To[0].getNode()->dump(&DAG);
824 dbgs() << " and " << NumTo-1 << " other values\n");
825 for (unsigned i = 0, e = NumTo; i != e; ++i)
826 assert((!To[i].getNode() ||
827 N->getValueType(i) == To[i].getValueType()) &&
828 "Cannot combine value to value of different type!");
830 WorklistRemover DeadNodes(*this);
831 DAG.ReplaceAllUsesWith(N, To);
833 // Push the new nodes and any users onto the worklist
834 for (unsigned i = 0, e = NumTo; i != e; ++i) {
835 if (To[i].getNode()) {
836 AddToWorklist(To[i].getNode());
837 AddUsersToWorklist(To[i].getNode());
842 // Finally, if the node is now dead, remove it from the graph. The node
843 // may not be dead if the replacement process recursively simplified to
844 // something else needing this node.
846 deleteAndRecombine(N);
847 return SDValue(N, 0);
851 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
852 // Replace all uses. If any nodes become isomorphic to other nodes and
853 // are deleted, make sure to remove them from our worklist.
854 WorklistRemover DeadNodes(*this);
855 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
857 // Push the new node and any (possibly new) users onto the worklist.
858 AddToWorklist(TLO.New.getNode());
859 AddUsersToWorklist(TLO.New.getNode());
861 // Finally, if the node is now dead, remove it from the graph. The node
862 // may not be dead if the replacement process recursively simplified to
863 // something else needing this node.
864 if (TLO.Old.getNode()->use_empty())
865 deleteAndRecombine(TLO.Old.getNode());
868 /// Check the specified integer node value to see if it can be simplified or if
869 /// things it uses can be simplified by bit propagation. If so, return true.
870 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
871 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
872 APInt KnownZero, KnownOne;
873 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
877 AddToWorklist(Op.getNode());
879 // Replace the old value with the new one.
881 DEBUG(dbgs() << "\nReplacing.2 ";
882 TLO.Old.getNode()->dump(&DAG);
883 dbgs() << "\nWith: ";
884 TLO.New.getNode()->dump(&DAG);
887 CommitTargetLoweringOpt(TLO);
891 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
893 EVT VT = Load->getValueType(0);
894 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
896 DEBUG(dbgs() << "\nReplacing.9 ";
898 dbgs() << "\nWith: ";
899 Trunc.getNode()->dump(&DAG);
901 WorklistRemover DeadNodes(*this);
902 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
903 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
904 deleteAndRecombine(Load);
905 AddToWorklist(Trunc.getNode());
908 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
911 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
912 EVT MemVT = LD->getMemoryVT();
913 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
914 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
916 : LD->getExtensionType();
918 return DAG.getExtLoad(ExtType, dl, PVT,
919 LD->getChain(), LD->getBasePtr(),
920 MemVT, LD->getMemOperand());
923 unsigned Opc = Op.getOpcode();
926 case ISD::AssertSext:
927 return DAG.getNode(ISD::AssertSext, dl, PVT,
928 SExtPromoteOperand(Op.getOperand(0), PVT),
930 case ISD::AssertZext:
931 return DAG.getNode(ISD::AssertZext, dl, PVT,
932 ZExtPromoteOperand(Op.getOperand(0), PVT),
934 case ISD::Constant: {
936 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
937 return DAG.getNode(ExtOpc, dl, PVT, Op);
941 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
943 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
946 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
947 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
949 EVT OldVT = Op.getValueType();
951 bool Replace = false;
952 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
953 if (!NewOp.getNode())
955 AddToWorklist(NewOp.getNode());
958 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
959 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
960 DAG.getValueType(OldVT));
963 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
964 EVT OldVT = Op.getValueType();
966 bool Replace = false;
967 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
968 if (!NewOp.getNode())
970 AddToWorklist(NewOp.getNode());
973 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
974 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
977 /// Promote the specified integer binary operation if the target indicates it is
978 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
979 /// i32 since i16 instructions are longer.
980 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
981 if (!LegalOperations)
984 EVT VT = Op.getValueType();
985 if (VT.isVector() || !VT.isInteger())
988 // If operation type is 'undesirable', e.g. i16 on x86, consider
990 unsigned Opc = Op.getOpcode();
991 if (TLI.isTypeDesirableForOp(Opc, VT))
995 // Consult target whether it is a good idea to promote this operation and
996 // what's the right type to promote it to.
997 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
998 assert(PVT != VT && "Don't know what type to promote to!");
1000 bool Replace0 = false;
1001 SDValue N0 = Op.getOperand(0);
1002 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1006 bool Replace1 = false;
1007 SDValue N1 = Op.getOperand(1);
1012 NN1 = PromoteOperand(N1, PVT, Replace1);
1017 AddToWorklist(NN0.getNode());
1019 AddToWorklist(NN1.getNode());
1022 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1024 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1026 DEBUG(dbgs() << "\nPromoting ";
1027 Op.getNode()->dump(&DAG));
1029 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1030 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1035 /// Promote the specified integer shift operation if the target indicates it is
1036 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1037 /// i32 since i16 instructions are longer.
1038 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1039 if (!LegalOperations)
1042 EVT VT = Op.getValueType();
1043 if (VT.isVector() || !VT.isInteger())
1046 // If operation type is 'undesirable', e.g. i16 on x86, consider
1048 unsigned Opc = Op.getOpcode();
1049 if (TLI.isTypeDesirableForOp(Opc, VT))
1053 // Consult target whether it is a good idea to promote this operation and
1054 // what's the right type to promote it to.
1055 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056 assert(PVT != VT && "Don't know what type to promote to!");
1058 bool Replace = false;
1059 SDValue N0 = Op.getOperand(0);
1060 if (Opc == ISD::SRA)
1061 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1062 else if (Opc == ISD::SRL)
1063 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1065 N0 = PromoteOperand(N0, PVT, Replace);
1069 AddToWorklist(N0.getNode());
1071 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1073 DEBUG(dbgs() << "\nPromoting ";
1074 Op.getNode()->dump(&DAG));
1076 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1077 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1082 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1083 if (!LegalOperations)
1086 EVT VT = Op.getValueType();
1087 if (VT.isVector() || !VT.isInteger())
1090 // If operation type is 'undesirable', e.g. i16 on x86, consider
1092 unsigned Opc = Op.getOpcode();
1093 if (TLI.isTypeDesirableForOp(Opc, VT))
1097 // Consult target whether it is a good idea to promote this operation and
1098 // what's the right type to promote it to.
1099 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100 assert(PVT != VT && "Don't know what type to promote to!");
1101 // fold (aext (aext x)) -> (aext x)
1102 // fold (aext (zext x)) -> (zext x)
1103 // fold (aext (sext x)) -> (sext x)
1104 DEBUG(dbgs() << "\nPromoting ";
1105 Op.getNode()->dump(&DAG));
1106 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1111 bool DAGCombiner::PromoteLoad(SDValue Op) {
1112 if (!LegalOperations)
1115 EVT VT = Op.getValueType();
1116 if (VT.isVector() || !VT.isInteger())
1119 // If operation type is 'undesirable', e.g. i16 on x86, consider
1121 unsigned Opc = Op.getOpcode();
1122 if (TLI.isTypeDesirableForOp(Opc, VT))
1126 // Consult target whether it is a good idea to promote this operation and
1127 // what's the right type to promote it to.
1128 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1129 assert(PVT != VT && "Don't know what type to promote to!");
1132 SDNode *N = Op.getNode();
1133 LoadSDNode *LD = cast<LoadSDNode>(N);
1134 EVT MemVT = LD->getMemoryVT();
1135 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1136 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1138 : LD->getExtensionType();
1139 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1140 LD->getChain(), LD->getBasePtr(),
1141 MemVT, LD->getMemOperand());
1142 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1144 DEBUG(dbgs() << "\nPromoting ";
1147 Result.getNode()->dump(&DAG);
1149 WorklistRemover DeadNodes(*this);
1150 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1151 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1152 deleteAndRecombine(N);
1153 AddToWorklist(Result.getNode());
1159 /// \brief Recursively delete a node which has no uses and any operands for
1160 /// which it is the only use.
1162 /// Note that this both deletes the nodes and removes them from the worklist.
1163 /// It also adds any nodes who have had a user deleted to the worklist as they
1164 /// may now have only one use and subject to other combines.
1165 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1166 if (!N->use_empty())
1169 SmallSetVector<SDNode *, 16> Nodes;
1172 N = Nodes.pop_back_val();
1176 if (N->use_empty()) {
1177 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1178 Nodes.insert(N->getOperand(i).getNode());
1180 removeFromWorklist(N);
1185 } while (!Nodes.empty());
1189 //===----------------------------------------------------------------------===//
1190 // Main DAG Combiner implementation
1191 //===----------------------------------------------------------------------===//
1193 void DAGCombiner::Run(CombineLevel AtLevel) {
1194 // set the instance variables, so that the various visit routines may use it.
1196 LegalOperations = Level >= AfterLegalizeVectorOps;
1197 LegalTypes = Level >= AfterLegalizeTypes;
1199 // Add all the dag nodes to the worklist.
1200 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1201 E = DAG.allnodes_end(); I != E; ++I)
1204 // Create a dummy node (which is not added to allnodes), that adds a reference
1205 // to the root node, preventing it from being deleted, and tracking any
1206 // changes of the root.
1207 HandleSDNode Dummy(DAG.getRoot());
1209 // while the worklist isn't empty, find a node and
1210 // try and combine it.
1211 while (!WorklistMap.empty()) {
1213 // The Worklist holds the SDNodes in order, but it may contain null entries.
1215 N = Worklist.pop_back_val();
1218 bool GoodWorklistEntry = WorklistMap.erase(N);
1219 (void)GoodWorklistEntry;
1220 assert(GoodWorklistEntry &&
1221 "Found a worklist entry without a corresponding map entry!");
1223 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1224 // N is deleted from the DAG, since they too may now be dead or may have a
1225 // reduced number of uses, allowing other xforms.
1226 if (recursivelyDeleteUnusedNodes(N))
1229 WorklistRemover DeadNodes(*this);
1231 // If this combine is running after legalizing the DAG, re-legalize any
1232 // nodes pulled off the worklist.
1233 if (Level == AfterLegalizeDAG) {
1234 SmallSetVector<SDNode *, 16> UpdatedNodes;
1235 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1237 for (SDNode *LN : UpdatedNodes) {
1239 AddUsersToWorklist(LN);
1245 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1247 // Add any operands of the new node which have not yet been combined to the
1248 // worklist as well. Because the worklist uniques things already, this
1249 // won't repeatedly process the same operand.
1250 CombinedNodes.insert(N);
1251 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1252 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1253 AddToWorklist(N->getOperand(i).getNode());
1255 SDValue RV = combine(N);
1262 // If we get back the same node we passed in, rather than a new node or
1263 // zero, we know that the node must have defined multiple values and
1264 // CombineTo was used. Since CombineTo takes care of the worklist
1265 // mechanics for us, we have no work to do in this case.
1266 if (RV.getNode() == N)
1269 assert(N->getOpcode() != ISD::DELETED_NODE &&
1270 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1271 "Node was deleted but visit returned new node!");
1273 DEBUG(dbgs() << " ... into: ";
1274 RV.getNode()->dump(&DAG));
1276 // Transfer debug value.
1277 DAG.TransferDbgValues(SDValue(N, 0), RV);
1278 if (N->getNumValues() == RV.getNode()->getNumValues())
1279 DAG.ReplaceAllUsesWith(N, RV.getNode());
1281 assert(N->getValueType(0) == RV.getValueType() &&
1282 N->getNumValues() == 1 && "Type mismatch");
1284 DAG.ReplaceAllUsesWith(N, &OpV);
1287 // Push the new node and any users onto the worklist
1288 AddToWorklist(RV.getNode());
1289 AddUsersToWorklist(RV.getNode());
1291 // Finally, if the node is now dead, remove it from the graph. The node
1292 // may not be dead if the replacement process recursively simplified to
1293 // something else needing this node. This will also take care of adding any
1294 // operands which have lost a user to the worklist.
1295 recursivelyDeleteUnusedNodes(N);
1298 // If the root changed (e.g. it was a dead load, update the root).
1299 DAG.setRoot(Dummy.getValue());
1300 DAG.RemoveDeadNodes();
1303 SDValue DAGCombiner::visit(SDNode *N) {
1304 switch (N->getOpcode()) {
1306 case ISD::TokenFactor: return visitTokenFactor(N);
1307 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1308 case ISD::ADD: return visitADD(N);
1309 case ISD::SUB: return visitSUB(N);
1310 case ISD::ADDC: return visitADDC(N);
1311 case ISD::SUBC: return visitSUBC(N);
1312 case ISD::ADDE: return visitADDE(N);
1313 case ISD::SUBE: return visitSUBE(N);
1314 case ISD::MUL: return visitMUL(N);
1315 case ISD::SDIV: return visitSDIV(N);
1316 case ISD::UDIV: return visitUDIV(N);
1317 case ISD::SREM: return visitSREM(N);
1318 case ISD::UREM: return visitUREM(N);
1319 case ISD::MULHU: return visitMULHU(N);
1320 case ISD::MULHS: return visitMULHS(N);
1321 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1322 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1323 case ISD::SMULO: return visitSMULO(N);
1324 case ISD::UMULO: return visitUMULO(N);
1325 case ISD::SDIVREM: return visitSDIVREM(N);
1326 case ISD::UDIVREM: return visitUDIVREM(N);
1327 case ISD::AND: return visitAND(N);
1328 case ISD::OR: return visitOR(N);
1329 case ISD::XOR: return visitXOR(N);
1330 case ISD::SHL: return visitSHL(N);
1331 case ISD::SRA: return visitSRA(N);
1332 case ISD::SRL: return visitSRL(N);
1334 case ISD::ROTL: return visitRotate(N);
1335 case ISD::CTLZ: return visitCTLZ(N);
1336 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1337 case ISD::CTTZ: return visitCTTZ(N);
1338 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1339 case ISD::CTPOP: return visitCTPOP(N);
1340 case ISD::SELECT: return visitSELECT(N);
1341 case ISD::VSELECT: return visitVSELECT(N);
1342 case ISD::SELECT_CC: return visitSELECT_CC(N);
1343 case ISD::SETCC: return visitSETCC(N);
1344 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1345 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1346 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1347 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1348 case ISD::TRUNCATE: return visitTRUNCATE(N);
1349 case ISD::BITCAST: return visitBITCAST(N);
1350 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1351 case ISD::FADD: return visitFADD(N);
1352 case ISD::FSUB: return visitFSUB(N);
1353 case ISD::FMUL: return visitFMUL(N);
1354 case ISD::FMA: return visitFMA(N);
1355 case ISD::FDIV: return visitFDIV(N);
1356 case ISD::FREM: return visitFREM(N);
1357 case ISD::FSQRT: return visitFSQRT(N);
1358 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1359 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1360 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1361 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1362 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1363 case ISD::FP_ROUND: return visitFP_ROUND(N);
1364 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1365 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1366 case ISD::FNEG: return visitFNEG(N);
1367 case ISD::FABS: return visitFABS(N);
1368 case ISD::FFLOOR: return visitFFLOOR(N);
1369 case ISD::FMINNUM: return visitFMINNUM(N);
1370 case ISD::FMAXNUM: return visitFMAXNUM(N);
1371 case ISD::FCEIL: return visitFCEIL(N);
1372 case ISD::FTRUNC: return visitFTRUNC(N);
1373 case ISD::BRCOND: return visitBRCOND(N);
1374 case ISD::BR_CC: return visitBR_CC(N);
1375 case ISD::LOAD: return visitLOAD(N);
1376 case ISD::STORE: return visitSTORE(N);
1377 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1378 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1379 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1380 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1381 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1382 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1383 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1384 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1385 case ISD::MLOAD: return visitMLOAD(N);
1386 case ISD::MSTORE: return visitMSTORE(N);
1387 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1392 SDValue DAGCombiner::combine(SDNode *N) {
1393 SDValue RV = visit(N);
1395 // If nothing happened, try a target-specific DAG combine.
1396 if (!RV.getNode()) {
1397 assert(N->getOpcode() != ISD::DELETED_NODE &&
1398 "Node was deleted but visit returned NULL!");
1400 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1401 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1403 // Expose the DAG combiner to the target combiner impls.
1404 TargetLowering::DAGCombinerInfo
1405 DagCombineInfo(DAG, Level, false, this);
1407 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1411 // If nothing happened still, try promoting the operation.
1412 if (!RV.getNode()) {
1413 switch (N->getOpcode()) {
1421 RV = PromoteIntBinOp(SDValue(N, 0));
1426 RV = PromoteIntShiftOp(SDValue(N, 0));
1428 case ISD::SIGN_EXTEND:
1429 case ISD::ZERO_EXTEND:
1430 case ISD::ANY_EXTEND:
1431 RV = PromoteExtend(SDValue(N, 0));
1434 if (PromoteLoad(SDValue(N, 0)))
1440 // If N is a commutative binary node, try commuting it to enable more
1442 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1443 N->getNumValues() == 1) {
1444 SDValue N0 = N->getOperand(0);
1445 SDValue N1 = N->getOperand(1);
1447 // Constant operands are canonicalized to RHS.
1448 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1449 SDValue Ops[] = {N1, N0};
1451 if (const BinaryWithFlagsSDNode *BinNode =
1452 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1453 CSENode = DAG.getNodeIfExists(
1454 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1455 BinNode->hasNoSignedWrap(), BinNode->isExact());
1457 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1460 return SDValue(CSENode, 0);
1467 /// Given a node, return its input chain if it has one, otherwise return a null
1469 static SDValue getInputChainForNode(SDNode *N) {
1470 if (unsigned NumOps = N->getNumOperands()) {
1471 if (N->getOperand(0).getValueType() == MVT::Other)
1472 return N->getOperand(0);
1473 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1474 return N->getOperand(NumOps-1);
1475 for (unsigned i = 1; i < NumOps-1; ++i)
1476 if (N->getOperand(i).getValueType() == MVT::Other)
1477 return N->getOperand(i);
1482 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1483 // If N has two operands, where one has an input chain equal to the other,
1484 // the 'other' chain is redundant.
1485 if (N->getNumOperands() == 2) {
1486 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1487 return N->getOperand(0);
1488 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1489 return N->getOperand(1);
1492 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1493 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1494 SmallPtrSet<SDNode*, 16> SeenOps;
1495 bool Changed = false; // If we should replace this token factor.
1497 // Start out with this token factor.
1500 // Iterate through token factors. The TFs grows when new token factors are
1502 for (unsigned i = 0; i < TFs.size(); ++i) {
1503 SDNode *TF = TFs[i];
1505 // Check each of the operands.
1506 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1507 SDValue Op = TF->getOperand(i);
1509 switch (Op.getOpcode()) {
1510 case ISD::EntryToken:
1511 // Entry tokens don't need to be added to the list. They are
1516 case ISD::TokenFactor:
1517 if (Op.hasOneUse() &&
1518 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1519 // Queue up for processing.
1520 TFs.push_back(Op.getNode());
1521 // Clean up in case the token factor is removed.
1522 AddToWorklist(Op.getNode());
1529 // Only add if it isn't already in the list.
1530 if (SeenOps.insert(Op.getNode()).second)
1541 // If we've changed things around then replace token factor.
1544 // The entry token is the only possible outcome.
1545 Result = DAG.getEntryNode();
1547 // New and improved token factor.
1548 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1551 // Add users to worklist if AA is enabled, since it may introduce
1552 // a lot of new chained token factors while removing memory deps.
1553 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1554 : DAG.getSubtarget().useAA();
1555 return CombineTo(N, Result, UseAA /*add to worklist*/);
1561 /// MERGE_VALUES can always be eliminated.
1562 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1563 WorklistRemover DeadNodes(*this);
1564 // Replacing results may cause a different MERGE_VALUES to suddenly
1565 // be CSE'd with N, and carry its uses with it. Iterate until no
1566 // uses remain, to ensure that the node can be safely deleted.
1567 // First add the users of this node to the work list so that they
1568 // can be tried again once they have new operands.
1569 AddUsersToWorklist(N);
1571 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1572 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1573 } while (!N->use_empty());
1574 deleteAndRecombine(N);
1575 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1578 SDValue DAGCombiner::visitADD(SDNode *N) {
1579 SDValue N0 = N->getOperand(0);
1580 SDValue N1 = N->getOperand(1);
1581 EVT VT = N0.getValueType();
1584 if (VT.isVector()) {
1585 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1588 // fold (add x, 0) -> x, vector edition
1589 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1591 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1595 // fold (add x, undef) -> undef
1596 if (N0.getOpcode() == ISD::UNDEF)
1598 if (N1.getOpcode() == ISD::UNDEF)
1600 // fold (add c1, c2) -> c1+c2
1601 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1602 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1604 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1605 // canonicalize constant to RHS
1606 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1607 !isConstantIntBuildVectorOrConstantInt(N1))
1608 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1609 // fold (add x, 0) -> x
1610 if (N1C && N1C->isNullValue())
1612 // fold (add Sym, c) -> Sym+c
1613 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1614 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1615 GA->getOpcode() == ISD::GlobalAddress)
1616 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1618 (uint64_t)N1C->getSExtValue());
1619 // fold ((c1-A)+c2) -> (c1+c2)-A
1620 if (N1C && N0.getOpcode() == ISD::SUB)
1621 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1622 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1623 DAG.getConstant(N1C->getAPIntValue()+
1624 N0C->getAPIntValue(), VT),
1627 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1629 // fold ((0-A) + B) -> B-A
1630 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1631 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1632 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1633 // fold (A + (0-B)) -> A-B
1634 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1635 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1636 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1637 // fold (A+(B-A)) -> B
1638 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1639 return N1.getOperand(0);
1640 // fold ((B-A)+A) -> B
1641 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1642 return N0.getOperand(0);
1643 // fold (A+(B-(A+C))) to (B-C)
1644 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1645 N0 == N1.getOperand(1).getOperand(0))
1646 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1647 N1.getOperand(1).getOperand(1));
1648 // fold (A+(B-(C+A))) to (B-C)
1649 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1650 N0 == N1.getOperand(1).getOperand(1))
1651 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1652 N1.getOperand(1).getOperand(0));
1653 // fold (A+((B-A)+or-C)) to (B+or-C)
1654 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1655 N1.getOperand(0).getOpcode() == ISD::SUB &&
1656 N0 == N1.getOperand(0).getOperand(1))
1657 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1658 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1660 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1661 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1662 SDValue N00 = N0.getOperand(0);
1663 SDValue N01 = N0.getOperand(1);
1664 SDValue N10 = N1.getOperand(0);
1665 SDValue N11 = N1.getOperand(1);
1667 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1668 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1669 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1670 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1673 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1674 return SDValue(N, 0);
1676 // fold (a+b) -> (a|b) iff a and b share no bits.
1677 if (VT.isInteger() && !VT.isVector()) {
1678 APInt LHSZero, LHSOne;
1679 APInt RHSZero, RHSOne;
1680 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1682 if (LHSZero.getBoolValue()) {
1683 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1685 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1686 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1687 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1688 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1689 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1694 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1695 if (N1.getOpcode() == ISD::SHL &&
1696 N1.getOperand(0).getOpcode() == ISD::SUB)
1697 if (ConstantSDNode *C =
1698 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1699 if (C->getAPIntValue() == 0)
1700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1701 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1702 N1.getOperand(0).getOperand(1),
1704 if (N0.getOpcode() == ISD::SHL &&
1705 N0.getOperand(0).getOpcode() == ISD::SUB)
1706 if (ConstantSDNode *C =
1707 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1708 if (C->getAPIntValue() == 0)
1709 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1710 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1711 N0.getOperand(0).getOperand(1),
1714 if (N1.getOpcode() == ISD::AND) {
1715 SDValue AndOp0 = N1.getOperand(0);
1716 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1717 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1718 unsigned DestBits = VT.getScalarType().getSizeInBits();
1720 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1721 // and similar xforms where the inner op is either ~0 or 0.
1722 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1724 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1728 // add (sext i1), X -> sub X, (zext i1)
1729 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1730 N0.getOperand(0).getValueType() == MVT::i1 &&
1731 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1733 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1734 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1737 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1738 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1739 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1740 if (TN->getVT() == MVT::i1) {
1742 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1743 DAG.getConstant(1, VT));
1744 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1751 SDValue DAGCombiner::visitADDC(SDNode *N) {
1752 SDValue N0 = N->getOperand(0);
1753 SDValue N1 = N->getOperand(1);
1754 EVT VT = N0.getValueType();
1756 // If the flag result is dead, turn this into an ADD.
1757 if (!N->hasAnyUseOfValue(1))
1758 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1759 DAG.getNode(ISD::CARRY_FALSE,
1760 SDLoc(N), MVT::Glue));
1762 // canonicalize constant to RHS.
1763 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1766 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1768 // fold (addc x, 0) -> x + no carry out
1769 if (N1C && N1C->isNullValue())
1770 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1771 SDLoc(N), MVT::Glue));
1773 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1774 APInt LHSZero, LHSOne;
1775 APInt RHSZero, RHSOne;
1776 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1778 if (LHSZero.getBoolValue()) {
1779 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1781 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1782 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1783 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1784 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1785 DAG.getNode(ISD::CARRY_FALSE,
1786 SDLoc(N), MVT::Glue));
1792 SDValue DAGCombiner::visitADDE(SDNode *N) {
1793 SDValue N0 = N->getOperand(0);
1794 SDValue N1 = N->getOperand(1);
1795 SDValue CarryIn = N->getOperand(2);
1797 // canonicalize constant to RHS
1798 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1799 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1801 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1804 // fold (adde x, y, false) -> (addc x, y)
1805 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1806 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1811 // Since it may not be valid to emit a fold to zero for vector initializers
1812 // check if we can before folding.
1813 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1815 bool LegalOperations, bool LegalTypes) {
1817 return DAG.getConstant(0, VT);
1818 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1819 return DAG.getConstant(0, VT);
1823 SDValue DAGCombiner::visitSUB(SDNode *N) {
1824 SDValue N0 = N->getOperand(0);
1825 SDValue N1 = N->getOperand(1);
1826 EVT VT = N0.getValueType();
1829 if (VT.isVector()) {
1830 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1833 // fold (sub x, 0) -> x, vector edition
1834 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1838 // fold (sub x, x) -> 0
1839 // FIXME: Refactor this and xor and other similar operations together.
1841 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1842 // fold (sub c1, c2) -> c1-c2
1843 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1844 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1846 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1847 // fold (sub x, c) -> (add x, -c)
1849 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1850 DAG.getConstant(-N1C->getAPIntValue(), VT));
1851 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1852 if (N0C && N0C->isAllOnesValue())
1853 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1854 // fold A-(A-B) -> B
1855 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1856 return N1.getOperand(1);
1857 // fold (A+B)-A -> B
1858 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1859 return N0.getOperand(1);
1860 // fold (A+B)-B -> A
1861 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1862 return N0.getOperand(0);
1863 // fold C2-(A+C1) -> (C2-C1)-A
1864 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1865 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1866 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1867 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1869 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1872 // fold ((A+(B+or-C))-B) -> A+or-C
1873 if (N0.getOpcode() == ISD::ADD &&
1874 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1875 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1876 N0.getOperand(1).getOperand(0) == N1)
1877 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1878 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1879 // fold ((A+(C+B))-B) -> A+C
1880 if (N0.getOpcode() == ISD::ADD &&
1881 N0.getOperand(1).getOpcode() == ISD::ADD &&
1882 N0.getOperand(1).getOperand(1) == N1)
1883 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1884 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1885 // fold ((A-(B-C))-C) -> A-B
1886 if (N0.getOpcode() == ISD::SUB &&
1887 N0.getOperand(1).getOpcode() == ISD::SUB &&
1888 N0.getOperand(1).getOperand(1) == N1)
1889 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1890 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1892 // If either operand of a sub is undef, the result is undef
1893 if (N0.getOpcode() == ISD::UNDEF)
1895 if (N1.getOpcode() == ISD::UNDEF)
1898 // If the relocation model supports it, consider symbol offsets.
1899 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1900 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1901 // fold (sub Sym, c) -> Sym-c
1902 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1903 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1905 (uint64_t)N1C->getSExtValue());
1906 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1907 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1908 if (GA->getGlobal() == GB->getGlobal())
1909 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1913 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1914 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1915 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1916 if (TN->getVT() == MVT::i1) {
1918 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1919 DAG.getConstant(1, VT));
1920 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1927 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1928 SDValue N0 = N->getOperand(0);
1929 SDValue N1 = N->getOperand(1);
1930 EVT VT = N0.getValueType();
1932 // If the flag result is dead, turn this into an SUB.
1933 if (!N->hasAnyUseOfValue(1))
1934 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1935 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1938 // fold (subc x, x) -> 0 + no borrow
1940 return CombineTo(N, DAG.getConstant(0, VT),
1941 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1944 // fold (subc x, 0) -> x + no borrow
1945 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1946 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1947 if (N1C && N1C->isNullValue())
1948 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1951 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1952 if (N0C && N0C->isAllOnesValue())
1953 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1954 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1960 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1961 SDValue N0 = N->getOperand(0);
1962 SDValue N1 = N->getOperand(1);
1963 SDValue CarryIn = N->getOperand(2);
1965 // fold (sube x, y, false) -> (subc x, y)
1966 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1967 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1972 SDValue DAGCombiner::visitMUL(SDNode *N) {
1973 SDValue N0 = N->getOperand(0);
1974 SDValue N1 = N->getOperand(1);
1975 EVT VT = N0.getValueType();
1977 // fold (mul x, undef) -> 0
1978 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1979 return DAG.getConstant(0, VT);
1981 bool N0IsConst = false;
1982 bool N1IsConst = false;
1983 APInt ConstValue0, ConstValue1;
1985 if (VT.isVector()) {
1986 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1989 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1990 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1992 N0IsConst = isa<ConstantSDNode>(N0);
1994 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
1995 N1IsConst = isa<ConstantSDNode>(N1);
1997 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2000 // fold (mul c1, c2) -> c1*c2
2001 if (N0IsConst && N1IsConst)
2002 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
2004 // canonicalize constant to RHS (vector doesn't have to splat)
2005 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2006 !isConstantIntBuildVectorOrConstantInt(N1))
2007 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2008 // fold (mul x, 0) -> 0
2009 if (N1IsConst && ConstValue1 == 0)
2011 // We require a splat of the entire scalar bit width for non-contiguous
2014 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2015 // fold (mul x, 1) -> x
2016 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2018 // fold (mul x, -1) -> 0-x
2019 if (N1IsConst && ConstValue1.isAllOnesValue())
2020 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2021 DAG.getConstant(0, VT), N0);
2022 // fold (mul x, (1 << c)) -> x << c
2023 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2024 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2025 DAG.getConstant(ConstValue1.logBase2(),
2026 getShiftAmountTy(N0.getValueType())));
2027 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2028 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2029 unsigned Log2Val = (-ConstValue1).logBase2();
2030 // FIXME: If the input is something that is easily negated (e.g. a
2031 // single-use add), we should put the negate there.
2032 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2033 DAG.getConstant(0, VT),
2034 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2035 DAG.getConstant(Log2Val,
2036 getShiftAmountTy(N0.getValueType()))));
2040 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2041 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2042 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2043 isa<ConstantSDNode>(N0.getOperand(1)))) {
2044 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2045 N1, N0.getOperand(1));
2046 AddToWorklist(C3.getNode());
2047 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2048 N0.getOperand(0), C3);
2051 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2054 SDValue Sh(nullptr,0), Y(nullptr,0);
2055 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2056 if (N0.getOpcode() == ISD::SHL &&
2057 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2058 isa<ConstantSDNode>(N0.getOperand(1))) &&
2059 N0.getNode()->hasOneUse()) {
2061 } else if (N1.getOpcode() == ISD::SHL &&
2062 isa<ConstantSDNode>(N1.getOperand(1)) &&
2063 N1.getNode()->hasOneUse()) {
2068 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2069 Sh.getOperand(0), Y);
2070 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2071 Mul, Sh.getOperand(1));
2075 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2076 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2077 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2078 isa<ConstantSDNode>(N0.getOperand(1))))
2079 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2080 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2081 N0.getOperand(0), N1),
2082 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2083 N0.getOperand(1), N1));
2086 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2092 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2093 SDValue N0 = N->getOperand(0);
2094 SDValue N1 = N->getOperand(1);
2095 EVT VT = N->getValueType(0);
2099 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2102 // fold (sdiv c1, c2) -> c1/c2
2103 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2104 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2105 if (N0C && N1C && !N1C->isNullValue())
2106 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2107 // fold (sdiv X, 1) -> X
2108 if (N1C && N1C->getAPIntValue() == 1LL)
2110 // fold (sdiv X, -1) -> 0-X
2111 if (N1C && N1C->isAllOnesValue())
2112 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2113 DAG.getConstant(0, VT), N0);
2114 // If we know the sign bits of both operands are zero, strength reduce to a
2115 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2116 if (!VT.isVector()) {
2117 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2118 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2122 // fold (sdiv X, pow2) -> simple ops after legalize
2123 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2124 (-N1C->getAPIntValue()).isPowerOf2())) {
2125 // If dividing by powers of two is cheap, then don't perform the following
2127 if (TLI.isPow2SDivCheap())
2130 // Target-specific implementation of sdiv x, pow2.
2131 SDValue Res = BuildSDIVPow2(N);
2135 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2137 // Splat the sign bit into the register
2139 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2140 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2141 getShiftAmountTy(N0.getValueType())));
2142 AddToWorklist(SGN.getNode());
2144 // Add (N0 < 0) ? abs2 - 1 : 0;
2146 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2147 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2148 getShiftAmountTy(SGN.getValueType())));
2149 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2150 AddToWorklist(SRL.getNode());
2151 AddToWorklist(ADD.getNode()); // Divide by pow2
2152 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2153 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2155 // If we're dividing by a positive value, we're done. Otherwise, we must
2156 // negate the result.
2157 if (N1C->getAPIntValue().isNonNegative())
2160 AddToWorklist(SRA.getNode());
2161 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2164 // If integer divide is expensive and we satisfy the requirements, emit an
2165 // alternate sequence.
2166 if (N1C && !TLI.isIntDivCheap()) {
2167 SDValue Op = BuildSDIV(N);
2168 if (Op.getNode()) return Op;
2172 if (N0.getOpcode() == ISD::UNDEF)
2173 return DAG.getConstant(0, VT);
2174 // X / undef -> undef
2175 if (N1.getOpcode() == ISD::UNDEF)
2181 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2182 SDValue N0 = N->getOperand(0);
2183 SDValue N1 = N->getOperand(1);
2184 EVT VT = N->getValueType(0);
2188 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2191 // fold (udiv c1, c2) -> c1/c2
2192 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2193 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2194 if (N0C && N1C && !N1C->isNullValue())
2195 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2196 // fold (udiv x, (1 << c)) -> x >>u c
2197 if (N1C && N1C->getAPIntValue().isPowerOf2())
2198 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2199 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2200 getShiftAmountTy(N0.getValueType())));
2201 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2202 if (N1.getOpcode() == ISD::SHL) {
2203 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2204 if (SHC->getAPIntValue().isPowerOf2()) {
2205 EVT ADDVT = N1.getOperand(1).getValueType();
2206 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2208 DAG.getConstant(SHC->getAPIntValue()
2211 AddToWorklist(Add.getNode());
2212 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2216 // fold (udiv x, c) -> alternate
2217 if (N1C && !TLI.isIntDivCheap()) {
2218 SDValue Op = BuildUDIV(N);
2219 if (Op.getNode()) return Op;
2223 if (N0.getOpcode() == ISD::UNDEF)
2224 return DAG.getConstant(0, VT);
2225 // X / undef -> undef
2226 if (N1.getOpcode() == ISD::UNDEF)
2232 SDValue DAGCombiner::visitSREM(SDNode *N) {
2233 SDValue N0 = N->getOperand(0);
2234 SDValue N1 = N->getOperand(1);
2235 EVT VT = N->getValueType(0);
2237 // fold (srem c1, c2) -> c1%c2
2238 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2239 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2240 if (N0C && N1C && !N1C->isNullValue())
2241 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2242 // If we know the sign bits of both operands are zero, strength reduce to a
2243 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2244 if (!VT.isVector()) {
2245 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2246 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2249 // If X/C can be simplified by the division-by-constant logic, lower
2250 // X%C to the equivalent of X-X/C*C.
2251 if (N1C && !N1C->isNullValue()) {
2252 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2253 AddToWorklist(Div.getNode());
2254 SDValue OptimizedDiv = combine(Div.getNode());
2255 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2256 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2258 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2259 AddToWorklist(Mul.getNode());
2265 if (N0.getOpcode() == ISD::UNDEF)
2266 return DAG.getConstant(0, VT);
2267 // X % undef -> undef
2268 if (N1.getOpcode() == ISD::UNDEF)
2274 SDValue DAGCombiner::visitUREM(SDNode *N) {
2275 SDValue N0 = N->getOperand(0);
2276 SDValue N1 = N->getOperand(1);
2277 EVT VT = N->getValueType(0);
2279 // fold (urem c1, c2) -> c1%c2
2280 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2281 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2282 if (N0C && N1C && !N1C->isNullValue())
2283 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2284 // fold (urem x, pow2) -> (and x, pow2-1)
2285 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2286 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2287 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2288 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2289 if (N1.getOpcode() == ISD::SHL) {
2290 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2291 if (SHC->getAPIntValue().isPowerOf2()) {
2293 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2294 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2296 AddToWorklist(Add.getNode());
2297 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2302 // If X/C can be simplified by the division-by-constant logic, lower
2303 // X%C to the equivalent of X-X/C*C.
2304 if (N1C && !N1C->isNullValue()) {
2305 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2306 AddToWorklist(Div.getNode());
2307 SDValue OptimizedDiv = combine(Div.getNode());
2308 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2309 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2311 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2312 AddToWorklist(Mul.getNode());
2318 if (N0.getOpcode() == ISD::UNDEF)
2319 return DAG.getConstant(0, VT);
2320 // X % undef -> undef
2321 if (N1.getOpcode() == ISD::UNDEF)
2327 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2328 SDValue N0 = N->getOperand(0);
2329 SDValue N1 = N->getOperand(1);
2330 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2331 EVT VT = N->getValueType(0);
2334 // fold (mulhs x, 0) -> 0
2335 if (N1C && N1C->isNullValue())
2337 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2338 if (N1C && N1C->getAPIntValue() == 1)
2339 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2340 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2341 getShiftAmountTy(N0.getValueType())));
2342 // fold (mulhs x, undef) -> 0
2343 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2344 return DAG.getConstant(0, VT);
2346 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2348 if (VT.isSimple() && !VT.isVector()) {
2349 MVT Simple = VT.getSimpleVT();
2350 unsigned SimpleSize = Simple.getSizeInBits();
2351 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2352 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2353 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2354 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2355 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2356 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2357 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2358 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2365 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2366 SDValue N0 = N->getOperand(0);
2367 SDValue N1 = N->getOperand(1);
2368 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2369 EVT VT = N->getValueType(0);
2372 // fold (mulhu x, 0) -> 0
2373 if (N1C && N1C->isNullValue())
2375 // fold (mulhu x, 1) -> 0
2376 if (N1C && N1C->getAPIntValue() == 1)
2377 return DAG.getConstant(0, N0.getValueType());
2378 // fold (mulhu x, undef) -> 0
2379 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2380 return DAG.getConstant(0, VT);
2382 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2384 if (VT.isSimple() && !VT.isVector()) {
2385 MVT Simple = VT.getSimpleVT();
2386 unsigned SimpleSize = Simple.getSizeInBits();
2387 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2388 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2389 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2390 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2391 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2392 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2393 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2394 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2401 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2402 /// give the opcodes for the two computations that are being performed. Return
2403 /// true if a simplification was made.
2404 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2406 // If the high half is not needed, just compute the low half.
2407 bool HiExists = N->hasAnyUseOfValue(1);
2409 (!LegalOperations ||
2410 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2411 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2412 return CombineTo(N, Res, Res);
2415 // If the low half is not needed, just compute the high half.
2416 bool LoExists = N->hasAnyUseOfValue(0);
2418 (!LegalOperations ||
2419 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2420 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2421 return CombineTo(N, Res, Res);
2424 // If both halves are used, return as it is.
2425 if (LoExists && HiExists)
2428 // If the two computed results can be simplified separately, separate them.
2430 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2431 AddToWorklist(Lo.getNode());
2432 SDValue LoOpt = combine(Lo.getNode());
2433 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2434 (!LegalOperations ||
2435 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2436 return CombineTo(N, LoOpt, LoOpt);
2440 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2441 AddToWorklist(Hi.getNode());
2442 SDValue HiOpt = combine(Hi.getNode());
2443 if (HiOpt.getNode() && HiOpt != Hi &&
2444 (!LegalOperations ||
2445 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2446 return CombineTo(N, HiOpt, HiOpt);
2452 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2453 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2454 if (Res.getNode()) return Res;
2456 EVT VT = N->getValueType(0);
2459 // If the type is twice as wide is legal, transform the mulhu to a wider
2460 // multiply plus a shift.
2461 if (VT.isSimple() && !VT.isVector()) {
2462 MVT Simple = VT.getSimpleVT();
2463 unsigned SimpleSize = Simple.getSizeInBits();
2464 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2465 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2466 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2467 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2468 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2469 // Compute the high part as N1.
2470 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2471 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2472 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2473 // Compute the low part as N0.
2474 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2475 return CombineTo(N, Lo, Hi);
2482 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2483 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2484 if (Res.getNode()) return Res;
2486 EVT VT = N->getValueType(0);
2489 // If the type is twice as wide is legal, transform the mulhu to a wider
2490 // multiply plus a shift.
2491 if (VT.isSimple() && !VT.isVector()) {
2492 MVT Simple = VT.getSimpleVT();
2493 unsigned SimpleSize = Simple.getSizeInBits();
2494 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2495 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2496 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2497 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2498 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2499 // Compute the high part as N1.
2500 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2501 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2502 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2503 // Compute the low part as N0.
2504 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2505 return CombineTo(N, Lo, Hi);
2512 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2513 // (smulo x, 2) -> (saddo x, x)
2514 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2515 if (C2->getAPIntValue() == 2)
2516 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2517 N->getOperand(0), N->getOperand(0));
2522 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2523 // (umulo x, 2) -> (uaddo x, x)
2524 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2525 if (C2->getAPIntValue() == 2)
2526 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2527 N->getOperand(0), N->getOperand(0));
2532 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2533 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2534 if (Res.getNode()) return Res;
2539 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2540 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2541 if (Res.getNode()) return Res;
2546 /// If this is a binary operator with two operands of the same opcode, try to
2548 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2549 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2550 EVT VT = N0.getValueType();
2551 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2553 // Bail early if none of these transforms apply.
2554 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2556 // For each of OP in AND/OR/XOR:
2557 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2558 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2559 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2560 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2561 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2563 // do not sink logical op inside of a vector extend, since it may combine
2565 EVT Op0VT = N0.getOperand(0).getValueType();
2566 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2567 N0.getOpcode() == ISD::SIGN_EXTEND ||
2568 N0.getOpcode() == ISD::BSWAP ||
2569 // Avoid infinite looping with PromoteIntBinOp.
2570 (N0.getOpcode() == ISD::ANY_EXTEND &&
2571 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2572 (N0.getOpcode() == ISD::TRUNCATE &&
2573 (!TLI.isZExtFree(VT, Op0VT) ||
2574 !TLI.isTruncateFree(Op0VT, VT)) &&
2575 TLI.isTypeLegal(Op0VT))) &&
2577 Op0VT == N1.getOperand(0).getValueType() &&
2578 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2579 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2580 N0.getOperand(0).getValueType(),
2581 N0.getOperand(0), N1.getOperand(0));
2582 AddToWorklist(ORNode.getNode());
2583 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2586 // For each of OP in SHL/SRL/SRA/AND...
2587 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2588 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2589 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2590 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2591 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2592 N0.getOperand(1) == N1.getOperand(1)) {
2593 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2594 N0.getOperand(0).getValueType(),
2595 N0.getOperand(0), N1.getOperand(0));
2596 AddToWorklist(ORNode.getNode());
2597 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2598 ORNode, N0.getOperand(1));
2601 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2602 // Only perform this optimization after type legalization and before
2603 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2604 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2605 // we don't want to undo this promotion.
2606 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2608 if ((N0.getOpcode() == ISD::BITCAST ||
2609 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2610 Level == AfterLegalizeTypes) {
2611 SDValue In0 = N0.getOperand(0);
2612 SDValue In1 = N1.getOperand(0);
2613 EVT In0Ty = In0.getValueType();
2614 EVT In1Ty = In1.getValueType();
2616 // If both incoming values are integers, and the original types are the
2618 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2619 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2620 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2621 AddToWorklist(Op.getNode());
2626 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2627 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2628 // If both shuffles use the same mask, and both shuffle within a single
2629 // vector, then it is worthwhile to move the swizzle after the operation.
2630 // The type-legalizer generates this pattern when loading illegal
2631 // vector types from memory. In many cases this allows additional shuffle
2633 // There are other cases where moving the shuffle after the xor/and/or
2634 // is profitable even if shuffles don't perform a swizzle.
2635 // If both shuffles use the same mask, and both shuffles have the same first
2636 // or second operand, then it might still be profitable to move the shuffle
2637 // after the xor/and/or operation.
2638 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2639 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2640 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2642 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2643 "Inputs to shuffles are not the same type");
2645 // Check that both shuffles use the same mask. The masks are known to be of
2646 // the same length because the result vector type is the same.
2647 // Check also that shuffles have only one use to avoid introducing extra
2649 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2650 SVN0->getMask().equals(SVN1->getMask())) {
2651 SDValue ShOp = N0->getOperand(1);
2653 // Don't try to fold this node if it requires introducing a
2654 // build vector of all zeros that might be illegal at this stage.
2655 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2657 ShOp = DAG.getConstant(0, VT);
2662 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2663 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2664 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2665 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2666 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2667 N0->getOperand(0), N1->getOperand(0));
2668 AddToWorklist(NewNode.getNode());
2669 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2670 &SVN0->getMask()[0]);
2673 // Don't try to fold this node if it requires introducing a
2674 // build vector of all zeros that might be illegal at this stage.
2675 ShOp = N0->getOperand(0);
2676 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2678 ShOp = DAG.getConstant(0, VT);
2683 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2684 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2685 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2686 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2687 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2688 N0->getOperand(1), N1->getOperand(1));
2689 AddToWorklist(NewNode.getNode());
2690 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2691 &SVN0->getMask()[0]);
2699 /// This contains all DAGCombine rules which reduce two values combined by
2700 /// an And operation to a single value. This makes them reusable in the context
2701 /// of visitSELECT(). Rules involving constants are not included as
2702 /// visitSELECT() already handles those cases.
2703 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2704 SDNode *LocReference) {
2705 EVT VT = N1.getValueType();
2707 // fold (and x, undef) -> 0
2708 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2709 return DAG.getConstant(0, VT);
2710 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2711 SDValue LL, LR, RL, RR, CC0, CC1;
2712 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2713 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2714 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2716 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2717 LL.getValueType().isInteger()) {
2718 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2719 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2720 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2721 LR.getValueType(), LL, RL);
2722 AddToWorklist(ORNode.getNode());
2723 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2725 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2726 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2727 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2728 LR.getValueType(), LL, RL);
2729 AddToWorklist(ANDNode.getNode());
2730 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2732 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2733 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2734 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2735 LR.getValueType(), LL, RL);
2736 AddToWorklist(ORNode.getNode());
2737 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2740 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2741 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2742 Op0 == Op1 && LL.getValueType().isInteger() &&
2743 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2744 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2745 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2746 cast<ConstantSDNode>(RR)->isNullValue()))) {
2747 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2748 LL, DAG.getConstant(1, LL.getValueType()));
2749 AddToWorklist(ADDNode.getNode());
2750 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2751 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2753 // canonicalize equivalent to ll == rl
2754 if (LL == RR && LR == RL) {
2755 Op1 = ISD::getSetCCSwappedOperands(Op1);
2758 if (LL == RL && LR == RR) {
2759 bool isInteger = LL.getValueType().isInteger();
2760 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2761 if (Result != ISD::SETCC_INVALID &&
2762 (!LegalOperations ||
2763 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2764 TLI.isOperationLegal(ISD::SETCC,
2765 getSetCCResultType(N0.getSimpleValueType())))))
2766 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2771 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2772 VT.getSizeInBits() <= 64) {
2773 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2774 APInt ADDC = ADDI->getAPIntValue();
2775 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2776 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2777 // immediate for an add, but it is legal if its top c2 bits are set,
2778 // transform the ADD so the immediate doesn't need to be materialized
2780 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2781 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2782 SRLI->getZExtValue());
2783 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2785 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2787 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2788 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2789 CombineTo(N0.getNode(), NewAdd);
2790 // Return N so it doesn't get rechecked!
2791 return SDValue(LocReference, 0);
2802 SDValue DAGCombiner::visitAND(SDNode *N) {
2803 SDValue N0 = N->getOperand(0);
2804 SDValue N1 = N->getOperand(1);
2805 EVT VT = N1.getValueType();
2808 if (VT.isVector()) {
2809 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2812 // fold (and x, 0) -> 0, vector edition
2813 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2814 // do not return N0, because undef node may exist in N0
2815 return DAG.getConstant(
2816 APInt::getNullValue(
2817 N0.getValueType().getScalarType().getSizeInBits()),
2819 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2820 // do not return N1, because undef node may exist in N1
2821 return DAG.getConstant(
2822 APInt::getNullValue(
2823 N1.getValueType().getScalarType().getSizeInBits()),
2826 // fold (and x, -1) -> x, vector edition
2827 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2829 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2833 // fold (and c1, c2) -> c1&c2
2834 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2835 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2837 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2838 // canonicalize constant to RHS
2839 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2840 !isConstantIntBuildVectorOrConstantInt(N1))
2841 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2842 // fold (and x, -1) -> x
2843 if (N1C && N1C->isAllOnesValue())
2845 // if (and x, c) is known to be zero, return 0
2846 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2847 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2848 APInt::getAllOnesValue(BitWidth)))
2849 return DAG.getConstant(0, VT);
2851 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2853 // fold (and (or x, C), D) -> D if (C & D) == D
2854 if (N1C && N0.getOpcode() == ISD::OR)
2855 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2856 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2858 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2859 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2860 SDValue N0Op0 = N0.getOperand(0);
2861 APInt Mask = ~N1C->getAPIntValue();
2862 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2863 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2864 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2865 N0.getValueType(), N0Op0);
2867 // Replace uses of the AND with uses of the Zero extend node.
2870 // We actually want to replace all uses of the any_extend with the
2871 // zero_extend, to avoid duplicating things. This will later cause this
2872 // AND to be folded.
2873 CombineTo(N0.getNode(), Zext);
2874 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2877 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2878 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2879 // already be zero by virtue of the width of the base type of the load.
2881 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2883 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2884 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2885 N0.getOpcode() == ISD::LOAD) {
2886 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2887 N0 : N0.getOperand(0) );
2889 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2890 // This can be a pure constant or a vector splat, in which case we treat the
2891 // vector as a scalar and use the splat value.
2892 APInt Constant = APInt::getNullValue(1);
2893 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2894 Constant = C->getAPIntValue();
2895 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2896 APInt SplatValue, SplatUndef;
2897 unsigned SplatBitSize;
2899 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2900 SplatBitSize, HasAnyUndefs);
2902 // Undef bits can contribute to a possible optimisation if set, so
2904 SplatValue |= SplatUndef;
2906 // The splat value may be something like "0x00FFFFFF", which means 0 for
2907 // the first vector value and FF for the rest, repeating. We need a mask
2908 // that will apply equally to all members of the vector, so AND all the
2909 // lanes of the constant together.
2910 EVT VT = Vector->getValueType(0);
2911 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2913 // If the splat value has been compressed to a bitlength lower
2914 // than the size of the vector lane, we need to re-expand it to
2916 if (BitWidth > SplatBitSize)
2917 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2918 SplatBitSize < BitWidth;
2919 SplatBitSize = SplatBitSize * 2)
2920 SplatValue |= SplatValue.shl(SplatBitSize);
2922 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2923 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2924 if (SplatBitSize % BitWidth == 0) {
2925 Constant = APInt::getAllOnesValue(BitWidth);
2926 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2927 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2932 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2933 // actually legal and isn't going to get expanded, else this is a false
2935 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2936 Load->getValueType(0),
2937 Load->getMemoryVT());
2939 // Resize the constant to the same size as the original memory access before
2940 // extension. If it is still the AllOnesValue then this AND is completely
2943 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2946 switch (Load->getExtensionType()) {
2947 default: B = false; break;
2948 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2950 case ISD::NON_EXTLOAD: B = true; break;
2953 if (B && Constant.isAllOnesValue()) {
2954 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2955 // preserve semantics once we get rid of the AND.
2956 SDValue NewLoad(Load, 0);
2957 if (Load->getExtensionType() == ISD::EXTLOAD) {
2958 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2959 Load->getValueType(0), SDLoc(Load),
2960 Load->getChain(), Load->getBasePtr(),
2961 Load->getOffset(), Load->getMemoryVT(),
2962 Load->getMemOperand());
2963 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2964 if (Load->getNumValues() == 3) {
2965 // PRE/POST_INC loads have 3 values.
2966 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2967 NewLoad.getValue(2) };
2968 CombineTo(Load, To, 3, true);
2970 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2974 // Fold the AND away, taking care not to fold to the old load node if we
2976 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2978 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2982 // fold (and (load x), 255) -> (zextload x, i8)
2983 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2984 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2985 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2986 (N0.getOpcode() == ISD::ANY_EXTEND &&
2987 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2988 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2989 LoadSDNode *LN0 = HasAnyExt
2990 ? cast<LoadSDNode>(N0.getOperand(0))
2991 : cast<LoadSDNode>(N0);
2992 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2993 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2994 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2995 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2996 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2997 EVT LoadedVT = LN0->getMemoryVT();
2998 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3000 if (ExtVT == LoadedVT &&
3001 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3005 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3006 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3007 LN0->getMemOperand());
3009 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3010 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3013 // Do not change the width of a volatile load.
3014 // Do not generate loads of non-round integer types since these can
3015 // be expensive (and would be wrong if the type is not byte sized).
3016 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3017 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3019 EVT PtrType = LN0->getOperand(1).getValueType();
3021 unsigned Alignment = LN0->getAlignment();
3022 SDValue NewPtr = LN0->getBasePtr();
3024 // For big endian targets, we need to add an offset to the pointer
3025 // to load the correct bytes. For little endian systems, we merely
3026 // need to read fewer bytes from the same pointer.
3027 if (TLI.isBigEndian()) {
3028 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3029 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3030 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3031 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3032 NewPtr, DAG.getConstant(PtrOff, PtrType));
3033 Alignment = MinAlign(Alignment, PtrOff);
3036 AddToWorklist(NewPtr.getNode());
3039 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3040 LN0->getChain(), NewPtr,
3041 LN0->getPointerInfo(),
3042 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3043 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3045 CombineTo(LN0, Load, Load.getValue(1));
3046 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3052 if (SDValue Combined = visitANDLike(N0, N1, N))
3055 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3056 if (N0.getOpcode() == N1.getOpcode()) {
3057 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3058 if (Tmp.getNode()) return Tmp;
3061 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3062 // fold (and (sra)) -> (and (srl)) when possible.
3063 if (!VT.isVector() &&
3064 SimplifyDemandedBits(SDValue(N, 0)))
3065 return SDValue(N, 0);
3067 // fold (zext_inreg (extload x)) -> (zextload x)
3068 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3069 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3070 EVT MemVT = LN0->getMemoryVT();
3071 // If we zero all the possible extended bits, then we can turn this into
3072 // a zextload if we are running before legalize or the operation is legal.
3073 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3074 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3075 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3076 ((!LegalOperations && !LN0->isVolatile()) ||
3077 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3078 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3079 LN0->getChain(), LN0->getBasePtr(),
3080 MemVT, LN0->getMemOperand());
3082 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3083 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3086 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3087 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3089 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3090 EVT MemVT = LN0->getMemoryVT();
3091 // If we zero all the possible extended bits, then we can turn this into
3092 // a zextload if we are running before legalize or the operation is legal.
3093 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3094 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3095 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3096 ((!LegalOperations && !LN0->isVolatile()) ||
3097 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3098 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3099 LN0->getChain(), LN0->getBasePtr(),
3100 MemVT, LN0->getMemOperand());
3102 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3103 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3106 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3107 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3108 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3109 N0.getOperand(1), false);
3110 if (BSwap.getNode())
3117 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3118 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3119 bool DemandHighBits) {
3120 if (!LegalOperations)
3123 EVT VT = N->getValueType(0);
3124 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3126 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3129 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3130 bool LookPassAnd0 = false;
3131 bool LookPassAnd1 = false;
3132 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3134 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3136 if (N0.getOpcode() == ISD::AND) {
3137 if (!N0.getNode()->hasOneUse())
3139 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3140 if (!N01C || N01C->getZExtValue() != 0xFF00)
3142 N0 = N0.getOperand(0);
3143 LookPassAnd0 = true;
3146 if (N1.getOpcode() == ISD::AND) {
3147 if (!N1.getNode()->hasOneUse())
3149 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3150 if (!N11C || N11C->getZExtValue() != 0xFF)
3152 N1 = N1.getOperand(0);
3153 LookPassAnd1 = true;
3156 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3158 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3160 if (!N0.getNode()->hasOneUse() ||
3161 !N1.getNode()->hasOneUse())
3164 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3165 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3168 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3171 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3172 SDValue N00 = N0->getOperand(0);
3173 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3174 if (!N00.getNode()->hasOneUse())
3176 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3177 if (!N001C || N001C->getZExtValue() != 0xFF)
3179 N00 = N00.getOperand(0);
3180 LookPassAnd0 = true;
3183 SDValue N10 = N1->getOperand(0);
3184 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3185 if (!N10.getNode()->hasOneUse())
3187 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3188 if (!N101C || N101C->getZExtValue() != 0xFF00)
3190 N10 = N10.getOperand(0);
3191 LookPassAnd1 = true;
3197 // Make sure everything beyond the low halfword gets set to zero since the SRL
3198 // 16 will clear the top bits.
3199 unsigned OpSizeInBits = VT.getSizeInBits();
3200 if (DemandHighBits && OpSizeInBits > 16) {
3201 // If the left-shift isn't masked out then the only way this is a bswap is
3202 // if all bits beyond the low 8 are 0. In that case the entire pattern
3203 // reduces to a left shift anyway: leave it for other parts of the combiner.
3207 // However, if the right shift isn't masked out then it might be because
3208 // it's not needed. See if we can spot that too.
3209 if (!LookPassAnd1 &&
3210 !DAG.MaskedValueIsZero(
3211 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3215 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3216 if (OpSizeInBits > 16)
3217 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3218 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3222 /// Return true if the specified node is an element that makes up a 32-bit
3223 /// packed halfword byteswap.
3224 /// ((x & 0x000000ff) << 8) |
3225 /// ((x & 0x0000ff00) >> 8) |
3226 /// ((x & 0x00ff0000) << 8) |
3227 /// ((x & 0xff000000) >> 8)
3228 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3229 if (!N.getNode()->hasOneUse())
3232 unsigned Opc = N.getOpcode();
3233 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3236 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3241 switch (N1C->getZExtValue()) {
3244 case 0xFF: Num = 0; break;
3245 case 0xFF00: Num = 1; break;
3246 case 0xFF0000: Num = 2; break;
3247 case 0xFF000000: Num = 3; break;
3250 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3251 SDValue N0 = N.getOperand(0);
3252 if (Opc == ISD::AND) {
3253 if (Num == 0 || Num == 2) {
3255 // (x >> 8) & 0xff0000
3256 if (N0.getOpcode() != ISD::SRL)
3258 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3259 if (!C || C->getZExtValue() != 8)
3262 // (x << 8) & 0xff00
3263 // (x << 8) & 0xff000000
3264 if (N0.getOpcode() != ISD::SHL)
3266 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3267 if (!C || C->getZExtValue() != 8)
3270 } else if (Opc == ISD::SHL) {
3272 // (x & 0xff0000) << 8
3273 if (Num != 0 && Num != 2)
3275 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3276 if (!C || C->getZExtValue() != 8)
3278 } else { // Opc == ISD::SRL
3279 // (x & 0xff00) >> 8
3280 // (x & 0xff000000) >> 8
3281 if (Num != 1 && Num != 3)
3283 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3284 if (!C || C->getZExtValue() != 8)
3291 Parts[Num] = N0.getOperand(0).getNode();
3295 /// Match a 32-bit packed halfword bswap. That is
3296 /// ((x & 0x000000ff) << 8) |
3297 /// ((x & 0x0000ff00) >> 8) |
3298 /// ((x & 0x00ff0000) << 8) |
3299 /// ((x & 0xff000000) >> 8)
3300 /// => (rotl (bswap x), 16)
3301 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3302 if (!LegalOperations)
3305 EVT VT = N->getValueType(0);
3308 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3312 // (or (or (and), (and)), (or (and), (and)))
3313 // (or (or (or (and), (and)), (and)), (and))
3314 if (N0.getOpcode() != ISD::OR)
3316 SDValue N00 = N0.getOperand(0);
3317 SDValue N01 = N0.getOperand(1);
3318 SDNode *Parts[4] = {};
3320 if (N1.getOpcode() == ISD::OR &&
3321 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3322 // (or (or (and), (and)), (or (and), (and)))
3323 SDValue N000 = N00.getOperand(0);
3324 if (!isBSwapHWordElement(N000, Parts))
3327 SDValue N001 = N00.getOperand(1);
3328 if (!isBSwapHWordElement(N001, Parts))
3330 SDValue N010 = N01.getOperand(0);
3331 if (!isBSwapHWordElement(N010, Parts))
3333 SDValue N011 = N01.getOperand(1);
3334 if (!isBSwapHWordElement(N011, Parts))
3337 // (or (or (or (and), (and)), (and)), (and))
3338 if (!isBSwapHWordElement(N1, Parts))
3340 if (!isBSwapHWordElement(N01, Parts))
3342 if (N00.getOpcode() != ISD::OR)
3344 SDValue N000 = N00.getOperand(0);
3345 if (!isBSwapHWordElement(N000, Parts))
3347 SDValue N001 = N00.getOperand(1);
3348 if (!isBSwapHWordElement(N001, Parts))
3352 // Make sure the parts are all coming from the same node.
3353 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3356 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3357 SDValue(Parts[0],0));
3359 // Result of the bswap should be rotated by 16. If it's not legal, then
3360 // do (x << 16) | (x >> 16).
3361 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3362 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3363 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3364 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3365 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3366 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3367 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3368 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3371 /// This contains all DAGCombine rules which reduce two values combined by
3372 /// an Or operation to a single value \see visitANDLike().
3373 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3374 EVT VT = N1.getValueType();
3375 // fold (or x, undef) -> -1
3376 if (!LegalOperations &&
3377 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3378 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3379 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3381 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3382 SDValue LL, LR, RL, RR, CC0, CC1;
3383 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3384 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3385 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3387 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3388 LL.getValueType().isInteger()) {
3389 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3390 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3391 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3392 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3393 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3394 LR.getValueType(), LL, RL);
3395 AddToWorklist(ORNode.getNode());
3396 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3398 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3399 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3400 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3401 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3402 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3403 LR.getValueType(), LL, RL);
3404 AddToWorklist(ANDNode.getNode());
3405 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3408 // canonicalize equivalent to ll == rl
3409 if (LL == RR && LR == RL) {
3410 Op1 = ISD::getSetCCSwappedOperands(Op1);
3413 if (LL == RL && LR == RR) {
3414 bool isInteger = LL.getValueType().isInteger();
3415 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3416 if (Result != ISD::SETCC_INVALID &&
3417 (!LegalOperations ||
3418 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3419 TLI.isOperationLegal(ISD::SETCC,
3420 getSetCCResultType(N0.getValueType())))))
3421 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3426 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3427 if (N0.getOpcode() == ISD::AND &&
3428 N1.getOpcode() == ISD::AND &&
3429 N0.getOperand(1).getOpcode() == ISD::Constant &&
3430 N1.getOperand(1).getOpcode() == ISD::Constant &&
3431 // Don't increase # computations.
3432 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3433 // We can only do this xform if we know that bits from X that are set in C2
3434 // but not in C1 are already zero. Likewise for Y.
3435 const APInt &LHSMask =
3436 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3437 const APInt &RHSMask =
3438 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3440 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3441 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3442 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3443 N0.getOperand(0), N1.getOperand(0));
3444 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3445 DAG.getConstant(LHSMask | RHSMask, VT));
3449 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3450 if (N0.getOpcode() == ISD::AND &&
3451 N1.getOpcode() == ISD::AND &&
3452 N0.getOperand(0) == N1.getOperand(0) &&
3453 // Don't increase # computations.
3454 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3455 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3456 N0.getOperand(1), N1.getOperand(1));
3457 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3463 SDValue DAGCombiner::visitOR(SDNode *N) {
3464 SDValue N0 = N->getOperand(0);
3465 SDValue N1 = N->getOperand(1);
3466 EVT VT = N1.getValueType();
3469 if (VT.isVector()) {
3470 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3473 // fold (or x, 0) -> x, vector edition
3474 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3476 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3479 // fold (or x, -1) -> -1, vector edition
3480 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3481 // do not return N0, because undef node may exist in N0
3482 return DAG.getConstant(
3483 APInt::getAllOnesValue(
3484 N0.getValueType().getScalarType().getSizeInBits()),
3486 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3487 // do not return N1, because undef node may exist in N1
3488 return DAG.getConstant(
3489 APInt::getAllOnesValue(
3490 N1.getValueType().getScalarType().getSizeInBits()),
3493 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3494 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3495 // Do this only if the resulting shuffle is legal.
3496 if (isa<ShuffleVectorSDNode>(N0) &&
3497 isa<ShuffleVectorSDNode>(N1) &&
3498 // Avoid folding a node with illegal type.
3499 TLI.isTypeLegal(VT) &&
3500 N0->getOperand(1) == N1->getOperand(1) &&
3501 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3502 bool CanFold = true;
3503 unsigned NumElts = VT.getVectorNumElements();
3504 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3505 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3506 // We construct two shuffle masks:
3507 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3508 // and N1 as the second operand.
3509 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3510 // and N0 as the second operand.
3511 // We do this because OR is commutable and therefore there might be
3512 // two ways to fold this node into a shuffle.
3513 SmallVector<int,4> Mask1;
3514 SmallVector<int,4> Mask2;
3516 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3517 int M0 = SV0->getMaskElt(i);
3518 int M1 = SV1->getMaskElt(i);
3520 // Both shuffle indexes are undef. Propagate Undef.
3521 if (M0 < 0 && M1 < 0) {
3522 Mask1.push_back(M0);
3523 Mask2.push_back(M0);
3527 if (M0 < 0 || M1 < 0 ||
3528 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3529 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3534 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3535 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3539 // Fold this sequence only if the resulting shuffle is 'legal'.
3540 if (TLI.isShuffleMaskLegal(Mask1, VT))
3541 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3542 N1->getOperand(0), &Mask1[0]);
3543 if (TLI.isShuffleMaskLegal(Mask2, VT))
3544 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3545 N0->getOperand(0), &Mask2[0]);
3550 // fold (or c1, c2) -> c1|c2
3551 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3552 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3554 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3555 // canonicalize constant to RHS
3556 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3557 !isConstantIntBuildVectorOrConstantInt(N1))
3558 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3559 // fold (or x, 0) -> x
3560 if (N1C && N1C->isNullValue())
3562 // fold (or x, -1) -> -1
3563 if (N1C && N1C->isAllOnesValue())
3565 // fold (or x, c) -> c iff (x & ~c) == 0
3566 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3569 if (SDValue Combined = visitORLike(N0, N1, N))
3572 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3573 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3574 if (BSwap.getNode())
3576 BSwap = MatchBSwapHWordLow(N, N0, N1);
3577 if (BSwap.getNode())
3581 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3583 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3584 // iff (c1 & c2) == 0.
3585 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3586 isa<ConstantSDNode>(N0.getOperand(1))) {
3587 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3588 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3589 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3591 ISD::AND, SDLoc(N), VT,
3592 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3596 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3597 if (N0.getOpcode() == N1.getOpcode()) {
3598 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3599 if (Tmp.getNode()) return Tmp;
3602 // See if this is some rotate idiom.
3603 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3604 return SDValue(Rot, 0);
3606 // Simplify the operands using demanded-bits information.
3607 if (!VT.isVector() &&
3608 SimplifyDemandedBits(SDValue(N, 0)))
3609 return SDValue(N, 0);
3614 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3615 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3616 if (Op.getOpcode() == ISD::AND) {
3617 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3618 Mask = Op.getOperand(1);
3619 Op = Op.getOperand(0);
3625 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3633 // Return true if we can prove that, whenever Neg and Pos are both in the
3634 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3635 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3637 // (or (shift1 X, Neg), (shift2 X, Pos))
3639 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3640 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3641 // to consider shift amounts with defined behavior.
3642 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3643 // If OpSize is a power of 2 then:
3645 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3646 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3648 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3649 // for the stronger condition:
3651 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3653 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3654 // we can just replace Neg with Neg' for the rest of the function.
3656 // In other cases we check for the even stronger condition:
3658 // Neg == OpSize - Pos [B]
3660 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3661 // behavior if Pos == 0 (and consequently Neg == OpSize).
3663 // We could actually use [A] whenever OpSize is a power of 2, but the
3664 // only extra cases that it would match are those uninteresting ones
3665 // where Neg and Pos are never in range at the same time. E.g. for
3666 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3667 // as well as (sub 32, Pos), but:
3669 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3671 // always invokes undefined behavior for 32-bit X.
3673 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3674 unsigned MaskLoBits = 0;
3675 if (Neg.getOpcode() == ISD::AND &&
3676 isPowerOf2_64(OpSize) &&
3677 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3678 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3679 Neg = Neg.getOperand(0);
3680 MaskLoBits = Log2_64(OpSize);
3683 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3684 if (Neg.getOpcode() != ISD::SUB)
3686 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3689 SDValue NegOp1 = Neg.getOperand(1);
3691 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3692 // Pos'. The truncation is redundant for the purpose of the equality.
3694 Pos.getOpcode() == ISD::AND &&
3695 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3696 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3697 Pos = Pos.getOperand(0);
3699 // The condition we need is now:
3701 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3703 // If NegOp1 == Pos then we need:
3705 // OpSize & Mask == NegC & Mask
3707 // (because "x & Mask" is a truncation and distributes through subtraction).
3710 Width = NegC->getAPIntValue();
3711 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3712 // Then the condition we want to prove becomes:
3714 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3716 // which, again because "x & Mask" is a truncation, becomes:
3718 // NegC & Mask == (OpSize - PosC) & Mask
3719 // OpSize & Mask == (NegC + PosC) & Mask
3720 else if (Pos.getOpcode() == ISD::ADD &&
3721 Pos.getOperand(0) == NegOp1 &&
3722 Pos.getOperand(1).getOpcode() == ISD::Constant)
3723 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3724 NegC->getAPIntValue());
3728 // Now we just need to check that OpSize & Mask == Width & Mask.
3730 // Opsize & Mask is 0 since Mask is Opsize - 1.
3731 return Width.getLoBits(MaskLoBits) == 0;
3732 return Width == OpSize;
3735 // A subroutine of MatchRotate used once we have found an OR of two opposite
3736 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3737 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3738 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3739 // Neg with outer conversions stripped away.
3740 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3741 SDValue Neg, SDValue InnerPos,
3742 SDValue InnerNeg, unsigned PosOpcode,
3743 unsigned NegOpcode, SDLoc DL) {
3744 // fold (or (shl x, (*ext y)),
3745 // (srl x, (*ext (sub 32, y)))) ->
3746 // (rotl x, y) or (rotr x, (sub 32, y))
3748 // fold (or (shl x, (*ext (sub 32, y))),
3749 // (srl x, (*ext y))) ->
3750 // (rotr x, y) or (rotl x, (sub 32, y))
3751 EVT VT = Shifted.getValueType();
3752 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3753 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3754 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3755 HasPos ? Pos : Neg).getNode();
3761 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3762 // idioms for rotate, and if the target supports rotation instructions, generate
3764 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3765 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3766 EVT VT = LHS.getValueType();
3767 if (!TLI.isTypeLegal(VT)) return nullptr;
3769 // The target must have at least one rotate flavor.
3770 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3771 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3772 if (!HasROTL && !HasROTR) return nullptr;
3774 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3775 SDValue LHSShift; // The shift.
3776 SDValue LHSMask; // AND value if any.
3777 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3778 return nullptr; // Not part of a rotate.
3780 SDValue RHSShift; // The shift.
3781 SDValue RHSMask; // AND value if any.
3782 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3783 return nullptr; // Not part of a rotate.
3785 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3786 return nullptr; // Not shifting the same value.
3788 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3789 return nullptr; // Shifts must disagree.
3791 // Canonicalize shl to left side in a shl/srl pair.
3792 if (RHSShift.getOpcode() == ISD::SHL) {
3793 std::swap(LHS, RHS);
3794 std::swap(LHSShift, RHSShift);
3795 std::swap(LHSMask , RHSMask );
3798 unsigned OpSizeInBits = VT.getSizeInBits();
3799 SDValue LHSShiftArg = LHSShift.getOperand(0);
3800 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3801 SDValue RHSShiftArg = RHSShift.getOperand(0);
3802 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3804 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3805 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3806 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3807 RHSShiftAmt.getOpcode() == ISD::Constant) {
3808 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3809 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3810 if ((LShVal + RShVal) != OpSizeInBits)
3813 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3814 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3816 // If there is an AND of either shifted operand, apply it to the result.
3817 if (LHSMask.getNode() || RHSMask.getNode()) {
3818 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3820 if (LHSMask.getNode()) {
3821 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3822 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3824 if (RHSMask.getNode()) {
3825 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3826 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3829 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3832 return Rot.getNode();
3835 // If there is a mask here, and we have a variable shift, we can't be sure
3836 // that we're masking out the right stuff.
3837 if (LHSMask.getNode() || RHSMask.getNode())
3840 // If the shift amount is sign/zext/any-extended just peel it off.
3841 SDValue LExtOp0 = LHSShiftAmt;
3842 SDValue RExtOp0 = RHSShiftAmt;
3843 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3844 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3845 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3846 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3847 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3848 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3849 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3850 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3851 LExtOp0 = LHSShiftAmt.getOperand(0);
3852 RExtOp0 = RHSShiftAmt.getOperand(0);
3855 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3856 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3860 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3861 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3868 SDValue DAGCombiner::visitXOR(SDNode *N) {
3869 SDValue N0 = N->getOperand(0);
3870 SDValue N1 = N->getOperand(1);
3871 EVT VT = N0.getValueType();
3874 if (VT.isVector()) {
3875 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3878 // fold (xor x, 0) -> x, vector edition
3879 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3881 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3885 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3886 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3887 return DAG.getConstant(0, VT);
3888 // fold (xor x, undef) -> undef
3889 if (N0.getOpcode() == ISD::UNDEF)
3891 if (N1.getOpcode() == ISD::UNDEF)
3893 // fold (xor c1, c2) -> c1^c2
3894 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3895 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3897 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3898 // canonicalize constant to RHS
3899 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3900 !isConstantIntBuildVectorOrConstantInt(N1))
3901 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3902 // fold (xor x, 0) -> x
3903 if (N1C && N1C->isNullValue())
3906 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3909 // fold !(x cc y) -> (x !cc y)
3910 SDValue LHS, RHS, CC;
3911 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3912 bool isInt = LHS.getValueType().isInteger();
3913 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3916 if (!LegalOperations ||
3917 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3918 switch (N0.getOpcode()) {
3920 llvm_unreachable("Unhandled SetCC Equivalent!");
3922 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3923 case ISD::SELECT_CC:
3924 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3925 N0.getOperand(3), NotCC);
3930 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3931 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3932 N0.getNode()->hasOneUse() &&
3933 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3934 SDValue V = N0.getOperand(0);
3935 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3936 DAG.getConstant(1, V.getValueType()));
3937 AddToWorklist(V.getNode());
3938 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3941 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3942 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3943 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3944 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3945 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3946 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3947 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3948 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3949 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3950 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3953 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3954 if (N1C && N1C->isAllOnesValue() &&
3955 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3956 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3957 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3958 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3959 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3960 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3961 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3962 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3965 // fold (xor (and x, y), y) -> (and (not x), y)
3966 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3967 N0->getOperand(1) == N1) {
3968 SDValue X = N0->getOperand(0);
3969 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3970 AddToWorklist(NotX.getNode());
3971 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3973 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3974 if (N1C && N0.getOpcode() == ISD::XOR) {
3975 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3976 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3978 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3979 DAG.getConstant(N1C->getAPIntValue() ^
3980 N00C->getAPIntValue(), VT));
3982 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3983 DAG.getConstant(N1C->getAPIntValue() ^
3984 N01C->getAPIntValue(), VT));
3986 // fold (xor x, x) -> 0
3988 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3990 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
3991 // Here is a concrete example of this equivalence:
3993 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
3994 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
3998 // i16 ~1 == 0b1111111111111110
3999 // i16 rol(~1, 14) == 0b1011111111111111
4001 // Some additional tips to help conceptualize this transform:
4002 // - Try to see the operation as placing a single zero in a value of all ones.
4003 // - There exists no value for x which would allow the result to contain zero.
4004 // - Values of x larger than the bitwidth are undefined and do not require a
4005 // consistent result.
4006 // - Pushing the zero left requires shifting one bits in from the right.
4007 // A rotate left of ~1 is a nice way of achieving the desired result.
4008 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4009 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4010 if (N0.getOpcode() == ISD::SHL)
4011 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4012 if (N1C->isAllOnesValue() && ShlLHS->isOne())
4013 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT),
4016 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4017 if (N0.getOpcode() == N1.getOpcode()) {
4018 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4019 if (Tmp.getNode()) return Tmp;
4022 // Simplify the expression using non-local knowledge.
4023 if (!VT.isVector() &&
4024 SimplifyDemandedBits(SDValue(N, 0)))
4025 return SDValue(N, 0);
4030 /// Handle transforms common to the three shifts, when the shift amount is a
4032 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4033 // We can't and shouldn't fold opaque constants.
4034 if (Amt->isOpaque())
4037 SDNode *LHS = N->getOperand(0).getNode();
4038 if (!LHS->hasOneUse()) return SDValue();
4040 // We want to pull some binops through shifts, so that we have (and (shift))
4041 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4042 // thing happens with address calculations, so it's important to canonicalize
4044 bool HighBitSet = false; // Can we transform this if the high bit is set?
4046 switch (LHS->getOpcode()) {
4047 default: return SDValue();
4050 HighBitSet = false; // We can only transform sra if the high bit is clear.
4053 HighBitSet = true; // We can only transform sra if the high bit is set.
4056 if (N->getOpcode() != ISD::SHL)
4057 return SDValue(); // only shl(add) not sr[al](add).
4058 HighBitSet = false; // We can only transform sra if the high bit is clear.
4062 // We require the RHS of the binop to be a constant and not opaque as well.
4063 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4064 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4066 // FIXME: disable this unless the input to the binop is a shift by a constant.
4067 // If it is not a shift, it pessimizes some common cases like:
4069 // void foo(int *X, int i) { X[i & 1235] = 1; }
4070 // int bar(int *X, int i) { return X[i & 255]; }
4071 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4072 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4073 BinOpLHSVal->getOpcode() != ISD::SRA &&
4074 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4075 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4078 EVT VT = N->getValueType(0);
4080 // If this is a signed shift right, and the high bit is modified by the
4081 // logical operation, do not perform the transformation. The highBitSet
4082 // boolean indicates the value of the high bit of the constant which would
4083 // cause it to be modified for this operation.
4084 if (N->getOpcode() == ISD::SRA) {
4085 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4086 if (BinOpRHSSignSet != HighBitSet)
4090 if (!TLI.isDesirableToCommuteWithShift(LHS))
4093 // Fold the constants, shifting the binop RHS by the shift amount.
4094 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4096 LHS->getOperand(1), N->getOperand(1));
4097 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4099 // Create the new shift.
4100 SDValue NewShift = DAG.getNode(N->getOpcode(),
4101 SDLoc(LHS->getOperand(0)),
4102 VT, LHS->getOperand(0), N->getOperand(1));
4104 // Create the new binop.
4105 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4108 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4109 assert(N->getOpcode() == ISD::TRUNCATE);
4110 assert(N->getOperand(0).getOpcode() == ISD::AND);
4112 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4113 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4114 SDValue N01 = N->getOperand(0).getOperand(1);
4116 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4117 EVT TruncVT = N->getValueType(0);
4118 SDValue N00 = N->getOperand(0).getOperand(0);
4119 APInt TruncC = N01C->getAPIntValue();
4120 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4122 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4123 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4124 DAG.getConstant(TruncC, TruncVT));
4131 SDValue DAGCombiner::visitRotate(SDNode *N) {
4132 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4133 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4134 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4135 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4136 if (NewOp1.getNode())
4137 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4138 N->getOperand(0), NewOp1);
4143 SDValue DAGCombiner::visitSHL(SDNode *N) {
4144 SDValue N0 = N->getOperand(0);
4145 SDValue N1 = N->getOperand(1);
4146 EVT VT = N0.getValueType();
4147 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4150 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4151 if (VT.isVector()) {
4152 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4155 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4156 // If setcc produces all-one true value then:
4157 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4158 if (N1CV && N1CV->isConstant()) {
4159 if (N0.getOpcode() == ISD::AND) {
4160 SDValue N00 = N0->getOperand(0);
4161 SDValue N01 = N0->getOperand(1);
4162 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4164 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4165 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4166 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4167 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4168 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4171 N1C = isConstOrConstSplat(N1);
4176 // fold (shl c1, c2) -> c1<<c2
4177 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4179 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4180 // fold (shl 0, x) -> 0
4181 if (N0C && N0C->isNullValue())
4183 // fold (shl x, c >= size(x)) -> undef
4184 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4185 return DAG.getUNDEF(VT);
4186 // fold (shl x, 0) -> x
4187 if (N1C && N1C->isNullValue())
4189 // fold (shl undef, x) -> 0
4190 if (N0.getOpcode() == ISD::UNDEF)
4191 return DAG.getConstant(0, VT);
4192 // if (shl x, c) is known to be zero, return 0
4193 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4194 APInt::getAllOnesValue(OpSizeInBits)))
4195 return DAG.getConstant(0, VT);
4196 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4197 if (N1.getOpcode() == ISD::TRUNCATE &&
4198 N1.getOperand(0).getOpcode() == ISD::AND) {
4199 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4200 if (NewOp1.getNode())
4201 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4204 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4205 return SDValue(N, 0);
4207 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4208 if (N1C && N0.getOpcode() == ISD::SHL) {
4209 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4210 uint64_t c1 = N0C1->getZExtValue();
4211 uint64_t c2 = N1C->getZExtValue();
4212 if (c1 + c2 >= OpSizeInBits)
4213 return DAG.getConstant(0, VT);
4214 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4215 DAG.getConstant(c1 + c2, N1.getValueType()));
4219 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4220 // For this to be valid, the second form must not preserve any of the bits
4221 // that are shifted out by the inner shift in the first form. This means
4222 // the outer shift size must be >= the number of bits added by the ext.
4223 // As a corollary, we don't care what kind of ext it is.
4224 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4225 N0.getOpcode() == ISD::ANY_EXTEND ||
4226 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4227 N0.getOperand(0).getOpcode() == ISD::SHL) {
4228 SDValue N0Op0 = N0.getOperand(0);
4229 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4230 uint64_t c1 = N0Op0C1->getZExtValue();
4231 uint64_t c2 = N1C->getZExtValue();
4232 EVT InnerShiftVT = N0Op0.getValueType();
4233 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4234 if (c2 >= OpSizeInBits - InnerShiftSize) {
4235 if (c1 + c2 >= OpSizeInBits)
4236 return DAG.getConstant(0, VT);
4237 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4238 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4239 N0Op0->getOperand(0)),
4240 DAG.getConstant(c1 + c2, N1.getValueType()));
4245 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4246 // Only fold this if the inner zext has no other uses to avoid increasing
4247 // the total number of instructions.
4248 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4249 N0.getOperand(0).getOpcode() == ISD::SRL) {
4250 SDValue N0Op0 = N0.getOperand(0);
4251 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4252 uint64_t c1 = N0Op0C1->getZExtValue();
4253 if (c1 < VT.getScalarSizeInBits()) {
4254 uint64_t c2 = N1C->getZExtValue();
4256 SDValue NewOp0 = N0.getOperand(0);
4257 EVT CountVT = NewOp0.getOperand(1).getValueType();
4258 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4259 NewOp0, DAG.getConstant(c2, CountVT));
4260 AddToWorklist(NewSHL.getNode());
4261 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4267 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4268 // (and (srl x, (sub c1, c2), MASK)
4269 // Only fold this if the inner shift has no other uses -- if it does, folding
4270 // this will increase the total number of instructions.
4271 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4272 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4273 uint64_t c1 = N0C1->getZExtValue();
4274 if (c1 < OpSizeInBits) {
4275 uint64_t c2 = N1C->getZExtValue();
4276 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4279 Mask = Mask.shl(c2 - c1);
4280 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4281 DAG.getConstant(c2 - c1, N1.getValueType()));
4283 Mask = Mask.lshr(c1 - c2);
4284 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4285 DAG.getConstant(c1 - c2, N1.getValueType()));
4287 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4288 DAG.getConstant(Mask, VT));
4292 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4293 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4294 unsigned BitSize = VT.getScalarSizeInBits();
4295 SDValue HiBitsMask =
4296 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4297 BitSize - N1C->getZExtValue()), VT);
4298 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4302 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4303 // Variant of version done on multiply, except mul by a power of 2 is turned
4306 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4307 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4308 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4309 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4310 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4311 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4315 SDValue NewSHL = visitShiftByConstant(N, N1C);
4316 if (NewSHL.getNode())
4323 SDValue DAGCombiner::visitSRA(SDNode *N) {
4324 SDValue N0 = N->getOperand(0);
4325 SDValue N1 = N->getOperand(1);
4326 EVT VT = N0.getValueType();
4327 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4330 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4331 if (VT.isVector()) {
4332 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4335 N1C = isConstOrConstSplat(N1);
4338 // fold (sra c1, c2) -> (sra c1, c2)
4339 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4341 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4342 // fold (sra 0, x) -> 0
4343 if (N0C && N0C->isNullValue())
4345 // fold (sra -1, x) -> -1
4346 if (N0C && N0C->isAllOnesValue())
4348 // fold (sra x, (setge c, size(x))) -> undef
4349 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4350 return DAG.getUNDEF(VT);
4351 // fold (sra x, 0) -> x
4352 if (N1C && N1C->isNullValue())
4354 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4356 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4357 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4358 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4360 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4361 ExtVT, VT.getVectorNumElements());
4362 if ((!LegalOperations ||
4363 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4364 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4365 N0.getOperand(0), DAG.getValueType(ExtVT));
4368 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4369 if (N1C && N0.getOpcode() == ISD::SRA) {
4370 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4371 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4372 if (Sum >= OpSizeInBits)
4373 Sum = OpSizeInBits - 1;
4374 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4375 DAG.getConstant(Sum, N1.getValueType()));
4379 // fold (sra (shl X, m), (sub result_size, n))
4380 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4381 // result_size - n != m.
4382 // If truncate is free for the target sext(shl) is likely to result in better
4384 if (N0.getOpcode() == ISD::SHL && N1C) {
4385 // Get the two constanst of the shifts, CN0 = m, CN = n.
4386 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4388 LLVMContext &Ctx = *DAG.getContext();
4389 // Determine what the truncate's result bitsize and type would be.
4390 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4393 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4395 // Determine the residual right-shift amount.
4396 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4398 // If the shift is not a no-op (in which case this should be just a sign
4399 // extend already), the truncated to type is legal, sign_extend is legal
4400 // on that type, and the truncate to that type is both legal and free,
4401 // perform the transform.
4402 if ((ShiftAmt > 0) &&
4403 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4404 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4405 TLI.isTruncateFree(VT, TruncVT)) {
4407 SDValue Amt = DAG.getConstant(ShiftAmt,
4408 getShiftAmountTy(N0.getOperand(0).getValueType()));
4409 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4410 N0.getOperand(0), Amt);
4411 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4413 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4414 N->getValueType(0), Trunc);
4419 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4420 if (N1.getOpcode() == ISD::TRUNCATE &&
4421 N1.getOperand(0).getOpcode() == ISD::AND) {
4422 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4423 if (NewOp1.getNode())
4424 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4427 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4428 // if c1 is equal to the number of bits the trunc removes
4429 if (N0.getOpcode() == ISD::TRUNCATE &&
4430 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4431 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4432 N0.getOperand(0).hasOneUse() &&
4433 N0.getOperand(0).getOperand(1).hasOneUse() &&
4435 SDValue N0Op0 = N0.getOperand(0);
4436 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4437 unsigned LargeShiftVal = LargeShift->getZExtValue();
4438 EVT LargeVT = N0Op0.getValueType();
4440 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4442 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4443 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4444 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4445 N0Op0.getOperand(0), Amt);
4446 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4451 // Simplify, based on bits shifted out of the LHS.
4452 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4453 return SDValue(N, 0);
4456 // If the sign bit is known to be zero, switch this to a SRL.
4457 if (DAG.SignBitIsZero(N0))
4458 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4461 SDValue NewSRA = visitShiftByConstant(N, N1C);
4462 if (NewSRA.getNode())
4469 SDValue DAGCombiner::visitSRL(SDNode *N) {
4470 SDValue N0 = N->getOperand(0);
4471 SDValue N1 = N->getOperand(1);
4472 EVT VT = N0.getValueType();
4473 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4476 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4477 if (VT.isVector()) {
4478 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4481 N1C = isConstOrConstSplat(N1);
4484 // fold (srl c1, c2) -> c1 >>u c2
4485 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4487 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4488 // fold (srl 0, x) -> 0
4489 if (N0C && N0C->isNullValue())
4491 // fold (srl x, c >= size(x)) -> undef
4492 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4493 return DAG.getUNDEF(VT);
4494 // fold (srl x, 0) -> x
4495 if (N1C && N1C->isNullValue())
4497 // if (srl x, c) is known to be zero, return 0
4498 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4499 APInt::getAllOnesValue(OpSizeInBits)))
4500 return DAG.getConstant(0, VT);
4502 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4503 if (N1C && N0.getOpcode() == ISD::SRL) {
4504 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4505 uint64_t c1 = N01C->getZExtValue();
4506 uint64_t c2 = N1C->getZExtValue();
4507 if (c1 + c2 >= OpSizeInBits)
4508 return DAG.getConstant(0, VT);
4509 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4510 DAG.getConstant(c1 + c2, N1.getValueType()));
4514 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4515 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4516 N0.getOperand(0).getOpcode() == ISD::SRL &&
4517 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4519 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4520 uint64_t c2 = N1C->getZExtValue();
4521 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4522 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4523 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4524 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4525 if (c1 + OpSizeInBits == InnerShiftSize) {
4526 if (c1 + c2 >= InnerShiftSize)
4527 return DAG.getConstant(0, VT);
4528 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4529 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4530 N0.getOperand(0)->getOperand(0),
4531 DAG.getConstant(c1 + c2, ShiftCountVT)));
4535 // fold (srl (shl x, c), c) -> (and x, cst2)
4536 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4537 unsigned BitSize = N0.getScalarValueSizeInBits();
4538 if (BitSize <= 64) {
4539 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4540 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4541 DAG.getConstant(~0ULL >> ShAmt, VT));
4545 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4546 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4547 // Shifting in all undef bits?
4548 EVT SmallVT = N0.getOperand(0).getValueType();
4549 unsigned BitSize = SmallVT.getScalarSizeInBits();
4550 if (N1C->getZExtValue() >= BitSize)
4551 return DAG.getUNDEF(VT);
4553 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4554 uint64_t ShiftAmt = N1C->getZExtValue();
4555 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4557 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4558 AddToWorklist(SmallShift.getNode());
4559 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4560 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4561 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4562 DAG.getConstant(Mask, VT));
4566 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4567 // bit, which is unmodified by sra.
4568 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4569 if (N0.getOpcode() == ISD::SRA)
4570 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4573 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4574 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4575 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4576 APInt KnownZero, KnownOne;
4577 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4579 // If any of the input bits are KnownOne, then the input couldn't be all
4580 // zeros, thus the result of the srl will always be zero.
4581 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4583 // If all of the bits input the to ctlz node are known to be zero, then
4584 // the result of the ctlz is "32" and the result of the shift is one.
4585 APInt UnknownBits = ~KnownZero;
4586 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4588 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4589 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4590 // Okay, we know that only that the single bit specified by UnknownBits
4591 // could be set on input to the CTLZ node. If this bit is set, the SRL
4592 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4593 // to an SRL/XOR pair, which is likely to simplify more.
4594 unsigned ShAmt = UnknownBits.countTrailingZeros();
4595 SDValue Op = N0.getOperand(0);
4598 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4599 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4600 AddToWorklist(Op.getNode());
4603 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4604 Op, DAG.getConstant(1, VT));
4608 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4609 if (N1.getOpcode() == ISD::TRUNCATE &&
4610 N1.getOperand(0).getOpcode() == ISD::AND) {
4611 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4612 if (NewOp1.getNode())
4613 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4616 // fold operands of srl based on knowledge that the low bits are not
4618 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4619 return SDValue(N, 0);
4622 SDValue NewSRL = visitShiftByConstant(N, N1C);
4623 if (NewSRL.getNode())
4627 // Attempt to convert a srl of a load into a narrower zero-extending load.
4628 SDValue NarrowLoad = ReduceLoadWidth(N);
4629 if (NarrowLoad.getNode())
4632 // Here is a common situation. We want to optimize:
4635 // %b = and i32 %a, 2
4636 // %c = srl i32 %b, 1
4637 // brcond i32 %c ...
4643 // %c = setcc eq %b, 0
4646 // However when after the source operand of SRL is optimized into AND, the SRL
4647 // itself may not be optimized further. Look for it and add the BRCOND into
4649 if (N->hasOneUse()) {
4650 SDNode *Use = *N->use_begin();
4651 if (Use->getOpcode() == ISD::BRCOND)
4653 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4654 // Also look pass the truncate.
4655 Use = *Use->use_begin();
4656 if (Use->getOpcode() == ISD::BRCOND)
4664 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4665 SDValue N0 = N->getOperand(0);
4666 EVT VT = N->getValueType(0);
4668 // fold (ctlz c1) -> c2
4669 if (isa<ConstantSDNode>(N0))
4670 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4674 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4675 SDValue N0 = N->getOperand(0);
4676 EVT VT = N->getValueType(0);
4678 // fold (ctlz_zero_undef c1) -> c2
4679 if (isa<ConstantSDNode>(N0))
4680 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4684 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4685 SDValue N0 = N->getOperand(0);
4686 EVT VT = N->getValueType(0);
4688 // fold (cttz c1) -> c2
4689 if (isa<ConstantSDNode>(N0))
4690 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4694 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4695 SDValue N0 = N->getOperand(0);
4696 EVT VT = N->getValueType(0);
4698 // fold (cttz_zero_undef c1) -> c2
4699 if (isa<ConstantSDNode>(N0))
4700 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4704 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4705 SDValue N0 = N->getOperand(0);
4706 EVT VT = N->getValueType(0);
4708 // fold (ctpop c1) -> c2
4709 if (isa<ConstantSDNode>(N0))
4710 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4715 /// \brief Generate Min/Max node
4716 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4717 SDValue True, SDValue False,
4718 ISD::CondCode CC, const TargetLowering &TLI,
4719 SelectionDAG &DAG) {
4720 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4730 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4731 if (TLI.isOperationLegal(Opcode, VT))
4732 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4741 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4742 if (TLI.isOperationLegal(Opcode, VT))
4743 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4751 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4752 SDValue N0 = N->getOperand(0);
4753 SDValue N1 = N->getOperand(1);
4754 SDValue N2 = N->getOperand(2);
4755 EVT VT = N->getValueType(0);
4756 EVT VT0 = N0.getValueType();
4758 // fold (select C, X, X) -> X
4761 // fold (select true, X, Y) -> X
4762 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4763 if (N0C && !N0C->isNullValue())
4765 // fold (select false, X, Y) -> Y
4766 if (N0C && N0C->isNullValue())
4768 // fold (select C, 1, X) -> (or C, X)
4769 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4770 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4771 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4772 // fold (select C, 0, 1) -> (xor C, 1)
4773 // We can't do this reliably if integer based booleans have different contents
4774 // to floating point based booleans. This is because we can't tell whether we
4775 // have an integer-based boolean or a floating-point-based boolean unless we
4776 // can find the SETCC that produced it and inspect its operands. This is
4777 // fairly easy if C is the SETCC node, but it can potentially be
4778 // undiscoverable (or not reasonably discoverable). For example, it could be
4779 // in another basic block or it could require searching a complicated
4781 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4782 if (VT.isInteger() &&
4783 (VT0 == MVT::i1 || (VT0.isInteger() &&
4784 TLI.getBooleanContents(false, false) ==
4785 TLI.getBooleanContents(false, true) &&
4786 TLI.getBooleanContents(false, false) ==
4787 TargetLowering::ZeroOrOneBooleanContent)) &&
4788 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4791 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4792 N0, DAG.getConstant(1, VT0));
4793 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4794 N0, DAG.getConstant(1, VT0));
4795 AddToWorklist(XORNode.getNode());
4797 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4798 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4800 // fold (select C, 0, X) -> (and (not C), X)
4801 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4802 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4803 AddToWorklist(NOTNode.getNode());
4804 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4806 // fold (select C, X, 1) -> (or (not C), X)
4807 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4808 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4809 AddToWorklist(NOTNode.getNode());
4810 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4812 // fold (select C, X, 0) -> (and C, X)
4813 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4814 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4815 // fold (select X, X, Y) -> (or X, Y)
4816 // fold (select X, 1, Y) -> (or X, Y)
4817 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4818 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4819 // fold (select X, Y, X) -> (and X, Y)
4820 // fold (select X, Y, 0) -> (and X, Y)
4821 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4822 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4824 // If we can fold this based on the true/false value, do so.
4825 if (SimplifySelectOps(N, N1, N2))
4826 return SDValue(N, 0); // Don't revisit N.
4828 // fold selects based on a setcc into other things, such as min/max/abs
4829 if (N0.getOpcode() == ISD::SETCC) {
4830 // select x, y (fcmp lt x, y) -> fminnum x, y
4831 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4833 // This is OK if we don't care about what happens if either operand is a
4837 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4838 // no signed zeros as well as no nans.
4839 const TargetOptions &Options = DAG.getTarget().Options;
4840 if (Options.UnsafeFPMath &&
4841 VT.isFloatingPoint() && N0.hasOneUse() &&
4842 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4843 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4846 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4847 N1, N2, CC, TLI, DAG);
4852 if ((!LegalOperations &&
4853 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4854 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4855 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4856 N0.getOperand(0), N0.getOperand(1),
4857 N1, N2, N0.getOperand(2));
4858 return SimplifySelect(SDLoc(N), N0, N1, N2);
4861 if (VT0 == MVT::i1) {
4862 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4863 // select (and Cond0, Cond1), X, Y
4864 // -> select Cond0, (select Cond1, X, Y), Y
4865 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4866 SDValue Cond0 = N0->getOperand(0);
4867 SDValue Cond1 = N0->getOperand(1);
4868 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4869 N1.getValueType(), Cond1, N1, N2);
4870 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4873 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4874 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4875 SDValue Cond0 = N0->getOperand(0);
4876 SDValue Cond1 = N0->getOperand(1);
4877 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4878 N1.getValueType(), Cond1, N1, N2);
4879 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4884 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4885 if (N1->getOpcode() == ISD::SELECT) {
4886 SDValue N1_0 = N1->getOperand(0);
4887 SDValue N1_1 = N1->getOperand(1);
4888 SDValue N1_2 = N1->getOperand(2);
4889 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4890 // Create the actual and node if we can generate good code for it.
4891 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4892 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4894 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4897 // Otherwise see if we can optimize the "and" to a better pattern.
4898 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4899 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4903 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4904 if (N2->getOpcode() == ISD::SELECT) {
4905 SDValue N2_0 = N2->getOperand(0);
4906 SDValue N2_1 = N2->getOperand(1);
4907 SDValue N2_2 = N2->getOperand(2);
4908 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4909 // Create the actual or node if we can generate good code for it.
4910 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4911 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4913 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4916 // Otherwise see if we can optimize to a better pattern.
4917 if (SDValue Combined = visitORLike(N0, N2_0, N))
4918 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4928 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4931 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4933 // Split the inputs.
4934 SDValue Lo, Hi, LL, LH, RL, RH;
4935 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4936 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4938 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4939 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4941 return std::make_pair(Lo, Hi);
4944 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4945 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4946 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4948 SDValue Cond = N->getOperand(0);
4949 SDValue LHS = N->getOperand(1);
4950 SDValue RHS = N->getOperand(2);
4951 EVT VT = N->getValueType(0);
4952 int NumElems = VT.getVectorNumElements();
4953 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4954 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4955 Cond.getOpcode() == ISD::BUILD_VECTOR);
4957 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4958 // binary ones here.
4959 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4962 // We're sure we have an even number of elements due to the
4963 // concat_vectors we have as arguments to vselect.
4964 // Skip BV elements until we find one that's not an UNDEF
4965 // After we find an UNDEF element, keep looping until we get to half the
4966 // length of the BV and see if all the non-undef nodes are the same.
4967 ConstantSDNode *BottomHalf = nullptr;
4968 for (int i = 0; i < NumElems / 2; ++i) {
4969 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4972 if (BottomHalf == nullptr)
4973 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4974 else if (Cond->getOperand(i).getNode() != BottomHalf)
4978 // Do the same for the second half of the BuildVector
4979 ConstantSDNode *TopHalf = nullptr;
4980 for (int i = NumElems / 2; i < NumElems; ++i) {
4981 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4984 if (TopHalf == nullptr)
4985 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4986 else if (Cond->getOperand(i).getNode() != TopHalf)
4990 assert(TopHalf && BottomHalf &&
4991 "One half of the selector was all UNDEFs and the other was all the "
4992 "same value. This should have been addressed before this function.");
4994 ISD::CONCAT_VECTORS, dl, VT,
4995 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4996 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4999 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5001 if (Level >= AfterLegalizeTypes)
5004 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5005 SDValue Mask = MST->getMask();
5006 SDValue Data = MST->getValue();
5009 // If the MSTORE data type requires splitting and the mask is provided by a
5010 // SETCC, then split both nodes and its operands before legalization. This
5011 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5012 // and enables future optimizations (e.g. min/max pattern matching on X86).
5013 if (Mask.getOpcode() == ISD::SETCC) {
5015 // Check if any splitting is required.
5016 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5017 TargetLowering::TypeSplitVector)
5020 SDValue MaskLo, MaskHi, Lo, Hi;
5021 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5024 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5026 SDValue Chain = MST->getChain();
5027 SDValue Ptr = MST->getBasePtr();
5029 EVT MemoryVT = MST->getMemoryVT();
5030 unsigned Alignment = MST->getOriginalAlignment();
5032 // if Alignment is equal to the vector size,
5033 // take the half of it for the second part
5034 unsigned SecondHalfAlignment =
5035 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5036 Alignment/2 : Alignment;
5038 EVT LoMemVT, HiMemVT;
5039 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5041 SDValue DataLo, DataHi;
5042 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5044 MachineMemOperand *MMO = DAG.getMachineFunction().
5045 getMachineMemOperand(MST->getPointerInfo(),
5046 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5047 Alignment, MST->getAAInfo(), MST->getRanges());
5049 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5050 MST->isTruncatingStore());
5052 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5053 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5054 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5056 MMO = DAG.getMachineFunction().
5057 getMachineMemOperand(MST->getPointerInfo(),
5058 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5059 SecondHalfAlignment, MST->getAAInfo(),
5062 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5063 MST->isTruncatingStore());
5065 AddToWorklist(Lo.getNode());
5066 AddToWorklist(Hi.getNode());
5068 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5073 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5075 if (Level >= AfterLegalizeTypes)
5078 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5079 SDValue Mask = MLD->getMask();
5082 // If the MLOAD result requires splitting and the mask is provided by a
5083 // SETCC, then split both nodes and its operands before legalization. This
5084 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5085 // and enables future optimizations (e.g. min/max pattern matching on X86).
5087 if (Mask.getOpcode() == ISD::SETCC) {
5088 EVT VT = N->getValueType(0);
5090 // Check if any splitting is required.
5091 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5092 TargetLowering::TypeSplitVector)
5095 SDValue MaskLo, MaskHi, Lo, Hi;
5096 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5098 SDValue Src0 = MLD->getSrc0();
5099 SDValue Src0Lo, Src0Hi;
5100 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5103 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5105 SDValue Chain = MLD->getChain();
5106 SDValue Ptr = MLD->getBasePtr();
5107 EVT MemoryVT = MLD->getMemoryVT();
5108 unsigned Alignment = MLD->getOriginalAlignment();
5110 // if Alignment is equal to the vector size,
5111 // take the half of it for the second part
5112 unsigned SecondHalfAlignment =
5113 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5114 Alignment/2 : Alignment;
5116 EVT LoMemVT, HiMemVT;
5117 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5119 MachineMemOperand *MMO = DAG.getMachineFunction().
5120 getMachineMemOperand(MLD->getPointerInfo(),
5121 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5122 Alignment, MLD->getAAInfo(), MLD->getRanges());
5124 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5127 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5128 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5129 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5131 MMO = DAG.getMachineFunction().
5132 getMachineMemOperand(MLD->getPointerInfo(),
5133 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5134 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5136 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5139 AddToWorklist(Lo.getNode());
5140 AddToWorklist(Hi.getNode());
5142 // Build a factor node to remember that this load is independent of the
5144 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5147 // Legalized the chain result - switch anything that used the old chain to
5149 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5151 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5153 SDValue RetOps[] = { LoadRes, Chain };
5154 return DAG.getMergeValues(RetOps, DL);
5159 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5160 SDValue N0 = N->getOperand(0);
5161 SDValue N1 = N->getOperand(1);
5162 SDValue N2 = N->getOperand(2);
5165 // Canonicalize integer abs.
5166 // vselect (setg[te] X, 0), X, -X ->
5167 // vselect (setgt X, -1), X, -X ->
5168 // vselect (setl[te] X, 0), -X, X ->
5169 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5170 if (N0.getOpcode() == ISD::SETCC) {
5171 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5172 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5174 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5176 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5177 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5178 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5179 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5180 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5181 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5182 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5185 EVT VT = LHS.getValueType();
5186 SDValue Shift = DAG.getNode(
5187 ISD::SRA, DL, VT, LHS,
5188 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5189 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5190 AddToWorklist(Shift.getNode());
5191 AddToWorklist(Add.getNode());
5192 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5196 if (SimplifySelectOps(N, N1, N2))
5197 return SDValue(N, 0); // Don't revisit N.
5199 // If the VSELECT result requires splitting and the mask is provided by a
5200 // SETCC, then split both nodes and its operands before legalization. This
5201 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5202 // and enables future optimizations (e.g. min/max pattern matching on X86).
5203 if (N0.getOpcode() == ISD::SETCC) {
5204 EVT VT = N->getValueType(0);
5206 // Check if any splitting is required.
5207 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5208 TargetLowering::TypeSplitVector)
5211 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5212 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5213 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5214 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5216 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5217 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5219 // Add the new VSELECT nodes to the work list in case they need to be split
5221 AddToWorklist(Lo.getNode());
5222 AddToWorklist(Hi.getNode());
5224 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5227 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5228 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5230 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5231 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5234 // The ConvertSelectToConcatVector function is assuming both the above
5235 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5237 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5238 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5239 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5240 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5248 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5249 SDValue N0 = N->getOperand(0);
5250 SDValue N1 = N->getOperand(1);
5251 SDValue N2 = N->getOperand(2);
5252 SDValue N3 = N->getOperand(3);
5253 SDValue N4 = N->getOperand(4);
5254 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5256 // fold select_cc lhs, rhs, x, x, cc -> x
5260 // Determine if the condition we're dealing with is constant
5261 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5262 N0, N1, CC, SDLoc(N), false);
5263 if (SCC.getNode()) {
5264 AddToWorklist(SCC.getNode());
5266 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5267 if (!SCCC->isNullValue())
5268 return N2; // cond always true -> true val
5270 return N3; // cond always false -> false val
5271 } else if (SCC->getOpcode() == ISD::UNDEF) {
5272 // When the condition is UNDEF, just return the first operand. This is
5273 // coherent the DAG creation, no setcc node is created in this case
5275 } else if (SCC.getOpcode() == ISD::SETCC) {
5276 // Fold to a simpler select_cc
5277 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5278 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5283 // If we can fold this based on the true/false value, do so.
5284 if (SimplifySelectOps(N, N2, N3))
5285 return SDValue(N, 0); // Don't revisit N.
5287 // fold select_cc into other things, such as min/max/abs
5288 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5291 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5292 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5293 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5297 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5298 // dag node into a ConstantSDNode or a build_vector of constants.
5299 // This function is called by the DAGCombiner when visiting sext/zext/aext
5300 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5301 // Vector extends are not folded if operations are legal; this is to
5302 // avoid introducing illegal build_vector dag nodes.
5303 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5304 SelectionDAG &DAG, bool LegalTypes,
5305 bool LegalOperations) {
5306 unsigned Opcode = N->getOpcode();
5307 SDValue N0 = N->getOperand(0);
5308 EVT VT = N->getValueType(0);
5310 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5311 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5313 // fold (sext c1) -> c1
5314 // fold (zext c1) -> c1
5315 // fold (aext c1) -> c1
5316 if (isa<ConstantSDNode>(N0))
5317 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5319 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5320 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5321 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5322 EVT SVT = VT.getScalarType();
5323 if (!(VT.isVector() &&
5324 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5325 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5328 // We can fold this node into a build_vector.
5329 unsigned VTBits = SVT.getSizeInBits();
5330 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5331 unsigned ShAmt = VTBits - EVTBits;
5332 SmallVector<SDValue, 8> Elts;
5333 unsigned NumElts = N0->getNumOperands();
5336 for (unsigned i=0; i != NumElts; ++i) {
5337 SDValue Op = N0->getOperand(i);
5338 if (Op->getOpcode() == ISD::UNDEF) {
5339 Elts.push_back(DAG.getUNDEF(SVT));
5343 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5344 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5345 if (Opcode == ISD::SIGN_EXTEND)
5346 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5349 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5353 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5356 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5357 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5358 // transformation. Returns true if extension are possible and the above
5359 // mentioned transformation is profitable.
5360 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5362 SmallVectorImpl<SDNode *> &ExtendNodes,
5363 const TargetLowering &TLI) {
5364 bool HasCopyToRegUses = false;
5365 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5366 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5367 UE = N0.getNode()->use_end();
5372 if (UI.getUse().getResNo() != N0.getResNo())
5374 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5375 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5376 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5377 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5378 // Sign bits will be lost after a zext.
5381 for (unsigned i = 0; i != 2; ++i) {
5382 SDValue UseOp = User->getOperand(i);
5385 if (!isa<ConstantSDNode>(UseOp))
5390 ExtendNodes.push_back(User);
5393 // If truncates aren't free and there are users we can't
5394 // extend, it isn't worthwhile.
5397 // Remember if this value is live-out.
5398 if (User->getOpcode() == ISD::CopyToReg)
5399 HasCopyToRegUses = true;
5402 if (HasCopyToRegUses) {
5403 bool BothLiveOut = false;
5404 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5406 SDUse &Use = UI.getUse();
5407 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5413 // Both unextended and extended values are live out. There had better be
5414 // a good reason for the transformation.
5415 return ExtendNodes.size();
5420 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5421 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5422 ISD::NodeType ExtType) {
5423 // Extend SetCC uses if necessary.
5424 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5425 SDNode *SetCC = SetCCs[i];
5426 SmallVector<SDValue, 4> Ops;
5428 for (unsigned j = 0; j != 2; ++j) {
5429 SDValue SOp = SetCC->getOperand(j);
5431 Ops.push_back(ExtLoad);
5433 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5436 Ops.push_back(SetCC->getOperand(2));
5437 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5441 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5442 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5443 SDValue N0 = N->getOperand(0);
5444 EVT DstVT = N->getValueType(0);
5445 EVT SrcVT = N0.getValueType();
5447 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5448 N->getOpcode() == ISD::ZERO_EXTEND) &&
5449 "Unexpected node type (not an extend)!");
5451 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5452 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5453 // (v8i32 (sext (v8i16 (load x))))
5455 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5456 // (v4i32 (sextload (x + 16)))))
5457 // Where uses of the original load, i.e.:
5459 // are replaced with:
5461 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5462 // (v4i32 (sextload (x + 16)))))))
5464 // This combine is only applicable to illegal, but splittable, vectors.
5465 // All legal types, and illegal non-vector types, are handled elsewhere.
5466 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5468 if (N0->getOpcode() != ISD::LOAD)
5471 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5473 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5474 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5475 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5478 SmallVector<SDNode *, 4> SetCCs;
5479 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5482 ISD::LoadExtType ExtType =
5483 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5485 // Try to split the vector types to get down to legal types.
5486 EVT SplitSrcVT = SrcVT;
5487 EVT SplitDstVT = DstVT;
5488 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5489 SplitSrcVT.getVectorNumElements() > 1) {
5490 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5491 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5494 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5498 const unsigned NumSplits =
5499 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5500 const unsigned Stride = SplitSrcVT.getStoreSize();
5501 SmallVector<SDValue, 4> Loads;
5502 SmallVector<SDValue, 4> Chains;
5504 SDValue BasePtr = LN0->getBasePtr();
5505 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5506 const unsigned Offset = Idx * Stride;
5507 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5509 SDValue SplitLoad = DAG.getExtLoad(
5510 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5511 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5512 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5513 Align, LN0->getAAInfo());
5515 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5516 DAG.getConstant(Stride, BasePtr.getValueType()));
5518 Loads.push_back(SplitLoad.getValue(0));
5519 Chains.push_back(SplitLoad.getValue(1));
5522 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5523 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5525 CombineTo(N, NewValue);
5527 // Replace uses of the original load (before extension)
5528 // with a truncate of the concatenated sextloaded vectors.
5530 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5531 CombineTo(N0.getNode(), Trunc, NewChain);
5532 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5533 (ISD::NodeType)N->getOpcode());
5534 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5537 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5538 SDValue N0 = N->getOperand(0);
5539 EVT VT = N->getValueType(0);
5541 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5543 return SDValue(Res, 0);
5545 // fold (sext (sext x)) -> (sext x)
5546 // fold (sext (aext x)) -> (sext x)
5547 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5548 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5551 if (N0.getOpcode() == ISD::TRUNCATE) {
5552 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5553 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5554 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5555 if (NarrowLoad.getNode()) {
5556 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5557 if (NarrowLoad.getNode() != N0.getNode()) {
5558 CombineTo(N0.getNode(), NarrowLoad);
5559 // CombineTo deleted the truncate, if needed, but not what's under it.
5562 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5565 // See if the value being truncated is already sign extended. If so, just
5566 // eliminate the trunc/sext pair.
5567 SDValue Op = N0.getOperand(0);
5568 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5569 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5570 unsigned DestBits = VT.getScalarType().getSizeInBits();
5571 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5573 if (OpBits == DestBits) {
5574 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5575 // bits, it is already ready.
5576 if (NumSignBits > DestBits-MidBits)
5578 } else if (OpBits < DestBits) {
5579 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5580 // bits, just sext from i32.
5581 if (NumSignBits > OpBits-MidBits)
5582 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5584 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5585 // bits, just truncate to i32.
5586 if (NumSignBits > OpBits-MidBits)
5587 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5590 // fold (sext (truncate x)) -> (sextinreg x).
5591 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5592 N0.getValueType())) {
5593 if (OpBits < DestBits)
5594 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5595 else if (OpBits > DestBits)
5596 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5597 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5598 DAG.getValueType(N0.getValueType()));
5602 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5603 // Only generate vector extloads when 1) they're legal, and 2) they are
5604 // deemed desirable by the target.
5605 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5606 ((!LegalOperations && !VT.isVector() &&
5607 !cast<LoadSDNode>(N0)->isVolatile()) ||
5608 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5609 bool DoXform = true;
5610 SmallVector<SDNode*, 4> SetCCs;
5611 if (!N0.hasOneUse())
5612 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5614 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5616 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5617 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5619 LN0->getBasePtr(), N0.getValueType(),
5620 LN0->getMemOperand());
5621 CombineTo(N, ExtLoad);
5622 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5623 N0.getValueType(), ExtLoad);
5624 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5625 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5627 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5631 // fold (sext (load x)) to multiple smaller sextloads.
5632 // Only on illegal but splittable vectors.
5633 if (SDValue ExtLoad = CombineExtLoad(N))
5636 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5637 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5638 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5639 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5640 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5641 EVT MemVT = LN0->getMemoryVT();
5642 if ((!LegalOperations && !LN0->isVolatile()) ||
5643 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5644 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5646 LN0->getBasePtr(), MemVT,
5647 LN0->getMemOperand());
5648 CombineTo(N, ExtLoad);
5649 CombineTo(N0.getNode(),
5650 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5651 N0.getValueType(), ExtLoad),
5652 ExtLoad.getValue(1));
5653 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5657 // fold (sext (and/or/xor (load x), cst)) ->
5658 // (and/or/xor (sextload x), (sext cst))
5659 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5660 N0.getOpcode() == ISD::XOR) &&
5661 isa<LoadSDNode>(N0.getOperand(0)) &&
5662 N0.getOperand(1).getOpcode() == ISD::Constant &&
5663 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5664 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5665 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5666 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5667 bool DoXform = true;
5668 SmallVector<SDNode*, 4> SetCCs;
5669 if (!N0.hasOneUse())
5670 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5673 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5674 LN0->getChain(), LN0->getBasePtr(),
5676 LN0->getMemOperand());
5677 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5678 Mask = Mask.sext(VT.getSizeInBits());
5679 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5680 ExtLoad, DAG.getConstant(Mask, VT));
5681 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5682 SDLoc(N0.getOperand(0)),
5683 N0.getOperand(0).getValueType(), ExtLoad);
5685 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5686 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5688 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5693 if (N0.getOpcode() == ISD::SETCC) {
5694 EVT N0VT = N0.getOperand(0).getValueType();
5695 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5696 // Only do this before legalize for now.
5697 if (VT.isVector() && !LegalOperations &&
5698 TLI.getBooleanContents(N0VT) ==
5699 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5700 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5701 // of the same size as the compared operands. Only optimize sext(setcc())
5702 // if this is the case.
5703 EVT SVT = getSetCCResultType(N0VT);
5705 // We know that the # elements of the results is the same as the
5706 // # elements of the compare (and the # elements of the compare result
5707 // for that matter). Check to see that they are the same size. If so,
5708 // we know that the element size of the sext'd result matches the
5709 // element size of the compare operands.
5710 if (VT.getSizeInBits() == SVT.getSizeInBits())
5711 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5713 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5715 // If the desired elements are smaller or larger than the source
5716 // elements we can use a matching integer vector type and then
5717 // truncate/sign extend
5718 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5719 if (SVT == MatchingVectorType) {
5720 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5721 N0.getOperand(0), N0.getOperand(1),
5722 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5723 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5727 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5728 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5730 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5732 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5733 NegOne, DAG.getConstant(0, VT),
5734 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5735 if (SCC.getNode()) return SCC;
5737 if (!VT.isVector()) {
5738 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5739 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5741 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5742 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5743 N0.getOperand(0), N0.getOperand(1), CC);
5744 return DAG.getSelect(DL, VT, SetCC,
5745 NegOne, DAG.getConstant(0, VT));
5750 // fold (sext x) -> (zext x) if the sign bit is known zero.
5751 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5752 DAG.SignBitIsZero(N0))
5753 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5758 // isTruncateOf - If N is a truncate of some other value, return true, record
5759 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5760 // This function computes KnownZero to avoid a duplicated call to
5761 // computeKnownBits in the caller.
5762 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5765 if (N->getOpcode() == ISD::TRUNCATE) {
5766 Op = N->getOperand(0);
5767 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5771 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5772 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5775 SDValue Op0 = N->getOperand(0);
5776 SDValue Op1 = N->getOperand(1);
5777 assert(Op0.getValueType() == Op1.getValueType());
5779 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5780 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5781 if (COp0 && COp0->isNullValue())
5783 else if (COp1 && COp1->isNullValue())
5788 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5790 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5796 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5797 SDValue N0 = N->getOperand(0);
5798 EVT VT = N->getValueType(0);
5800 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5802 return SDValue(Res, 0);
5804 // fold (zext (zext x)) -> (zext x)
5805 // fold (zext (aext x)) -> (zext x)
5806 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5807 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5810 // fold (zext (truncate x)) -> (zext x) or
5811 // (zext (truncate x)) -> (truncate x)
5812 // This is valid when the truncated bits of x are already zero.
5813 // FIXME: We should extend this to work for vectors too.
5816 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5817 APInt TruncatedBits =
5818 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5819 APInt(Op.getValueSizeInBits(), 0) :
5820 APInt::getBitsSet(Op.getValueSizeInBits(),
5821 N0.getValueSizeInBits(),
5822 std::min(Op.getValueSizeInBits(),
5823 VT.getSizeInBits()));
5824 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5825 if (VT.bitsGT(Op.getValueType()))
5826 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5827 if (VT.bitsLT(Op.getValueType()))
5828 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5834 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5835 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5836 if (N0.getOpcode() == ISD::TRUNCATE) {
5837 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5838 if (NarrowLoad.getNode()) {
5839 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5840 if (NarrowLoad.getNode() != N0.getNode()) {
5841 CombineTo(N0.getNode(), NarrowLoad);
5842 // CombineTo deleted the truncate, if needed, but not what's under it.
5845 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5849 // fold (zext (truncate x)) -> (and x, mask)
5850 if (N0.getOpcode() == ISD::TRUNCATE &&
5851 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5853 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5854 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5855 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5856 if (NarrowLoad.getNode()) {
5857 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5858 if (NarrowLoad.getNode() != N0.getNode()) {
5859 CombineTo(N0.getNode(), NarrowLoad);
5860 // CombineTo deleted the truncate, if needed, but not what's under it.
5863 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5866 SDValue Op = N0.getOperand(0);
5867 if (Op.getValueType().bitsLT(VT)) {
5868 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5869 AddToWorklist(Op.getNode());
5870 } else if (Op.getValueType().bitsGT(VT)) {
5871 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5872 AddToWorklist(Op.getNode());
5874 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5875 N0.getValueType().getScalarType());
5878 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5879 // if either of the casts is not free.
5880 if (N0.getOpcode() == ISD::AND &&
5881 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5882 N0.getOperand(1).getOpcode() == ISD::Constant &&
5883 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5884 N0.getValueType()) ||
5885 !TLI.isZExtFree(N0.getValueType(), VT))) {
5886 SDValue X = N0.getOperand(0).getOperand(0);
5887 if (X.getValueType().bitsLT(VT)) {
5888 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5889 } else if (X.getValueType().bitsGT(VT)) {
5890 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5892 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5893 Mask = Mask.zext(VT.getSizeInBits());
5894 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5895 X, DAG.getConstant(Mask, VT));
5898 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5899 // Only generate vector extloads when 1) they're legal, and 2) they are
5900 // deemed desirable by the target.
5901 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5902 ((!LegalOperations && !VT.isVector() &&
5903 !cast<LoadSDNode>(N0)->isVolatile()) ||
5904 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5905 bool DoXform = true;
5906 SmallVector<SDNode*, 4> SetCCs;
5907 if (!N0.hasOneUse())
5908 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5910 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5912 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5913 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5915 LN0->getBasePtr(), N0.getValueType(),
5916 LN0->getMemOperand());
5917 CombineTo(N, ExtLoad);
5918 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5919 N0.getValueType(), ExtLoad);
5920 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5922 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5924 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5928 // fold (zext (load x)) to multiple smaller zextloads.
5929 // Only on illegal but splittable vectors.
5930 if (SDValue ExtLoad = CombineExtLoad(N))
5933 // fold (zext (and/or/xor (load x), cst)) ->
5934 // (and/or/xor (zextload x), (zext cst))
5935 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5936 N0.getOpcode() == ISD::XOR) &&
5937 isa<LoadSDNode>(N0.getOperand(0)) &&
5938 N0.getOperand(1).getOpcode() == ISD::Constant &&
5939 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5940 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5941 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5942 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5943 bool DoXform = true;
5944 SmallVector<SDNode*, 4> SetCCs;
5945 if (!N0.hasOneUse())
5946 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5949 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5950 LN0->getChain(), LN0->getBasePtr(),
5952 LN0->getMemOperand());
5953 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5954 Mask = Mask.zext(VT.getSizeInBits());
5955 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5956 ExtLoad, DAG.getConstant(Mask, VT));
5957 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5958 SDLoc(N0.getOperand(0)),
5959 N0.getOperand(0).getValueType(), ExtLoad);
5961 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5962 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5964 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5969 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5970 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5971 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5972 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5973 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5974 EVT MemVT = LN0->getMemoryVT();
5975 if ((!LegalOperations && !LN0->isVolatile()) ||
5976 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5977 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5979 LN0->getBasePtr(), MemVT,
5980 LN0->getMemOperand());
5981 CombineTo(N, ExtLoad);
5982 CombineTo(N0.getNode(),
5983 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5985 ExtLoad.getValue(1));
5986 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5990 if (N0.getOpcode() == ISD::SETCC) {
5991 if (!LegalOperations && VT.isVector() &&
5992 N0.getValueType().getVectorElementType() == MVT::i1) {
5993 EVT N0VT = N0.getOperand(0).getValueType();
5994 if (getSetCCResultType(N0VT) == N0.getValueType())
5997 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5998 // Only do this before legalize for now.
5999 EVT EltVT = VT.getVectorElementType();
6000 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6001 DAG.getConstant(1, EltVT));
6002 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6003 // We know that the # elements of the results is the same as the
6004 // # elements of the compare (and the # elements of the compare result
6005 // for that matter). Check to see that they are the same size. If so,
6006 // we know that the element size of the sext'd result matches the
6007 // element size of the compare operands.
6008 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6009 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6011 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6012 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
6015 // If the desired elements are smaller or larger than the source
6016 // elements we can use a matching integer vector type and then
6017 // truncate/sign extend
6018 EVT MatchingElementType =
6019 EVT::getIntegerVT(*DAG.getContext(),
6020 N0VT.getScalarType().getSizeInBits());
6021 EVT MatchingVectorType =
6022 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6023 N0VT.getVectorNumElements());
6025 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6027 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6028 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6029 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
6030 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
6033 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6035 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6036 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6037 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6038 if (SCC.getNode()) return SCC;
6041 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6042 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6043 isa<ConstantSDNode>(N0.getOperand(1)) &&
6044 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6046 SDValue ShAmt = N0.getOperand(1);
6047 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6048 if (N0.getOpcode() == ISD::SHL) {
6049 SDValue InnerZExt = N0.getOperand(0);
6050 // If the original shl may be shifting out bits, do not perform this
6052 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6053 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6054 if (ShAmtVal > KnownZeroBits)
6060 // Ensure that the shift amount is wide enough for the shifted value.
6061 if (VT.getSizeInBits() >= 256)
6062 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6064 return DAG.getNode(N0.getOpcode(), DL, VT,
6065 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6072 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6073 SDValue N0 = N->getOperand(0);
6074 EVT VT = N->getValueType(0);
6076 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6078 return SDValue(Res, 0);
6080 // fold (aext (aext x)) -> (aext x)
6081 // fold (aext (zext x)) -> (zext x)
6082 // fold (aext (sext x)) -> (sext x)
6083 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6084 N0.getOpcode() == ISD::ZERO_EXTEND ||
6085 N0.getOpcode() == ISD::SIGN_EXTEND)
6086 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6088 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6089 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6090 if (N0.getOpcode() == ISD::TRUNCATE) {
6091 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6092 if (NarrowLoad.getNode()) {
6093 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6094 if (NarrowLoad.getNode() != N0.getNode()) {
6095 CombineTo(N0.getNode(), NarrowLoad);
6096 // CombineTo deleted the truncate, if needed, but not what's under it.
6099 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6103 // fold (aext (truncate x))
6104 if (N0.getOpcode() == ISD::TRUNCATE) {
6105 SDValue TruncOp = N0.getOperand(0);
6106 if (TruncOp.getValueType() == VT)
6107 return TruncOp; // x iff x size == zext size.
6108 if (TruncOp.getValueType().bitsGT(VT))
6109 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6110 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6113 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6114 // if the trunc is not free.
6115 if (N0.getOpcode() == ISD::AND &&
6116 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6117 N0.getOperand(1).getOpcode() == ISD::Constant &&
6118 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6119 N0.getValueType())) {
6120 SDValue X = N0.getOperand(0).getOperand(0);
6121 if (X.getValueType().bitsLT(VT)) {
6122 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6123 } else if (X.getValueType().bitsGT(VT)) {
6124 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6126 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6127 Mask = Mask.zext(VT.getSizeInBits());
6128 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6129 X, DAG.getConstant(Mask, VT));
6132 // fold (aext (load x)) -> (aext (truncate (extload x)))
6133 // None of the supported targets knows how to perform load and any_ext
6134 // on vectors in one instruction. We only perform this transformation on
6136 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6137 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6138 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6139 bool DoXform = true;
6140 SmallVector<SDNode*, 4> SetCCs;
6141 if (!N0.hasOneUse())
6142 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6144 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6145 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6147 LN0->getBasePtr(), N0.getValueType(),
6148 LN0->getMemOperand());
6149 CombineTo(N, ExtLoad);
6150 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6151 N0.getValueType(), ExtLoad);
6152 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6153 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6155 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6159 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6160 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6161 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6162 if (N0.getOpcode() == ISD::LOAD &&
6163 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6165 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6166 ISD::LoadExtType ExtType = LN0->getExtensionType();
6167 EVT MemVT = LN0->getMemoryVT();
6168 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6169 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6170 VT, LN0->getChain(), LN0->getBasePtr(),
6171 MemVT, LN0->getMemOperand());
6172 CombineTo(N, ExtLoad);
6173 CombineTo(N0.getNode(),
6174 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6175 N0.getValueType(), ExtLoad),
6176 ExtLoad.getValue(1));
6177 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6181 if (N0.getOpcode() == ISD::SETCC) {
6183 // aext(setcc) -> vsetcc
6184 // aext(setcc) -> truncate(vsetcc)
6185 // aext(setcc) -> aext(vsetcc)
6186 // Only do this before legalize for now.
6187 if (VT.isVector() && !LegalOperations) {
6188 EVT N0VT = N0.getOperand(0).getValueType();
6189 // We know that the # elements of the results is the same as the
6190 // # elements of the compare (and the # elements of the compare result
6191 // for that matter). Check to see that they are the same size. If so,
6192 // we know that the element size of the sext'd result matches the
6193 // element size of the compare operands.
6194 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6195 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6197 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6198 // If the desired elements are smaller or larger than the source
6199 // elements we can use a matching integer vector type and then
6200 // truncate/any extend
6202 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6204 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6206 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6207 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6211 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6213 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6214 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6215 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6223 /// See if the specified operand can be simplified with the knowledge that only
6224 /// the bits specified by Mask are used. If so, return the simpler operand,
6225 /// otherwise return a null SDValue.
6226 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6227 switch (V.getOpcode()) {
6229 case ISD::Constant: {
6230 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6231 assert(CV && "Const value should be ConstSDNode.");
6232 const APInt &CVal = CV->getAPIntValue();
6233 APInt NewVal = CVal & Mask;
6235 return DAG.getConstant(NewVal, V.getValueType());
6240 // If the LHS or RHS don't contribute bits to the or, drop them.
6241 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6242 return V.getOperand(1);
6243 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6244 return V.getOperand(0);
6247 // Only look at single-use SRLs.
6248 if (!V.getNode()->hasOneUse())
6250 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6251 // See if we can recursively simplify the LHS.
6252 unsigned Amt = RHSC->getZExtValue();
6254 // Watch out for shift count overflow though.
6255 if (Amt >= Mask.getBitWidth()) break;
6256 APInt NewMask = Mask << Amt;
6257 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6258 if (SimplifyLHS.getNode())
6259 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6260 SimplifyLHS, V.getOperand(1));
6266 /// If the result of a wider load is shifted to right of N bits and then
6267 /// truncated to a narrower type and where N is a multiple of number of bits of
6268 /// the narrower type, transform it to a narrower load from address + N / num of
6269 /// bits of new type. If the result is to be extended, also fold the extension
6270 /// to form a extending load.
6271 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6272 unsigned Opc = N->getOpcode();
6274 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6275 SDValue N0 = N->getOperand(0);
6276 EVT VT = N->getValueType(0);
6279 // This transformation isn't valid for vector loads.
6283 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6285 if (Opc == ISD::SIGN_EXTEND_INREG) {
6286 ExtType = ISD::SEXTLOAD;
6287 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6288 } else if (Opc == ISD::SRL) {
6289 // Another special-case: SRL is basically zero-extending a narrower value.
6290 ExtType = ISD::ZEXTLOAD;
6292 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6293 if (!N01) return SDValue();
6294 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6295 VT.getSizeInBits() - N01->getZExtValue());
6297 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6300 unsigned EVTBits = ExtVT.getSizeInBits();
6302 // Do not generate loads of non-round integer types since these can
6303 // be expensive (and would be wrong if the type is not byte sized).
6304 if (!ExtVT.isRound())
6308 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6309 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6310 ShAmt = N01->getZExtValue();
6311 // Is the shift amount a multiple of size of VT?
6312 if ((ShAmt & (EVTBits-1)) == 0) {
6313 N0 = N0.getOperand(0);
6314 // Is the load width a multiple of size of VT?
6315 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6319 // At this point, we must have a load or else we can't do the transform.
6320 if (!isa<LoadSDNode>(N0)) return SDValue();
6322 // Because a SRL must be assumed to *need* to zero-extend the high bits
6323 // (as opposed to anyext the high bits), we can't combine the zextload
6324 // lowering of SRL and an sextload.
6325 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6328 // If the shift amount is larger than the input type then we're not
6329 // accessing any of the loaded bytes. If the load was a zextload/extload
6330 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6331 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6336 // If the load is shifted left (and the result isn't shifted back right),
6337 // we can fold the truncate through the shift.
6338 unsigned ShLeftAmt = 0;
6339 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6340 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6341 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6342 ShLeftAmt = N01->getZExtValue();
6343 N0 = N0.getOperand(0);
6347 // If we haven't found a load, we can't narrow it. Don't transform one with
6348 // multiple uses, this would require adding a new load.
6349 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6352 // Don't change the width of a volatile load.
6353 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6354 if (LN0->isVolatile())
6357 // Verify that we are actually reducing a load width here.
6358 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6361 // For the transform to be legal, the load must produce only two values
6362 // (the value loaded and the chain). Don't transform a pre-increment
6363 // load, for example, which produces an extra value. Otherwise the
6364 // transformation is not equivalent, and the downstream logic to replace
6365 // uses gets things wrong.
6366 if (LN0->getNumValues() > 2)
6369 // If the load that we're shrinking is an extload and we're not just
6370 // discarding the extension we can't simply shrink the load. Bail.
6371 // TODO: It would be possible to merge the extensions in some cases.
6372 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6373 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6376 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6379 EVT PtrType = N0.getOperand(1).getValueType();
6381 if (PtrType == MVT::Untyped || PtrType.isExtended())
6382 // It's not possible to generate a constant of extended or untyped type.
6385 // For big endian targets, we need to adjust the offset to the pointer to
6386 // load the correct bytes.
6387 if (TLI.isBigEndian()) {
6388 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6389 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6390 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6393 uint64_t PtrOff = ShAmt / 8;
6394 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6395 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6396 PtrType, LN0->getBasePtr(),
6397 DAG.getConstant(PtrOff, PtrType));
6398 AddToWorklist(NewPtr.getNode());
6401 if (ExtType == ISD::NON_EXTLOAD)
6402 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6403 LN0->getPointerInfo().getWithOffset(PtrOff),
6404 LN0->isVolatile(), LN0->isNonTemporal(),
6405 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6407 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6408 LN0->getPointerInfo().getWithOffset(PtrOff),
6409 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6410 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6412 // Replace the old load's chain with the new load's chain.
6413 WorklistRemover DeadNodes(*this);
6414 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6416 // Shift the result left, if we've swallowed a left shift.
6417 SDValue Result = Load;
6418 if (ShLeftAmt != 0) {
6419 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6420 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6422 // If the shift amount is as large as the result size (but, presumably,
6423 // no larger than the source) then the useful bits of the result are
6424 // zero; we can't simply return the shortened shift, because the result
6425 // of that operation is undefined.
6426 if (ShLeftAmt >= VT.getSizeInBits())
6427 Result = DAG.getConstant(0, VT);
6429 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6430 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6433 // Return the new loaded value.
6437 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6438 SDValue N0 = N->getOperand(0);
6439 SDValue N1 = N->getOperand(1);
6440 EVT VT = N->getValueType(0);
6441 EVT EVT = cast<VTSDNode>(N1)->getVT();
6442 unsigned VTBits = VT.getScalarType().getSizeInBits();
6443 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6445 // fold (sext_in_reg c1) -> c1
6446 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6447 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6449 // If the input is already sign extended, just drop the extension.
6450 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6453 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6454 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6455 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6456 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6457 N0.getOperand(0), N1);
6459 // fold (sext_in_reg (sext x)) -> (sext x)
6460 // fold (sext_in_reg (aext x)) -> (sext x)
6461 // if x is small enough.
6462 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6463 SDValue N00 = N0.getOperand(0);
6464 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6465 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6466 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6469 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6470 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6471 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6473 // fold operands of sext_in_reg based on knowledge that the top bits are not
6475 if (SimplifyDemandedBits(SDValue(N, 0)))
6476 return SDValue(N, 0);
6478 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6479 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6480 SDValue NarrowLoad = ReduceLoadWidth(N);
6481 if (NarrowLoad.getNode())
6484 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6485 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6486 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6487 if (N0.getOpcode() == ISD::SRL) {
6488 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6489 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6490 // We can turn this into an SRA iff the input to the SRL is already sign
6492 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6493 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6494 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6495 N0.getOperand(0), N0.getOperand(1));
6499 // fold (sext_inreg (extload x)) -> (sextload x)
6500 if (ISD::isEXTLoad(N0.getNode()) &&
6501 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6502 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6503 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6504 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6505 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6506 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6508 LN0->getBasePtr(), EVT,
6509 LN0->getMemOperand());
6510 CombineTo(N, ExtLoad);
6511 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6512 AddToWorklist(ExtLoad.getNode());
6513 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6515 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6516 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6518 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6519 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6520 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6521 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6522 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6524 LN0->getBasePtr(), EVT,
6525 LN0->getMemOperand());
6526 CombineTo(N, ExtLoad);
6527 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6528 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6531 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6532 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6533 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6534 N0.getOperand(1), false);
6535 if (BSwap.getNode())
6536 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6540 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6541 // into a build_vector.
6542 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6543 SmallVector<SDValue, 8> Elts;
6544 unsigned NumElts = N0->getNumOperands();
6545 unsigned ShAmt = VTBits - EVTBits;
6547 for (unsigned i = 0; i != NumElts; ++i) {
6548 SDValue Op = N0->getOperand(i);
6549 if (Op->getOpcode() == ISD::UNDEF) {
6554 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6555 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6556 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6557 Op.getValueType()));
6560 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6566 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6567 SDValue N0 = N->getOperand(0);
6568 EVT VT = N->getValueType(0);
6569 bool isLE = TLI.isLittleEndian();
6572 if (N0.getValueType() == N->getValueType(0))
6574 // fold (truncate c1) -> c1
6575 if (isConstantIntBuildVectorOrConstantInt(N0))
6576 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6577 // fold (truncate (truncate x)) -> (truncate x)
6578 if (N0.getOpcode() == ISD::TRUNCATE)
6579 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6580 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6581 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6582 N0.getOpcode() == ISD::SIGN_EXTEND ||
6583 N0.getOpcode() == ISD::ANY_EXTEND) {
6584 if (N0.getOperand(0).getValueType().bitsLT(VT))
6585 // if the source is smaller than the dest, we still need an extend
6586 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6588 if (N0.getOperand(0).getValueType().bitsGT(VT))
6589 // if the source is larger than the dest, than we just need the truncate
6590 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6591 // if the source and dest are the same type, we can drop both the extend
6592 // and the truncate.
6593 return N0.getOperand(0);
6596 // Fold extract-and-trunc into a narrow extract. For example:
6597 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6598 // i32 y = TRUNCATE(i64 x)
6600 // v16i8 b = BITCAST (v2i64 val)
6601 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6603 // Note: We only run this optimization after type legalization (which often
6604 // creates this pattern) and before operation legalization after which
6605 // we need to be more careful about the vector instructions that we generate.
6606 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6607 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6609 EVT VecTy = N0.getOperand(0).getValueType();
6610 EVT ExTy = N0.getValueType();
6611 EVT TrTy = N->getValueType(0);
6613 unsigned NumElem = VecTy.getVectorNumElements();
6614 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6616 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6617 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6619 SDValue EltNo = N0->getOperand(1);
6620 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6621 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6622 EVT IndexTy = TLI.getVectorIdxTy();
6623 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6625 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6626 NVT, N0.getOperand(0));
6628 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6630 DAG.getConstant(Index, IndexTy));
6634 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6635 if (N0.getOpcode() == ISD::SELECT) {
6636 EVT SrcVT = N0.getValueType();
6637 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6638 TLI.isTruncateFree(SrcVT, VT)) {
6640 SDValue Cond = N0.getOperand(0);
6641 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6642 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6643 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6647 // Fold a series of buildvector, bitcast, and truncate if possible.
6649 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6650 // (2xi32 (buildvector x, y)).
6651 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6652 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6653 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6654 N0.getOperand(0).hasOneUse()) {
6656 SDValue BuildVect = N0.getOperand(0);
6657 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6658 EVT TruncVecEltTy = VT.getVectorElementType();
6660 // Check that the element types match.
6661 if (BuildVectEltTy == TruncVecEltTy) {
6662 // Now we only need to compute the offset of the truncated elements.
6663 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6664 unsigned TruncVecNumElts = VT.getVectorNumElements();
6665 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6667 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6668 "Invalid number of elements");
6670 SmallVector<SDValue, 8> Opnds;
6671 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6672 Opnds.push_back(BuildVect.getOperand(i));
6674 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6678 // See if we can simplify the input to this truncate through knowledge that
6679 // only the low bits are being used.
6680 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6681 // Currently we only perform this optimization on scalars because vectors
6682 // may have different active low bits.
6683 if (!VT.isVector()) {
6685 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6686 VT.getSizeInBits()));
6687 if (Shorter.getNode())
6688 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6690 // fold (truncate (load x)) -> (smaller load x)
6691 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6692 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6693 SDValue Reduced = ReduceLoadWidth(N);
6694 if (Reduced.getNode())
6696 // Handle the case where the load remains an extending load even
6697 // after truncation.
6698 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6699 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6700 if (!LN0->isVolatile() &&
6701 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6702 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6703 VT, LN0->getChain(), LN0->getBasePtr(),
6705 LN0->getMemOperand());
6706 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6711 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6712 // where ... are all 'undef'.
6713 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6714 SmallVector<EVT, 8> VTs;
6717 unsigned NumDefs = 0;
6719 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6720 SDValue X = N0.getOperand(i);
6721 if (X.getOpcode() != ISD::UNDEF) {
6726 // Stop if more than one members are non-undef.
6729 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6730 VT.getVectorElementType(),
6731 X.getValueType().getVectorNumElements()));
6735 return DAG.getUNDEF(VT);
6738 assert(V.getNode() && "The single defined operand is empty!");
6739 SmallVector<SDValue, 8> Opnds;
6740 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6742 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6745 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6746 AddToWorklist(NV.getNode());
6747 Opnds.push_back(NV);
6749 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6753 // Simplify the operands using demanded-bits information.
6754 if (!VT.isVector() &&
6755 SimplifyDemandedBits(SDValue(N, 0)))
6756 return SDValue(N, 0);
6761 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6762 SDValue Elt = N->getOperand(i);
6763 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6764 return Elt.getNode();
6765 return Elt.getOperand(Elt.getResNo()).getNode();
6768 /// build_pair (load, load) -> load
6769 /// if load locations are consecutive.
6770 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6771 assert(N->getOpcode() == ISD::BUILD_PAIR);
6773 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6774 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6775 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6776 LD1->getAddressSpace() != LD2->getAddressSpace())
6778 EVT LD1VT = LD1->getValueType(0);
6780 if (ISD::isNON_EXTLoad(LD2) &&
6782 // If both are volatile this would reduce the number of volatile loads.
6783 // If one is volatile it might be ok, but play conservative and bail out.
6784 !LD1->isVolatile() &&
6785 !LD2->isVolatile() &&
6786 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6787 unsigned Align = LD1->getAlignment();
6788 unsigned NewAlign = TLI.getDataLayout()->
6789 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6791 if (NewAlign <= Align &&
6792 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6793 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6794 LD1->getBasePtr(), LD1->getPointerInfo(),
6795 false, false, false, Align);
6801 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6802 SDValue N0 = N->getOperand(0);
6803 EVT VT = N->getValueType(0);
6805 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6806 // Only do this before legalize, since afterward the target may be depending
6807 // on the bitconvert.
6808 // First check to see if this is all constant.
6810 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6812 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6814 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6815 assert(!DestEltVT.isVector() &&
6816 "Element type of vector ValueType must not be vector!");
6818 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6821 // If the input is a constant, let getNode fold it.
6822 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6823 // If we can't allow illegal operations, we need to check that this is just
6824 // a fp -> int or int -> conversion and that the resulting operation will
6826 if (!LegalOperations ||
6827 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6828 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6829 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6830 TLI.isOperationLegal(ISD::Constant, VT)))
6831 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6834 // (conv (conv x, t1), t2) -> (conv x, t2)
6835 if (N0.getOpcode() == ISD::BITCAST)
6836 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6839 // fold (conv (load x)) -> (load (conv*)x)
6840 // If the resultant load doesn't need a higher alignment than the original!
6841 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6842 // Do not change the width of a volatile load.
6843 !cast<LoadSDNode>(N0)->isVolatile() &&
6844 // Do not remove the cast if the types differ in endian layout.
6845 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6846 TLI.hasBigEndianPartOrdering(VT) &&
6847 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6848 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6849 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6850 unsigned Align = TLI.getDataLayout()->
6851 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6852 unsigned OrigAlign = LN0->getAlignment();
6854 if (Align <= OrigAlign) {
6855 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6856 LN0->getBasePtr(), LN0->getPointerInfo(),
6857 LN0->isVolatile(), LN0->isNonTemporal(),
6858 LN0->isInvariant(), OrigAlign,
6860 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6865 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6866 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6867 // This often reduces constant pool loads.
6868 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6869 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6870 N0.getNode()->hasOneUse() && VT.isInteger() &&
6871 !VT.isVector() && !N0.getValueType().isVector()) {
6872 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6874 AddToWorklist(NewConv.getNode());
6876 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6877 if (N0.getOpcode() == ISD::FNEG)
6878 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6879 NewConv, DAG.getConstant(SignBit, VT));
6880 assert(N0.getOpcode() == ISD::FABS);
6881 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6882 NewConv, DAG.getConstant(~SignBit, VT));
6885 // fold (bitconvert (fcopysign cst, x)) ->
6886 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6887 // Note that we don't handle (copysign x, cst) because this can always be
6888 // folded to an fneg or fabs.
6889 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6890 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6891 VT.isInteger() && !VT.isVector()) {
6892 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6893 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6894 if (isTypeLegal(IntXVT)) {
6895 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6896 IntXVT, N0.getOperand(1));
6897 AddToWorklist(X.getNode());
6899 // If X has a different width than the result/lhs, sext it or truncate it.
6900 unsigned VTWidth = VT.getSizeInBits();
6901 if (OrigXWidth < VTWidth) {
6902 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6903 AddToWorklist(X.getNode());
6904 } else if (OrigXWidth > VTWidth) {
6905 // To get the sign bit in the right place, we have to shift it right
6906 // before truncating.
6907 X = DAG.getNode(ISD::SRL, SDLoc(X),
6908 X.getValueType(), X,
6909 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6910 AddToWorklist(X.getNode());
6911 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6912 AddToWorklist(X.getNode());
6915 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6916 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6917 X, DAG.getConstant(SignBit, VT));
6918 AddToWorklist(X.getNode());
6920 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6921 VT, N0.getOperand(0));
6922 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6923 Cst, DAG.getConstant(~SignBit, VT));
6924 AddToWorklist(Cst.getNode());
6926 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6930 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6931 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6932 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6933 if (CombineLD.getNode())
6940 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6941 EVT VT = N->getValueType(0);
6942 return CombineConsecutiveLoads(N, VT);
6945 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6946 /// operands. DstEltVT indicates the destination element value type.
6947 SDValue DAGCombiner::
6948 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6949 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6951 // If this is already the right type, we're done.
6952 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6954 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6955 unsigned DstBitSize = DstEltVT.getSizeInBits();
6957 // If this is a conversion of N elements of one type to N elements of another
6958 // type, convert each element. This handles FP<->INT cases.
6959 if (SrcBitSize == DstBitSize) {
6960 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6961 BV->getValueType(0).getVectorNumElements());
6963 // Due to the FP element handling below calling this routine recursively,
6964 // we can end up with a scalar-to-vector node here.
6965 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6966 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6967 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6968 DstEltVT, BV->getOperand(0)));
6970 SmallVector<SDValue, 8> Ops;
6971 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6972 SDValue Op = BV->getOperand(i);
6973 // If the vector element type is not legal, the BUILD_VECTOR operands
6974 // are promoted and implicitly truncated. Make that explicit here.
6975 if (Op.getValueType() != SrcEltVT)
6976 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6977 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6979 AddToWorklist(Ops.back().getNode());
6981 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6984 // Otherwise, we're growing or shrinking the elements. To avoid having to
6985 // handle annoying details of growing/shrinking FP values, we convert them to
6987 if (SrcEltVT.isFloatingPoint()) {
6988 // Convert the input float vector to a int vector where the elements are the
6990 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6991 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6995 // Now we know the input is an integer vector. If the output is a FP type,
6996 // convert to integer first, then to FP of the right size.
6997 if (DstEltVT.isFloatingPoint()) {
6998 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6999 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7001 // Next, convert to FP elements of the same size.
7002 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7005 // Okay, we know the src/dst types are both integers of differing types.
7006 // Handling growing first.
7007 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7008 if (SrcBitSize < DstBitSize) {
7009 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7011 SmallVector<SDValue, 8> Ops;
7012 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7013 i += NumInputsPerOutput) {
7014 bool isLE = TLI.isLittleEndian();
7015 APInt NewBits = APInt(DstBitSize, 0);
7016 bool EltIsUndef = true;
7017 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7018 // Shift the previously computed bits over.
7019 NewBits <<= SrcBitSize;
7020 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7021 if (Op.getOpcode() == ISD::UNDEF) continue;
7024 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7025 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7029 Ops.push_back(DAG.getUNDEF(DstEltVT));
7031 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
7034 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7035 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7038 // Finally, this must be the case where we are shrinking elements: each input
7039 // turns into multiple outputs.
7040 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7041 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7042 NumOutputsPerInput*BV->getNumOperands());
7043 SmallVector<SDValue, 8> Ops;
7045 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7046 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7047 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7051 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7052 getAPIntValue().zextOrTrunc(SrcBitSize);
7054 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7055 APInt ThisVal = OpVal.trunc(DstBitSize);
7056 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
7057 OpVal = OpVal.lshr(DstBitSize);
7060 // For big endian targets, swap the order of the pieces of each element.
7061 if (TLI.isBigEndian())
7062 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7065 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7068 /// Try to perform FMA combining on a given FADD node.
7069 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7074 SDValue N0 = N->getOperand(0);
7075 SDValue N1 = N->getOperand(1);
7076 EVT VT = N->getValueType(0);
7079 const TargetOptions &Options = DAG.getTarget().Options;
7080 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7081 Options.UnsafeFPMath);
7083 // Floating-point multiply-add with intermediate rounding.
7084 bool HasFMAD = (LegalOperations &&
7085 TLI.isOperationLegal(ISD::FMAD, VT));
7087 // Floating-point multiply-add without intermediate rounding.
7088 bool HasFMA = ((!LegalOperations ||
7089 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7090 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7093 // No valid opcode, do not combine.
7094 if (!HasFMAD && !HasFMA)
7097 // Always prefer FMAD to FMA for precision.
7098 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7099 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7100 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7102 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7103 if (N0.getOpcode() == ISD::FMUL &&
7104 (Aggressive || N0->hasOneUse())) {
7105 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7106 N0.getOperand(0), N0.getOperand(1), N1);
7109 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7110 // Note: Commutes FADD operands.
7111 if (N1.getOpcode() == ISD::FMUL &&
7112 (Aggressive || N1->hasOneUse())) {
7113 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7114 N1.getOperand(0), N1.getOperand(1), N0);
7117 // Look through FP_EXTEND nodes to do more combining.
7118 if (UnsafeFPMath && LookThroughFPExt) {
7119 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7120 if (N0.getOpcode() == ISD::FP_EXTEND) {
7121 SDValue N00 = N0.getOperand(0);
7122 if (N00.getOpcode() == ISD::FMUL)
7123 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7124 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7126 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7127 N00.getOperand(1)), N1);
7130 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7131 // Note: Commutes FADD operands.
7132 if (N1.getOpcode() == ISD::FP_EXTEND) {
7133 SDValue N10 = N1.getOperand(0);
7134 if (N10.getOpcode() == ISD::FMUL)
7135 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7136 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7138 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7139 N10.getOperand(1)), N0);
7143 // More folding opportunities when target permits.
7144 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7145 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7146 if (N0.getOpcode() == PreferredFusedOpcode &&
7147 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7148 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7149 N0.getOperand(0), N0.getOperand(1),
7150 DAG.getNode(PreferredFusedOpcode, SL, VT,
7151 N0.getOperand(2).getOperand(0),
7152 N0.getOperand(2).getOperand(1),
7156 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7157 if (N1->getOpcode() == PreferredFusedOpcode &&
7158 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7159 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7160 N1.getOperand(0), N1.getOperand(1),
7161 DAG.getNode(PreferredFusedOpcode, SL, VT,
7162 N1.getOperand(2).getOperand(0),
7163 N1.getOperand(2).getOperand(1),
7167 if (LookThroughFPExt) {
7168 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7169 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7170 auto FoldFAddFMAFPExtFMul = [&] (
7171 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7172 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7173 DAG.getNode(PreferredFusedOpcode, SL, VT,
7174 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7175 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7178 if (N0.getOpcode() == PreferredFusedOpcode) {
7179 SDValue N02 = N0.getOperand(2);
7180 if (N02.getOpcode() == ISD::FP_EXTEND) {
7181 SDValue N020 = N02.getOperand(0);
7182 if (N020.getOpcode() == ISD::FMUL)
7183 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7184 N020.getOperand(0), N020.getOperand(1),
7189 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7190 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7191 // FIXME: This turns two single-precision and one double-precision
7192 // operation into two double-precision operations, which might not be
7193 // interesting for all targets, especially GPUs.
7194 auto FoldFAddFPExtFMAFMul = [&] (
7195 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7196 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7197 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7198 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7199 DAG.getNode(PreferredFusedOpcode, SL, VT,
7200 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7201 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7204 if (N0.getOpcode() == ISD::FP_EXTEND) {
7205 SDValue N00 = N0.getOperand(0);
7206 if (N00.getOpcode() == PreferredFusedOpcode) {
7207 SDValue N002 = N00.getOperand(2);
7208 if (N002.getOpcode() == ISD::FMUL)
7209 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7210 N002.getOperand(0), N002.getOperand(1),
7215 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7216 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7217 if (N1.getOpcode() == PreferredFusedOpcode) {
7218 SDValue N12 = N1.getOperand(2);
7219 if (N12.getOpcode() == ISD::FP_EXTEND) {
7220 SDValue N120 = N12.getOperand(0);
7221 if (N120.getOpcode() == ISD::FMUL)
7222 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7223 N120.getOperand(0), N120.getOperand(1),
7228 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7229 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7230 // FIXME: This turns two single-precision and one double-precision
7231 // operation into two double-precision operations, which might not be
7232 // interesting for all targets, especially GPUs.
7233 if (N1.getOpcode() == ISD::FP_EXTEND) {
7234 SDValue N10 = N1.getOperand(0);
7235 if (N10.getOpcode() == PreferredFusedOpcode) {
7236 SDValue N102 = N10.getOperand(2);
7237 if (N102.getOpcode() == ISD::FMUL)
7238 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7239 N102.getOperand(0), N102.getOperand(1),
7249 /// Try to perform FMA combining on a given FSUB node.
7250 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7254 SDValue N0 = N->getOperand(0);
7255 SDValue N1 = N->getOperand(1);
7256 EVT VT = N->getValueType(0);
7260 const TargetOptions &Options = DAG.getTarget().Options;
7261 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7262 Options.UnsafeFPMath);
7264 // Floating-point multiply-add with intermediate rounding.
7265 bool HasFMAD = (LegalOperations &&
7266 TLI.isOperationLegal(ISD::FMAD, VT));
7268 // Floating-point multiply-add without intermediate rounding.
7269 bool HasFMA = ((!LegalOperations ||
7270 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7271 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7274 // No valid opcode, do not combine.
7275 if (!HasFMAD && !HasFMA)
7278 // Always prefer FMAD to FMA for precision.
7279 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7280 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7281 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7283 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7284 if (N0.getOpcode() == ISD::FMUL &&
7285 (Aggressive || N0->hasOneUse())) {
7286 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7287 N0.getOperand(0), N0.getOperand(1),
7288 DAG.getNode(ISD::FNEG, SL, VT, N1));
7291 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7292 // Note: Commutes FSUB operands.
7293 if (N1.getOpcode() == ISD::FMUL &&
7294 (Aggressive || N1->hasOneUse()))
7295 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7296 DAG.getNode(ISD::FNEG, SL, VT,
7298 N1.getOperand(1), N0);
7300 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7301 if (N0.getOpcode() == ISD::FNEG &&
7302 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7303 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7304 SDValue N00 = N0.getOperand(0).getOperand(0);
7305 SDValue N01 = N0.getOperand(0).getOperand(1);
7306 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7307 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7308 DAG.getNode(ISD::FNEG, SL, VT, N1));
7311 // Look through FP_EXTEND nodes to do more combining.
7312 if (UnsafeFPMath && LookThroughFPExt) {
7313 // fold (fsub (fpext (fmul x, y)), z)
7314 // -> (fma (fpext x), (fpext y), (fneg z))
7315 if (N0.getOpcode() == ISD::FP_EXTEND) {
7316 SDValue N00 = N0.getOperand(0);
7317 if (N00.getOpcode() == ISD::FMUL)
7318 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7319 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7321 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7323 DAG.getNode(ISD::FNEG, SL, VT, N1));
7326 // fold (fsub x, (fpext (fmul y, z)))
7327 // -> (fma (fneg (fpext y)), (fpext z), x)
7328 // Note: Commutes FSUB operands.
7329 if (N1.getOpcode() == ISD::FP_EXTEND) {
7330 SDValue N10 = N1.getOperand(0);
7331 if (N10.getOpcode() == ISD::FMUL)
7332 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7333 DAG.getNode(ISD::FNEG, SL, VT,
7334 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7335 N10.getOperand(0))),
7336 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7341 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7342 // -> (fneg (fma (fpext x), (fpext y), z))
7343 // Note: This could be removed with appropriate canonicalization of the
7344 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7345 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7346 // from implementing the canonicalization in visitFSUB.
7347 if (N0.getOpcode() == ISD::FP_EXTEND) {
7348 SDValue N00 = N0.getOperand(0);
7349 if (N00.getOpcode() == ISD::FNEG) {
7350 SDValue N000 = N00.getOperand(0);
7351 if (N000.getOpcode() == ISD::FMUL) {
7352 return DAG.getNode(ISD::FNEG, SL, VT,
7353 DAG.getNode(PreferredFusedOpcode, SL, VT,
7354 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7355 N000.getOperand(0)),
7356 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7357 N000.getOperand(1)),
7363 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7364 // -> (fneg (fma (fpext x)), (fpext y), z)
7365 // Note: This could be removed with appropriate canonicalization of the
7366 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7367 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7368 // from implementing the canonicalization in visitFSUB.
7369 if (N0.getOpcode() == ISD::FNEG) {
7370 SDValue N00 = N0.getOperand(0);
7371 if (N00.getOpcode() == ISD::FP_EXTEND) {
7372 SDValue N000 = N00.getOperand(0);
7373 if (N000.getOpcode() == ISD::FMUL) {
7374 return DAG.getNode(ISD::FNEG, SL, VT,
7375 DAG.getNode(PreferredFusedOpcode, SL, VT,
7376 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7377 N000.getOperand(0)),
7378 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7379 N000.getOperand(1)),
7387 // More folding opportunities when target permits.
7388 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7389 // fold (fsub (fma x, y, (fmul u, v)), z)
7390 // -> (fma x, y (fma u, v, (fneg z)))
7391 if (N0.getOpcode() == PreferredFusedOpcode &&
7392 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7393 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7394 N0.getOperand(0), N0.getOperand(1),
7395 DAG.getNode(PreferredFusedOpcode, SL, VT,
7396 N0.getOperand(2).getOperand(0),
7397 N0.getOperand(2).getOperand(1),
7398 DAG.getNode(ISD::FNEG, SL, VT,
7402 // fold (fsub x, (fma y, z, (fmul u, v)))
7403 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7404 if (N1.getOpcode() == PreferredFusedOpcode &&
7405 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7406 SDValue N20 = N1.getOperand(2).getOperand(0);
7407 SDValue N21 = N1.getOperand(2).getOperand(1);
7408 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7409 DAG.getNode(ISD::FNEG, SL, VT,
7412 DAG.getNode(PreferredFusedOpcode, SL, VT,
7413 DAG.getNode(ISD::FNEG, SL, VT, N20),
7418 if (LookThroughFPExt) {
7419 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7420 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7421 if (N0.getOpcode() == PreferredFusedOpcode) {
7422 SDValue N02 = N0.getOperand(2);
7423 if (N02.getOpcode() == ISD::FP_EXTEND) {
7424 SDValue N020 = N02.getOperand(0);
7425 if (N020.getOpcode() == ISD::FMUL)
7426 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7427 N0.getOperand(0), N0.getOperand(1),
7428 DAG.getNode(PreferredFusedOpcode, SL, VT,
7429 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7430 N020.getOperand(0)),
7431 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7432 N020.getOperand(1)),
7433 DAG.getNode(ISD::FNEG, SL, VT,
7438 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7439 // -> (fma (fpext x), (fpext y),
7440 // (fma (fpext u), (fpext v), (fneg z)))
7441 // FIXME: This turns two single-precision and one double-precision
7442 // operation into two double-precision operations, which might not be
7443 // interesting for all targets, especially GPUs.
7444 if (N0.getOpcode() == ISD::FP_EXTEND) {
7445 SDValue N00 = N0.getOperand(0);
7446 if (N00.getOpcode() == PreferredFusedOpcode) {
7447 SDValue N002 = N00.getOperand(2);
7448 if (N002.getOpcode() == ISD::FMUL)
7449 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7450 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7452 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7454 DAG.getNode(PreferredFusedOpcode, SL, VT,
7455 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7456 N002.getOperand(0)),
7457 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7458 N002.getOperand(1)),
7459 DAG.getNode(ISD::FNEG, SL, VT,
7464 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7465 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7466 if (N1.getOpcode() == PreferredFusedOpcode &&
7467 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7468 SDValue N120 = N1.getOperand(2).getOperand(0);
7469 if (N120.getOpcode() == ISD::FMUL) {
7470 SDValue N1200 = N120.getOperand(0);
7471 SDValue N1201 = N120.getOperand(1);
7472 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7473 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7475 DAG.getNode(PreferredFusedOpcode, SL, VT,
7476 DAG.getNode(ISD::FNEG, SL, VT,
7477 DAG.getNode(ISD::FP_EXTEND, SL,
7479 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7485 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7486 // -> (fma (fneg (fpext y)), (fpext z),
7487 // (fma (fneg (fpext u)), (fpext v), x))
7488 // FIXME: This turns two single-precision and one double-precision
7489 // operation into two double-precision operations, which might not be
7490 // interesting for all targets, especially GPUs.
7491 if (N1.getOpcode() == ISD::FP_EXTEND &&
7492 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7493 SDValue N100 = N1.getOperand(0).getOperand(0);
7494 SDValue N101 = N1.getOperand(0).getOperand(1);
7495 SDValue N102 = N1.getOperand(0).getOperand(2);
7496 if (N102.getOpcode() == ISD::FMUL) {
7497 SDValue N1020 = N102.getOperand(0);
7498 SDValue N1021 = N102.getOperand(1);
7499 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7500 DAG.getNode(ISD::FNEG, SL, VT,
7501 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7503 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7504 DAG.getNode(PreferredFusedOpcode, SL, VT,
7505 DAG.getNode(ISD::FNEG, SL, VT,
7506 DAG.getNode(ISD::FP_EXTEND, SL,
7508 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7519 SDValue DAGCombiner::visitFADD(SDNode *N) {
7520 SDValue N0 = N->getOperand(0);
7521 SDValue N1 = N->getOperand(1);
7522 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7523 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7524 EVT VT = N->getValueType(0);
7525 const TargetOptions &Options = DAG.getTarget().Options;
7529 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7532 // fold (fadd c1, c2) -> c1 + c2
7534 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7536 // canonicalize constant to RHS
7537 if (N0CFP && !N1CFP)
7538 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7540 // fold (fadd A, (fneg B)) -> (fsub A, B)
7541 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7542 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7543 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7544 GetNegatedExpression(N1, DAG, LegalOperations));
7546 // fold (fadd (fneg A), B) -> (fsub B, A)
7547 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7548 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7549 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7550 GetNegatedExpression(N0, DAG, LegalOperations));
7552 // If 'unsafe math' is enabled, fold lots of things.
7553 if (Options.UnsafeFPMath) {
7554 // No FP constant should be created after legalization as Instruction
7555 // Selection pass has a hard time dealing with FP constants.
7556 bool AllowNewConst = (Level < AfterLegalizeDAG);
7558 // fold (fadd A, 0) -> A
7559 if (N1CFP && N1CFP->getValueAPF().isZero())
7562 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7563 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7564 isa<ConstantFPSDNode>(N0.getOperand(1)))
7565 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7566 DAG.getNode(ISD::FADD, SDLoc(N), VT,
7567 N0.getOperand(1), N1));
7569 // If allowed, fold (fadd (fneg x), x) -> 0.0
7570 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7571 return DAG.getConstantFP(0.0, VT);
7573 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7574 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7575 return DAG.getConstantFP(0.0, VT);
7577 // We can fold chains of FADD's of the same value into multiplications.
7578 // This transform is not safe in general because we are reducing the number
7579 // of rounding steps.
7580 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7581 if (N0.getOpcode() == ISD::FMUL) {
7582 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7583 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7585 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7586 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7587 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7589 DAG.getConstantFP(1.0, VT));
7590 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7593 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7594 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7595 N1.getOperand(0) == N1.getOperand(1) &&
7596 N0.getOperand(0) == N1.getOperand(0)) {
7597 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7599 DAG.getConstantFP(2.0, VT));
7600 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7601 N0.getOperand(0), NewCFP);
7605 if (N1.getOpcode() == ISD::FMUL) {
7606 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7607 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7609 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7610 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7611 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7613 DAG.getConstantFP(1.0, VT));
7614 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7617 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7618 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7619 N0.getOperand(0) == N0.getOperand(1) &&
7620 N1.getOperand(0) == N0.getOperand(0)) {
7621 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7623 DAG.getConstantFP(2.0, VT));
7624 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7628 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7629 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7630 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7631 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7632 (N0.getOperand(0) == N1))
7633 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7634 N1, DAG.getConstantFP(3.0, VT));
7637 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7638 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7639 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7640 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7641 N1.getOperand(0) == N0)
7642 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7643 N0, DAG.getConstantFP(3.0, VT));
7646 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7647 if (AllowNewConst &&
7648 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7649 N0.getOperand(0) == N0.getOperand(1) &&
7650 N1.getOperand(0) == N1.getOperand(1) &&
7651 N0.getOperand(0) == N1.getOperand(0))
7652 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7653 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7655 } // enable-unsafe-fp-math
7657 // FADD -> FMA combines:
7658 SDValue Fused = visitFADDForFMACombine(N);
7660 AddToWorklist(Fused.getNode());
7667 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7668 SDValue N0 = N->getOperand(0);
7669 SDValue N1 = N->getOperand(1);
7670 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7671 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7672 EVT VT = N->getValueType(0);
7674 const TargetOptions &Options = DAG.getTarget().Options;
7678 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7681 // fold (fsub c1, c2) -> c1-c2
7683 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7685 // fold (fsub A, (fneg B)) -> (fadd A, B)
7686 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7687 return DAG.getNode(ISD::FADD, dl, VT, N0,
7688 GetNegatedExpression(N1, DAG, LegalOperations));
7690 // If 'unsafe math' is enabled, fold lots of things.
7691 if (Options.UnsafeFPMath) {
7693 if (N1CFP && N1CFP->getValueAPF().isZero())
7696 // (fsub 0, B) -> -B
7697 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7698 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7699 return GetNegatedExpression(N1, DAG, LegalOperations);
7700 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7701 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7704 // (fsub x, x) -> 0.0
7706 return DAG.getConstantFP(0.0f, VT);
7708 // (fsub x, (fadd x, y)) -> (fneg y)
7709 // (fsub x, (fadd y, x)) -> (fneg y)
7710 if (N1.getOpcode() == ISD::FADD) {
7711 SDValue N10 = N1->getOperand(0);
7712 SDValue N11 = N1->getOperand(1);
7714 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7715 return GetNegatedExpression(N11, DAG, LegalOperations);
7717 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7718 return GetNegatedExpression(N10, DAG, LegalOperations);
7722 // FSUB -> FMA combines:
7723 SDValue Fused = visitFSUBForFMACombine(N);
7725 AddToWorklist(Fused.getNode());
7732 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7733 SDValue N0 = N->getOperand(0);
7734 SDValue N1 = N->getOperand(1);
7735 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7736 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7737 EVT VT = N->getValueType(0);
7738 const TargetOptions &Options = DAG.getTarget().Options;
7741 if (VT.isVector()) {
7742 // This just handles C1 * C2 for vectors. Other vector folds are below.
7743 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7747 // fold (fmul c1, c2) -> c1*c2
7749 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7751 // canonicalize constant to RHS
7752 if (isConstantFPBuildVectorOrConstantFP(N0) &&
7753 !isConstantFPBuildVectorOrConstantFP(N1))
7754 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7756 // fold (fmul A, 1.0) -> A
7757 if (N1CFP && N1CFP->isExactlyValue(1.0))
7760 if (Options.UnsafeFPMath) {
7761 // fold (fmul A, 0) -> 0
7762 if (N1CFP && N1CFP->getValueAPF().isZero())
7765 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7766 if (N0.getOpcode() == ISD::FMUL) {
7767 // Fold scalars or any vector constants (not just splats).
7768 // This fold is done in general by InstCombine, but extra fmul insts
7769 // may have been generated during lowering.
7770 SDValue N00 = N0.getOperand(0);
7771 SDValue N01 = N0.getOperand(1);
7772 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7773 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7774 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7776 // Check 1: Make sure that the first operand of the inner multiply is NOT
7777 // a constant. Otherwise, we may induce infinite looping.
7778 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7779 // Check 2: Make sure that the second operand of the inner multiply and
7780 // the second operand of the outer multiply are constants.
7781 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7782 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7784 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7785 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7790 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7791 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7792 // during an early run of DAGCombiner can prevent folding with fmuls
7793 // inserted during lowering.
7794 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7796 const SDValue Two = DAG.getConstantFP(2.0, VT);
7797 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7798 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7802 // fold (fmul X, 2.0) -> (fadd X, X)
7803 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7804 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7806 // fold (fmul X, -1.0) -> (fneg X)
7807 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7808 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7809 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7811 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7812 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7813 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7814 // Both can be negated for free, check to see if at least one is cheaper
7816 if (LHSNeg == 2 || RHSNeg == 2)
7817 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7818 GetNegatedExpression(N0, DAG, LegalOperations),
7819 GetNegatedExpression(N1, DAG, LegalOperations));
7826 SDValue DAGCombiner::visitFMA(SDNode *N) {
7827 SDValue N0 = N->getOperand(0);
7828 SDValue N1 = N->getOperand(1);
7829 SDValue N2 = N->getOperand(2);
7830 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7831 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7832 EVT VT = N->getValueType(0);
7834 const TargetOptions &Options = DAG.getTarget().Options;
7836 // Constant fold FMA.
7837 if (isa<ConstantFPSDNode>(N0) &&
7838 isa<ConstantFPSDNode>(N1) &&
7839 isa<ConstantFPSDNode>(N2)) {
7840 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7843 if (Options.UnsafeFPMath) {
7844 if (N0CFP && N0CFP->isZero())
7846 if (N1CFP && N1CFP->isZero())
7849 if (N0CFP && N0CFP->isExactlyValue(1.0))
7850 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7851 if (N1CFP && N1CFP->isExactlyValue(1.0))
7852 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7854 // Canonicalize (fma c, x, y) -> (fma x, c, y)
7855 if (N0CFP && !N1CFP)
7856 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7858 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7859 if (Options.UnsafeFPMath && N1CFP &&
7860 N2.getOpcode() == ISD::FMUL &&
7861 N0 == N2.getOperand(0) &&
7862 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7863 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7864 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7868 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7869 if (Options.UnsafeFPMath &&
7870 N0.getOpcode() == ISD::FMUL && N1CFP &&
7871 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7872 return DAG.getNode(ISD::FMA, dl, VT,
7874 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7878 // (fma x, 1, y) -> (fadd x, y)
7879 // (fma x, -1, y) -> (fadd (fneg x), y)
7881 if (N1CFP->isExactlyValue(1.0))
7882 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7884 if (N1CFP->isExactlyValue(-1.0) &&
7885 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7886 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7887 AddToWorklist(RHSNeg.getNode());
7888 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7892 // (fma x, c, x) -> (fmul x, (c+1))
7893 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7894 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7895 DAG.getNode(ISD::FADD, dl, VT,
7896 N1, DAG.getConstantFP(1.0, VT)));
7898 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7899 if (Options.UnsafeFPMath && N1CFP &&
7900 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7901 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7902 DAG.getNode(ISD::FADD, dl, VT,
7903 N1, DAG.getConstantFP(-1.0, VT)));
7909 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7910 SDValue N0 = N->getOperand(0);
7911 SDValue N1 = N->getOperand(1);
7912 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7913 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7914 EVT VT = N->getValueType(0);
7916 const TargetOptions &Options = DAG.getTarget().Options;
7920 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7923 // fold (fdiv c1, c2) -> c1/c2
7925 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7927 if (Options.UnsafeFPMath) {
7928 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7930 // Compute the reciprocal 1.0 / c2.
7931 APFloat N1APF = N1CFP->getValueAPF();
7932 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7933 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7934 // Only do the transform if the reciprocal is a legal fp immediate that
7935 // isn't too nasty (eg NaN, denormal, ...).
7936 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7937 (!LegalOperations ||
7938 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7939 // backend)... we should handle this gracefully after Legalize.
7940 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7941 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7942 TLI.isFPImmLegal(Recip, VT)))
7943 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7944 DAG.getConstantFP(Recip, VT));
7947 // If this FDIV is part of a reciprocal square root, it may be folded
7948 // into a target-specific square root estimate instruction.
7949 if (N1.getOpcode() == ISD::FSQRT) {
7950 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7951 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7953 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7954 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7955 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7956 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7957 AddToWorklist(RV.getNode());
7958 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7960 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7961 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7962 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7963 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7964 AddToWorklist(RV.getNode());
7965 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7967 } else if (N1.getOpcode() == ISD::FMUL) {
7968 // Look through an FMUL. Even though this won't remove the FDIV directly,
7969 // it's still worthwhile to get rid of the FSQRT if possible.
7972 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7973 SqrtOp = N1.getOperand(0);
7974 OtherOp = N1.getOperand(1);
7975 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7976 SqrtOp = N1.getOperand(1);
7977 OtherOp = N1.getOperand(0);
7979 if (SqrtOp.getNode()) {
7980 // We found a FSQRT, so try to make this fold:
7981 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7982 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7983 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7984 AddToWorklist(RV.getNode());
7985 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7990 // Fold into a reciprocal estimate and multiply instead of a real divide.
7991 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7992 AddToWorklist(RV.getNode());
7993 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7997 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7998 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7999 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8000 // Both can be negated for free, check to see if at least one is cheaper
8002 if (LHSNeg == 2 || RHSNeg == 2)
8003 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8004 GetNegatedExpression(N0, DAG, LegalOperations),
8005 GetNegatedExpression(N1, DAG, LegalOperations));
8009 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8011 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8012 // Notice that this is not always beneficial. One reason is different target
8013 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8014 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8015 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8016 if (Options.UnsafeFPMath) {
8017 // Skip if current node is a reciprocal.
8018 if (N0CFP && N0CFP->isExactlyValue(1.0))
8021 SmallVector<SDNode *, 4> Users;
8022 // Find all FDIV users of the same divisor.
8023 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8024 UE = N1.getNode()->use_end();
8026 SDNode *User = UI.getUse().getUser();
8027 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8028 Users.push_back(User);
8031 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8032 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
8033 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
8035 // Dividend / Divisor -> Dividend * Reciprocal
8036 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8037 if ((*I)->getOperand(0) != FPOne) {
8038 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8039 (*I)->getOperand(0), Reciprocal);
8040 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8050 SDValue DAGCombiner::visitFREM(SDNode *N) {
8051 SDValue N0 = N->getOperand(0);
8052 SDValue N1 = N->getOperand(1);
8053 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8054 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8055 EVT VT = N->getValueType(0);
8057 // fold (frem c1, c2) -> fmod(c1,c2)
8059 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8064 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8065 if (DAG.getTarget().Options.UnsafeFPMath &&
8066 !TLI.isFsqrtCheap()) {
8067 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8068 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8069 EVT VT = RV.getValueType();
8070 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
8071 AddToWorklist(RV.getNode());
8073 // Unfortunately, RV is now NaN if the input was exactly 0.
8074 // Select out this case and force the answer to 0.
8075 SDValue Zero = DAG.getConstantFP(0.0, VT);
8077 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
8078 N->getOperand(0), Zero, ISD::SETEQ);
8079 AddToWorklist(ZeroCmp.getNode());
8080 AddToWorklist(RV.getNode());
8082 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8083 SDLoc(N), VT, ZeroCmp, Zero, RV);
8090 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8091 SDValue N0 = N->getOperand(0);
8092 SDValue N1 = N->getOperand(1);
8093 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8094 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8095 EVT VT = N->getValueType(0);
8097 if (N0CFP && N1CFP) // Constant fold
8098 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8101 const APFloat& V = N1CFP->getValueAPF();
8102 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8103 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8104 if (!V.isNegative()) {
8105 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8106 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8108 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8109 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8110 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8114 // copysign(fabs(x), y) -> copysign(x, y)
8115 // copysign(fneg(x), y) -> copysign(x, y)
8116 // copysign(copysign(x,z), y) -> copysign(x, y)
8117 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8118 N0.getOpcode() == ISD::FCOPYSIGN)
8119 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8120 N0.getOperand(0), N1);
8122 // copysign(x, abs(y)) -> abs(x)
8123 if (N1.getOpcode() == ISD::FABS)
8124 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8126 // copysign(x, copysign(y,z)) -> copysign(x, z)
8127 if (N1.getOpcode() == ISD::FCOPYSIGN)
8128 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8129 N0, N1.getOperand(1));
8131 // copysign(x, fp_extend(y)) -> copysign(x, y)
8132 // copysign(x, fp_round(y)) -> copysign(x, y)
8133 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8134 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8135 N0, N1.getOperand(0));
8140 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8141 SDValue N0 = N->getOperand(0);
8142 EVT VT = N->getValueType(0);
8143 EVT OpVT = N0.getValueType();
8145 // fold (sint_to_fp c1) -> c1fp
8146 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8147 // ...but only if the target supports immediate floating-point values
8148 (!LegalOperations ||
8149 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8150 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8152 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8153 // but UINT_TO_FP is legal on this target, try to convert.
8154 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8155 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8156 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8157 if (DAG.SignBitIsZero(N0))
8158 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8161 // The next optimizations are desirable only if SELECT_CC can be lowered.
8162 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8163 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8164 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8166 (!LegalOperations ||
8167 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8169 { N0.getOperand(0), N0.getOperand(1),
8170 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
8172 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8175 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8176 // (select_cc x, y, 1.0, 0.0,, cc)
8177 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8178 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8179 (!LegalOperations ||
8180 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8182 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8183 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
8184 N0.getOperand(0).getOperand(2) };
8185 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8192 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8193 SDValue N0 = N->getOperand(0);
8194 EVT VT = N->getValueType(0);
8195 EVT OpVT = N0.getValueType();
8197 // fold (uint_to_fp c1) -> c1fp
8198 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8199 // ...but only if the target supports immediate floating-point values
8200 (!LegalOperations ||
8201 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8202 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8204 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8205 // but SINT_TO_FP is legal on this target, try to convert.
8206 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8207 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8208 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8209 if (DAG.SignBitIsZero(N0))
8210 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8213 // The next optimizations are desirable only if SELECT_CC can be lowered.
8214 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8215 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8217 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8218 (!LegalOperations ||
8219 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8221 { N0.getOperand(0), N0.getOperand(1),
8222 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
8224 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8231 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8232 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8233 SDValue N0 = N->getOperand(0);
8234 EVT VT = N->getValueType(0);
8236 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8239 SDValue Src = N0.getOperand(0);
8240 EVT SrcVT = Src.getValueType();
8241 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8242 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8244 // We can safely assume the conversion won't overflow the output range,
8245 // because (for example) (uint8_t)18293.f is undefined behavior.
8247 // Since we can assume the conversion won't overflow, our decision as to
8248 // whether the input will fit in the float should depend on the minimum
8249 // of the input range and output range.
8251 // This means this is also safe for a signed input and unsigned output, since
8252 // a negative input would lead to undefined behavior.
8253 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8254 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8255 unsigned ActualSize = std::min(InputSize, OutputSize);
8256 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8258 // We can only fold away the float conversion if the input range can be
8259 // represented exactly in the float range.
8260 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8261 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8262 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8264 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8266 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8267 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8270 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8275 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8276 SDValue N0 = N->getOperand(0);
8277 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8278 EVT VT = N->getValueType(0);
8280 // fold (fp_to_sint c1fp) -> c1
8282 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8284 return FoldIntToFPToInt(N, DAG);
8287 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8288 SDValue N0 = N->getOperand(0);
8289 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8290 EVT VT = N->getValueType(0);
8292 // fold (fp_to_uint c1fp) -> c1
8294 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8296 return FoldIntToFPToInt(N, DAG);
8299 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8300 SDValue N0 = N->getOperand(0);
8301 SDValue N1 = N->getOperand(1);
8302 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8303 EVT VT = N->getValueType(0);
8305 // fold (fp_round c1fp) -> c1fp
8307 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8309 // fold (fp_round (fp_extend x)) -> x
8310 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8311 return N0.getOperand(0);
8313 // fold (fp_round (fp_round x)) -> (fp_round x)
8314 if (N0.getOpcode() == ISD::FP_ROUND) {
8315 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8316 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8317 // If the first fp_round isn't a value preserving truncation, it might
8318 // introduce a tie in the second fp_round, that wouldn't occur in the
8319 // single-step fp_round we want to fold to.
8320 // In other words, double rounding isn't the same as rounding.
8321 // Also, this is a value preserving truncation iff both fp_round's are.
8322 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8323 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8324 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8327 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8328 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8329 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8330 N0.getOperand(0), N1);
8331 AddToWorklist(Tmp.getNode());
8332 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8333 Tmp, N0.getOperand(1));
8339 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8340 SDValue N0 = N->getOperand(0);
8341 EVT VT = N->getValueType(0);
8342 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8343 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8345 // fold (fp_round_inreg c1fp) -> c1fp
8346 if (N0CFP && isTypeLegal(EVT)) {
8347 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8348 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8354 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8355 SDValue N0 = N->getOperand(0);
8356 EVT VT = N->getValueType(0);
8358 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8359 if (N->hasOneUse() &&
8360 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8363 // fold (fp_extend c1fp) -> c1fp
8364 if (isConstantFPBuildVectorOrConstantFP(N0))
8365 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8367 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8368 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8369 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8370 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8372 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8374 if (N0.getOpcode() == ISD::FP_ROUND
8375 && N0.getNode()->getConstantOperandVal(1) == 1) {
8376 SDValue In = N0.getOperand(0);
8377 if (In.getValueType() == VT) return In;
8378 if (VT.bitsLT(In.getValueType()))
8379 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8380 In, N0.getOperand(1));
8381 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8384 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8385 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8386 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8387 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8388 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8390 LN0->getBasePtr(), N0.getValueType(),
8391 LN0->getMemOperand());
8392 CombineTo(N, ExtLoad);
8393 CombineTo(N0.getNode(),
8394 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8395 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8396 ExtLoad.getValue(1));
8397 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8403 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8404 SDValue N0 = N->getOperand(0);
8405 EVT VT = N->getValueType(0);
8407 // fold (fceil c1) -> fceil(c1)
8408 if (isConstantFPBuildVectorOrConstantFP(N0))
8409 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8414 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8415 SDValue N0 = N->getOperand(0);
8416 EVT VT = N->getValueType(0);
8418 // fold (ftrunc c1) -> ftrunc(c1)
8419 if (isConstantFPBuildVectorOrConstantFP(N0))
8420 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8425 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8426 SDValue N0 = N->getOperand(0);
8427 EVT VT = N->getValueType(0);
8429 // fold (ffloor c1) -> ffloor(c1)
8430 if (isConstantFPBuildVectorOrConstantFP(N0))
8431 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8436 // FIXME: FNEG and FABS have a lot in common; refactor.
8437 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8438 SDValue N0 = N->getOperand(0);
8439 EVT VT = N->getValueType(0);
8441 // Constant fold FNEG.
8442 if (isConstantFPBuildVectorOrConstantFP(N0))
8443 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8445 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8446 &DAG.getTarget().Options))
8447 return GetNegatedExpression(N0, DAG, LegalOperations);
8449 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8450 // constant pool values.
8451 if (!TLI.isFNegFree(VT) &&
8452 N0.getOpcode() == ISD::BITCAST &&
8453 N0.getNode()->hasOneUse()) {
8454 SDValue Int = N0.getOperand(0);
8455 EVT IntVT = Int.getValueType();
8456 if (IntVT.isInteger() && !IntVT.isVector()) {
8458 if (N0.getValueType().isVector()) {
8459 // For a vector, get a mask such as 0x80... per scalar element
8461 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8462 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8464 // For a scalar, just generate 0x80...
8465 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8467 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8468 DAG.getConstant(SignMask, IntVT));
8469 AddToWorklist(Int.getNode());
8470 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8474 // (fneg (fmul c, x)) -> (fmul -c, x)
8475 if (N0.getOpcode() == ISD::FMUL) {
8476 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8478 APFloat CVal = CFP1->getValueAPF();
8480 if (Level >= AfterLegalizeDAG &&
8481 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8482 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8484 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8485 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8492 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8493 SDValue N0 = N->getOperand(0);
8494 SDValue N1 = N->getOperand(1);
8495 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8496 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8498 if (N0CFP && N1CFP) {
8499 const APFloat &C0 = N0CFP->getValueAPF();
8500 const APFloat &C1 = N1CFP->getValueAPF();
8501 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8505 EVT VT = N->getValueType(0);
8506 // Canonicalize to constant on RHS.
8507 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8513 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8514 SDValue N0 = N->getOperand(0);
8515 SDValue N1 = N->getOperand(1);
8516 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8517 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8519 if (N0CFP && N1CFP) {
8520 const APFloat &C0 = N0CFP->getValueAPF();
8521 const APFloat &C1 = N1CFP->getValueAPF();
8522 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8526 EVT VT = N->getValueType(0);
8527 // Canonicalize to constant on RHS.
8528 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8534 SDValue DAGCombiner::visitFABS(SDNode *N) {
8535 SDValue N0 = N->getOperand(0);
8536 EVT VT = N->getValueType(0);
8538 // fold (fabs c1) -> fabs(c1)
8539 if (isConstantFPBuildVectorOrConstantFP(N0))
8540 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8542 // fold (fabs (fabs x)) -> (fabs x)
8543 if (N0.getOpcode() == ISD::FABS)
8544 return N->getOperand(0);
8546 // fold (fabs (fneg x)) -> (fabs x)
8547 // fold (fabs (fcopysign x, y)) -> (fabs x)
8548 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8549 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8551 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8552 // constant pool values.
8553 if (!TLI.isFAbsFree(VT) &&
8554 N0.getOpcode() == ISD::BITCAST &&
8555 N0.getNode()->hasOneUse()) {
8556 SDValue Int = N0.getOperand(0);
8557 EVT IntVT = Int.getValueType();
8558 if (IntVT.isInteger() && !IntVT.isVector()) {
8560 if (N0.getValueType().isVector()) {
8561 // For a vector, get a mask such as 0x7f... per scalar element
8563 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8564 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8566 // For a scalar, just generate 0x7f...
8567 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8569 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8570 DAG.getConstant(SignMask, IntVT));
8571 AddToWorklist(Int.getNode());
8572 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8579 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8580 SDValue Chain = N->getOperand(0);
8581 SDValue N1 = N->getOperand(1);
8582 SDValue N2 = N->getOperand(2);
8584 // If N is a constant we could fold this into a fallthrough or unconditional
8585 // branch. However that doesn't happen very often in normal code, because
8586 // Instcombine/SimplifyCFG should have handled the available opportunities.
8587 // If we did this folding here, it would be necessary to update the
8588 // MachineBasicBlock CFG, which is awkward.
8590 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8592 if (N1.getOpcode() == ISD::SETCC &&
8593 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8594 N1.getOperand(0).getValueType())) {
8595 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8596 Chain, N1.getOperand(2),
8597 N1.getOperand(0), N1.getOperand(1), N2);
8600 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8601 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8602 (N1.getOperand(0).hasOneUse() &&
8603 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8604 SDNode *Trunc = nullptr;
8605 if (N1.getOpcode() == ISD::TRUNCATE) {
8606 // Look pass the truncate.
8607 Trunc = N1.getNode();
8608 N1 = N1.getOperand(0);
8611 // Match this pattern so that we can generate simpler code:
8614 // %b = and i32 %a, 2
8615 // %c = srl i32 %b, 1
8616 // brcond i32 %c ...
8621 // %b = and i32 %a, 2
8622 // %c = setcc eq %b, 0
8625 // This applies only when the AND constant value has one bit set and the
8626 // SRL constant is equal to the log2 of the AND constant. The back-end is
8627 // smart enough to convert the result into a TEST/JMP sequence.
8628 SDValue Op0 = N1.getOperand(0);
8629 SDValue Op1 = N1.getOperand(1);
8631 if (Op0.getOpcode() == ISD::AND &&
8632 Op1.getOpcode() == ISD::Constant) {
8633 SDValue AndOp1 = Op0.getOperand(1);
8635 if (AndOp1.getOpcode() == ISD::Constant) {
8636 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8638 if (AndConst.isPowerOf2() &&
8639 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8641 DAG.getSetCC(SDLoc(N),
8642 getSetCCResultType(Op0.getValueType()),
8643 Op0, DAG.getConstant(0, Op0.getValueType()),
8646 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8647 MVT::Other, Chain, SetCC, N2);
8648 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8649 // will convert it back to (X & C1) >> C2.
8650 CombineTo(N, NewBRCond, false);
8651 // Truncate is dead.
8653 deleteAndRecombine(Trunc);
8654 // Replace the uses of SRL with SETCC
8655 WorklistRemover DeadNodes(*this);
8656 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8657 deleteAndRecombine(N1.getNode());
8658 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8664 // Restore N1 if the above transformation doesn't match.
8665 N1 = N->getOperand(1);
8668 // Transform br(xor(x, y)) -> br(x != y)
8669 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8670 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8671 SDNode *TheXor = N1.getNode();
8672 SDValue Op0 = TheXor->getOperand(0);
8673 SDValue Op1 = TheXor->getOperand(1);
8674 if (Op0.getOpcode() == Op1.getOpcode()) {
8675 // Avoid missing important xor optimizations.
8676 SDValue Tmp = visitXOR(TheXor);
8677 if (Tmp.getNode()) {
8678 if (Tmp.getNode() != TheXor) {
8679 DEBUG(dbgs() << "\nReplacing.8 ";
8681 dbgs() << "\nWith: ";
8682 Tmp.getNode()->dump(&DAG);
8684 WorklistRemover DeadNodes(*this);
8685 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8686 deleteAndRecombine(TheXor);
8687 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8688 MVT::Other, Chain, Tmp, N2);
8691 // visitXOR has changed XOR's operands or replaced the XOR completely,
8693 return SDValue(N, 0);
8697 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8699 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8700 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8701 Op0.getOpcode() == ISD::XOR) {
8702 TheXor = Op0.getNode();
8706 EVT SetCCVT = N1.getValueType();
8708 SetCCVT = getSetCCResultType(SetCCVT);
8709 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8712 Equal ? ISD::SETEQ : ISD::SETNE);
8713 // Replace the uses of XOR with SETCC
8714 WorklistRemover DeadNodes(*this);
8715 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8716 deleteAndRecombine(N1.getNode());
8717 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8718 MVT::Other, Chain, SetCC, N2);
8725 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8727 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8728 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8729 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8731 // If N is a constant we could fold this into a fallthrough or unconditional
8732 // branch. However that doesn't happen very often in normal code, because
8733 // Instcombine/SimplifyCFG should have handled the available opportunities.
8734 // If we did this folding here, it would be necessary to update the
8735 // MachineBasicBlock CFG, which is awkward.
8737 // Use SimplifySetCC to simplify SETCC's.
8738 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8739 CondLHS, CondRHS, CC->get(), SDLoc(N),
8741 if (Simp.getNode()) AddToWorklist(Simp.getNode());
8743 // fold to a simpler setcc
8744 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8745 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8746 N->getOperand(0), Simp.getOperand(2),
8747 Simp.getOperand(0), Simp.getOperand(1),
8753 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8754 /// and that N may be folded in the load / store addressing mode.
8755 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8757 const TargetLowering &TLI) {
8759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8760 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8762 VT = Use->getValueType(0);
8763 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8764 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8766 VT = ST->getValue().getValueType();
8770 TargetLowering::AddrMode AM;
8771 if (N->getOpcode() == ISD::ADD) {
8772 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8775 AM.BaseOffs = Offset->getSExtValue();
8779 } else if (N->getOpcode() == ISD::SUB) {
8780 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8783 AM.BaseOffs = -Offset->getSExtValue();
8790 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8793 /// Try turning a load/store into a pre-indexed load/store when the base
8794 /// pointer is an add or subtract and it has other uses besides the load/store.
8795 /// After the transformation, the new indexed load/store has effectively folded
8796 /// the add/subtract in and all of its other uses are redirected to the
8798 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8799 if (Level < AfterLegalizeDAG)
8805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8806 if (LD->isIndexed())
8808 VT = LD->getMemoryVT();
8809 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8810 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8812 Ptr = LD->getBasePtr();
8813 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8814 if (ST->isIndexed())
8816 VT = ST->getMemoryVT();
8817 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8818 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8820 Ptr = ST->getBasePtr();
8826 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8827 // out. There is no reason to make this a preinc/predec.
8828 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8829 Ptr.getNode()->hasOneUse())
8832 // Ask the target to do addressing mode selection.
8835 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8836 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8839 // Backends without true r+i pre-indexed forms may need to pass a
8840 // constant base with a variable offset so that constant coercion
8841 // will work with the patterns in canonical form.
8842 bool Swapped = false;
8843 if (isa<ConstantSDNode>(BasePtr)) {
8844 std::swap(BasePtr, Offset);
8848 // Don't create a indexed load / store with zero offset.
8849 if (isa<ConstantSDNode>(Offset) &&
8850 cast<ConstantSDNode>(Offset)->isNullValue())
8853 // Try turning it into a pre-indexed load / store except when:
8854 // 1) The new base ptr is a frame index.
8855 // 2) If N is a store and the new base ptr is either the same as or is a
8856 // predecessor of the value being stored.
8857 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8858 // that would create a cycle.
8859 // 4) All uses are load / store ops that use it as old base ptr.
8861 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8862 // (plus the implicit offset) to a register to preinc anyway.
8863 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8868 SDValue Val = cast<StoreSDNode>(N)->getValue();
8869 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8873 // If the offset is a constant, there may be other adds of constants that
8874 // can be folded with this one. We should do this to avoid having to keep
8875 // a copy of the original base pointer.
8876 SmallVector<SDNode *, 16> OtherUses;
8877 if (isa<ConstantSDNode>(Offset))
8878 for (SDNode *Use : BasePtr.getNode()->uses()) {
8879 if (Use == Ptr.getNode())
8882 if (Use->isPredecessorOf(N))
8885 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8890 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8891 if (Op1.getNode() == BasePtr.getNode())
8892 std::swap(Op0, Op1);
8893 assert(Op0.getNode() == BasePtr.getNode() &&
8894 "Use of ADD/SUB but not an operand");
8896 if (!isa<ConstantSDNode>(Op1)) {
8901 // FIXME: In some cases, we can be smarter about this.
8902 if (Op1.getValueType() != Offset.getValueType()) {
8907 OtherUses.push_back(Use);
8911 std::swap(BasePtr, Offset);
8913 // Now check for #3 and #4.
8914 bool RealUse = false;
8916 // Caches for hasPredecessorHelper
8917 SmallPtrSet<const SDNode *, 32> Visited;
8918 SmallVector<const SDNode *, 16> Worklist;
8920 for (SDNode *Use : Ptr.getNode()->uses()) {
8923 if (N->hasPredecessorHelper(Use, Visited, Worklist))
8926 // If Ptr may be folded in addressing mode of other use, then it's
8927 // not profitable to do this transformation.
8928 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8937 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8938 BasePtr, Offset, AM);
8940 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8941 BasePtr, Offset, AM);
8944 DEBUG(dbgs() << "\nReplacing.4 ";
8946 dbgs() << "\nWith: ";
8947 Result.getNode()->dump(&DAG);
8949 WorklistRemover DeadNodes(*this);
8951 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8952 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8954 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8957 // Finally, since the node is now dead, remove it from the graph.
8958 deleteAndRecombine(N);
8961 std::swap(BasePtr, Offset);
8963 // Replace other uses of BasePtr that can be updated to use Ptr
8964 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8965 unsigned OffsetIdx = 1;
8966 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8968 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8969 BasePtr.getNode() && "Expected BasePtr operand");
8971 // We need to replace ptr0 in the following expression:
8972 // x0 * offset0 + y0 * ptr0 = t0
8974 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8976 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8977 // indexed load/store and the expresion that needs to be re-written.
8979 // Therefore, we have:
8980 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8982 ConstantSDNode *CN =
8983 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8985 APInt Offset0 = CN->getAPIntValue();
8986 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8988 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8989 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8990 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8991 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8993 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8995 APInt CNV = Offset0;
8996 if (X0 < 0) CNV = -CNV;
8997 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8998 else CNV = CNV - Offset1;
9000 // We can now generate the new expression.
9001 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
9002 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9004 SDValue NewUse = DAG.getNode(Opcode,
9005 SDLoc(OtherUses[i]),
9006 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9007 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9008 deleteAndRecombine(OtherUses[i]);
9011 // Replace the uses of Ptr with uses of the updated base value.
9012 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9013 deleteAndRecombine(Ptr.getNode());
9018 /// Try to combine a load/store with a add/sub of the base pointer node into a
9019 /// post-indexed load/store. The transformation folded the add/subtract into the
9020 /// new indexed load/store effectively and all of its uses are redirected to the
9022 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9023 if (Level < AfterLegalizeDAG)
9029 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9030 if (LD->isIndexed())
9032 VT = LD->getMemoryVT();
9033 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9034 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9036 Ptr = LD->getBasePtr();
9037 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9038 if (ST->isIndexed())
9040 VT = ST->getMemoryVT();
9041 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9042 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9044 Ptr = ST->getBasePtr();
9050 if (Ptr.getNode()->hasOneUse())
9053 for (SDNode *Op : Ptr.getNode()->uses()) {
9055 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9060 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9061 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9062 // Don't create a indexed load / store with zero offset.
9063 if (isa<ConstantSDNode>(Offset) &&
9064 cast<ConstantSDNode>(Offset)->isNullValue())
9067 // Try turning it into a post-indexed load / store except when
9068 // 1) All uses are load / store ops that use it as base ptr (and
9069 // it may be folded as addressing mmode).
9070 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9071 // nor a successor of N. Otherwise, if Op is folded that would
9074 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9078 bool TryNext = false;
9079 for (SDNode *Use : BasePtr.getNode()->uses()) {
9080 if (Use == Ptr.getNode())
9083 // If all the uses are load / store addresses, then don't do the
9085 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9086 bool RealUse = false;
9087 for (SDNode *UseUse : Use->uses()) {
9088 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9103 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9104 SDValue Result = isLoad
9105 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9106 BasePtr, Offset, AM)
9107 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9108 BasePtr, Offset, AM);
9111 DEBUG(dbgs() << "\nReplacing.5 ";
9113 dbgs() << "\nWith: ";
9114 Result.getNode()->dump(&DAG);
9116 WorklistRemover DeadNodes(*this);
9118 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9119 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9121 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9124 // Finally, since the node is now dead, remove it from the graph.
9125 deleteAndRecombine(N);
9127 // Replace the uses of Use with uses of the updated base value.
9128 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9129 Result.getValue(isLoad ? 1 : 0));
9130 deleteAndRecombine(Op);
9139 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9140 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9141 ISD::MemIndexedMode AM = LD->getAddressingMode();
9142 assert(AM != ISD::UNINDEXED);
9143 SDValue BP = LD->getOperand(1);
9144 SDValue Inc = LD->getOperand(2);
9146 // Some backends use TargetConstants for load offsets, but don't expect
9147 // TargetConstants in general ADD nodes. We can convert these constants into
9148 // regular Constants (if the constant is not opaque).
9149 assert((Inc.getOpcode() != ISD::TargetConstant ||
9150 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9151 "Cannot split out indexing using opaque target constants");
9152 if (Inc.getOpcode() == ISD::TargetConstant) {
9153 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9154 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
9155 ConstInc->getValueType(0));
9159 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9160 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9163 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9164 LoadSDNode *LD = cast<LoadSDNode>(N);
9165 SDValue Chain = LD->getChain();
9166 SDValue Ptr = LD->getBasePtr();
9168 // If load is not volatile and there are no uses of the loaded value (and
9169 // the updated indexed value in case of indexed loads), change uses of the
9170 // chain value into uses of the chain input (i.e. delete the dead load).
9171 if (!LD->isVolatile()) {
9172 if (N->getValueType(1) == MVT::Other) {
9174 if (!N->hasAnyUseOfValue(0)) {
9175 // It's not safe to use the two value CombineTo variant here. e.g.
9176 // v1, chain2 = load chain1, loc
9177 // v2, chain3 = load chain2, loc
9179 // Now we replace use of chain2 with chain1. This makes the second load
9180 // isomorphic to the one we are deleting, and thus makes this load live.
9181 DEBUG(dbgs() << "\nReplacing.6 ";
9183 dbgs() << "\nWith chain: ";
9184 Chain.getNode()->dump(&DAG);
9186 WorklistRemover DeadNodes(*this);
9187 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9190 deleteAndRecombine(N);
9192 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9196 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9198 // If this load has an opaque TargetConstant offset, then we cannot split
9199 // the indexing into an add/sub directly (that TargetConstant may not be
9200 // valid for a different type of node, and we cannot convert an opaque
9201 // target constant into a regular constant).
9202 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9203 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9205 if (!N->hasAnyUseOfValue(0) &&
9206 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9207 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9209 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9210 Index = SplitIndexingFromLoad(LD);
9211 // Try to fold the base pointer arithmetic into subsequent loads and
9213 AddUsersToWorklist(N);
9215 Index = DAG.getUNDEF(N->getValueType(1));
9216 DEBUG(dbgs() << "\nReplacing.7 ";
9218 dbgs() << "\nWith: ";
9219 Undef.getNode()->dump(&DAG);
9220 dbgs() << " and 2 other values\n");
9221 WorklistRemover DeadNodes(*this);
9222 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9223 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9224 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9225 deleteAndRecombine(N);
9226 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9231 // If this load is directly stored, replace the load value with the stored
9233 // TODO: Handle store large -> read small portion.
9234 // TODO: Handle TRUNCSTORE/LOADEXT
9235 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9236 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9237 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9238 if (PrevST->getBasePtr() == Ptr &&
9239 PrevST->getValue().getValueType() == N->getValueType(0))
9240 return CombineTo(N, Chain.getOperand(1), Chain);
9244 // Try to infer better alignment information than the load already has.
9245 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9246 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9247 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9249 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9250 LD->getValueType(0),
9251 Chain, Ptr, LD->getPointerInfo(),
9253 LD->isVolatile(), LD->isNonTemporal(),
9254 LD->isInvariant(), Align, LD->getAAInfo());
9255 if (NewLoad.getNode() != N)
9256 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9261 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9262 : DAG.getSubtarget().useAA();
9264 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9265 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9268 if (UseAA && LD->isUnindexed()) {
9269 // Walk up chain skipping non-aliasing memory nodes.
9270 SDValue BetterChain = FindBetterChain(N, Chain);
9272 // If there is a better chain.
9273 if (Chain != BetterChain) {
9276 // Replace the chain to void dependency.
9277 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9278 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9279 BetterChain, Ptr, LD->getMemOperand());
9281 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9282 LD->getValueType(0),
9283 BetterChain, Ptr, LD->getMemoryVT(),
9284 LD->getMemOperand());
9287 // Create token factor to keep old chain connected.
9288 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9289 MVT::Other, Chain, ReplLoad.getValue(1));
9291 // Make sure the new and old chains are cleaned up.
9292 AddToWorklist(Token.getNode());
9294 // Replace uses with load result and token factor. Don't add users
9296 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9300 // Try transforming N to an indexed load.
9301 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9302 return SDValue(N, 0);
9304 // Try to slice up N to more direct loads if the slices are mapped to
9305 // different register banks or pairing can take place.
9307 return SDValue(N, 0);
9313 /// \brief Helper structure used to slice a load in smaller loads.
9314 /// Basically a slice is obtained from the following sequence:
9315 /// Origin = load Ty1, Base
9316 /// Shift = srl Ty1 Origin, CstTy Amount
9317 /// Inst = trunc Shift to Ty2
9319 /// Then, it will be rewriten into:
9320 /// Slice = load SliceTy, Base + SliceOffset
9321 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9323 /// SliceTy is deduced from the number of bits that are actually used to
9325 struct LoadedSlice {
9326 /// \brief Helper structure used to compute the cost of a slice.
9328 /// Are we optimizing for code size.
9333 unsigned CrossRegisterBanksCopies;
9337 Cost(bool ForCodeSize = false)
9338 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9339 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9341 /// \brief Get the cost of one isolated slice.
9342 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9343 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9344 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9345 EVT TruncType = LS.Inst->getValueType(0);
9346 EVT LoadedType = LS.getLoadedType();
9347 if (TruncType != LoadedType &&
9348 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9352 /// \brief Account for slicing gain in the current cost.
9353 /// Slicing provide a few gains like removing a shift or a
9354 /// truncate. This method allows to grow the cost of the original
9355 /// load with the gain from this slice.
9356 void addSliceGain(const LoadedSlice &LS) {
9357 // Each slice saves a truncate.
9358 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9359 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9360 LS.Inst->getOperand(0).getValueType()))
9362 // If there is a shift amount, this slice gets rid of it.
9365 // If this slice can merge a cross register bank copy, account for it.
9366 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9367 ++CrossRegisterBanksCopies;
9370 Cost &operator+=(const Cost &RHS) {
9372 Truncates += RHS.Truncates;
9373 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9379 bool operator==(const Cost &RHS) const {
9380 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9381 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9382 ZExts == RHS.ZExts && Shift == RHS.Shift;
9385 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9387 bool operator<(const Cost &RHS) const {
9388 // Assume cross register banks copies are as expensive as loads.
9389 // FIXME: Do we want some more target hooks?
9390 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9391 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9392 // Unless we are optimizing for code size, consider the
9393 // expensive operation first.
9394 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9395 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9396 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9397 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9400 bool operator>(const Cost &RHS) const { return RHS < *this; }
9402 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9404 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9406 // The last instruction that represent the slice. This should be a
9407 // truncate instruction.
9409 // The original load instruction.
9411 // The right shift amount in bits from the original load.
9413 // The DAG from which Origin came from.
9414 // This is used to get some contextual information about legal types, etc.
9417 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9418 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9419 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9421 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9422 /// \return Result is \p BitWidth and has used bits set to 1 and
9423 /// not used bits set to 0.
9424 APInt getUsedBits() const {
9425 // Reproduce the trunc(lshr) sequence:
9426 // - Start from the truncated value.
9427 // - Zero extend to the desired bit width.
9429 assert(Origin && "No original load to compare against.");
9430 unsigned BitWidth = Origin->getValueSizeInBits(0);
9431 assert(Inst && "This slice is not bound to an instruction");
9432 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9433 "Extracted slice is bigger than the whole type!");
9434 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9435 UsedBits.setAllBits();
9436 UsedBits = UsedBits.zext(BitWidth);
9441 /// \brief Get the size of the slice to be loaded in bytes.
9442 unsigned getLoadedSize() const {
9443 unsigned SliceSize = getUsedBits().countPopulation();
9444 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9445 return SliceSize / 8;
9448 /// \brief Get the type that will be loaded for this slice.
9449 /// Note: This may not be the final type for the slice.
9450 EVT getLoadedType() const {
9451 assert(DAG && "Missing context");
9452 LLVMContext &Ctxt = *DAG->getContext();
9453 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9456 /// \brief Get the alignment of the load used for this slice.
9457 unsigned getAlignment() const {
9458 unsigned Alignment = Origin->getAlignment();
9459 unsigned Offset = getOffsetFromBase();
9461 Alignment = MinAlign(Alignment, Alignment + Offset);
9465 /// \brief Check if this slice can be rewritten with legal operations.
9466 bool isLegal() const {
9467 // An invalid slice is not legal.
9468 if (!Origin || !Inst || !DAG)
9471 // Offsets are for indexed load only, we do not handle that.
9472 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9475 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9477 // Check that the type is legal.
9478 EVT SliceType = getLoadedType();
9479 if (!TLI.isTypeLegal(SliceType))
9482 // Check that the load is legal for this type.
9483 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9486 // Check that the offset can be computed.
9487 // 1. Check its type.
9488 EVT PtrType = Origin->getBasePtr().getValueType();
9489 if (PtrType == MVT::Untyped || PtrType.isExtended())
9492 // 2. Check that it fits in the immediate.
9493 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9496 // 3. Check that the computation is legal.
9497 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9500 // Check that the zext is legal if it needs one.
9501 EVT TruncateType = Inst->getValueType(0);
9502 if (TruncateType != SliceType &&
9503 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9509 /// \brief Get the offset in bytes of this slice in the original chunk of
9511 /// \pre DAG != nullptr.
9512 uint64_t getOffsetFromBase() const {
9513 assert(DAG && "Missing context.");
9515 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9516 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9517 uint64_t Offset = Shift / 8;
9518 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9519 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9520 "The size of the original loaded type is not a multiple of a"
9522 // If Offset is bigger than TySizeInBytes, it means we are loading all
9523 // zeros. This should have been optimized before in the process.
9524 assert(TySizeInBytes > Offset &&
9525 "Invalid shift amount for given loaded size");
9527 Offset = TySizeInBytes - Offset - getLoadedSize();
9531 /// \brief Generate the sequence of instructions to load the slice
9532 /// represented by this object and redirect the uses of this slice to
9533 /// this new sequence of instructions.
9534 /// \pre this->Inst && this->Origin are valid Instructions and this
9535 /// object passed the legal check: LoadedSlice::isLegal returned true.
9536 /// \return The last instruction of the sequence used to load the slice.
9537 SDValue loadSlice() const {
9538 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9539 const SDValue &OldBaseAddr = Origin->getBasePtr();
9540 SDValue BaseAddr = OldBaseAddr;
9541 // Get the offset in that chunk of bytes w.r.t. the endianess.
9542 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9543 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9545 // BaseAddr = BaseAddr + Offset.
9546 EVT ArithType = BaseAddr.getValueType();
9547 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9548 DAG->getConstant(Offset, ArithType));
9551 // Create the type of the loaded slice according to its size.
9552 EVT SliceType = getLoadedType();
9554 // Create the load for the slice.
9555 SDValue LastInst = DAG->getLoad(
9556 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9557 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9558 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9559 // If the final type is not the same as the loaded type, this means that
9560 // we have to pad with zero. Create a zero extend for that.
9561 EVT FinalType = Inst->getValueType(0);
9562 if (SliceType != FinalType)
9564 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9568 /// \brief Check if this slice can be merged with an expensive cross register
9569 /// bank copy. E.g.,
9571 /// f = bitcast i32 i to float
9572 bool canMergeExpensiveCrossRegisterBankCopy() const {
9573 if (!Inst || !Inst->hasOneUse())
9575 SDNode *Use = *Inst->use_begin();
9576 if (Use->getOpcode() != ISD::BITCAST)
9578 assert(DAG && "Missing context");
9579 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9580 EVT ResVT = Use->getValueType(0);
9581 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9582 const TargetRegisterClass *ArgRC =
9583 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9584 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9587 // At this point, we know that we perform a cross-register-bank copy.
9588 // Check if it is expensive.
9589 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9590 // Assume bitcasts are cheap, unless both register classes do not
9591 // explicitly share a common sub class.
9592 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9595 // Check if it will be merged with the load.
9596 // 1. Check the alignment constraint.
9597 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9598 ResVT.getTypeForEVT(*DAG->getContext()));
9600 if (RequiredAlignment > getAlignment())
9603 // 2. Check that the load is a legal operation for that type.
9604 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9607 // 3. Check that we do not have a zext in the way.
9608 if (Inst->getValueType(0) != getLoadedType())
9616 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9617 /// \p UsedBits looks like 0..0 1..1 0..0.
9618 static bool areUsedBitsDense(const APInt &UsedBits) {
9619 // If all the bits are one, this is dense!
9620 if (UsedBits.isAllOnesValue())
9623 // Get rid of the unused bits on the right.
9624 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9625 // Get rid of the unused bits on the left.
9626 if (NarrowedUsedBits.countLeadingZeros())
9627 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9628 // Check that the chunk of bits is completely used.
9629 return NarrowedUsedBits.isAllOnesValue();
9632 /// \brief Check whether or not \p First and \p Second are next to each other
9633 /// in memory. This means that there is no hole between the bits loaded
9634 /// by \p First and the bits loaded by \p Second.
9635 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9636 const LoadedSlice &Second) {
9637 assert(First.Origin == Second.Origin && First.Origin &&
9638 "Unable to match different memory origins.");
9639 APInt UsedBits = First.getUsedBits();
9640 assert((UsedBits & Second.getUsedBits()) == 0 &&
9641 "Slices are not supposed to overlap.");
9642 UsedBits |= Second.getUsedBits();
9643 return areUsedBitsDense(UsedBits);
9646 /// \brief Adjust the \p GlobalLSCost according to the target
9647 /// paring capabilities and the layout of the slices.
9648 /// \pre \p GlobalLSCost should account for at least as many loads as
9649 /// there is in the slices in \p LoadedSlices.
9650 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9651 LoadedSlice::Cost &GlobalLSCost) {
9652 unsigned NumberOfSlices = LoadedSlices.size();
9653 // If there is less than 2 elements, no pairing is possible.
9654 if (NumberOfSlices < 2)
9657 // Sort the slices so that elements that are likely to be next to each
9658 // other in memory are next to each other in the list.
9659 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9660 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9661 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9662 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9664 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9665 // First (resp. Second) is the first (resp. Second) potentially candidate
9666 // to be placed in a paired load.
9667 const LoadedSlice *First = nullptr;
9668 const LoadedSlice *Second = nullptr;
9669 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9670 // Set the beginning of the pair.
9673 Second = &LoadedSlices[CurrSlice];
9675 // If First is NULL, it means we start a new pair.
9676 // Get to the next slice.
9680 EVT LoadedType = First->getLoadedType();
9682 // If the types of the slices are different, we cannot pair them.
9683 if (LoadedType != Second->getLoadedType())
9686 // Check if the target supplies paired loads for this type.
9687 unsigned RequiredAlignment = 0;
9688 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9689 // move to the next pair, this type is hopeless.
9693 // Check if we meet the alignment requirement.
9694 if (RequiredAlignment > First->getAlignment())
9697 // Check that both loads are next to each other in memory.
9698 if (!areSlicesNextToEachOther(*First, *Second))
9701 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9702 --GlobalLSCost.Loads;
9703 // Move to the next pair.
9708 /// \brief Check the profitability of all involved LoadedSlice.
9709 /// Currently, it is considered profitable if there is exactly two
9710 /// involved slices (1) which are (2) next to each other in memory, and
9711 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9713 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9714 /// the elements themselves.
9716 /// FIXME: When the cost model will be mature enough, we can relax
9717 /// constraints (1) and (2).
9718 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9719 const APInt &UsedBits, bool ForCodeSize) {
9720 unsigned NumberOfSlices = LoadedSlices.size();
9721 if (StressLoadSlicing)
9722 return NumberOfSlices > 1;
9725 if (NumberOfSlices != 2)
9729 if (!areUsedBitsDense(UsedBits))
9733 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9734 // The original code has one big load.
9736 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9737 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9738 // Accumulate the cost of all the slices.
9739 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9740 GlobalSlicingCost += SliceCost;
9742 // Account as cost in the original configuration the gain obtained
9743 // with the current slices.
9744 OrigCost.addSliceGain(LS);
9747 // If the target supports paired load, adjust the cost accordingly.
9748 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9749 return OrigCost > GlobalSlicingCost;
9752 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9753 /// operations, split it in the various pieces being extracted.
9755 /// This sort of thing is introduced by SROA.
9756 /// This slicing takes care not to insert overlapping loads.
9757 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9758 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9759 if (Level < AfterLegalizeDAG)
9762 LoadSDNode *LD = cast<LoadSDNode>(N);
9763 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9764 !LD->getValueType(0).isInteger())
9767 // Keep track of already used bits to detect overlapping values.
9768 // In that case, we will just abort the transformation.
9769 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9771 SmallVector<LoadedSlice, 4> LoadedSlices;
9773 // Check if this load is used as several smaller chunks of bits.
9774 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9775 // of computation for each trunc.
9776 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9777 UI != UIEnd; ++UI) {
9778 // Skip the uses of the chain.
9779 if (UI.getUse().getResNo() != 0)
9785 // Check if this is a trunc(lshr).
9786 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9787 isa<ConstantSDNode>(User->getOperand(1))) {
9788 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9789 User = *User->use_begin();
9792 // At this point, User is a Truncate, iff we encountered, trunc or
9794 if (User->getOpcode() != ISD::TRUNCATE)
9797 // The width of the type must be a power of 2 and greater than 8-bits.
9798 // Otherwise the load cannot be represented in LLVM IR.
9799 // Moreover, if we shifted with a non-8-bits multiple, the slice
9800 // will be across several bytes. We do not support that.
9801 unsigned Width = User->getValueSizeInBits(0);
9802 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9805 // Build the slice for this chain of computations.
9806 LoadedSlice LS(User, LD, Shift, &DAG);
9807 APInt CurrentUsedBits = LS.getUsedBits();
9809 // Check if this slice overlaps with another.
9810 if ((CurrentUsedBits & UsedBits) != 0)
9812 // Update the bits used globally.
9813 UsedBits |= CurrentUsedBits;
9815 // Check if the new slice would be legal.
9819 // Record the slice.
9820 LoadedSlices.push_back(LS);
9823 // Abort slicing if it does not seem to be profitable.
9824 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9829 // Rewrite each chain to use an independent load.
9830 // By construction, each chain can be represented by a unique load.
9832 // Prepare the argument for the new token factor for all the slices.
9833 SmallVector<SDValue, 8> ArgChains;
9834 for (SmallVectorImpl<LoadedSlice>::const_iterator
9835 LSIt = LoadedSlices.begin(),
9836 LSItEnd = LoadedSlices.end();
9837 LSIt != LSItEnd; ++LSIt) {
9838 SDValue SliceInst = LSIt->loadSlice();
9839 CombineTo(LSIt->Inst, SliceInst, true);
9840 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9841 SliceInst = SliceInst.getOperand(0);
9842 assert(SliceInst->getOpcode() == ISD::LOAD &&
9843 "It takes more than a zext to get to the loaded slice!!");
9844 ArgChains.push_back(SliceInst.getValue(1));
9847 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9849 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9853 /// Check to see if V is (and load (ptr), imm), where the load is having
9854 /// specific bytes cleared out. If so, return the byte size being masked out
9855 /// and the shift amount.
9856 static std::pair<unsigned, unsigned>
9857 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9858 std::pair<unsigned, unsigned> Result(0, 0);
9860 // Check for the structure we're looking for.
9861 if (V->getOpcode() != ISD::AND ||
9862 !isa<ConstantSDNode>(V->getOperand(1)) ||
9863 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9866 // Check the chain and pointer.
9867 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9868 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
9870 // The store should be chained directly to the load or be an operand of a
9872 if (LD == Chain.getNode())
9874 else if (Chain->getOpcode() != ISD::TokenFactor)
9875 return Result; // Fail.
9878 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9879 if (Chain->getOperand(i).getNode() == LD) {
9883 if (!isOk) return Result;
9886 // This only handles simple types.
9887 if (V.getValueType() != MVT::i16 &&
9888 V.getValueType() != MVT::i32 &&
9889 V.getValueType() != MVT::i64)
9892 // Check the constant mask. Invert it so that the bits being masked out are
9893 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9894 // follow the sign bit for uniformity.
9895 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9896 unsigned NotMaskLZ = countLeadingZeros(NotMask);
9897 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
9898 unsigned NotMaskTZ = countTrailingZeros(NotMask);
9899 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9900 if (NotMaskLZ == 64) return Result; // All zero mask.
9902 // See if we have a continuous run of bits. If so, we have 0*1+0*
9903 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9906 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9907 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9908 NotMaskLZ -= 64-V.getValueSizeInBits();
9910 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9911 switch (MaskedBytes) {
9915 default: return Result; // All one mask, or 5-byte mask.
9918 // Verify that the first bit starts at a multiple of mask so that the access
9919 // is aligned the same as the access width.
9920 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9922 Result.first = MaskedBytes;
9923 Result.second = NotMaskTZ/8;
9928 /// Check to see if IVal is something that provides a value as specified by
9929 /// MaskInfo. If so, replace the specified store with a narrower store of
9932 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9933 SDValue IVal, StoreSDNode *St,
9935 unsigned NumBytes = MaskInfo.first;
9936 unsigned ByteShift = MaskInfo.second;
9937 SelectionDAG &DAG = DC->getDAG();
9939 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9940 // that uses this. If not, this is not a replacement.
9941 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9942 ByteShift*8, (ByteShift+NumBytes)*8);
9943 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9945 // Check that it is legal on the target to do this. It is legal if the new
9946 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9948 MVT VT = MVT::getIntegerVT(NumBytes*8);
9949 if (!DC->isTypeLegal(VT))
9952 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9953 // shifted by ByteShift and truncated down to NumBytes.
9955 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9956 DAG.getConstant(ByteShift*8,
9957 DC->getShiftAmountTy(IVal.getValueType())));
9959 // Figure out the offset for the store and the alignment of the access.
9961 unsigned NewAlign = St->getAlignment();
9963 if (DAG.getTargetLoweringInfo().isLittleEndian())
9964 StOffset = ByteShift;
9966 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9968 SDValue Ptr = St->getBasePtr();
9970 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9971 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9972 NewAlign = MinAlign(NewAlign, StOffset);
9975 // Truncate down to the new size.
9976 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9979 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9980 St->getPointerInfo().getWithOffset(StOffset),
9981 false, false, NewAlign).getNode();
9985 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9986 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9987 /// narrowing the load and store if it would end up being a win for performance
9989 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9990 StoreSDNode *ST = cast<StoreSDNode>(N);
9991 if (ST->isVolatile())
9994 SDValue Chain = ST->getChain();
9995 SDValue Value = ST->getValue();
9996 SDValue Ptr = ST->getBasePtr();
9997 EVT VT = Value.getValueType();
9999 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10002 unsigned Opc = Value.getOpcode();
10004 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10005 // is a byte mask indicating a consecutive number of bytes, check to see if
10006 // Y is known to provide just those bytes. If so, we try to replace the
10007 // load + replace + store sequence with a single (narrower) store, which makes
10009 if (Opc == ISD::OR) {
10010 std::pair<unsigned, unsigned> MaskedLoad;
10011 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10012 if (MaskedLoad.first)
10013 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10014 Value.getOperand(1), ST,this))
10015 return SDValue(NewST, 0);
10017 // Or is commutative, so try swapping X and Y.
10018 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10019 if (MaskedLoad.first)
10020 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10021 Value.getOperand(0), ST,this))
10022 return SDValue(NewST, 0);
10025 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10026 Value.getOperand(1).getOpcode() != ISD::Constant)
10029 SDValue N0 = Value.getOperand(0);
10030 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10031 Chain == SDValue(N0.getNode(), 1)) {
10032 LoadSDNode *LD = cast<LoadSDNode>(N0);
10033 if (LD->getBasePtr() != Ptr ||
10034 LD->getPointerInfo().getAddrSpace() !=
10035 ST->getPointerInfo().getAddrSpace())
10038 // Find the type to narrow it the load / op / store to.
10039 SDValue N1 = Value.getOperand(1);
10040 unsigned BitWidth = N1.getValueSizeInBits();
10041 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10042 if (Opc == ISD::AND)
10043 Imm ^= APInt::getAllOnesValue(BitWidth);
10044 if (Imm == 0 || Imm.isAllOnesValue())
10046 unsigned ShAmt = Imm.countTrailingZeros();
10047 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10048 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10049 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10050 // The narrowing should be profitable, the load/store operation should be
10051 // legal (or custom) and the store size should be equal to the NewVT width.
10052 while (NewBW < BitWidth &&
10053 (NewVT.getStoreSizeInBits() != NewBW ||
10054 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10055 !TLI.isNarrowingProfitable(VT, NewVT))) {
10056 NewBW = NextPowerOf2(NewBW);
10057 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10059 if (NewBW >= BitWidth)
10062 // If the lsb changed does not start at the type bitwidth boundary,
10063 // start at the previous one.
10065 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10066 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10067 std::min(BitWidth, ShAmt + NewBW));
10068 if ((Imm & Mask) == Imm) {
10069 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10070 if (Opc == ISD::AND)
10071 NewImm ^= APInt::getAllOnesValue(NewBW);
10072 uint64_t PtrOff = ShAmt / 8;
10073 // For big endian targets, we need to adjust the offset to the pointer to
10074 // load the correct bytes.
10075 if (TLI.isBigEndian())
10076 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10078 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10079 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10080 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10083 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10084 Ptr.getValueType(), Ptr,
10085 DAG.getConstant(PtrOff, Ptr.getValueType()));
10086 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10087 LD->getChain(), NewPtr,
10088 LD->getPointerInfo().getWithOffset(PtrOff),
10089 LD->isVolatile(), LD->isNonTemporal(),
10090 LD->isInvariant(), NewAlign,
10092 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10093 DAG.getConstant(NewImm, NewVT));
10094 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10096 ST->getPointerInfo().getWithOffset(PtrOff),
10097 false, false, NewAlign);
10099 AddToWorklist(NewPtr.getNode());
10100 AddToWorklist(NewLD.getNode());
10101 AddToWorklist(NewVal.getNode());
10102 WorklistRemover DeadNodes(*this);
10103 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10112 /// For a given floating point load / store pair, if the load value isn't used
10113 /// by any other operations, then consider transforming the pair to integer
10114 /// load / store operations if the target deems the transformation profitable.
10115 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10116 StoreSDNode *ST = cast<StoreSDNode>(N);
10117 SDValue Chain = ST->getChain();
10118 SDValue Value = ST->getValue();
10119 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10120 Value.hasOneUse() &&
10121 Chain == SDValue(Value.getNode(), 1)) {
10122 LoadSDNode *LD = cast<LoadSDNode>(Value);
10123 EVT VT = LD->getMemoryVT();
10124 if (!VT.isFloatingPoint() ||
10125 VT != ST->getMemoryVT() ||
10126 LD->isNonTemporal() ||
10127 ST->isNonTemporal() ||
10128 LD->getPointerInfo().getAddrSpace() != 0 ||
10129 ST->getPointerInfo().getAddrSpace() != 0)
10132 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10133 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10134 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10135 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10136 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10139 unsigned LDAlign = LD->getAlignment();
10140 unsigned STAlign = ST->getAlignment();
10141 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10142 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10143 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10146 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10147 LD->getChain(), LD->getBasePtr(),
10148 LD->getPointerInfo(),
10149 false, false, false, LDAlign);
10151 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10152 NewLD, ST->getBasePtr(),
10153 ST->getPointerInfo(),
10154 false, false, STAlign);
10156 AddToWorklist(NewLD.getNode());
10157 AddToWorklist(NewST.getNode());
10158 WorklistRemover DeadNodes(*this);
10159 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10168 /// Helper struct to parse and store a memory address as base + index + offset.
10169 /// We ignore sign extensions when it is safe to do so.
10170 /// The following two expressions are not equivalent. To differentiate we need
10171 /// to store whether there was a sign extension involved in the index
10173 /// (load (i64 add (i64 copyfromreg %c)
10174 /// (i64 signextend (add (i8 load %index)
10178 /// (load (i64 add (i64 copyfromreg %c)
10179 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10181 struct BaseIndexOffset {
10185 bool IsIndexSignExt;
10187 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10189 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10190 bool IsIndexSignExt) :
10191 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10193 bool equalBaseIndex(const BaseIndexOffset &Other) {
10194 return Other.Base == Base && Other.Index == Index &&
10195 Other.IsIndexSignExt == IsIndexSignExt;
10198 /// Parses tree in Ptr for base, index, offset addresses.
10199 static BaseIndexOffset match(SDValue Ptr) {
10200 bool IsIndexSignExt = false;
10202 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10203 // instruction, then it could be just the BASE or everything else we don't
10204 // know how to handle. Just use Ptr as BASE and give up.
10205 if (Ptr->getOpcode() != ISD::ADD)
10206 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10208 // We know that we have at least an ADD instruction. Try to pattern match
10209 // the simple case of BASE + OFFSET.
10210 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10211 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10212 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10216 // Inside a loop the current BASE pointer is calculated using an ADD and a
10217 // MUL instruction. In this case Ptr is the actual BASE pointer.
10218 // (i64 add (i64 %array_ptr)
10219 // (i64 mul (i64 %induction_var)
10220 // (i64 %element_size)))
10221 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10222 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10224 // Look at Base + Index + Offset cases.
10225 SDValue Base = Ptr->getOperand(0);
10226 SDValue IndexOffset = Ptr->getOperand(1);
10228 // Skip signextends.
10229 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10230 IndexOffset = IndexOffset->getOperand(0);
10231 IsIndexSignExt = true;
10234 // Either the case of Base + Index (no offset) or something else.
10235 if (IndexOffset->getOpcode() != ISD::ADD)
10236 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10238 // Now we have the case of Base + Index + offset.
10239 SDValue Index = IndexOffset->getOperand(0);
10240 SDValue Offset = IndexOffset->getOperand(1);
10242 if (!isa<ConstantSDNode>(Offset))
10243 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10245 // Ignore signextends.
10246 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10247 Index = Index->getOperand(0);
10248 IsIndexSignExt = true;
10249 } else IsIndexSignExt = false;
10251 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10252 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10257 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10258 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10259 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10260 // Make sure we have something to merge.
10264 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10265 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10266 unsigned LatestNodeUsed = 0;
10268 for (unsigned i=0; i < NumElem; ++i) {
10269 // Find a chain for the new wide-store operand. Notice that some
10270 // of the store nodes that we found may not be selected for inclusion
10271 // in the wide store. The chain we use needs to be the chain of the
10272 // latest store node which is *used* and replaced by the wide store.
10273 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10274 LatestNodeUsed = i;
10277 // The latest Node in the DAG.
10278 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10279 SDLoc DL(StoreNodes[0].MemNode);
10283 // Find a legal type for the vector store.
10284 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10285 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10286 if (IsConstantSrc) {
10287 // A vector store with a constant source implies that the constant is
10288 // zero; we only handle merging stores of constant zeros because the zero
10289 // can be materialized without a load.
10290 // It may be beneficial to loosen this restriction to allow non-zero
10292 StoredVal = DAG.getConstant(0, Ty);
10294 SmallVector<SDValue, 8> Ops;
10295 for (unsigned i = 0; i < NumElem ; ++i) {
10296 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10297 SDValue Val = St->getValue();
10298 // All of the operands of a BUILD_VECTOR must have the same type.
10299 if (Val.getValueType() != MemVT)
10301 Ops.push_back(Val);
10304 // Build the extracted vector elements back into a vector.
10305 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10308 // We should always use a vector store when merging extracted vector
10309 // elements, so this path implies a store of constants.
10310 assert(IsConstantSrc && "Merged vector elements should use vector store");
10312 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10313 APInt StoreInt(StoreBW, 0);
10315 // Construct a single integer constant which is made of the smaller
10316 // constant inputs.
10317 bool IsLE = TLI.isLittleEndian();
10318 for (unsigned i = 0; i < NumElem ; ++i) {
10319 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10320 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10321 SDValue Val = St->getValue();
10322 StoreInt <<= ElementSizeBytes*8;
10323 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10324 StoreInt |= C->getAPIntValue().zext(StoreBW);
10325 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10326 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10328 llvm_unreachable("Invalid constant element type");
10332 // Create the new Load and Store operations.
10333 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10334 StoredVal = DAG.getConstant(StoreInt, StoreTy);
10337 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10338 FirstInChain->getBasePtr(),
10339 FirstInChain->getPointerInfo(),
10341 FirstInChain->getAlignment());
10343 // Replace the last store with the new store
10344 CombineTo(LatestOp, NewStore);
10345 // Erase all other stores.
10346 for (unsigned i = 0; i < NumElem ; ++i) {
10347 if (StoreNodes[i].MemNode == LatestOp)
10349 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10350 // ReplaceAllUsesWith will replace all uses that existed when it was
10351 // called, but graph optimizations may cause new ones to appear. For
10352 // example, the case in pr14333 looks like
10354 // St's chain -> St -> another store -> X
10356 // And the only difference from St to the other store is the chain.
10357 // When we change it's chain to be St's chain they become identical,
10358 // get CSEed and the net result is that X is now a use of St.
10359 // Since we know that St is redundant, just iterate.
10360 while (!St->use_empty())
10361 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10362 deleteAndRecombine(St);
10368 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10369 if (OptLevel == CodeGenOpt::None)
10372 EVT MemVT = St->getMemoryVT();
10373 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10374 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10375 Attribute::NoImplicitFloat);
10377 // Don't merge vectors into wider inputs.
10378 if (MemVT.isVector() || !MemVT.isSimple())
10381 // Perform an early exit check. Do not bother looking at stored values that
10382 // are not constants, loads, or extracted vector elements.
10383 SDValue StoredVal = St->getValue();
10384 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10385 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10386 isa<ConstantFPSDNode>(StoredVal);
10387 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10389 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10392 // Only look at ends of store sequences.
10393 SDValue Chain = SDValue(St, 0);
10394 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10397 // This holds the base pointer, index, and the offset in bytes from the base
10399 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10401 // We must have a base and an offset.
10402 if (!BasePtr.Base.getNode())
10405 // Do not handle stores to undef base pointers.
10406 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10409 // Save the LoadSDNodes that we find in the chain.
10410 // We need to make sure that these nodes do not interfere with
10411 // any of the store nodes.
10412 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10414 // Save the StoreSDNodes that we find in the chain.
10415 SmallVector<MemOpLink, 8> StoreNodes;
10417 // Walk up the chain and look for nodes with offsets from the same
10418 // base pointer. Stop when reaching an instruction with a different kind
10419 // or instruction which has a different base pointer.
10421 StoreSDNode *Index = St;
10423 // If the chain has more than one use, then we can't reorder the mem ops.
10424 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10427 // Find the base pointer and offset for this memory node.
10428 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10430 // Check that the base pointer is the same as the original one.
10431 if (!Ptr.equalBaseIndex(BasePtr))
10434 // Check that the alignment is the same.
10435 if (Index->getAlignment() != St->getAlignment())
10438 // The memory operands must not be volatile.
10439 if (Index->isVolatile() || Index->isIndexed())
10443 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10444 if (St->isTruncatingStore())
10447 // The stored memory type must be the same.
10448 if (Index->getMemoryVT() != MemVT)
10451 // We do not allow unaligned stores because we want to prevent overriding
10453 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10456 // We found a potential memory operand to merge.
10457 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10459 // Find the next memory operand in the chain. If the next operand in the
10460 // chain is a store then move up and continue the scan with the next
10461 // memory operand. If the next operand is a load save it and use alias
10462 // information to check if it interferes with anything.
10463 SDNode *NextInChain = Index->getChain().getNode();
10465 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10466 // We found a store node. Use it for the next iteration.
10469 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10470 if (Ldn->isVolatile()) {
10475 // Save the load node for later. Continue the scan.
10476 AliasLoadNodes.push_back(Ldn);
10477 NextInChain = Ldn->getChain().getNode();
10486 // Check if there is anything to merge.
10487 if (StoreNodes.size() < 2)
10490 // Sort the memory operands according to their distance from the base pointer.
10491 std::sort(StoreNodes.begin(), StoreNodes.end(),
10492 [](MemOpLink LHS, MemOpLink RHS) {
10493 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10494 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10495 LHS.SequenceNum > RHS.SequenceNum);
10498 // Scan the memory operations on the chain and find the first non-consecutive
10499 // store memory address.
10500 unsigned LastConsecutiveStore = 0;
10501 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10502 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10504 // Check that the addresses are consecutive starting from the second
10505 // element in the list of stores.
10507 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10508 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10512 bool Alias = false;
10513 // Check if this store interferes with any of the loads that we found.
10514 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10515 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10519 // We found a load that alias with this store. Stop the sequence.
10523 // Mark this node as useful.
10524 LastConsecutiveStore = i;
10527 // The node with the lowest store address.
10528 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10530 // Store the constants into memory as one consecutive store.
10531 if (IsConstantSrc) {
10532 unsigned LastLegalType = 0;
10533 unsigned LastLegalVectorType = 0;
10534 bool NonZero = false;
10535 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10536 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10537 SDValue StoredVal = St->getValue();
10539 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10540 NonZero |= !C->isNullValue();
10541 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10542 NonZero |= !C->getConstantFPValue()->isNullValue();
10548 // Find a legal type for the constant store.
10549 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10550 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10551 if (TLI.isTypeLegal(StoreTy))
10552 LastLegalType = i+1;
10553 // Or check whether a truncstore is legal.
10554 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10555 TargetLowering::TypePromoteInteger) {
10556 EVT LegalizedStoredValueTy =
10557 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10558 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10559 LastLegalType = i+1;
10562 // Find a legal type for the vector store.
10563 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10564 if (TLI.isTypeLegal(Ty))
10565 LastLegalVectorType = i + 1;
10568 // We only use vectors if the constant is known to be zero and the
10569 // function is not marked with the noimplicitfloat attribute.
10570 if (NonZero || NoVectors)
10571 LastLegalVectorType = 0;
10573 // Check if we found a legal integer type to store.
10574 if (LastLegalType == 0 && LastLegalVectorType == 0)
10577 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10578 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10580 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10584 // When extracting multiple vector elements, try to store them
10585 // in one vector store rather than a sequence of scalar stores.
10586 if (IsExtractVecEltSrc) {
10587 unsigned NumElem = 0;
10588 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10589 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10590 SDValue StoredVal = St->getValue();
10591 // This restriction could be loosened.
10592 // Bail out if any stored values are not elements extracted from a vector.
10593 // It should be possible to handle mixed sources, but load sources need
10594 // more careful handling (see the block of code below that handles
10595 // consecutive loads).
10596 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10599 // Find a legal type for the vector store.
10600 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10601 if (TLI.isTypeLegal(Ty))
10605 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10609 // Below we handle the case of multiple consecutive stores that
10610 // come from multiple consecutive loads. We merge them into a single
10611 // wide load and a single wide store.
10613 // Look for load nodes which are used by the stored values.
10614 SmallVector<MemOpLink, 8> LoadNodes;
10616 // Find acceptable loads. Loads need to have the same chain (token factor),
10617 // must not be zext, volatile, indexed, and they must be consecutive.
10618 BaseIndexOffset LdBasePtr;
10619 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10620 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10621 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10624 // Loads must only have one use.
10625 if (!Ld->hasNUsesOfValue(1, 0))
10628 // Check that the alignment is the same as the stores.
10629 if (Ld->getAlignment() != St->getAlignment())
10632 // The memory operands must not be volatile.
10633 if (Ld->isVolatile() || Ld->isIndexed())
10636 // We do not accept ext loads.
10637 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10640 // The stored memory type must be the same.
10641 if (Ld->getMemoryVT() != MemVT)
10644 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10645 // If this is not the first ptr that we check.
10646 if (LdBasePtr.Base.getNode()) {
10647 // The base ptr must be the same.
10648 if (!LdPtr.equalBaseIndex(LdBasePtr))
10651 // Check that all other base pointers are the same as this one.
10655 // We found a potential memory operand to merge.
10656 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10659 if (LoadNodes.size() < 2)
10662 // If we have load/store pair instructions and we only have two values,
10664 unsigned RequiredAlignment;
10665 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10666 St->getAlignment() >= RequiredAlignment)
10669 // Scan the memory operations on the chain and find the first non-consecutive
10670 // load memory address. These variables hold the index in the store node
10672 unsigned LastConsecutiveLoad = 0;
10673 // This variable refers to the size and not index in the array.
10674 unsigned LastLegalVectorType = 0;
10675 unsigned LastLegalIntegerType = 0;
10676 StartAddress = LoadNodes[0].OffsetFromBase;
10677 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10678 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10679 // All loads much share the same chain.
10680 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10683 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10684 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10686 LastConsecutiveLoad = i;
10688 // Find a legal type for the vector store.
10689 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10690 if (TLI.isTypeLegal(StoreTy))
10691 LastLegalVectorType = i + 1;
10693 // Find a legal type for the integer store.
10694 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10695 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10696 if (TLI.isTypeLegal(StoreTy))
10697 LastLegalIntegerType = i + 1;
10698 // Or check whether a truncstore and extload is legal.
10699 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10700 TargetLowering::TypePromoteInteger) {
10701 EVT LegalizedStoredValueTy =
10702 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10703 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10704 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10705 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10706 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10707 LastLegalIntegerType = i+1;
10711 // Only use vector types if the vector type is larger than the integer type.
10712 // If they are the same, use integers.
10713 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10714 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10716 // We add +1 here because the LastXXX variables refer to location while
10717 // the NumElem refers to array/index size.
10718 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10719 NumElem = std::min(LastLegalType, NumElem);
10724 // The latest Node in the DAG.
10725 unsigned LatestNodeUsed = 0;
10726 for (unsigned i=1; i<NumElem; ++i) {
10727 // Find a chain for the new wide-store operand. Notice that some
10728 // of the store nodes that we found may not be selected for inclusion
10729 // in the wide store. The chain we use needs to be the chain of the
10730 // latest store node which is *used* and replaced by the wide store.
10731 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10732 LatestNodeUsed = i;
10735 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10737 // Find if it is better to use vectors or integers to load and store
10741 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10743 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10744 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10747 SDLoc LoadDL(LoadNodes[0].MemNode);
10748 SDLoc StoreDL(StoreNodes[0].MemNode);
10750 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10751 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10752 FirstLoad->getChain(),
10753 FirstLoad->getBasePtr(),
10754 FirstLoad->getPointerInfo(),
10755 false, false, false,
10756 FirstLoad->getAlignment());
10758 SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
10759 FirstInChain->getBasePtr(),
10760 FirstInChain->getPointerInfo(), false, false,
10761 FirstInChain->getAlignment());
10763 // Replace one of the loads with the new load.
10764 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10765 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10766 SDValue(NewLoad.getNode(), 1));
10768 // Remove the rest of the load chains.
10769 for (unsigned i = 1; i < NumElem ; ++i) {
10770 // Replace all chain users of the old load nodes with the chain of the new
10772 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10773 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10776 // Replace the last store with the new store.
10777 CombineTo(LatestOp, NewStore);
10778 // Erase all other stores.
10779 for (unsigned i = 0; i < NumElem ; ++i) {
10780 // Remove all Store nodes.
10781 if (StoreNodes[i].MemNode == LatestOp)
10783 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10784 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10785 deleteAndRecombine(St);
10791 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10792 StoreSDNode *ST = cast<StoreSDNode>(N);
10793 SDValue Chain = ST->getChain();
10794 SDValue Value = ST->getValue();
10795 SDValue Ptr = ST->getBasePtr();
10797 // If this is a store of a bit convert, store the input value if the
10798 // resultant store does not need a higher alignment than the original.
10799 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10800 ST->isUnindexed()) {
10801 unsigned OrigAlign = ST->getAlignment();
10802 EVT SVT = Value.getOperand(0).getValueType();
10803 unsigned Align = TLI.getDataLayout()->
10804 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10805 if (Align <= OrigAlign &&
10806 ((!LegalOperations && !ST->isVolatile()) ||
10807 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10808 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10809 Ptr, ST->getPointerInfo(), ST->isVolatile(),
10810 ST->isNonTemporal(), OrigAlign,
10814 // Turn 'store undef, Ptr' -> nothing.
10815 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10818 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10819 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10820 // NOTE: If the original store is volatile, this transform must not increase
10821 // the number of stores. For example, on x86-32 an f64 can be stored in one
10822 // processor operation but an i64 (which is not legal) requires two. So the
10823 // transform should not be done in this case.
10824 if (Value.getOpcode() != ISD::TargetConstantFP) {
10826 switch (CFP->getSimpleValueType(0).SimpleTy) {
10827 default: llvm_unreachable("Unknown FP type");
10828 case MVT::f16: // We don't do this for these yet.
10834 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10835 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10836 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10837 bitcastToAPInt().getZExtValue(), MVT::i32);
10838 return DAG.getStore(Chain, SDLoc(N), Tmp,
10839 Ptr, ST->getMemOperand());
10843 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10844 !ST->isVolatile()) ||
10845 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10846 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10847 getZExtValue(), MVT::i64);
10848 return DAG.getStore(Chain, SDLoc(N), Tmp,
10849 Ptr, ST->getMemOperand());
10852 if (!ST->isVolatile() &&
10853 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10854 // Many FP stores are not made apparent until after legalize, e.g. for
10855 // argument passing. Since this is so common, custom legalize the
10856 // 64-bit integer store into two 32-bit stores.
10857 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10858 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10859 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10860 if (TLI.isBigEndian()) std::swap(Lo, Hi);
10862 unsigned Alignment = ST->getAlignment();
10863 bool isVolatile = ST->isVolatile();
10864 bool isNonTemporal = ST->isNonTemporal();
10865 AAMDNodes AAInfo = ST->getAAInfo();
10867 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10868 Ptr, ST->getPointerInfo(),
10869 isVolatile, isNonTemporal,
10870 ST->getAlignment(), AAInfo);
10871 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10872 DAG.getConstant(4, Ptr.getValueType()));
10873 Alignment = MinAlign(Alignment, 4U);
10874 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10875 Ptr, ST->getPointerInfo().getWithOffset(4),
10876 isVolatile, isNonTemporal,
10877 Alignment, AAInfo);
10878 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10887 // Try to infer better alignment information than the store already has.
10888 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10889 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10890 if (Align > ST->getAlignment()) {
10892 DAG.getTruncStore(Chain, SDLoc(N), Value,
10893 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10894 ST->isVolatile(), ST->isNonTemporal(), Align,
10896 if (NewStore.getNode() != N)
10897 return CombineTo(ST, NewStore, true);
10902 // Try transforming a pair floating point load / store ops to integer
10903 // load / store ops.
10904 SDValue NewST = TransformFPLoadStorePair(N);
10905 if (NewST.getNode())
10908 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10909 : DAG.getSubtarget().useAA();
10911 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10912 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10915 if (UseAA && ST->isUnindexed()) {
10916 // Walk up chain skipping non-aliasing memory nodes.
10917 SDValue BetterChain = FindBetterChain(N, Chain);
10919 // If there is a better chain.
10920 if (Chain != BetterChain) {
10923 // Replace the chain to avoid dependency.
10924 if (ST->isTruncatingStore()) {
10925 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10926 ST->getMemoryVT(), ST->getMemOperand());
10928 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10929 ST->getMemOperand());
10932 // Create token to keep both nodes around.
10933 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10934 MVT::Other, Chain, ReplStore);
10936 // Make sure the new and old chains are cleaned up.
10937 AddToWorklist(Token.getNode());
10939 // Don't add users to work list.
10940 return CombineTo(N, Token, false);
10944 // Try transforming N to an indexed store.
10945 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10946 return SDValue(N, 0);
10948 // FIXME: is there such a thing as a truncating indexed store?
10949 if (ST->isTruncatingStore() && ST->isUnindexed() &&
10950 Value.getValueType().isInteger()) {
10951 // See if we can simplify the input to this truncstore with knowledge that
10952 // only the low bits are being used. For example:
10953 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
10955 GetDemandedBits(Value,
10956 APInt::getLowBitsSet(
10957 Value.getValueType().getScalarType().getSizeInBits(),
10958 ST->getMemoryVT().getScalarType().getSizeInBits()));
10959 AddToWorklist(Value.getNode());
10960 if (Shorter.getNode())
10961 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10962 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10964 // Otherwise, see if we can simplify the operation with
10965 // SimplifyDemandedBits, which only works if the value has a single use.
10966 if (SimplifyDemandedBits(Value,
10967 APInt::getLowBitsSet(
10968 Value.getValueType().getScalarType().getSizeInBits(),
10969 ST->getMemoryVT().getScalarType().getSizeInBits())))
10970 return SDValue(N, 0);
10973 // If this is a load followed by a store to the same location, then the store
10975 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10976 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10977 ST->isUnindexed() && !ST->isVolatile() &&
10978 // There can't be any side effects between the load and store, such as
10979 // a call or store.
10980 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10981 // The store is dead, remove it.
10986 // If this is a store followed by a store with the same value to the same
10987 // location, then the store is dead/noop.
10988 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10989 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10990 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10991 ST1->isUnindexed() && !ST1->isVolatile()) {
10992 // The store is dead, remove it.
10997 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10998 // truncating store. We can do this even if this is already a truncstore.
10999 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11000 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11001 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11002 ST->getMemoryVT())) {
11003 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11004 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11007 // Only perform this optimization before the types are legal, because we
11008 // don't want to perform this optimization on every DAGCombine invocation.
11010 bool EverChanged = false;
11013 // There can be multiple store sequences on the same chain.
11014 // Keep trying to merge store sequences until we are unable to do so
11015 // or until we merge the last store on the chain.
11016 bool Changed = MergeConsecutiveStores(ST);
11017 EverChanged |= Changed;
11018 if (!Changed) break;
11019 } while (ST->getOpcode() != ISD::DELETED_NODE);
11022 return SDValue(N, 0);
11025 return ReduceLoadOpStoreWidth(N);
11028 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11029 SDValue InVec = N->getOperand(0);
11030 SDValue InVal = N->getOperand(1);
11031 SDValue EltNo = N->getOperand(2);
11034 // If the inserted element is an UNDEF, just use the input vector.
11035 if (InVal.getOpcode() == ISD::UNDEF)
11038 EVT VT = InVec.getValueType();
11040 // If we can't generate a legal BUILD_VECTOR, exit
11041 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11044 // Check that we know which element is being inserted
11045 if (!isa<ConstantSDNode>(EltNo))
11047 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11049 // Canonicalize insert_vector_elt dag nodes.
11051 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11052 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11054 // Do this only if the child insert_vector node has one use; also
11055 // do this only if indices are both constants and Idx1 < Idx0.
11056 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11057 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11058 unsigned OtherElt =
11059 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11060 if (Elt < OtherElt) {
11062 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11063 InVec.getOperand(0), InVal, EltNo);
11064 AddToWorklist(NewOp.getNode());
11065 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11066 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11070 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11071 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11072 // vector elements.
11073 SmallVector<SDValue, 8> Ops;
11074 // Do not combine these two vectors if the output vector will not replace
11075 // the input vector.
11076 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11077 Ops.append(InVec.getNode()->op_begin(),
11078 InVec.getNode()->op_end());
11079 } else if (InVec.getOpcode() == ISD::UNDEF) {
11080 unsigned NElts = VT.getVectorNumElements();
11081 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11086 // Insert the element
11087 if (Elt < Ops.size()) {
11088 // All the operands of BUILD_VECTOR must have the same type;
11089 // we enforce that here.
11090 EVT OpVT = Ops[0].getValueType();
11091 if (InVal.getValueType() != OpVT)
11092 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11093 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11094 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11098 // Return the new vector
11099 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11102 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11103 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11104 EVT ResultVT = EVE->getValueType(0);
11105 EVT VecEltVT = InVecVT.getVectorElementType();
11106 unsigned Align = OriginalLoad->getAlignment();
11107 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11108 VecEltVT.getTypeForEVT(*DAG.getContext()));
11110 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11115 SDValue NewPtr = OriginalLoad->getBasePtr();
11117 EVT PtrType = NewPtr.getValueType();
11118 MachinePointerInfo MPI;
11119 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11120 int Elt = ConstEltNo->getZExtValue();
11121 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11122 if (TLI.isBigEndian())
11123 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11124 Offset = DAG.getConstant(PtrOff, PtrType);
11125 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11127 Offset = DAG.getNode(
11128 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
11129 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
11130 if (TLI.isBigEndian())
11131 Offset = DAG.getNode(
11132 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
11133 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
11134 MPI = OriginalLoad->getPointerInfo();
11136 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
11138 // The replacement we need to do here is a little tricky: we need to
11139 // replace an extractelement of a load with a load.
11140 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11141 // Note that this replacement assumes that the extractvalue is the only
11142 // use of the load; that's okay because we don't want to perform this
11143 // transformation in other cases anyway.
11146 if (ResultVT.bitsGT(VecEltVT)) {
11147 // If the result type of vextract is wider than the load, then issue an
11148 // extending load instead.
11149 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11153 Load = DAG.getExtLoad(
11154 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11155 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11156 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11157 Chain = Load.getValue(1);
11159 Load = DAG.getLoad(
11160 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11161 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11162 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11163 Chain = Load.getValue(1);
11164 if (ResultVT.bitsLT(VecEltVT))
11165 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11167 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11169 WorklistRemover DeadNodes(*this);
11170 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11171 SDValue To[] = { Load, Chain };
11172 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11173 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11174 // worklist explicitly as well.
11175 AddToWorklist(Load.getNode());
11176 AddUsersToWorklist(Load.getNode()); // Add users too
11177 // Make sure to revisit this node to clean it up; it will usually be dead.
11178 AddToWorklist(EVE);
11180 return SDValue(EVE, 0);
11183 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11184 // (vextract (scalar_to_vector val, 0) -> val
11185 SDValue InVec = N->getOperand(0);
11186 EVT VT = InVec.getValueType();
11187 EVT NVT = N->getValueType(0);
11189 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11190 // Check if the result type doesn't match the inserted element type. A
11191 // SCALAR_TO_VECTOR may truncate the inserted element and the
11192 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11193 SDValue InOp = InVec.getOperand(0);
11194 if (InOp.getValueType() != NVT) {
11195 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11196 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11201 SDValue EltNo = N->getOperand(1);
11202 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11204 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11205 // We only perform this optimization before the op legalization phase because
11206 // we may introduce new vector instructions which are not backed by TD
11207 // patterns. For example on AVX, extracting elements from a wide vector
11208 // without using extract_subvector. However, if we can find an underlying
11209 // scalar value, then we can always use that.
11210 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11212 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11213 int NumElem = VT.getVectorNumElements();
11214 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11215 // Find the new index to extract from.
11216 int OrigElt = SVOp->getMaskElt(Elt);
11218 // Extracting an undef index is undef.
11220 return DAG.getUNDEF(NVT);
11222 // Select the right vector half to extract from.
11224 if (OrigElt < NumElem) {
11225 SVInVec = InVec->getOperand(0);
11227 SVInVec = InVec->getOperand(1);
11228 OrigElt -= NumElem;
11231 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11232 SDValue InOp = SVInVec.getOperand(OrigElt);
11233 if (InOp.getValueType() != NVT) {
11234 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11235 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11241 // FIXME: We should handle recursing on other vector shuffles and
11242 // scalar_to_vector here as well.
11244 if (!LegalOperations) {
11245 EVT IndexTy = TLI.getVectorIdxTy();
11246 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11247 SVInVec, DAG.getConstant(OrigElt, IndexTy));
11251 bool BCNumEltsChanged = false;
11252 EVT ExtVT = VT.getVectorElementType();
11255 // If the result of load has to be truncated, then it's not necessarily
11257 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11260 if (InVec.getOpcode() == ISD::BITCAST) {
11261 // Don't duplicate a load with other uses.
11262 if (!InVec.hasOneUse())
11265 EVT BCVT = InVec.getOperand(0).getValueType();
11266 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11268 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11269 BCNumEltsChanged = true;
11270 InVec = InVec.getOperand(0);
11271 ExtVT = BCVT.getVectorElementType();
11274 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11275 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11276 ISD::isNormalLoad(InVec.getNode()) &&
11277 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11278 SDValue Index = N->getOperand(1);
11279 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11280 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11284 // Perform only after legalization to ensure build_vector / vector_shuffle
11285 // optimizations have already been done.
11286 if (!LegalOperations) return SDValue();
11288 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11289 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11290 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11293 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11295 LoadSDNode *LN0 = nullptr;
11296 const ShuffleVectorSDNode *SVN = nullptr;
11297 if (ISD::isNormalLoad(InVec.getNode())) {
11298 LN0 = cast<LoadSDNode>(InVec);
11299 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11300 InVec.getOperand(0).getValueType() == ExtVT &&
11301 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11302 // Don't duplicate a load with other uses.
11303 if (!InVec.hasOneUse())
11306 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11307 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11308 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11310 // (load $addr+1*size)
11312 // Don't duplicate a load with other uses.
11313 if (!InVec.hasOneUse())
11316 // If the bit convert changed the number of elements, it is unsafe
11317 // to examine the mask.
11318 if (BCNumEltsChanged)
11321 // Select the input vector, guarding against out of range extract vector.
11322 unsigned NumElems = VT.getVectorNumElements();
11323 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11324 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11326 if (InVec.getOpcode() == ISD::BITCAST) {
11327 // Don't duplicate a load with other uses.
11328 if (!InVec.hasOneUse())
11331 InVec = InVec.getOperand(0);
11333 if (ISD::isNormalLoad(InVec.getNode())) {
11334 LN0 = cast<LoadSDNode>(InVec);
11335 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11336 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11340 // Make sure we found a non-volatile load and the extractelement is
11342 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11345 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11347 return DAG.getUNDEF(LVT);
11349 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11355 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11356 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11357 // We perform this optimization post type-legalization because
11358 // the type-legalizer often scalarizes integer-promoted vectors.
11359 // Performing this optimization before may create bit-casts which
11360 // will be type-legalized to complex code sequences.
11361 // We perform this optimization only before the operation legalizer because we
11362 // may introduce illegal operations.
11363 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11366 unsigned NumInScalars = N->getNumOperands();
11368 EVT VT = N->getValueType(0);
11370 // Check to see if this is a BUILD_VECTOR of a bunch of values
11371 // which come from any_extend or zero_extend nodes. If so, we can create
11372 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11373 // optimizations. We do not handle sign-extend because we can't fill the sign
11375 EVT SourceType = MVT::Other;
11376 bool AllAnyExt = true;
11378 for (unsigned i = 0; i != NumInScalars; ++i) {
11379 SDValue In = N->getOperand(i);
11380 // Ignore undef inputs.
11381 if (In.getOpcode() == ISD::UNDEF) continue;
11383 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11384 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11386 // Abort if the element is not an extension.
11387 if (!ZeroExt && !AnyExt) {
11388 SourceType = MVT::Other;
11392 // The input is a ZeroExt or AnyExt. Check the original type.
11393 EVT InTy = In.getOperand(0).getValueType();
11395 // Check that all of the widened source types are the same.
11396 if (SourceType == MVT::Other)
11399 else if (InTy != SourceType) {
11400 // Multiple income types. Abort.
11401 SourceType = MVT::Other;
11405 // Check if all of the extends are ANY_EXTENDs.
11406 AllAnyExt &= AnyExt;
11409 // In order to have valid types, all of the inputs must be extended from the
11410 // same source type and all of the inputs must be any or zero extend.
11411 // Scalar sizes must be a power of two.
11412 EVT OutScalarTy = VT.getScalarType();
11413 bool ValidTypes = SourceType != MVT::Other &&
11414 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11415 isPowerOf2_32(SourceType.getSizeInBits());
11417 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11418 // turn into a single shuffle instruction.
11422 bool isLE = TLI.isLittleEndian();
11423 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11424 assert(ElemRatio > 1 && "Invalid element size ratio");
11425 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11426 DAG.getConstant(0, SourceType);
11428 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11429 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11431 // Populate the new build_vector
11432 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11433 SDValue Cast = N->getOperand(i);
11434 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11435 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11436 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11438 if (Cast.getOpcode() == ISD::UNDEF)
11439 In = DAG.getUNDEF(SourceType);
11441 In = Cast->getOperand(0);
11442 unsigned Index = isLE ? (i * ElemRatio) :
11443 (i * ElemRatio + (ElemRatio - 1));
11445 assert(Index < Ops.size() && "Invalid index");
11449 // The type of the new BUILD_VECTOR node.
11450 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11451 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11452 "Invalid vector size");
11453 // Check if the new vector type is legal.
11454 if (!isTypeLegal(VecVT)) return SDValue();
11456 // Make the new BUILD_VECTOR.
11457 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11459 // The new BUILD_VECTOR node has the potential to be further optimized.
11460 AddToWorklist(BV.getNode());
11461 // Bitcast to the desired type.
11462 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11465 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11466 EVT VT = N->getValueType(0);
11468 unsigned NumInScalars = N->getNumOperands();
11471 EVT SrcVT = MVT::Other;
11472 unsigned Opcode = ISD::DELETED_NODE;
11473 unsigned NumDefs = 0;
11475 for (unsigned i = 0; i != NumInScalars; ++i) {
11476 SDValue In = N->getOperand(i);
11477 unsigned Opc = In.getOpcode();
11479 if (Opc == ISD::UNDEF)
11482 // If all scalar values are floats and converted from integers.
11483 if (Opcode == ISD::DELETED_NODE &&
11484 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11491 EVT InVT = In.getOperand(0).getValueType();
11493 // If all scalar values are typed differently, bail out. It's chosen to
11494 // simplify BUILD_VECTOR of integer types.
11495 if (SrcVT == MVT::Other)
11502 // If the vector has just one element defined, it's not worth to fold it into
11503 // a vectorized one.
11507 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11508 && "Should only handle conversion from integer to float.");
11509 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11511 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11513 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11516 // Just because the floating-point vector type is legal does not necessarily
11517 // mean that the corresponding integer vector type is.
11518 if (!isTypeLegal(NVT))
11521 SmallVector<SDValue, 8> Opnds;
11522 for (unsigned i = 0; i != NumInScalars; ++i) {
11523 SDValue In = N->getOperand(i);
11525 if (In.getOpcode() == ISD::UNDEF)
11526 Opnds.push_back(DAG.getUNDEF(SrcVT));
11528 Opnds.push_back(In.getOperand(0));
11530 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11531 AddToWorklist(BV.getNode());
11533 return DAG.getNode(Opcode, dl, VT, BV);
11536 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11537 unsigned NumInScalars = N->getNumOperands();
11539 EVT VT = N->getValueType(0);
11541 // A vector built entirely of undefs is undef.
11542 if (ISD::allOperandsUndef(N))
11543 return DAG.getUNDEF(VT);
11545 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11548 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11551 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11552 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11553 // at most two distinct vectors, turn this into a shuffle node.
11555 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11556 if (!isTypeLegal(VT))
11559 // May only combine to shuffle after legalize if shuffle is legal.
11560 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11563 SDValue VecIn1, VecIn2;
11564 bool UsesZeroVector = false;
11565 for (unsigned i = 0; i != NumInScalars; ++i) {
11566 SDValue Op = N->getOperand(i);
11567 // Ignore undef inputs.
11568 if (Op.getOpcode() == ISD::UNDEF) continue;
11570 // See if we can combine this build_vector into a blend with a zero vector.
11571 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11572 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11573 (Op.getOpcode() == ISD::ConstantFP &&
11574 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11575 UsesZeroVector = true;
11579 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11580 // constant index, bail out.
11581 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11582 !isa<ConstantSDNode>(Op.getOperand(1))) {
11583 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11587 // We allow up to two distinct input vectors.
11588 SDValue ExtractedFromVec = Op.getOperand(0);
11589 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11592 if (!VecIn1.getNode()) {
11593 VecIn1 = ExtractedFromVec;
11594 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11595 VecIn2 = ExtractedFromVec;
11597 // Too many inputs.
11598 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11603 // If everything is good, we can make a shuffle operation.
11604 if (VecIn1.getNode()) {
11605 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11606 SmallVector<int, 8> Mask;
11607 for (unsigned i = 0; i != NumInScalars; ++i) {
11608 unsigned Opcode = N->getOperand(i).getOpcode();
11609 if (Opcode == ISD::UNDEF) {
11610 Mask.push_back(-1);
11614 // Operands can also be zero.
11615 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11616 assert(UsesZeroVector &&
11617 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11618 "Unexpected node found!");
11619 Mask.push_back(NumInScalars+i);
11623 // If extracting from the first vector, just use the index directly.
11624 SDValue Extract = N->getOperand(i);
11625 SDValue ExtVal = Extract.getOperand(1);
11626 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11627 if (Extract.getOperand(0) == VecIn1) {
11628 Mask.push_back(ExtIndex);
11632 // Otherwise, use InIdx + InputVecSize
11633 Mask.push_back(InNumElements + ExtIndex);
11636 // Avoid introducing illegal shuffles with zero.
11637 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11640 // We can't generate a shuffle node with mismatched input and output types.
11641 // Attempt to transform a single input vector to the correct type.
11642 if ((VT != VecIn1.getValueType())) {
11643 // If the input vector type has a different base type to the output
11644 // vector type, bail out.
11645 EVT VTElemType = VT.getVectorElementType();
11646 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11647 (VecIn2.getNode() &&
11648 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11651 // If the input vector is too small, widen it.
11652 // We only support widening of vectors which are half the size of the
11653 // output registers. For example XMM->YMM widening on X86 with AVX.
11654 EVT VecInT = VecIn1.getValueType();
11655 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11656 // If we only have one small input, widen it by adding undef values.
11657 if (!VecIn2.getNode())
11658 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11659 DAG.getUNDEF(VecIn1.getValueType()));
11660 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11661 // If we have two small inputs of the same type, try to concat them.
11662 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11663 VecIn2 = SDValue(nullptr, 0);
11666 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11667 // If the input vector is too large, try to split it.
11668 // We don't support having two input vectors that are too large.
11669 // If the zero vector was used, we can not split the vector,
11670 // since we'd need 3 inputs.
11671 if (UsesZeroVector || VecIn2.getNode())
11674 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11677 // Try to replace VecIn1 with two extract_subvectors
11678 // No need to update the masks, they should still be correct.
11679 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11680 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11681 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11682 DAG.getConstant(0, TLI.getVectorIdxTy()));
11687 if (UsesZeroVector)
11688 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11689 DAG.getConstantFP(0.0, VT);
11691 // If VecIn2 is unused then change it to undef.
11692 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11694 // Check that we were able to transform all incoming values to the same
11696 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11697 VecIn1.getValueType() != VT)
11700 // Return the new VECTOR_SHUFFLE node.
11704 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11710 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11711 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11712 EVT OpVT = N->getOperand(0).getValueType();
11714 // If the operands are legal vectors, leave them alone.
11715 if (TLI.isTypeLegal(OpVT))
11719 EVT VT = N->getValueType(0);
11720 SmallVector<SDValue, 8> Ops;
11722 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
11723 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11725 // Keep track of what we encounter.
11726 bool AnyInteger = false;
11727 bool AnyFP = false;
11728 for (const SDValue &Op : N->ops()) {
11729 if (ISD::BITCAST == Op.getOpcode() &&
11730 !Op.getOperand(0).getValueType().isVector())
11731 Ops.push_back(Op.getOperand(0));
11732 else if (ISD::UNDEF == Op.getOpcode())
11733 Ops.push_back(ScalarUndef);
11737 // Note whether we encounter an integer or floating point scalar.
11738 // If it's neither, bail out, it could be something weird like x86mmx.
11739 EVT LastOpVT = Ops.back().getValueType();
11740 if (LastOpVT.isFloatingPoint())
11742 else if (LastOpVT.isInteger())
11748 // If any of the operands is a floating point scalar bitcast to a vector,
11749 // use floating point types throughout, and bitcast everything.
11750 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
11752 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
11753 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11755 for (SDValue &Op : Ops) {
11756 if (Op.getValueType() == SVT)
11758 if (Op.getOpcode() == ISD::UNDEF)
11761 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
11766 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
11767 VT.getSizeInBits() / SVT.getSizeInBits());
11768 return DAG.getNode(ISD::BITCAST, DL, VT,
11769 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
11772 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11773 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11774 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11775 // inputs come from at most two distinct vectors, turn this into a shuffle
11778 // If we only have one input vector, we don't need to do any concatenation.
11779 if (N->getNumOperands() == 1)
11780 return N->getOperand(0);
11782 // Check if all of the operands are undefs.
11783 EVT VT = N->getValueType(0);
11784 if (ISD::allOperandsUndef(N))
11785 return DAG.getUNDEF(VT);
11787 // Optimize concat_vectors where all but the first of the vectors are undef.
11788 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
11789 return Op.getOpcode() == ISD::UNDEF;
11791 SDValue In = N->getOperand(0);
11792 assert(In.getValueType().isVector() && "Must concat vectors");
11794 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11795 if (In->getOpcode() == ISD::BITCAST &&
11796 !In->getOperand(0)->getValueType(0).isVector()) {
11797 SDValue Scalar = In->getOperand(0);
11799 // If the bitcast type isn't legal, it might be a trunc of a legal type;
11800 // look through the trunc so we can still do the transform:
11801 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
11802 if (Scalar->getOpcode() == ISD::TRUNCATE &&
11803 !TLI.isTypeLegal(Scalar.getValueType()) &&
11804 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
11805 Scalar = Scalar->getOperand(0);
11807 EVT SclTy = Scalar->getValueType(0);
11809 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11812 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11813 VT.getSizeInBits() / SclTy.getSizeInBits());
11814 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11817 SDLoc dl = SDLoc(N);
11818 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11819 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11823 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11824 // We have already tested above for an UNDEF only concatenation.
11825 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11826 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11827 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11828 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11830 bool AllBuildVectorsOrUndefs =
11831 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11832 if (AllBuildVectorsOrUndefs) {
11833 SmallVector<SDValue, 8> Opnds;
11834 EVT SVT = VT.getScalarType();
11837 if (!SVT.isFloatingPoint()) {
11838 // If BUILD_VECTOR are from built from integer, they may have different
11839 // operand types. Get the smallest type and truncate all operands to it.
11840 bool FoundMinVT = false;
11841 for (const SDValue &Op : N->ops())
11842 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11843 EVT OpSVT = Op.getOperand(0)->getValueType(0);
11844 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11847 assert(FoundMinVT && "Concat vector type mismatch");
11850 for (const SDValue &Op : N->ops()) {
11851 EVT OpVT = Op.getValueType();
11852 unsigned NumElts = OpVT.getVectorNumElements();
11854 if (ISD::UNDEF == Op.getOpcode())
11855 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11857 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11858 if (SVT.isFloatingPoint()) {
11859 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11860 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11862 for (unsigned i = 0; i != NumElts; ++i)
11864 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11869 assert(VT.getVectorNumElements() == Opnds.size() &&
11870 "Concat vector type mismatch");
11871 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11874 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
11875 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
11878 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11879 // nodes often generate nop CONCAT_VECTOR nodes.
11880 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11881 // place the incoming vectors at the exact same location.
11882 SDValue SingleSource = SDValue();
11883 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11885 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11886 SDValue Op = N->getOperand(i);
11888 if (Op.getOpcode() == ISD::UNDEF)
11891 // Check if this is the identity extract:
11892 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11895 // Find the single incoming vector for the extract_subvector.
11896 if (SingleSource.getNode()) {
11897 if (Op.getOperand(0) != SingleSource)
11900 SingleSource = Op.getOperand(0);
11902 // Check the source type is the same as the type of the result.
11903 // If not, this concat may extend the vector, so we can not
11904 // optimize it away.
11905 if (SingleSource.getValueType() != N->getValueType(0))
11909 unsigned IdentityIndex = i * PartNumElem;
11910 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11911 // The extract index must be constant.
11915 // Check that we are reading from the identity index.
11916 if (CS->getZExtValue() != IdentityIndex)
11920 if (SingleSource.getNode())
11921 return SingleSource;
11926 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11927 EVT NVT = N->getValueType(0);
11928 SDValue V = N->getOperand(0);
11930 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11932 // (extract_subvec (concat V1, V2, ...), i)
11935 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11937 if (V->getOperand(0).getValueType() != NVT)
11939 unsigned Idx = N->getConstantOperandVal(1);
11940 unsigned NumElems = NVT.getVectorNumElements();
11941 assert((Idx % NumElems) == 0 &&
11942 "IDX in concat is not a multiple of the result vector length.");
11943 return V->getOperand(Idx / NumElems);
11947 if (V->getOpcode() == ISD::BITCAST)
11948 V = V.getOperand(0);
11950 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11952 // Handle only simple case where vector being inserted and vector
11953 // being extracted are of same type, and are half size of larger vectors.
11954 EVT BigVT = V->getOperand(0).getValueType();
11955 EVT SmallVT = V->getOperand(1).getValueType();
11956 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11959 // Only handle cases where both indexes are constants with the same type.
11960 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11961 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11963 if (InsIdx && ExtIdx &&
11964 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11965 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11967 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11969 // indices are equal or bit offsets are equal => V1
11970 // otherwise => (extract_subvec V1, ExtIdx)
11971 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11972 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11973 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11974 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11975 DAG.getNode(ISD::BITCAST, dl,
11976 N->getOperand(0).getValueType(),
11977 V->getOperand(0)), N->getOperand(1));
11984 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11985 SDValue V, SelectionDAG &DAG) {
11987 EVT VT = V.getValueType();
11989 switch (V.getOpcode()) {
11993 case ISD::CONCAT_VECTORS: {
11994 EVT OpVT = V->getOperand(0).getValueType();
11995 int OpSize = OpVT.getVectorNumElements();
11996 SmallBitVector OpUsedElements(OpSize, false);
11997 bool FoundSimplification = false;
11998 SmallVector<SDValue, 4> NewOps;
11999 NewOps.reserve(V->getNumOperands());
12000 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12001 SDValue Op = V->getOperand(i);
12002 bool OpUsed = false;
12003 for (int j = 0; j < OpSize; ++j)
12004 if (UsedElements[i * OpSize + j]) {
12005 OpUsedElements[j] = true;
12009 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12010 : DAG.getUNDEF(OpVT));
12011 FoundSimplification |= Op == NewOps.back();
12012 OpUsedElements.reset();
12014 if (FoundSimplification)
12015 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12019 case ISD::INSERT_SUBVECTOR: {
12020 SDValue BaseV = V->getOperand(0);
12021 SDValue SubV = V->getOperand(1);
12022 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12026 int SubSize = SubV.getValueType().getVectorNumElements();
12027 int Idx = IdxN->getZExtValue();
12028 bool SubVectorUsed = false;
12029 SmallBitVector SubUsedElements(SubSize, false);
12030 for (int i = 0; i < SubSize; ++i)
12031 if (UsedElements[i + Idx]) {
12032 SubVectorUsed = true;
12033 SubUsedElements[i] = true;
12034 UsedElements[i + Idx] = false;
12037 // Now recurse on both the base and sub vectors.
12038 SDValue SimplifiedSubV =
12040 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12041 : DAG.getUNDEF(SubV.getValueType());
12042 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12043 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12044 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12045 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12051 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12052 SDValue N1, SelectionDAG &DAG) {
12053 EVT VT = SVN->getValueType(0);
12054 int NumElts = VT.getVectorNumElements();
12055 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12056 for (int M : SVN->getMask())
12057 if (M >= 0 && M < NumElts)
12058 N0UsedElements[M] = true;
12059 else if (M >= NumElts)
12060 N1UsedElements[M - NumElts] = true;
12062 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12063 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12064 if (S0 == N0 && S1 == N1)
12067 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12070 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12071 // or turn a shuffle of a single concat into simpler shuffle then concat.
12072 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12073 EVT VT = N->getValueType(0);
12074 unsigned NumElts = VT.getVectorNumElements();
12076 SDValue N0 = N->getOperand(0);
12077 SDValue N1 = N->getOperand(1);
12078 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12080 SmallVector<SDValue, 4> Ops;
12081 EVT ConcatVT = N0.getOperand(0).getValueType();
12082 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12083 unsigned NumConcats = NumElts / NumElemsPerConcat;
12085 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12086 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12087 // half vector elements.
12088 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12089 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12090 SVN->getMask().end(), [](int i) { return i == -1; })) {
12091 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12092 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12093 N1 = DAG.getUNDEF(ConcatVT);
12094 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12097 // Look at every vector that's inserted. We're looking for exact
12098 // subvector-sized copies from a concatenated vector
12099 for (unsigned I = 0; I != NumConcats; ++I) {
12100 // Make sure we're dealing with a copy.
12101 unsigned Begin = I * NumElemsPerConcat;
12102 bool AllUndef = true, NoUndef = true;
12103 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12104 if (SVN->getMaskElt(J) >= 0)
12111 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12114 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12115 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12118 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12119 if (FirstElt < N0.getNumOperands())
12120 Ops.push_back(N0.getOperand(FirstElt));
12122 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12124 } else if (AllUndef) {
12125 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12126 } else { // Mixed with general masks and undefs, can't do optimization.
12131 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12134 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12135 EVT VT = N->getValueType(0);
12136 unsigned NumElts = VT.getVectorNumElements();
12138 SDValue N0 = N->getOperand(0);
12139 SDValue N1 = N->getOperand(1);
12141 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12143 // Canonicalize shuffle undef, undef -> undef
12144 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12145 return DAG.getUNDEF(VT);
12147 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12149 // Canonicalize shuffle v, v -> v, undef
12151 SmallVector<int, 8> NewMask;
12152 for (unsigned i = 0; i != NumElts; ++i) {
12153 int Idx = SVN->getMaskElt(i);
12154 if (Idx >= (int)NumElts) Idx -= NumElts;
12155 NewMask.push_back(Idx);
12157 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12161 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12162 if (N0.getOpcode() == ISD::UNDEF) {
12163 SmallVector<int, 8> NewMask;
12164 for (unsigned i = 0; i != NumElts; ++i) {
12165 int Idx = SVN->getMaskElt(i);
12167 if (Idx >= (int)NumElts)
12170 Idx = -1; // remove reference to lhs
12172 NewMask.push_back(Idx);
12174 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12178 // Remove references to rhs if it is undef
12179 if (N1.getOpcode() == ISD::UNDEF) {
12180 bool Changed = false;
12181 SmallVector<int, 8> NewMask;
12182 for (unsigned i = 0; i != NumElts; ++i) {
12183 int Idx = SVN->getMaskElt(i);
12184 if (Idx >= (int)NumElts) {
12188 NewMask.push_back(Idx);
12191 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12194 // If it is a splat, check if the argument vector is another splat or a
12196 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12197 SDNode *V = N0.getNode();
12199 // If this is a bit convert that changes the element type of the vector but
12200 // not the number of vector elements, look through it. Be careful not to
12201 // look though conversions that change things like v4f32 to v2f64.
12202 if (V->getOpcode() == ISD::BITCAST) {
12203 SDValue ConvInput = V->getOperand(0);
12204 if (ConvInput.getValueType().isVector() &&
12205 ConvInput.getValueType().getVectorNumElements() == NumElts)
12206 V = ConvInput.getNode();
12209 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12210 assert(V->getNumOperands() == NumElts &&
12211 "BUILD_VECTOR has wrong number of operands");
12213 bool AllSame = true;
12214 for (unsigned i = 0; i != NumElts; ++i) {
12215 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12216 Base = V->getOperand(i);
12220 // Splat of <u, u, u, u>, return <u, u, u, u>
12221 if (!Base.getNode())
12223 for (unsigned i = 0; i != NumElts; ++i) {
12224 if (V->getOperand(i) != Base) {
12229 // Splat of <x, x, x, x>, return <x, x, x, x>
12233 // Canonicalize any other splat as a build_vector.
12234 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12235 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12236 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12237 V->getValueType(0), Ops);
12239 // We may have jumped through bitcasts, so the type of the
12240 // BUILD_VECTOR may not match the type of the shuffle.
12241 if (V->getValueType(0) != VT)
12242 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12247 // There are various patterns used to build up a vector from smaller vectors,
12248 // subvectors, or elements. Scan chains of these and replace unused insertions
12249 // or components with undef.
12250 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12253 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12254 Level < AfterLegalizeVectorOps &&
12255 (N1.getOpcode() == ISD::UNDEF ||
12256 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12257 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12258 SDValue V = partitionShuffleOfConcats(N, DAG);
12264 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12265 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12266 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12267 SmallVector<SDValue, 8> Ops;
12268 for (int M : SVN->getMask()) {
12269 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12271 int Idx = M % NumElts;
12272 SDValue &S = (M < (int)NumElts ? N0 : N1);
12273 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12274 Op = S.getOperand(Idx);
12275 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12277 Op = S.getOperand(0);
12279 // Operand can't be combined - bail out.
12285 if (Ops.size() == VT.getVectorNumElements()) {
12286 // BUILD_VECTOR requires all inputs to be of the same type, find the
12287 // maximum type and extend them all.
12288 EVT SVT = VT.getScalarType();
12289 if (SVT.isInteger())
12290 for (SDValue &Op : Ops)
12291 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12292 if (SVT != VT.getScalarType())
12293 for (SDValue &Op : Ops)
12294 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12295 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12296 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12297 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12301 // If this shuffle only has a single input that is a bitcasted shuffle,
12302 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12303 // back to their original types.
12304 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12305 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12306 TLI.isTypeLegal(VT)) {
12308 // Peek through the bitcast only if there is one user.
12310 while (BC0.getOpcode() == ISD::BITCAST) {
12311 if (!BC0.hasOneUse())
12313 BC0 = BC0.getOperand(0);
12316 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12318 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12320 SmallVector<int, 8> NewMask;
12322 for (int s = 0; s != Scale; ++s)
12323 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12327 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12328 EVT SVT = VT.getScalarType();
12329 EVT InnerVT = BC0->getValueType(0);
12330 EVT InnerSVT = InnerVT.getScalarType();
12332 // Determine which shuffle works with the smaller scalar type.
12333 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12334 EVT ScaleSVT = ScaleVT.getScalarType();
12336 if (TLI.isTypeLegal(ScaleVT) &&
12337 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12338 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12340 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12341 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12343 // Scale the shuffle masks to the smaller scalar type.
12344 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12345 SmallVector<int, 8> InnerMask =
12346 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12347 SmallVector<int, 8> OuterMask =
12348 ScaleShuffleMask(SVN->getMask(), OuterScale);
12350 // Merge the shuffle masks.
12351 SmallVector<int, 8> NewMask;
12352 for (int M : OuterMask)
12353 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12355 // Test for shuffle mask legality over both commutations.
12356 SDValue SV0 = BC0->getOperand(0);
12357 SDValue SV1 = BC0->getOperand(1);
12358 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12360 std::swap(SV0, SV1);
12361 ShuffleVectorSDNode::commuteMask(NewMask);
12362 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12366 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12367 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12368 return DAG.getNode(
12369 ISD::BITCAST, SDLoc(N), VT,
12370 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12376 // Canonicalize shuffles according to rules:
12377 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12378 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12379 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12380 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12381 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12382 TLI.isTypeLegal(VT)) {
12383 // The incoming shuffle must be of the same type as the result of the
12384 // current shuffle.
12385 assert(N1->getOperand(0).getValueType() == VT &&
12386 "Shuffle types don't match");
12388 SDValue SV0 = N1->getOperand(0);
12389 SDValue SV1 = N1->getOperand(1);
12390 bool HasSameOp0 = N0 == SV0;
12391 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12392 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12393 // Commute the operands of this shuffle so that next rule
12395 return DAG.getCommutedVectorShuffle(*SVN);
12398 // Try to fold according to rules:
12399 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12400 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12401 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12402 // Don't try to fold shuffles with illegal type.
12403 // Only fold if this shuffle is the only user of the other shuffle.
12404 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12405 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12406 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12408 // The incoming shuffle must be of the same type as the result of the
12409 // current shuffle.
12410 assert(OtherSV->getOperand(0).getValueType() == VT &&
12411 "Shuffle types don't match");
12414 SmallVector<int, 4> Mask;
12415 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12416 // operand, and SV1 as the second operand.
12417 for (unsigned i = 0; i != NumElts; ++i) {
12418 int Idx = SVN->getMaskElt(i);
12420 // Propagate Undef.
12421 Mask.push_back(Idx);
12425 SDValue CurrentVec;
12426 if (Idx < (int)NumElts) {
12427 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12428 // shuffle mask to identify which vector is actually referenced.
12429 Idx = OtherSV->getMaskElt(Idx);
12431 // Propagate Undef.
12432 Mask.push_back(Idx);
12436 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12437 : OtherSV->getOperand(1);
12439 // This shuffle index references an element within N1.
12443 // Simple case where 'CurrentVec' is UNDEF.
12444 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12445 Mask.push_back(-1);
12449 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12450 // will be the first or second operand of the combined shuffle.
12451 Idx = Idx % NumElts;
12452 if (!SV0.getNode() || SV0 == CurrentVec) {
12453 // Ok. CurrentVec is the left hand side.
12454 // Update the mask accordingly.
12456 Mask.push_back(Idx);
12460 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12461 if (SV1.getNode() && SV1 != CurrentVec)
12464 // Ok. CurrentVec is the right hand side.
12465 // Update the mask accordingly.
12467 Mask.push_back(Idx + NumElts);
12470 // Check if all indices in Mask are Undef. In case, propagate Undef.
12471 bool isUndefMask = true;
12472 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12473 isUndefMask &= Mask[i] < 0;
12476 return DAG.getUNDEF(VT);
12478 if (!SV0.getNode())
12479 SV0 = DAG.getUNDEF(VT);
12480 if (!SV1.getNode())
12481 SV1 = DAG.getUNDEF(VT);
12483 // Avoid introducing shuffles with illegal mask.
12484 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12485 ShuffleVectorSDNode::commuteMask(Mask);
12487 if (!TLI.isShuffleMaskLegal(Mask, VT))
12490 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12491 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12492 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12493 std::swap(SV0, SV1);
12496 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12497 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12498 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12499 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12505 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12506 SDValue InVal = N->getOperand(0);
12507 EVT VT = N->getValueType(0);
12509 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12510 // with a VECTOR_SHUFFLE.
12511 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12512 SDValue InVec = InVal->getOperand(0);
12513 SDValue EltNo = InVal->getOperand(1);
12515 // FIXME: We could support implicit truncation if the shuffle can be
12516 // scaled to a smaller vector scalar type.
12517 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12518 if (C0 && VT == InVec.getValueType() &&
12519 VT.getScalarType() == InVal.getValueType()) {
12520 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12521 int Elt = C0->getZExtValue();
12524 if (TLI.isShuffleMaskLegal(NewMask, VT))
12525 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12533 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12534 SDValue N0 = N->getOperand(0);
12535 SDValue N2 = N->getOperand(2);
12537 // If the input vector is a concatenation, and the insert replaces
12538 // one of the halves, we can optimize into a single concat_vectors.
12539 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12540 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12541 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12542 EVT VT = N->getValueType(0);
12544 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12545 // (concat_vectors Z, Y)
12547 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12548 N->getOperand(1), N0.getOperand(1));
12550 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12551 // (concat_vectors X, Z)
12552 if (InsIdx == VT.getVectorNumElements()/2)
12553 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12554 N0.getOperand(0), N->getOperand(1));
12560 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12561 SDValue N0 = N->getOperand(0);
12563 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12564 if (N0->getOpcode() == ISD::FP16_TO_FP)
12565 return N0->getOperand(0);
12570 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12571 /// with the destination vector and a zero vector.
12572 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12573 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12574 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12575 EVT VT = N->getValueType(0);
12576 SDValue LHS = N->getOperand(0);
12577 SDValue RHS = N->getOperand(1);
12580 // Make sure we're not running after operation legalization where it
12581 // may have custom lowered the vector shuffles.
12582 if (LegalOperations)
12585 if (N->getOpcode() != ISD::AND)
12588 if (RHS.getOpcode() == ISD::BITCAST)
12589 RHS = RHS.getOperand(0);
12591 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12592 SmallVector<int, 8> Indices;
12593 unsigned NumElts = RHS.getNumOperands();
12595 for (unsigned i = 0; i != NumElts; ++i) {
12596 SDValue Elt = RHS.getOperand(i);
12597 if (!isa<ConstantSDNode>(Elt))
12600 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12601 Indices.push_back(i);
12602 else if (cast<ConstantSDNode>(Elt)->isNullValue())
12603 Indices.push_back(NumElts+i);
12608 // Let's see if the target supports this vector_shuffle.
12609 EVT RVT = RHS.getValueType();
12610 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12613 // Return the new VECTOR_SHUFFLE node.
12614 EVT EltVT = RVT.getVectorElementType();
12615 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12616 DAG.getConstant(0, EltVT));
12617 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12618 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12619 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12620 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12626 /// Visit a binary vector operation, like ADD.
12627 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12628 assert(N->getValueType(0).isVector() &&
12629 "SimplifyVBinOp only works on vectors!");
12631 SDValue LHS = N->getOperand(0);
12632 SDValue RHS = N->getOperand(1);
12634 if (SDValue Shuffle = XformToShuffleWithZero(N))
12637 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12639 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12640 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12641 // Check if both vectors are constants. If not bail out.
12642 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12643 cast<BuildVectorSDNode>(RHS)->isConstant()))
12646 SmallVector<SDValue, 8> Ops;
12647 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12648 SDValue LHSOp = LHS.getOperand(i);
12649 SDValue RHSOp = RHS.getOperand(i);
12651 // Can't fold divide by zero.
12652 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12653 N->getOpcode() == ISD::FDIV) {
12654 if ((RHSOp.getOpcode() == ISD::Constant &&
12655 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12656 (RHSOp.getOpcode() == ISD::ConstantFP &&
12657 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12661 EVT VT = LHSOp.getValueType();
12662 EVT RVT = RHSOp.getValueType();
12664 // Integer BUILD_VECTOR operands may have types larger than the element
12665 // size (e.g., when the element type is not legal). Prior to type
12666 // legalization, the types may not match between the two BUILD_VECTORS.
12667 // Truncate one of the operands to make them match.
12668 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12669 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12671 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12675 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12677 if (FoldOp.getOpcode() != ISD::UNDEF &&
12678 FoldOp.getOpcode() != ISD::Constant &&
12679 FoldOp.getOpcode() != ISD::ConstantFP)
12681 Ops.push_back(FoldOp);
12682 AddToWorklist(FoldOp.getNode());
12685 if (Ops.size() == LHS.getNumOperands())
12686 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12689 // Type legalization might introduce new shuffles in the DAG.
12690 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12691 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12692 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12693 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12694 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12695 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12696 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12697 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12699 if (SVN0->getMask().equals(SVN1->getMask())) {
12700 EVT VT = N->getValueType(0);
12701 SDValue UndefVector = LHS.getOperand(1);
12702 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12703 LHS.getOperand(0), RHS.getOperand(0));
12704 AddUsersToWorklist(N);
12705 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12706 &SVN0->getMask()[0]);
12713 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12714 SDValue N1, SDValue N2){
12715 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12717 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12718 cast<CondCodeSDNode>(N0.getOperand(2))->get());
12720 // If we got a simplified select_cc node back from SimplifySelectCC, then
12721 // break it down into a new SETCC node, and a new SELECT node, and then return
12722 // the SELECT node, since we were called with a SELECT node.
12723 if (SCC.getNode()) {
12724 // Check to see if we got a select_cc back (to turn into setcc/select).
12725 // Otherwise, just return whatever node we got back, like fabs.
12726 if (SCC.getOpcode() == ISD::SELECT_CC) {
12727 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12729 SCC.getOperand(0), SCC.getOperand(1),
12730 SCC.getOperand(4));
12731 AddToWorklist(SETCC.getNode());
12732 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12733 SCC.getOperand(2), SCC.getOperand(3));
12741 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12742 /// being selected between, see if we can simplify the select. Callers of this
12743 /// should assume that TheSelect is deleted if this returns true. As such, they
12744 /// should return the appropriate thing (e.g. the node) back to the top-level of
12745 /// the DAG combiner loop to avoid it being looked at.
12746 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12749 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12750 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
12751 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
12752 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
12753 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
12754 SDValue Sqrt = RHS;
12757 const ConstantFPSDNode *NegZero = nullptr;
12759 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
12760 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
12761 CmpLHS = TheSelect->getOperand(0);
12762 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
12764 // SELECT or VSELECT
12765 SDValue Cmp = TheSelect->getOperand(0);
12766 if (Cmp.getOpcode() == ISD::SETCC) {
12767 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
12768 CmpLHS = Cmp.getOperand(0);
12769 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
12772 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
12773 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
12774 CC == ISD::SETULT || CC == ISD::SETLT)) {
12775 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12776 CombineTo(TheSelect, Sqrt);
12781 // Cannot simplify select with vector condition
12782 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12784 // If this is a select from two identical things, try to pull the operation
12785 // through the select.
12786 if (LHS.getOpcode() != RHS.getOpcode() ||
12787 !LHS.hasOneUse() || !RHS.hasOneUse())
12790 // If this is a load and the token chain is identical, replace the select
12791 // of two loads with a load through a select of the address to load from.
12792 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12793 // constants have been dropped into the constant pool.
12794 if (LHS.getOpcode() == ISD::LOAD) {
12795 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12796 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12798 // Token chains must be identical.
12799 if (LHS.getOperand(0) != RHS.getOperand(0) ||
12800 // Do not let this transformation reduce the number of volatile loads.
12801 LLD->isVolatile() || RLD->isVolatile() ||
12802 // FIXME: If either is a pre/post inc/dec load,
12803 // we'd need to split out the address adjustment.
12804 LLD->isIndexed() || RLD->isIndexed() ||
12805 // If this is an EXTLOAD, the VT's must match.
12806 LLD->getMemoryVT() != RLD->getMemoryVT() ||
12807 // If this is an EXTLOAD, the kind of extension must match.
12808 (LLD->getExtensionType() != RLD->getExtensionType() &&
12809 // The only exception is if one of the extensions is anyext.
12810 LLD->getExtensionType() != ISD::EXTLOAD &&
12811 RLD->getExtensionType() != ISD::EXTLOAD) ||
12812 // FIXME: this discards src value information. This is
12813 // over-conservative. It would be beneficial to be able to remember
12814 // both potential memory locations. Since we are discarding
12815 // src value info, don't do the transformation if the memory
12816 // locations are not in the default address space.
12817 LLD->getPointerInfo().getAddrSpace() != 0 ||
12818 RLD->getPointerInfo().getAddrSpace() != 0 ||
12819 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12820 LLD->getBasePtr().getValueType()))
12823 // Check that the select condition doesn't reach either load. If so,
12824 // folding this will induce a cycle into the DAG. If not, this is safe to
12825 // xform, so create a select of the addresses.
12827 if (TheSelect->getOpcode() == ISD::SELECT) {
12828 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12829 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12830 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12832 // The loads must not depend on one another.
12833 if (LLD->isPredecessorOf(RLD) ||
12834 RLD->isPredecessorOf(LLD))
12836 Addr = DAG.getSelect(SDLoc(TheSelect),
12837 LLD->getBasePtr().getValueType(),
12838 TheSelect->getOperand(0), LLD->getBasePtr(),
12839 RLD->getBasePtr());
12840 } else { // Otherwise SELECT_CC
12841 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12842 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12844 if ((LLD->hasAnyUseOfValue(1) &&
12845 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12846 (RLD->hasAnyUseOfValue(1) &&
12847 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12850 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12851 LLD->getBasePtr().getValueType(),
12852 TheSelect->getOperand(0),
12853 TheSelect->getOperand(1),
12854 LLD->getBasePtr(), RLD->getBasePtr(),
12855 TheSelect->getOperand(4));
12859 // It is safe to replace the two loads if they have different alignments,
12860 // but the new load must be the minimum (most restrictive) alignment of the
12862 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12863 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12864 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12865 Load = DAG.getLoad(TheSelect->getValueType(0),
12867 // FIXME: Discards pointer and AA info.
12868 LLD->getChain(), Addr, MachinePointerInfo(),
12869 LLD->isVolatile(), LLD->isNonTemporal(),
12870 isInvariant, Alignment);
12872 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12873 RLD->getExtensionType() : LLD->getExtensionType(),
12875 TheSelect->getValueType(0),
12876 // FIXME: Discards pointer and AA info.
12877 LLD->getChain(), Addr, MachinePointerInfo(),
12878 LLD->getMemoryVT(), LLD->isVolatile(),
12879 LLD->isNonTemporal(), isInvariant, Alignment);
12882 // Users of the select now use the result of the load.
12883 CombineTo(TheSelect, Load);
12885 // Users of the old loads now use the new load's chain. We know the
12886 // old-load value is dead now.
12887 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12888 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12895 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12896 /// where 'cond' is the comparison specified by CC.
12897 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12898 SDValue N2, SDValue N3,
12899 ISD::CondCode CC, bool NotExtCompare) {
12900 // (x ? y : y) -> y.
12901 if (N2 == N3) return N2;
12903 EVT VT = N2.getValueType();
12904 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12905 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12906 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12908 // Determine if the condition we're dealing with is constant
12909 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12910 N0, N1, CC, DL, false);
12911 if (SCC.getNode()) AddToWorklist(SCC.getNode());
12912 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12914 // fold select_cc true, x, y -> x
12915 if (SCCC && !SCCC->isNullValue())
12917 // fold select_cc false, x, y -> y
12918 if (SCCC && SCCC->isNullValue())
12921 // Check to see if we can simplify the select into an fabs node
12922 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12923 // Allow either -0.0 or 0.0
12924 if (CFP->getValueAPF().isZero()) {
12925 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12926 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12927 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12928 N2 == N3.getOperand(0))
12929 return DAG.getNode(ISD::FABS, DL, VT, N0);
12931 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12932 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12933 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12934 N2.getOperand(0) == N3)
12935 return DAG.getNode(ISD::FABS, DL, VT, N3);
12939 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12940 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12941 // in it. This is a win when the constant is not otherwise available because
12942 // it replaces two constant pool loads with one. We only do this if the FP
12943 // type is known to be legal, because if it isn't, then we are before legalize
12944 // types an we want the other legalization to happen first (e.g. to avoid
12945 // messing with soft float) and if the ConstantFP is not legal, because if
12946 // it is legal, we may not need to store the FP constant in a constant pool.
12947 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12948 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12949 if (TLI.isTypeLegal(N2.getValueType()) &&
12950 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12951 TargetLowering::Legal &&
12952 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12953 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12954 // If both constants have multiple uses, then we won't need to do an
12955 // extra load, they are likely around in registers for other users.
12956 (TV->hasOneUse() || FV->hasOneUse())) {
12957 Constant *Elts[] = {
12958 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12959 const_cast<ConstantFP*>(TV->getConstantFPValue())
12961 Type *FPTy = Elts[0]->getType();
12962 const DataLayout &TD = *TLI.getDataLayout();
12964 // Create a ConstantArray of the two constants.
12965 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12966 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12967 TD.getPrefTypeAlignment(FPTy));
12968 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12970 // Get the offsets to the 0 and 1 element of the array so that we can
12971 // select between them.
12972 SDValue Zero = DAG.getIntPtrConstant(0);
12973 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12974 SDValue One = DAG.getIntPtrConstant(EltSize);
12976 SDValue Cond = DAG.getSetCC(DL,
12977 getSetCCResultType(N0.getValueType()),
12979 AddToWorklist(Cond.getNode());
12980 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12982 AddToWorklist(CstOffset.getNode());
12983 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12985 AddToWorklist(CPIdx.getNode());
12986 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12987 MachinePointerInfo::getConstantPool(), false,
12988 false, false, Alignment);
12993 // Check to see if we can perform the "gzip trick", transforming
12994 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12995 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12996 (N1C->isNullValue() || // (a < 0) ? b : 0
12997 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
12998 EVT XType = N0.getValueType();
12999 EVT AType = N2.getValueType();
13000 if (XType.bitsGE(AType)) {
13001 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13002 // single-bit constant.
13003 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
13004 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13005 ShCtV = XType.getSizeInBits()-ShCtV-1;
13006 SDValue ShCt = DAG.getConstant(ShCtV,
13007 getShiftAmountTy(N0.getValueType()));
13008 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13010 AddToWorklist(Shift.getNode());
13012 if (XType.bitsGT(AType)) {
13013 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13014 AddToWorklist(Shift.getNode());
13017 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13020 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13022 DAG.getConstant(XType.getSizeInBits()-1,
13023 getShiftAmountTy(N0.getValueType())));
13024 AddToWorklist(Shift.getNode());
13026 if (XType.bitsGT(AType)) {
13027 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13028 AddToWorklist(Shift.getNode());
13031 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13035 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13036 // where y is has a single bit set.
13037 // A plaintext description would be, we can turn the SELECT_CC into an AND
13038 // when the condition can be materialized as an all-ones register. Any
13039 // single bit-test can be materialized as an all-ones register with
13040 // shift-left and shift-right-arith.
13041 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13042 N0->getValueType(0) == VT &&
13043 N1C && N1C->isNullValue() &&
13044 N2C && N2C->isNullValue()) {
13045 SDValue AndLHS = N0->getOperand(0);
13046 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13047 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13048 // Shift the tested bit over the sign bit.
13049 APInt AndMask = ConstAndRHS->getAPIntValue();
13051 DAG.getConstant(AndMask.countLeadingZeros(),
13052 getShiftAmountTy(AndLHS.getValueType()));
13053 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13055 // Now arithmetic right shift it all the way over, so the result is either
13056 // all-ones, or zero.
13058 DAG.getConstant(AndMask.getBitWidth()-1,
13059 getShiftAmountTy(Shl.getValueType()));
13060 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13062 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13066 // fold select C, 16, 0 -> shl C, 4
13067 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13068 TLI.getBooleanContents(N0.getValueType()) ==
13069 TargetLowering::ZeroOrOneBooleanContent) {
13071 // If the caller doesn't want us to simplify this into a zext of a compare,
13073 if (NotExtCompare && N2C->getAPIntValue() == 1)
13076 // Get a SetCC of the condition
13077 // NOTE: Don't create a SETCC if it's not legal on this target.
13078 if (!LegalOperations ||
13079 TLI.isOperationLegal(ISD::SETCC,
13080 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13082 // cast from setcc result type to select result type
13084 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13086 if (N2.getValueType().bitsLT(SCC.getValueType()))
13087 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13088 N2.getValueType());
13090 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13091 N2.getValueType(), SCC);
13093 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13094 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13095 N2.getValueType(), SCC);
13098 AddToWorklist(SCC.getNode());
13099 AddToWorklist(Temp.getNode());
13101 if (N2C->getAPIntValue() == 1)
13104 // shl setcc result by log2 n2c
13105 return DAG.getNode(
13106 ISD::SHL, DL, N2.getValueType(), Temp,
13107 DAG.getConstant(N2C->getAPIntValue().logBase2(),
13108 getShiftAmountTy(Temp.getValueType())));
13112 // Check to see if this is the equivalent of setcc
13113 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13114 // otherwise, go ahead with the folds.
13115 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13116 EVT XType = N0.getValueType();
13117 if (!LegalOperations ||
13118 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13119 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13120 if (Res.getValueType() != VT)
13121 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13125 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13126 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13127 (!LegalOperations ||
13128 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13129 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13130 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13131 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13132 getShiftAmountTy(Ctlz.getValueType())));
13134 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13135 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13136 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
13137 XType, DAG.getConstant(0, XType), N0);
13138 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
13139 return DAG.getNode(ISD::SRL, DL, XType,
13140 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13141 DAG.getConstant(XType.getSizeInBits()-1,
13142 getShiftAmountTy(XType)));
13144 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13145 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13146 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
13147 DAG.getConstant(XType.getSizeInBits()-1,
13148 getShiftAmountTy(N0.getValueType())));
13149 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
13153 // Check to see if this is an integer abs.
13154 // select_cc setg[te] X, 0, X, -X ->
13155 // select_cc setgt X, -1, X, -X ->
13156 // select_cc setl[te] X, 0, -X, X ->
13157 // select_cc setlt X, 1, -X, X ->
13158 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13160 ConstantSDNode *SubC = nullptr;
13161 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13162 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13163 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13164 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13165 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13166 (N1C->isOne() && CC == ISD::SETLT)) &&
13167 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13168 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13170 EVT XType = N0.getValueType();
13171 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13172 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
13174 DAG.getConstant(XType.getSizeInBits()-1,
13175 getShiftAmountTy(N0.getValueType())));
13176 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
13178 AddToWorklist(Shift.getNode());
13179 AddToWorklist(Add.getNode());
13180 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13187 /// This is a stub for TargetLowering::SimplifySetCC.
13188 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13189 SDValue N1, ISD::CondCode Cond,
13190 SDLoc DL, bool foldBooleans) {
13191 TargetLowering::DAGCombinerInfo
13192 DagCombineInfo(DAG, Level, false, this);
13193 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13196 /// Given an ISD::SDIV node expressing a divide by constant, return
13197 /// a DAG expression to select that will generate the same value by multiplying
13198 /// by a magic number.
13199 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13200 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13201 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13205 // Avoid division by zero.
13206 if (!C->getAPIntValue())
13209 std::vector<SDNode*> Built;
13211 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13213 for (SDNode *N : Built)
13218 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13219 /// DAG expression that will generate the same value by right shifting.
13220 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13221 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13225 // Avoid division by zero.
13226 if (!C->getAPIntValue())
13229 std::vector<SDNode *> Built;
13230 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13232 for (SDNode *N : Built)
13237 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13238 /// expression that will generate the same value by multiplying by a magic
13240 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13241 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13242 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13246 // Avoid division by zero.
13247 if (!C->getAPIntValue())
13250 std::vector<SDNode*> Built;
13252 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13254 for (SDNode *N : Built)
13259 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13260 if (Level >= AfterLegalizeDAG)
13263 // Expose the DAG combiner to the target combiner implementations.
13264 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13266 unsigned Iterations = 0;
13267 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13269 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13270 // For the reciprocal, we need to find the zero of the function:
13271 // F(X) = A X - 1 [which has a zero at X = 1/A]
13273 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13274 // does not require additional intermediate precision]
13275 EVT VT = Op.getValueType();
13277 SDValue FPOne = DAG.getConstantFP(1.0, VT);
13279 AddToWorklist(Est.getNode());
13281 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13282 for (unsigned i = 0; i < Iterations; ++i) {
13283 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13284 AddToWorklist(NewEst.getNode());
13286 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13287 AddToWorklist(NewEst.getNode());
13289 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13290 AddToWorklist(NewEst.getNode());
13292 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13293 AddToWorklist(Est.getNode());
13302 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13303 /// For the reciprocal sqrt, we need to find the zero of the function:
13304 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13306 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13307 /// As a result, we precompute A/2 prior to the iteration loop.
13308 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13309 unsigned Iterations) {
13310 EVT VT = Arg.getValueType();
13312 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
13314 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13315 // this entire sequence requires only one FP constant.
13316 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13317 AddToWorklist(HalfArg.getNode());
13319 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13320 AddToWorklist(HalfArg.getNode());
13322 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13323 for (unsigned i = 0; i < Iterations; ++i) {
13324 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13325 AddToWorklist(NewEst.getNode());
13327 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13328 AddToWorklist(NewEst.getNode());
13330 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13331 AddToWorklist(NewEst.getNode());
13333 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13334 AddToWorklist(Est.getNode());
13339 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13340 /// For the reciprocal sqrt, we need to find the zero of the function:
13341 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13343 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13344 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13345 unsigned Iterations) {
13346 EVT VT = Arg.getValueType();
13348 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13349 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13351 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13352 for (unsigned i = 0; i < Iterations; ++i) {
13353 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13354 AddToWorklist(HalfEst.getNode());
13356 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13357 AddToWorklist(Est.getNode());
13359 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13360 AddToWorklist(Est.getNode());
13362 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13363 AddToWorklist(Est.getNode());
13365 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13366 AddToWorklist(Est.getNode());
13371 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13372 if (Level >= AfterLegalizeDAG)
13375 // Expose the DAG combiner to the target combiner implementations.
13376 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13377 unsigned Iterations = 0;
13378 bool UseOneConstNR = false;
13379 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13380 AddToWorklist(Est.getNode());
13382 Est = UseOneConstNR ?
13383 BuildRsqrtNROneConst(Op, Est, Iterations) :
13384 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13392 /// Return true if base is a frame index, which is known not to alias with
13393 /// anything but itself. Provides base object and offset as results.
13394 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13395 const GlobalValue *&GV, const void *&CV) {
13396 // Assume it is a primitive operation.
13397 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13399 // If it's an adding a simple constant then integrate the offset.
13400 if (Base.getOpcode() == ISD::ADD) {
13401 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13402 Base = Base.getOperand(0);
13403 Offset += C->getZExtValue();
13407 // Return the underlying GlobalValue, and update the Offset. Return false
13408 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13409 // by multiple nodes with different offsets.
13410 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13411 GV = G->getGlobal();
13412 Offset += G->getOffset();
13416 // Return the underlying Constant value, and update the Offset. Return false
13417 // for ConstantSDNodes since the same constant pool entry may be represented
13418 // by multiple nodes with different offsets.
13419 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13420 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13421 : (const void *)C->getConstVal();
13422 Offset += C->getOffset();
13425 // If it's any of the following then it can't alias with anything but itself.
13426 return isa<FrameIndexSDNode>(Base);
13429 /// Return true if there is any possibility that the two addresses overlap.
13430 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13431 // If they are the same then they must be aliases.
13432 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13434 // If they are both volatile then they cannot be reordered.
13435 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13437 // Gather base node and offset information.
13438 SDValue Base1, Base2;
13439 int64_t Offset1, Offset2;
13440 const GlobalValue *GV1, *GV2;
13441 const void *CV1, *CV2;
13442 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13443 Base1, Offset1, GV1, CV1);
13444 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13445 Base2, Offset2, GV2, CV2);
13447 // If they have a same base address then check to see if they overlap.
13448 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13449 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13450 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13452 // It is possible for different frame indices to alias each other, mostly
13453 // when tail call optimization reuses return address slots for arguments.
13454 // To catch this case, look up the actual index of frame indices to compute
13455 // the real alias relationship.
13456 if (isFrameIndex1 && isFrameIndex2) {
13457 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13458 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13459 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13460 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13461 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13464 // Otherwise, if we know what the bases are, and they aren't identical, then
13465 // we know they cannot alias.
13466 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13469 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13470 // compared to the size and offset of the access, we may be able to prove they
13471 // do not alias. This check is conservative for now to catch cases created by
13472 // splitting vector types.
13473 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13474 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13475 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13476 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13477 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13478 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13479 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13481 // There is no overlap between these relatively aligned accesses of similar
13482 // size, return no alias.
13483 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13484 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13488 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13490 : DAG.getSubtarget().useAA();
13492 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13493 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13497 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13498 // Use alias analysis information.
13499 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13500 Op1->getSrcValueOffset());
13501 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13502 Op0->getSrcValueOffset() - MinOffset;
13503 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13504 Op1->getSrcValueOffset() - MinOffset;
13505 AliasAnalysis::AliasResult AAResult =
13506 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13508 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13509 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13511 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13512 if (AAResult == AliasAnalysis::NoAlias)
13516 // Otherwise we have to assume they alias.
13520 /// Walk up chain skipping non-aliasing memory nodes,
13521 /// looking for aliasing nodes and adding them to the Aliases vector.
13522 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13523 SmallVectorImpl<SDValue> &Aliases) {
13524 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13525 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13527 // Get alias information for node.
13528 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13531 Chains.push_back(OriginalChain);
13532 unsigned Depth = 0;
13534 // Look at each chain and determine if it is an alias. If so, add it to the
13535 // aliases list. If not, then continue up the chain looking for the next
13537 while (!Chains.empty()) {
13538 SDValue Chain = Chains.back();
13541 // For TokenFactor nodes, look at each operand and only continue up the
13542 // chain until we find two aliases. If we've seen two aliases, assume we'll
13543 // find more and revert to original chain since the xform is unlikely to be
13546 // FIXME: The depth check could be made to return the last non-aliasing
13547 // chain we found before we hit a tokenfactor rather than the original
13549 if (Depth > 6 || Aliases.size() == 2) {
13551 Aliases.push_back(OriginalChain);
13555 // Don't bother if we've been before.
13556 if (!Visited.insert(Chain.getNode()).second)
13559 switch (Chain.getOpcode()) {
13560 case ISD::EntryToken:
13561 // Entry token is ideal chain operand, but handled in FindBetterChain.
13566 // Get alias information for Chain.
13567 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13568 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13570 // If chain is alias then stop here.
13571 if (!(IsLoad && IsOpLoad) &&
13572 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13573 Aliases.push_back(Chain);
13575 // Look further up the chain.
13576 Chains.push_back(Chain.getOperand(0));
13582 case ISD::TokenFactor:
13583 // We have to check each of the operands of the token factor for "small"
13584 // token factors, so we queue them up. Adding the operands to the queue
13585 // (stack) in reverse order maintains the original order and increases the
13586 // likelihood that getNode will find a matching token factor (CSE.)
13587 if (Chain.getNumOperands() > 16) {
13588 Aliases.push_back(Chain);
13591 for (unsigned n = Chain.getNumOperands(); n;)
13592 Chains.push_back(Chain.getOperand(--n));
13597 // For all other instructions we will just have to take what we can get.
13598 Aliases.push_back(Chain);
13603 // We need to be careful here to also search for aliases through the
13604 // value operand of a store, etc. Consider the following situation:
13606 // L1 = load Token1, %52
13607 // S1 = store Token1, L1, %51
13608 // L2 = load Token1, %52+8
13609 // S2 = store Token1, L2, %51+8
13610 // Token2 = Token(S1, S2)
13611 // L3 = load Token2, %53
13612 // S3 = store Token2, L3, %52
13613 // L4 = load Token2, %53+8
13614 // S4 = store Token2, L4, %52+8
13615 // If we search for aliases of S3 (which loads address %52), and we look
13616 // only through the chain, then we'll miss the trivial dependence on L1
13617 // (which also loads from %52). We then might change all loads and
13618 // stores to use Token1 as their chain operand, which could result in
13619 // copying %53 into %52 before copying %52 into %51 (which should
13622 // The problem is, however, that searching for such data dependencies
13623 // can become expensive, and the cost is not directly related to the
13624 // chain depth. Instead, we'll rule out such configurations here by
13625 // insisting that we've visited all chain users (except for users
13626 // of the original chain, which is not necessary). When doing this,
13627 // we need to look through nodes we don't care about (otherwise, things
13628 // like register copies will interfere with trivial cases).
13630 SmallVector<const SDNode *, 16> Worklist;
13631 for (const SDNode *N : Visited)
13632 if (N != OriginalChain.getNode())
13633 Worklist.push_back(N);
13635 while (!Worklist.empty()) {
13636 const SDNode *M = Worklist.pop_back_val();
13638 // We have already visited M, and want to make sure we've visited any uses
13639 // of M that we care about. For uses that we've not visisted, and don't
13640 // care about, queue them to the worklist.
13642 for (SDNode::use_iterator UI = M->use_begin(),
13643 UIE = M->use_end(); UI != UIE; ++UI)
13644 if (UI.getUse().getValueType() == MVT::Other &&
13645 Visited.insert(*UI).second) {
13646 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13647 // We've not visited this use, and we care about it (it could have an
13648 // ordering dependency with the original node).
13650 Aliases.push_back(OriginalChain);
13654 // We've not visited this use, but we don't care about it. Mark it as
13655 // visited and enqueue it to the worklist.
13656 Worklist.push_back(*UI);
13661 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13662 /// (aliasing node.)
13663 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13664 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13666 // Accumulate all the aliases to this node.
13667 GatherAllAliases(N, OldChain, Aliases);
13669 // If no operands then chain to entry token.
13670 if (Aliases.size() == 0)
13671 return DAG.getEntryNode();
13673 // If a single operand then chain to it. We don't need to revisit it.
13674 if (Aliases.size() == 1)
13677 // Construct a custom tailored token factor.
13678 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13681 /// This is the entry point for the file.
13682 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13683 CodeGenOpt::Level OptLevel) {
13684 /// This is the main entry point to this class.
13685 DAGCombiner(*this, AA, OptLevel).Run(Level);