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 visitREM(SDNode *N);
239 SDValue visitMULHU(SDNode *N);
240 SDValue visitMULHS(SDNode *N);
241 SDValue visitSMUL_LOHI(SDNode *N);
242 SDValue visitUMUL_LOHI(SDNode *N);
243 SDValue visitSMULO(SDNode *N);
244 SDValue visitUMULO(SDNode *N);
245 SDValue visitSDIVREM(SDNode *N);
246 SDValue visitUDIVREM(SDNode *N);
247 SDValue visitIMINMAX(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 visitBSWAP(SDNode *N);
259 SDValue visitCTLZ(SDNode *N);
260 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTTZ(SDNode *N);
262 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263 SDValue visitCTPOP(SDNode *N);
264 SDValue visitSELECT(SDNode *N);
265 SDValue visitVSELECT(SDNode *N);
266 SDValue visitSELECT_CC(SDNode *N);
267 SDValue visitSETCC(SDNode *N);
268 SDValue visitSIGN_EXTEND(SDNode *N);
269 SDValue visitZERO_EXTEND(SDNode *N);
270 SDValue visitANY_EXTEND(SDNode *N);
271 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
273 SDValue visitTRUNCATE(SDNode *N);
274 SDValue visitBITCAST(SDNode *N);
275 SDValue visitBUILD_PAIR(SDNode *N);
276 SDValue visitFADD(SDNode *N);
277 SDValue visitFSUB(SDNode *N);
278 SDValue visitFMUL(SDNode *N);
279 SDValue visitFMA(SDNode *N);
280 SDValue visitFDIV(SDNode *N);
281 SDValue visitFREM(SDNode *N);
282 SDValue visitFSQRT(SDNode *N);
283 SDValue visitFCOPYSIGN(SDNode *N);
284 SDValue visitSINT_TO_FP(SDNode *N);
285 SDValue visitUINT_TO_FP(SDNode *N);
286 SDValue visitFP_TO_SINT(SDNode *N);
287 SDValue visitFP_TO_UINT(SDNode *N);
288 SDValue visitFP_ROUND(SDNode *N);
289 SDValue visitFP_ROUND_INREG(SDNode *N);
290 SDValue visitFP_EXTEND(SDNode *N);
291 SDValue visitFNEG(SDNode *N);
292 SDValue visitFABS(SDNode *N);
293 SDValue visitFCEIL(SDNode *N);
294 SDValue visitFTRUNC(SDNode *N);
295 SDValue visitFFLOOR(SDNode *N);
296 SDValue visitFMINNUM(SDNode *N);
297 SDValue visitFMAXNUM(SDNode *N);
298 SDValue visitBRCOND(SDNode *N);
299 SDValue visitBR_CC(SDNode *N);
300 SDValue visitLOAD(SDNode *N);
302 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
303 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
305 SDValue visitSTORE(SDNode *N);
306 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
307 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
308 SDValue visitBUILD_VECTOR(SDNode *N);
309 SDValue visitCONCAT_VECTORS(SDNode *N);
310 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
311 SDValue visitVECTOR_SHUFFLE(SDNode *N);
312 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
313 SDValue visitINSERT_SUBVECTOR(SDNode *N);
314 SDValue visitMLOAD(SDNode *N);
315 SDValue visitMSTORE(SDNode *N);
316 SDValue visitMGATHER(SDNode *N);
317 SDValue visitMSCATTER(SDNode *N);
318 SDValue visitFP_TO_FP16(SDNode *N);
319 SDValue visitFP16_TO_FP(SDNode *N);
321 SDValue visitFADDForFMACombine(SDNode *N);
322 SDValue visitFSUBForFMACombine(SDNode *N);
323 SDValue visitFMULForFMACombine(SDNode *N);
325 SDValue XformToShuffleWithZero(SDNode *N);
326 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
328 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
330 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
331 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
332 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
333 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
334 SDValue N3, ISD::CondCode CC,
335 bool NotExtCompare = false);
336 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
337 SDLoc DL, bool foldBooleans = true);
339 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
341 bool isOneUseSetCC(SDValue N) const;
343 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
345 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
346 SDValue CombineExtLoad(SDNode *N);
347 SDValue combineRepeatedFPDivisors(SDNode *N);
348 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
349 SDValue BuildSDIV(SDNode *N);
350 SDValue BuildSDIVPow2(SDNode *N);
351 SDValue BuildUDIV(SDNode *N);
352 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
353 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
354 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
356 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
358 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
359 bool DemandHighBits = true);
360 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
361 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
362 SDValue InnerPos, SDValue InnerNeg,
363 unsigned PosOpcode, unsigned NegOpcode,
365 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
366 SDValue ReduceLoadWidth(SDNode *N);
367 SDValue ReduceLoadOpStoreWidth(SDNode *N);
368 SDValue TransformFPLoadStorePair(SDNode *N);
369 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
370 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
372 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
374 /// Walk up chain skipping non-aliasing memory nodes,
375 /// looking for aliasing nodes and adding them to the Aliases vector.
376 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
377 SmallVectorImpl<SDValue> &Aliases);
379 /// Return true if there is any possibility that the two addresses overlap.
380 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
382 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
383 /// chain (aliasing node.)
384 SDValue FindBetterChain(SDNode *N, SDValue Chain);
386 /// Do FindBetterChain for a store and any possibly adjacent stores on
387 /// consecutive chains.
388 bool findBetterNeighborChains(StoreSDNode *St);
390 /// Holds a pointer to an LSBaseSDNode as well as information on where it
391 /// is located in a sequence of memory operations connected by a chain.
393 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
394 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
395 // Ptr to the mem node.
396 LSBaseSDNode *MemNode;
397 // Offset from the base ptr.
398 int64_t OffsetFromBase;
399 // What is the sequence number of this mem node.
400 // Lowest mem operand in the DAG starts at zero.
401 unsigned SequenceNum;
404 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
405 /// constant build_vector of the stored constant values in Stores.
406 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
408 ArrayRef<MemOpLink> Stores,
409 SmallVectorImpl<SDValue> &Chains,
412 /// This is a helper function for MergeConsecutiveStores. When the source
413 /// elements of the consecutive stores are all constants or all extracted
414 /// vector elements, try to merge them into one larger store.
415 /// \return True if a merged store was created.
416 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
417 EVT MemVT, unsigned NumStores,
418 bool IsConstantSrc, bool UseVector);
420 /// This is a helper function for MergeConsecutiveStores.
421 /// Stores that may be merged are placed in StoreNodes.
422 /// Loads that may alias with those stores are placed in AliasLoadNodes.
423 void getStoreMergeAndAliasCandidates(
424 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
425 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
427 /// Merge consecutive store operations into a wide store.
428 /// This optimization uses wide integers or vectors when possible.
429 /// \return True if some memory operations were changed.
430 bool MergeConsecutiveStores(StoreSDNode *N);
432 /// \brief Try to transform a truncation where C is a constant:
433 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
435 /// \p N needs to be a truncation and its first operand an AND. Other
436 /// requirements are checked by the function (e.g. that trunc is
437 /// single-use) and if missed an empty SDValue is returned.
438 SDValue distributeTruncateThroughAnd(SDNode *N);
441 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
442 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
443 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
444 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
447 /// Runs the dag combiner on all nodes in the work list
448 void Run(CombineLevel AtLevel);
450 SelectionDAG &getDAG() const { return DAG; }
452 /// Returns a type large enough to hold any valid shift amount - before type
453 /// legalization these can be huge.
454 EVT getShiftAmountTy(EVT LHSTy) {
455 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
456 if (LHSTy.isVector())
458 auto &DL = DAG.getDataLayout();
459 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
460 : TLI.getPointerTy(DL);
463 /// This method returns true if we are running before type legalization or
464 /// if the specified VT is legal.
465 bool isTypeLegal(const EVT &VT) {
466 if (!LegalTypes) return true;
467 return TLI.isTypeLegal(VT);
470 /// Convenience wrapper around TargetLowering::getSetCCResultType
471 EVT getSetCCResultType(EVT VT) const {
472 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
479 /// This class is a DAGUpdateListener that removes any deleted
480 /// nodes from the worklist.
481 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
484 explicit WorklistRemover(DAGCombiner &dc)
485 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
487 void NodeDeleted(SDNode *N, SDNode *E) override {
488 DC.removeFromWorklist(N);
493 //===----------------------------------------------------------------------===//
494 // TargetLowering::DAGCombinerInfo implementation
495 //===----------------------------------------------------------------------===//
497 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
498 ((DAGCombiner*)DC)->AddToWorklist(N);
501 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
502 ((DAGCombiner*)DC)->removeFromWorklist(N);
505 SDValue TargetLowering::DAGCombinerInfo::
506 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
507 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
510 SDValue TargetLowering::DAGCombinerInfo::
511 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
512 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
516 SDValue TargetLowering::DAGCombinerInfo::
517 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
518 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
521 void TargetLowering::DAGCombinerInfo::
522 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
523 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
526 //===----------------------------------------------------------------------===//
528 //===----------------------------------------------------------------------===//
530 void DAGCombiner::deleteAndRecombine(SDNode *N) {
531 removeFromWorklist(N);
533 // If the operands of this node are only used by the node, they will now be
534 // dead. Make sure to re-visit them and recursively delete dead nodes.
535 for (const SDValue &Op : N->ops())
536 // For an operand generating multiple values, one of the values may
537 // become dead allowing further simplification (e.g. split index
538 // arithmetic from an indexed load).
539 if (Op->hasOneUse() || Op->getNumValues() > 1)
540 AddToWorklist(Op.getNode());
545 /// Return 1 if we can compute the negated form of the specified expression for
546 /// the same cost as the expression itself, or 2 if we can compute the negated
547 /// form more cheaply than the expression itself.
548 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
549 const TargetLowering &TLI,
550 const TargetOptions *Options,
551 unsigned Depth = 0) {
552 // fneg is removable even if it has multiple uses.
553 if (Op.getOpcode() == ISD::FNEG) return 2;
555 // Don't allow anything with multiple uses.
556 if (!Op.hasOneUse()) return 0;
558 // Don't recurse exponentially.
559 if (Depth > 6) return 0;
561 switch (Op.getOpcode()) {
562 default: return false;
563 case ISD::ConstantFP:
564 // Don't invert constant FP values after legalize. The negated constant
565 // isn't necessarily legal.
566 return LegalOperations ? 0 : 1;
568 // FIXME: determine better conditions for this xform.
569 if (!Options->UnsafeFPMath) return 0;
571 // After operation legalization, it might not be legal to create new FSUBs.
572 if (LegalOperations &&
573 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
576 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
577 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
580 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
581 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
584 // We can't turn -(A-B) into B-A when we honor signed zeros.
585 if (!Options->UnsafeFPMath) return 0;
587 // fold (fneg (fsub A, B)) -> (fsub B, A)
592 if (Options->HonorSignDependentRoundingFPMath()) return 0;
594 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
595 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
599 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
605 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
610 /// If isNegatibleForFree returns true, return the newly negated expression.
611 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
612 bool LegalOperations, unsigned Depth = 0) {
613 const TargetOptions &Options = DAG.getTarget().Options;
614 // fneg is removable even if it has multiple uses.
615 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
617 // Don't allow anything with multiple uses.
618 assert(Op.hasOneUse() && "Unknown reuse!");
620 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
622 const SDNodeFlags *Flags = Op.getNode()->getFlags();
624 switch (Op.getOpcode()) {
625 default: llvm_unreachable("Unknown code");
626 case ISD::ConstantFP: {
627 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
629 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
632 // FIXME: determine better conditions for this xform.
633 assert(Options.UnsafeFPMath);
635 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
636 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
637 DAG.getTargetLoweringInfo(), &Options, Depth+1))
638 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
639 GetNegatedExpression(Op.getOperand(0), DAG,
640 LegalOperations, Depth+1),
641 Op.getOperand(1), Flags);
642 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
643 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
644 GetNegatedExpression(Op.getOperand(1), DAG,
645 LegalOperations, Depth+1),
646 Op.getOperand(0), Flags);
648 // We can't turn -(A-B) into B-A when we honor signed zeros.
649 assert(Options.UnsafeFPMath);
651 // fold (fneg (fsub 0, B)) -> B
652 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
654 return Op.getOperand(1);
656 // fold (fneg (fsub A, B)) -> (fsub B, A)
657 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
658 Op.getOperand(1), Op.getOperand(0), Flags);
662 assert(!Options.HonorSignDependentRoundingFPMath());
664 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
665 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
666 DAG.getTargetLoweringInfo(), &Options, Depth+1))
667 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
668 GetNegatedExpression(Op.getOperand(0), DAG,
669 LegalOperations, Depth+1),
670 Op.getOperand(1), Flags);
672 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
673 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
675 GetNegatedExpression(Op.getOperand(1), DAG,
676 LegalOperations, Depth+1), Flags);
680 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
681 GetNegatedExpression(Op.getOperand(0), DAG,
682 LegalOperations, Depth+1));
684 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
685 GetNegatedExpression(Op.getOperand(0), DAG,
686 LegalOperations, Depth+1),
691 // Return true if this node is a setcc, or is a select_cc
692 // that selects between the target values used for true and false, making it
693 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
694 // the appropriate nodes based on the type of node we are checking. This
695 // simplifies life a bit for the callers.
696 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
698 if (N.getOpcode() == ISD::SETCC) {
699 LHS = N.getOperand(0);
700 RHS = N.getOperand(1);
701 CC = N.getOperand(2);
705 if (N.getOpcode() != ISD::SELECT_CC ||
706 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
707 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
710 if (TLI.getBooleanContents(N.getValueType()) ==
711 TargetLowering::UndefinedBooleanContent)
714 LHS = N.getOperand(0);
715 RHS = N.getOperand(1);
716 CC = N.getOperand(4);
720 /// Return true if this is a SetCC-equivalent operation with only one use.
721 /// If this is true, it allows the users to invert the operation for free when
722 /// it is profitable to do so.
723 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
725 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
730 /// Returns true if N is a BUILD_VECTOR node whose
731 /// elements are all the same constant or undefined.
732 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
733 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
738 unsigned SplatBitSize;
740 EVT EltVT = N->getValueType(0).getVectorElementType();
741 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
743 EltVT.getSizeInBits() >= SplatBitSize);
746 // \brief Returns the SDNode if it is a constant integer BuildVector
747 // or constant integer.
748 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
749 if (isa<ConstantSDNode>(N))
751 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
756 // \brief Returns the SDNode if it is a constant float BuildVector
757 // or constant float.
758 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
759 if (isa<ConstantFPSDNode>(N))
761 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
766 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
768 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
769 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
772 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
773 BitVector UndefElements;
774 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
776 // BuildVectors can truncate their operands. Ignore that case here.
777 // FIXME: We blindly ignore splats which include undef which is overly
779 if (CN && UndefElements.none() &&
780 CN->getValueType(0) == N.getValueType().getScalarType())
787 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
789 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
790 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
793 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
794 BitVector UndefElements;
795 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
797 if (CN && UndefElements.none())
804 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
805 SDValue N0, SDValue N1) {
806 EVT VT = N0.getValueType();
807 if (N0.getOpcode() == Opc) {
808 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
809 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
810 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
811 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
812 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
815 if (N0.hasOneUse()) {
816 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
818 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
819 if (!OpNode.getNode())
821 AddToWorklist(OpNode.getNode());
822 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
827 if (N1.getOpcode() == Opc) {
828 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
829 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
830 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
831 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
832 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
835 if (N1.hasOneUse()) {
836 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
838 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
839 if (!OpNode.getNode())
841 AddToWorklist(OpNode.getNode());
842 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
850 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
852 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
854 DEBUG(dbgs() << "\nReplacing.1 ";
856 dbgs() << "\nWith: ";
857 To[0].getNode()->dump(&DAG);
858 dbgs() << " and " << NumTo-1 << " other values\n");
859 for (unsigned i = 0, e = NumTo; i != e; ++i)
860 assert((!To[i].getNode() ||
861 N->getValueType(i) == To[i].getValueType()) &&
862 "Cannot combine value to value of different type!");
864 WorklistRemover DeadNodes(*this);
865 DAG.ReplaceAllUsesWith(N, To);
867 // Push the new nodes and any users onto the worklist
868 for (unsigned i = 0, e = NumTo; i != e; ++i) {
869 if (To[i].getNode()) {
870 AddToWorklist(To[i].getNode());
871 AddUsersToWorklist(To[i].getNode());
876 // Finally, if the node is now dead, remove it from the graph. The node
877 // may not be dead if the replacement process recursively simplified to
878 // something else needing this node.
880 deleteAndRecombine(N);
881 return SDValue(N, 0);
885 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
886 // Replace all uses. If any nodes become isomorphic to other nodes and
887 // are deleted, make sure to remove them from our worklist.
888 WorklistRemover DeadNodes(*this);
889 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
891 // Push the new node and any (possibly new) users onto the worklist.
892 AddToWorklist(TLO.New.getNode());
893 AddUsersToWorklist(TLO.New.getNode());
895 // Finally, if the node is now dead, remove it from the graph. The node
896 // may not be dead if the replacement process recursively simplified to
897 // something else needing this node.
898 if (TLO.Old.getNode()->use_empty())
899 deleteAndRecombine(TLO.Old.getNode());
902 /// Check the specified integer node value to see if it can be simplified or if
903 /// things it uses can be simplified by bit propagation. If so, return true.
904 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
905 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
906 APInt KnownZero, KnownOne;
907 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
911 AddToWorklist(Op.getNode());
913 // Replace the old value with the new one.
915 DEBUG(dbgs() << "\nReplacing.2 ";
916 TLO.Old.getNode()->dump(&DAG);
917 dbgs() << "\nWith: ";
918 TLO.New.getNode()->dump(&DAG);
921 CommitTargetLoweringOpt(TLO);
925 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
927 EVT VT = Load->getValueType(0);
928 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
930 DEBUG(dbgs() << "\nReplacing.9 ";
932 dbgs() << "\nWith: ";
933 Trunc.getNode()->dump(&DAG);
935 WorklistRemover DeadNodes(*this);
936 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
937 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
938 deleteAndRecombine(Load);
939 AddToWorklist(Trunc.getNode());
942 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
945 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
946 EVT MemVT = LD->getMemoryVT();
947 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
948 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
950 : LD->getExtensionType();
952 return DAG.getExtLoad(ExtType, dl, PVT,
953 LD->getChain(), LD->getBasePtr(),
954 MemVT, LD->getMemOperand());
957 unsigned Opc = Op.getOpcode();
960 case ISD::AssertSext:
961 return DAG.getNode(ISD::AssertSext, dl, PVT,
962 SExtPromoteOperand(Op.getOperand(0), PVT),
964 case ISD::AssertZext:
965 return DAG.getNode(ISD::AssertZext, dl, PVT,
966 ZExtPromoteOperand(Op.getOperand(0), PVT),
968 case ISD::Constant: {
970 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
971 return DAG.getNode(ExtOpc, dl, PVT, Op);
975 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
977 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
980 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
981 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
983 EVT OldVT = Op.getValueType();
985 bool Replace = false;
986 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
987 if (!NewOp.getNode())
989 AddToWorklist(NewOp.getNode());
992 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
993 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
994 DAG.getValueType(OldVT));
997 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
998 EVT OldVT = Op.getValueType();
1000 bool Replace = false;
1001 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1002 if (!NewOp.getNode())
1004 AddToWorklist(NewOp.getNode());
1007 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1008 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1011 /// Promote the specified integer binary operation if the target indicates it is
1012 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1013 /// i32 since i16 instructions are longer.
1014 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1015 if (!LegalOperations)
1018 EVT VT = Op.getValueType();
1019 if (VT.isVector() || !VT.isInteger())
1022 // If operation type is 'undesirable', e.g. i16 on x86, consider
1024 unsigned Opc = Op.getOpcode();
1025 if (TLI.isTypeDesirableForOp(Opc, VT))
1029 // Consult target whether it is a good idea to promote this operation and
1030 // what's the right type to promote it to.
1031 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1032 assert(PVT != VT && "Don't know what type to promote to!");
1034 bool Replace0 = false;
1035 SDValue N0 = Op.getOperand(0);
1036 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1040 bool Replace1 = false;
1041 SDValue N1 = Op.getOperand(1);
1046 NN1 = PromoteOperand(N1, PVT, Replace1);
1051 AddToWorklist(NN0.getNode());
1053 AddToWorklist(NN1.getNode());
1056 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1058 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1060 DEBUG(dbgs() << "\nPromoting ";
1061 Op.getNode()->dump(&DAG));
1063 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1064 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1069 /// Promote the specified integer shift operation if the target indicates it is
1070 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1071 /// i32 since i16 instructions are longer.
1072 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1073 if (!LegalOperations)
1076 EVT VT = Op.getValueType();
1077 if (VT.isVector() || !VT.isInteger())
1080 // If operation type is 'undesirable', e.g. i16 on x86, consider
1082 unsigned Opc = Op.getOpcode();
1083 if (TLI.isTypeDesirableForOp(Opc, VT))
1087 // Consult target whether it is a good idea to promote this operation and
1088 // what's the right type to promote it to.
1089 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1090 assert(PVT != VT && "Don't know what type to promote to!");
1092 bool Replace = false;
1093 SDValue N0 = Op.getOperand(0);
1094 if (Opc == ISD::SRA)
1095 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1096 else if (Opc == ISD::SRL)
1097 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1099 N0 = PromoteOperand(N0, PVT, Replace);
1103 AddToWorklist(N0.getNode());
1105 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1107 DEBUG(dbgs() << "\nPromoting ";
1108 Op.getNode()->dump(&DAG));
1110 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1111 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1116 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1117 if (!LegalOperations)
1120 EVT VT = Op.getValueType();
1121 if (VT.isVector() || !VT.isInteger())
1124 // If operation type is 'undesirable', e.g. i16 on x86, consider
1126 unsigned Opc = Op.getOpcode();
1127 if (TLI.isTypeDesirableForOp(Opc, VT))
1131 // Consult target whether it is a good idea to promote this operation and
1132 // what's the right type to promote it to.
1133 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1134 assert(PVT != VT && "Don't know what type to promote to!");
1135 // fold (aext (aext x)) -> (aext x)
1136 // fold (aext (zext x)) -> (zext x)
1137 // fold (aext (sext x)) -> (sext x)
1138 DEBUG(dbgs() << "\nPromoting ";
1139 Op.getNode()->dump(&DAG));
1140 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1145 bool DAGCombiner::PromoteLoad(SDValue Op) {
1146 if (!LegalOperations)
1149 EVT VT = Op.getValueType();
1150 if (VT.isVector() || !VT.isInteger())
1153 // If operation type is 'undesirable', e.g. i16 on x86, consider
1155 unsigned Opc = Op.getOpcode();
1156 if (TLI.isTypeDesirableForOp(Opc, VT))
1160 // Consult target whether it is a good idea to promote this operation and
1161 // what's the right type to promote it to.
1162 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1163 assert(PVT != VT && "Don't know what type to promote to!");
1166 SDNode *N = Op.getNode();
1167 LoadSDNode *LD = cast<LoadSDNode>(N);
1168 EVT MemVT = LD->getMemoryVT();
1169 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1170 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1172 : LD->getExtensionType();
1173 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1174 LD->getChain(), LD->getBasePtr(),
1175 MemVT, LD->getMemOperand());
1176 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1178 DEBUG(dbgs() << "\nPromoting ";
1181 Result.getNode()->dump(&DAG);
1183 WorklistRemover DeadNodes(*this);
1184 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1185 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1186 deleteAndRecombine(N);
1187 AddToWorklist(Result.getNode());
1193 /// \brief Recursively delete a node which has no uses and any operands for
1194 /// which it is the only use.
1196 /// Note that this both deletes the nodes and removes them from the worklist.
1197 /// It also adds any nodes who have had a user deleted to the worklist as they
1198 /// may now have only one use and subject to other combines.
1199 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1200 if (!N->use_empty())
1203 SmallSetVector<SDNode *, 16> Nodes;
1206 N = Nodes.pop_back_val();
1210 if (N->use_empty()) {
1211 for (const SDValue &ChildN : N->op_values())
1212 Nodes.insert(ChildN.getNode());
1214 removeFromWorklist(N);
1219 } while (!Nodes.empty());
1223 //===----------------------------------------------------------------------===//
1224 // Main DAG Combiner implementation
1225 //===----------------------------------------------------------------------===//
1227 void DAGCombiner::Run(CombineLevel AtLevel) {
1228 // set the instance variables, so that the various visit routines may use it.
1230 LegalOperations = Level >= AfterLegalizeVectorOps;
1231 LegalTypes = Level >= AfterLegalizeTypes;
1233 // Add all the dag nodes to the worklist.
1234 for (SDNode &Node : DAG.allnodes())
1235 AddToWorklist(&Node);
1237 // Create a dummy node (which is not added to allnodes), that adds a reference
1238 // to the root node, preventing it from being deleted, and tracking any
1239 // changes of the root.
1240 HandleSDNode Dummy(DAG.getRoot());
1242 // while the worklist isn't empty, find a node and
1243 // try and combine it.
1244 while (!WorklistMap.empty()) {
1246 // The Worklist holds the SDNodes in order, but it may contain null entries.
1248 N = Worklist.pop_back_val();
1251 bool GoodWorklistEntry = WorklistMap.erase(N);
1252 (void)GoodWorklistEntry;
1253 assert(GoodWorklistEntry &&
1254 "Found a worklist entry without a corresponding map entry!");
1256 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1257 // N is deleted from the DAG, since they too may now be dead or may have a
1258 // reduced number of uses, allowing other xforms.
1259 if (recursivelyDeleteUnusedNodes(N))
1262 WorklistRemover DeadNodes(*this);
1264 // If this combine is running after legalizing the DAG, re-legalize any
1265 // nodes pulled off the worklist.
1266 if (Level == AfterLegalizeDAG) {
1267 SmallSetVector<SDNode *, 16> UpdatedNodes;
1268 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1270 for (SDNode *LN : UpdatedNodes) {
1272 AddUsersToWorklist(LN);
1278 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1280 // Add any operands of the new node which have not yet been combined to the
1281 // worklist as well. Because the worklist uniques things already, this
1282 // won't repeatedly process the same operand.
1283 CombinedNodes.insert(N);
1284 for (const SDValue &ChildN : N->op_values())
1285 if (!CombinedNodes.count(ChildN.getNode()))
1286 AddToWorklist(ChildN.getNode());
1288 SDValue RV = combine(N);
1295 // If we get back the same node we passed in, rather than a new node or
1296 // zero, we know that the node must have defined multiple values and
1297 // CombineTo was used. Since CombineTo takes care of the worklist
1298 // mechanics for us, we have no work to do in this case.
1299 if (RV.getNode() == N)
1302 assert(N->getOpcode() != ISD::DELETED_NODE &&
1303 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1304 "Node was deleted but visit returned new node!");
1306 DEBUG(dbgs() << " ... into: ";
1307 RV.getNode()->dump(&DAG));
1309 // Transfer debug value.
1310 DAG.TransferDbgValues(SDValue(N, 0), RV);
1311 if (N->getNumValues() == RV.getNode()->getNumValues())
1312 DAG.ReplaceAllUsesWith(N, RV.getNode());
1314 assert(N->getValueType(0) == RV.getValueType() &&
1315 N->getNumValues() == 1 && "Type mismatch");
1317 DAG.ReplaceAllUsesWith(N, &OpV);
1320 // Push the new node and any users onto the worklist
1321 AddToWorklist(RV.getNode());
1322 AddUsersToWorklist(RV.getNode());
1324 // Finally, if the node is now dead, remove it from the graph. The node
1325 // may not be dead if the replacement process recursively simplified to
1326 // something else needing this node. This will also take care of adding any
1327 // operands which have lost a user to the worklist.
1328 recursivelyDeleteUnusedNodes(N);
1331 // If the root changed (e.g. it was a dead load, update the root).
1332 DAG.setRoot(Dummy.getValue());
1333 DAG.RemoveDeadNodes();
1336 SDValue DAGCombiner::visit(SDNode *N) {
1337 switch (N->getOpcode()) {
1339 case ISD::TokenFactor: return visitTokenFactor(N);
1340 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1341 case ISD::ADD: return visitADD(N);
1342 case ISD::SUB: return visitSUB(N);
1343 case ISD::ADDC: return visitADDC(N);
1344 case ISD::SUBC: return visitSUBC(N);
1345 case ISD::ADDE: return visitADDE(N);
1346 case ISD::SUBE: return visitSUBE(N);
1347 case ISD::MUL: return visitMUL(N);
1348 case ISD::SDIV: return visitSDIV(N);
1349 case ISD::UDIV: return visitUDIV(N);
1351 case ISD::UREM: return visitREM(N);
1352 case ISD::MULHU: return visitMULHU(N);
1353 case ISD::MULHS: return visitMULHS(N);
1354 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1355 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1356 case ISD::SMULO: return visitSMULO(N);
1357 case ISD::UMULO: return visitUMULO(N);
1358 case ISD::SDIVREM: return visitSDIVREM(N);
1359 case ISD::UDIVREM: return visitUDIVREM(N);
1363 case ISD::UMAX: return visitIMINMAX(N);
1364 case ISD::AND: return visitAND(N);
1365 case ISD::OR: return visitOR(N);
1366 case ISD::XOR: return visitXOR(N);
1367 case ISD::SHL: return visitSHL(N);
1368 case ISD::SRA: return visitSRA(N);
1369 case ISD::SRL: return visitSRL(N);
1371 case ISD::ROTL: return visitRotate(N);
1372 case ISD::BSWAP: return visitBSWAP(N);
1373 case ISD::CTLZ: return visitCTLZ(N);
1374 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1375 case ISD::CTTZ: return visitCTTZ(N);
1376 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1377 case ISD::CTPOP: return visitCTPOP(N);
1378 case ISD::SELECT: return visitSELECT(N);
1379 case ISD::VSELECT: return visitVSELECT(N);
1380 case ISD::SELECT_CC: return visitSELECT_CC(N);
1381 case ISD::SETCC: return visitSETCC(N);
1382 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1383 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1384 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1385 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1386 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1387 case ISD::TRUNCATE: return visitTRUNCATE(N);
1388 case ISD::BITCAST: return visitBITCAST(N);
1389 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1390 case ISD::FADD: return visitFADD(N);
1391 case ISD::FSUB: return visitFSUB(N);
1392 case ISD::FMUL: return visitFMUL(N);
1393 case ISD::FMA: return visitFMA(N);
1394 case ISD::FDIV: return visitFDIV(N);
1395 case ISD::FREM: return visitFREM(N);
1396 case ISD::FSQRT: return visitFSQRT(N);
1397 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1398 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1399 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1400 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1401 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1402 case ISD::FP_ROUND: return visitFP_ROUND(N);
1403 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1404 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1405 case ISD::FNEG: return visitFNEG(N);
1406 case ISD::FABS: return visitFABS(N);
1407 case ISD::FFLOOR: return visitFFLOOR(N);
1408 case ISD::FMINNUM: return visitFMINNUM(N);
1409 case ISD::FMAXNUM: return visitFMAXNUM(N);
1410 case ISD::FCEIL: return visitFCEIL(N);
1411 case ISD::FTRUNC: return visitFTRUNC(N);
1412 case ISD::BRCOND: return visitBRCOND(N);
1413 case ISD::BR_CC: return visitBR_CC(N);
1414 case ISD::LOAD: return visitLOAD(N);
1415 case ISD::STORE: return visitSTORE(N);
1416 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1417 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1418 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1419 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1420 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1421 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1422 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1423 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1424 case ISD::MGATHER: return visitMGATHER(N);
1425 case ISD::MLOAD: return visitMLOAD(N);
1426 case ISD::MSCATTER: return visitMSCATTER(N);
1427 case ISD::MSTORE: return visitMSTORE(N);
1428 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1429 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1434 SDValue DAGCombiner::combine(SDNode *N) {
1435 SDValue RV = visit(N);
1437 // If nothing happened, try a target-specific DAG combine.
1438 if (!RV.getNode()) {
1439 assert(N->getOpcode() != ISD::DELETED_NODE &&
1440 "Node was deleted but visit returned NULL!");
1442 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1443 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1445 // Expose the DAG combiner to the target combiner impls.
1446 TargetLowering::DAGCombinerInfo
1447 DagCombineInfo(DAG, Level, false, this);
1449 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1453 // If nothing happened still, try promoting the operation.
1454 if (!RV.getNode()) {
1455 switch (N->getOpcode()) {
1463 RV = PromoteIntBinOp(SDValue(N, 0));
1468 RV = PromoteIntShiftOp(SDValue(N, 0));
1470 case ISD::SIGN_EXTEND:
1471 case ISD::ZERO_EXTEND:
1472 case ISD::ANY_EXTEND:
1473 RV = PromoteExtend(SDValue(N, 0));
1476 if (PromoteLoad(SDValue(N, 0)))
1482 // If N is a commutative binary node, try commuting it to enable more
1484 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1485 N->getNumValues() == 1) {
1486 SDValue N0 = N->getOperand(0);
1487 SDValue N1 = N->getOperand(1);
1489 // Constant operands are canonicalized to RHS.
1490 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1491 SDValue Ops[] = {N1, N0};
1492 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1495 return SDValue(CSENode, 0);
1502 /// Given a node, return its input chain if it has one, otherwise return a null
1504 static SDValue getInputChainForNode(SDNode *N) {
1505 if (unsigned NumOps = N->getNumOperands()) {
1506 if (N->getOperand(0).getValueType() == MVT::Other)
1507 return N->getOperand(0);
1508 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1509 return N->getOperand(NumOps-1);
1510 for (unsigned i = 1; i < NumOps-1; ++i)
1511 if (N->getOperand(i).getValueType() == MVT::Other)
1512 return N->getOperand(i);
1517 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1518 // If N has two operands, where one has an input chain equal to the other,
1519 // the 'other' chain is redundant.
1520 if (N->getNumOperands() == 2) {
1521 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1522 return N->getOperand(0);
1523 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1524 return N->getOperand(1);
1527 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1528 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1529 SmallPtrSet<SDNode*, 16> SeenOps;
1530 bool Changed = false; // If we should replace this token factor.
1532 // Start out with this token factor.
1535 // Iterate through token factors. The TFs grows when new token factors are
1537 for (unsigned i = 0; i < TFs.size(); ++i) {
1538 SDNode *TF = TFs[i];
1540 // Check each of the operands.
1541 for (const SDValue &Op : TF->op_values()) {
1543 switch (Op.getOpcode()) {
1544 case ISD::EntryToken:
1545 // Entry tokens don't need to be added to the list. They are
1550 case ISD::TokenFactor:
1551 if (Op.hasOneUse() &&
1552 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1553 // Queue up for processing.
1554 TFs.push_back(Op.getNode());
1555 // Clean up in case the token factor is removed.
1556 AddToWorklist(Op.getNode());
1563 // Only add if it isn't already in the list.
1564 if (SeenOps.insert(Op.getNode()).second)
1575 // If we've changed things around then replace token factor.
1578 // The entry token is the only possible outcome.
1579 Result = DAG.getEntryNode();
1581 // New and improved token factor.
1582 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1585 // Add users to worklist if AA is enabled, since it may introduce
1586 // a lot of new chained token factors while removing memory deps.
1587 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1588 : DAG.getSubtarget().useAA();
1589 return CombineTo(N, Result, UseAA /*add to worklist*/);
1595 /// MERGE_VALUES can always be eliminated.
1596 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1597 WorklistRemover DeadNodes(*this);
1598 // Replacing results may cause a different MERGE_VALUES to suddenly
1599 // be CSE'd with N, and carry its uses with it. Iterate until no
1600 // uses remain, to ensure that the node can be safely deleted.
1601 // First add the users of this node to the work list so that they
1602 // can be tried again once they have new operands.
1603 AddUsersToWorklist(N);
1605 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1606 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1607 } while (!N->use_empty());
1608 deleteAndRecombine(N);
1609 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1612 static bool isNullConstant(SDValue V) {
1613 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1614 return Const != nullptr && Const->isNullValue();
1617 static bool isNullFPConstant(SDValue V) {
1618 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1619 return Const != nullptr && Const->isZero() && !Const->isNegative();
1622 static bool isAllOnesConstant(SDValue V) {
1623 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1624 return Const != nullptr && Const->isAllOnesValue();
1627 static bool isOneConstant(SDValue V) {
1628 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1629 return Const != nullptr && Const->isOne();
1632 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1633 /// ContantSDNode pointer else nullptr.
1634 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1635 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1636 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1639 SDValue DAGCombiner::visitADD(SDNode *N) {
1640 SDValue N0 = N->getOperand(0);
1641 SDValue N1 = N->getOperand(1);
1642 EVT VT = N0.getValueType();
1645 if (VT.isVector()) {
1646 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1649 // fold (add x, 0) -> x, vector edition
1650 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1652 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1656 // fold (add x, undef) -> undef
1657 if (N0.getOpcode() == ISD::UNDEF)
1659 if (N1.getOpcode() == ISD::UNDEF)
1661 // fold (add c1, c2) -> c1+c2
1662 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1663 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1665 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1666 // canonicalize constant to RHS
1667 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1668 !isConstantIntBuildVectorOrConstantInt(N1))
1669 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1670 // fold (add x, 0) -> x
1671 if (isNullConstant(N1))
1673 // fold (add Sym, c) -> Sym+c
1674 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1675 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1676 GA->getOpcode() == ISD::GlobalAddress)
1677 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1679 (uint64_t)N1C->getSExtValue());
1680 // fold ((c1-A)+c2) -> (c1+c2)-A
1681 if (N1C && N0.getOpcode() == ISD::SUB)
1682 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1684 return DAG.getNode(ISD::SUB, DL, VT,
1685 DAG.getConstant(N1C->getAPIntValue()+
1686 N0C->getAPIntValue(), DL, VT),
1690 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1692 // fold ((0-A) + B) -> B-A
1693 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1694 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1695 // fold (A + (0-B)) -> A-B
1696 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1697 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1698 // fold (A+(B-A)) -> B
1699 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1700 return N1.getOperand(0);
1701 // fold ((B-A)+A) -> B
1702 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1703 return N0.getOperand(0);
1704 // fold (A+(B-(A+C))) to (B-C)
1705 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1706 N0 == N1.getOperand(1).getOperand(0))
1707 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1708 N1.getOperand(1).getOperand(1));
1709 // fold (A+(B-(C+A))) to (B-C)
1710 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1711 N0 == N1.getOperand(1).getOperand(1))
1712 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1713 N1.getOperand(1).getOperand(0));
1714 // fold (A+((B-A)+or-C)) to (B+or-C)
1715 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1716 N1.getOperand(0).getOpcode() == ISD::SUB &&
1717 N0 == N1.getOperand(0).getOperand(1))
1718 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1719 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1721 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1722 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1723 SDValue N00 = N0.getOperand(0);
1724 SDValue N01 = N0.getOperand(1);
1725 SDValue N10 = N1.getOperand(0);
1726 SDValue N11 = N1.getOperand(1);
1728 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1729 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1730 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1731 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1734 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1735 return SDValue(N, 0);
1737 // fold (a+b) -> (a|b) iff a and b share no bits.
1738 if (VT.isInteger() && !VT.isVector()) {
1739 APInt LHSZero, LHSOne;
1740 APInt RHSZero, RHSOne;
1741 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1743 if (LHSZero.getBoolValue()) {
1744 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1746 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1747 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1748 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1749 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1750 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1755 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1756 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1757 isNullConstant(N1.getOperand(0).getOperand(0)))
1758 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1759 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1760 N1.getOperand(0).getOperand(1),
1762 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1763 isNullConstant(N0.getOperand(0).getOperand(0)))
1764 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1765 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1766 N0.getOperand(0).getOperand(1),
1769 if (N1.getOpcode() == ISD::AND) {
1770 SDValue AndOp0 = N1.getOperand(0);
1771 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1772 unsigned DestBits = VT.getScalarType().getSizeInBits();
1774 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1775 // and similar xforms where the inner op is either ~0 or 0.
1776 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1778 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1782 // add (sext i1), X -> sub X, (zext i1)
1783 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1784 N0.getOperand(0).getValueType() == MVT::i1 &&
1785 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1787 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1788 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1791 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1792 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1793 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1794 if (TN->getVT() == MVT::i1) {
1796 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1797 DAG.getConstant(1, DL, VT));
1798 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1805 SDValue DAGCombiner::visitADDC(SDNode *N) {
1806 SDValue N0 = N->getOperand(0);
1807 SDValue N1 = N->getOperand(1);
1808 EVT VT = N0.getValueType();
1810 // If the flag result is dead, turn this into an ADD.
1811 if (!N->hasAnyUseOfValue(1))
1812 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1813 DAG.getNode(ISD::CARRY_FALSE,
1814 SDLoc(N), MVT::Glue));
1816 // canonicalize constant to RHS.
1817 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1818 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1820 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1822 // fold (addc x, 0) -> x + no carry out
1823 if (isNullConstant(N1))
1824 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1825 SDLoc(N), MVT::Glue));
1827 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1828 APInt LHSZero, LHSOne;
1829 APInt RHSZero, RHSOne;
1830 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1832 if (LHSZero.getBoolValue()) {
1833 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1835 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1836 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1837 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1838 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1839 DAG.getNode(ISD::CARRY_FALSE,
1840 SDLoc(N), MVT::Glue));
1846 SDValue DAGCombiner::visitADDE(SDNode *N) {
1847 SDValue N0 = N->getOperand(0);
1848 SDValue N1 = N->getOperand(1);
1849 SDValue CarryIn = N->getOperand(2);
1851 // canonicalize constant to RHS
1852 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1853 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1855 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1858 // fold (adde x, y, false) -> (addc x, y)
1859 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1860 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1865 // Since it may not be valid to emit a fold to zero for vector initializers
1866 // check if we can before folding.
1867 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1869 bool LegalOperations, bool LegalTypes) {
1871 return DAG.getConstant(0, DL, VT);
1872 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1873 return DAG.getConstant(0, DL, VT);
1877 SDValue DAGCombiner::visitSUB(SDNode *N) {
1878 SDValue N0 = N->getOperand(0);
1879 SDValue N1 = N->getOperand(1);
1880 EVT VT = N0.getValueType();
1883 if (VT.isVector()) {
1884 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1887 // fold (sub x, 0) -> x, vector edition
1888 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1892 // fold (sub x, x) -> 0
1893 // FIXME: Refactor this and xor and other similar operations together.
1895 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1896 // fold (sub c1, c2) -> c1-c2
1897 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1898 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1900 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1901 // fold (sub x, c) -> (add x, -c)
1904 return DAG.getNode(ISD::ADD, DL, VT, N0,
1905 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1907 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1908 if (isAllOnesConstant(N0))
1909 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1910 // fold A-(A-B) -> B
1911 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1912 return N1.getOperand(1);
1913 // fold (A+B)-A -> B
1914 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1915 return N0.getOperand(1);
1916 // fold (A+B)-B -> A
1917 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1918 return N0.getOperand(0);
1919 // fold C2-(A+C1) -> (C2-C1)-A
1920 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1921 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1922 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1924 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1926 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1929 // fold ((A+(B+or-C))-B) -> A+or-C
1930 if (N0.getOpcode() == ISD::ADD &&
1931 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1932 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1933 N0.getOperand(1).getOperand(0) == N1)
1934 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1935 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1936 // fold ((A+(C+B))-B) -> A+C
1937 if (N0.getOpcode() == ISD::ADD &&
1938 N0.getOperand(1).getOpcode() == ISD::ADD &&
1939 N0.getOperand(1).getOperand(1) == N1)
1940 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1941 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1942 // fold ((A-(B-C))-C) -> A-B
1943 if (N0.getOpcode() == ISD::SUB &&
1944 N0.getOperand(1).getOpcode() == ISD::SUB &&
1945 N0.getOperand(1).getOperand(1) == N1)
1946 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1947 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1949 // If either operand of a sub is undef, the result is undef
1950 if (N0.getOpcode() == ISD::UNDEF)
1952 if (N1.getOpcode() == ISD::UNDEF)
1955 // If the relocation model supports it, consider symbol offsets.
1956 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1957 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1958 // fold (sub Sym, c) -> Sym-c
1959 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1960 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1962 (uint64_t)N1C->getSExtValue());
1963 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1964 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1965 if (GA->getGlobal() == GB->getGlobal())
1966 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1970 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1971 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1972 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1973 if (TN->getVT() == MVT::i1) {
1975 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1976 DAG.getConstant(1, DL, VT));
1977 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1984 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1985 SDValue N0 = N->getOperand(0);
1986 SDValue N1 = N->getOperand(1);
1987 EVT VT = N0.getValueType();
1989 // If the flag result is dead, turn this into an SUB.
1990 if (!N->hasAnyUseOfValue(1))
1991 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1992 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1995 // fold (subc x, x) -> 0 + no borrow
1998 return CombineTo(N, DAG.getConstant(0, DL, VT),
1999 DAG.getNode(ISD::CARRY_FALSE, DL,
2003 // fold (subc x, 0) -> x + no borrow
2004 if (isNullConstant(N1))
2005 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2008 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2009 if (isAllOnesConstant(N0))
2010 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2011 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2017 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2018 SDValue N0 = N->getOperand(0);
2019 SDValue N1 = N->getOperand(1);
2020 SDValue CarryIn = N->getOperand(2);
2022 // fold (sube x, y, false) -> (subc x, y)
2023 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2024 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2029 SDValue DAGCombiner::visitMUL(SDNode *N) {
2030 SDValue N0 = N->getOperand(0);
2031 SDValue N1 = N->getOperand(1);
2032 EVT VT = N0.getValueType();
2034 // fold (mul x, undef) -> 0
2035 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2036 return DAG.getConstant(0, SDLoc(N), VT);
2038 bool N0IsConst = false;
2039 bool N1IsConst = false;
2040 bool N1IsOpaqueConst = false;
2041 bool N0IsOpaqueConst = false;
2042 APInt ConstValue0, ConstValue1;
2044 if (VT.isVector()) {
2045 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2048 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2049 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2051 N0IsConst = isa<ConstantSDNode>(N0);
2053 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2054 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2056 N1IsConst = isa<ConstantSDNode>(N1);
2058 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2059 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2063 // fold (mul c1, c2) -> c1*c2
2064 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2065 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2066 N0.getNode(), N1.getNode());
2068 // canonicalize constant to RHS (vector doesn't have to splat)
2069 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2070 !isConstantIntBuildVectorOrConstantInt(N1))
2071 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2072 // fold (mul x, 0) -> 0
2073 if (N1IsConst && ConstValue1 == 0)
2075 // We require a splat of the entire scalar bit width for non-contiguous
2078 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2079 // fold (mul x, 1) -> x
2080 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2082 // fold (mul x, -1) -> 0-x
2083 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2085 return DAG.getNode(ISD::SUB, DL, VT,
2086 DAG.getConstant(0, DL, VT), N0);
2088 // fold (mul x, (1 << c)) -> x << c
2089 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2092 return DAG.getNode(ISD::SHL, DL, VT, N0,
2093 DAG.getConstant(ConstValue1.logBase2(), DL,
2094 getShiftAmountTy(N0.getValueType())));
2096 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2097 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2099 unsigned Log2Val = (-ConstValue1).logBase2();
2101 // FIXME: If the input is something that is easily negated (e.g. a
2102 // single-use add), we should put the negate there.
2103 return DAG.getNode(ISD::SUB, DL, VT,
2104 DAG.getConstant(0, DL, VT),
2105 DAG.getNode(ISD::SHL, DL, VT, N0,
2106 DAG.getConstant(Log2Val, DL,
2107 getShiftAmountTy(N0.getValueType()))));
2111 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2112 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2113 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2114 isa<ConstantSDNode>(N0.getOperand(1)))) {
2115 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2116 N1, N0.getOperand(1));
2117 AddToWorklist(C3.getNode());
2118 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2119 N0.getOperand(0), C3);
2122 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2125 SDValue Sh(nullptr,0), Y(nullptr,0);
2126 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2127 if (N0.getOpcode() == ISD::SHL &&
2128 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2129 isa<ConstantSDNode>(N0.getOperand(1))) &&
2130 N0.getNode()->hasOneUse()) {
2132 } else if (N1.getOpcode() == ISD::SHL &&
2133 isa<ConstantSDNode>(N1.getOperand(1)) &&
2134 N1.getNode()->hasOneUse()) {
2139 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2140 Sh.getOperand(0), Y);
2141 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2142 Mul, Sh.getOperand(1));
2146 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2147 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2148 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2149 isa<ConstantSDNode>(N0.getOperand(1))))
2150 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2151 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2152 N0.getOperand(0), N1),
2153 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2154 N0.getOperand(1), N1));
2157 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2163 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2164 SDValue N0 = N->getOperand(0);
2165 SDValue N1 = N->getOperand(1);
2166 EVT VT = N->getValueType(0);
2170 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2173 // fold (sdiv c1, c2) -> c1/c2
2174 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2175 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2176 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2177 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2178 // fold (sdiv X, 1) -> X
2179 if (N1C && N1C->isOne())
2181 // fold (sdiv X, -1) -> 0-X
2182 if (N1C && N1C->isAllOnesValue()) {
2184 return DAG.getNode(ISD::SUB, DL, VT,
2185 DAG.getConstant(0, DL, VT), N0);
2187 // If we know the sign bits of both operands are zero, strength reduce to a
2188 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2189 if (!VT.isVector()) {
2190 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2191 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2195 // fold (sdiv X, pow2) -> simple ops after legalize
2196 // FIXME: We check for the exact bit here because the generic lowering gives
2197 // better results in that case. The target-specific lowering should learn how
2198 // to handle exact sdivs efficiently.
2199 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2200 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2201 (N1C->getAPIntValue().isPowerOf2() ||
2202 (-N1C->getAPIntValue()).isPowerOf2())) {
2203 // Target-specific implementation of sdiv x, pow2.
2204 if (SDValue Res = BuildSDIVPow2(N))
2207 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2210 // Splat the sign bit into the register
2212 DAG.getNode(ISD::SRA, DL, VT, N0,
2213 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2214 getShiftAmountTy(N0.getValueType())));
2215 AddToWorklist(SGN.getNode());
2217 // Add (N0 < 0) ? abs2 - 1 : 0;
2219 DAG.getNode(ISD::SRL, DL, VT, SGN,
2220 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2221 getShiftAmountTy(SGN.getValueType())));
2222 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2223 AddToWorklist(SRL.getNode());
2224 AddToWorklist(ADD.getNode()); // Divide by pow2
2225 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2226 DAG.getConstant(lg2, DL,
2227 getShiftAmountTy(ADD.getValueType())));
2229 // If we're dividing by a positive value, we're done. Otherwise, we must
2230 // negate the result.
2231 if (N1C->getAPIntValue().isNonNegative())
2234 AddToWorklist(SRA.getNode());
2235 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2238 // If integer divide is expensive and we satisfy the requirements, emit an
2239 // alternate sequence. Targets may check function attributes for size/speed
2241 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2242 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2243 if (SDValue Op = BuildSDIV(N))
2247 if (N0.getOpcode() == ISD::UNDEF)
2248 return DAG.getConstant(0, SDLoc(N), VT);
2249 // X / undef -> undef
2250 if (N1.getOpcode() == ISD::UNDEF)
2256 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2257 SDValue N0 = N->getOperand(0);
2258 SDValue N1 = N->getOperand(1);
2259 EVT VT = N->getValueType(0);
2263 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2266 // fold (udiv c1, c2) -> c1/c2
2267 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2268 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2270 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2273 // fold (udiv x, (1 << c)) -> x >>u c
2274 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2276 return DAG.getNode(ISD::SRL, DL, VT, N0,
2277 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2278 getShiftAmountTy(N0.getValueType())));
2280 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2281 if (N1.getOpcode() == ISD::SHL) {
2282 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2283 if (SHC->getAPIntValue().isPowerOf2()) {
2284 EVT ADDVT = N1.getOperand(1).getValueType();
2286 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2288 DAG.getConstant(SHC->getAPIntValue()
2291 AddToWorklist(Add.getNode());
2292 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2297 // fold (udiv x, c) -> alternate
2298 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2299 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2300 if (SDValue Op = BuildUDIV(N))
2304 if (N0.getOpcode() == ISD::UNDEF)
2305 return DAG.getConstant(0, SDLoc(N), VT);
2306 // X / undef -> undef
2307 if (N1.getOpcode() == ISD::UNDEF)
2313 // handles ISD::SREM and ISD::UREM
2314 SDValue DAGCombiner::visitREM(SDNode *N) {
2315 unsigned Opcode = N->getOpcode();
2316 SDValue N0 = N->getOperand(0);
2317 SDValue N1 = N->getOperand(1);
2318 EVT VT = N->getValueType(0);
2320 // fold (rem c1, c2) -> c1%c2
2321 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2322 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2324 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, SDLoc(N), VT,
2328 if (Opcode == ISD::SREM) {
2329 // If we know the sign bits of both operands are zero, strength reduce to a
2330 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2331 if (!VT.isVector()) {
2332 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2333 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2336 // fold (urem x, pow2) -> (and x, pow2-1)
2337 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2338 N1C->getAPIntValue().isPowerOf2()) {
2340 return DAG.getNode(ISD::AND, DL, VT, N0,
2341 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2343 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2344 if (N1.getOpcode() == ISD::SHL) {
2345 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2346 if (SHC->getAPIntValue().isPowerOf2()) {
2349 DAG.getNode(ISD::ADD, DL, VT, N1,
2350 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2352 AddToWorklist(Add.getNode());
2353 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2359 // If X/C can be simplified by the division-by-constant logic, lower
2360 // X%C to the equivalent of X-X/C*C.
2361 if (N1C && !N1C->isNullValue()) {
2362 unsigned DivOpcode = (Opcode == ISD::SREM ? ISD::SDIV : ISD::UDIV);
2363 SDValue Div = DAG.getNode(DivOpcode, SDLoc(N), VT, N0, N1);
2364 AddToWorklist(Div.getNode());
2365 SDValue OptimizedDiv = combine(Div.getNode());
2366 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2367 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2369 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2370 AddToWorklist(Mul.getNode());
2376 if (N0.getOpcode() == ISD::UNDEF)
2377 return DAG.getConstant(0, SDLoc(N), VT);
2378 // X % undef -> undef
2379 if (N1.getOpcode() == ISD::UNDEF)
2385 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2386 SDValue N0 = N->getOperand(0);
2387 SDValue N1 = N->getOperand(1);
2388 EVT VT = N->getValueType(0);
2391 // fold (mulhs x, 0) -> 0
2392 if (isNullConstant(N1))
2394 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2395 if (isOneConstant(N1)) {
2397 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2398 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2400 getShiftAmountTy(N0.getValueType())));
2402 // fold (mulhs x, undef) -> 0
2403 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2404 return DAG.getConstant(0, SDLoc(N), VT);
2406 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2408 if (VT.isSimple() && !VT.isVector()) {
2409 MVT Simple = VT.getSimpleVT();
2410 unsigned SimpleSize = Simple.getSizeInBits();
2411 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2412 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2413 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2414 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2415 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2416 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2417 DAG.getConstant(SimpleSize, DL,
2418 getShiftAmountTy(N1.getValueType())));
2419 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2426 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2427 SDValue N0 = N->getOperand(0);
2428 SDValue N1 = N->getOperand(1);
2429 EVT VT = N->getValueType(0);
2432 // fold (mulhu x, 0) -> 0
2433 if (isNullConstant(N1))
2435 // fold (mulhu x, 1) -> 0
2436 if (isOneConstant(N1))
2437 return DAG.getConstant(0, DL, N0.getValueType());
2438 // fold (mulhu x, undef) -> 0
2439 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2440 return DAG.getConstant(0, DL, VT);
2442 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2444 if (VT.isSimple() && !VT.isVector()) {
2445 MVT Simple = VT.getSimpleVT();
2446 unsigned SimpleSize = Simple.getSizeInBits();
2447 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2448 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2449 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2450 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2451 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2452 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2453 DAG.getConstant(SimpleSize, DL,
2454 getShiftAmountTy(N1.getValueType())));
2455 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2462 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2463 /// give the opcodes for the two computations that are being performed. Return
2464 /// true if a simplification was made.
2465 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2467 // If the high half is not needed, just compute the low half.
2468 bool HiExists = N->hasAnyUseOfValue(1);
2470 (!LegalOperations ||
2471 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2472 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2473 return CombineTo(N, Res, Res);
2476 // If the low half is not needed, just compute the high half.
2477 bool LoExists = N->hasAnyUseOfValue(0);
2479 (!LegalOperations ||
2480 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2481 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2482 return CombineTo(N, Res, Res);
2485 // If both halves are used, return as it is.
2486 if (LoExists && HiExists)
2489 // If the two computed results can be simplified separately, separate them.
2491 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2492 AddToWorklist(Lo.getNode());
2493 SDValue LoOpt = combine(Lo.getNode());
2494 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2495 (!LegalOperations ||
2496 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2497 return CombineTo(N, LoOpt, LoOpt);
2501 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2502 AddToWorklist(Hi.getNode());
2503 SDValue HiOpt = combine(Hi.getNode());
2504 if (HiOpt.getNode() && HiOpt != Hi &&
2505 (!LegalOperations ||
2506 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2507 return CombineTo(N, HiOpt, HiOpt);
2513 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2514 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2517 EVT VT = N->getValueType(0);
2520 // If the type is twice as wide is legal, transform the mulhu to a wider
2521 // multiply plus a shift.
2522 if (VT.isSimple() && !VT.isVector()) {
2523 MVT Simple = VT.getSimpleVT();
2524 unsigned SimpleSize = Simple.getSizeInBits();
2525 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2526 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2527 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2528 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2529 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2530 // Compute the high part as N1.
2531 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2532 DAG.getConstant(SimpleSize, DL,
2533 getShiftAmountTy(Lo.getValueType())));
2534 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2535 // Compute the low part as N0.
2536 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2537 return CombineTo(N, Lo, Hi);
2544 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2545 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2548 EVT VT = N->getValueType(0);
2551 // If the type is twice as wide is legal, transform the mulhu to a wider
2552 // multiply plus a shift.
2553 if (VT.isSimple() && !VT.isVector()) {
2554 MVT Simple = VT.getSimpleVT();
2555 unsigned SimpleSize = Simple.getSizeInBits();
2556 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2557 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2558 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2559 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2560 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2561 // Compute the high part as N1.
2562 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2563 DAG.getConstant(SimpleSize, DL,
2564 getShiftAmountTy(Lo.getValueType())));
2565 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2566 // Compute the low part as N0.
2567 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2568 return CombineTo(N, Lo, Hi);
2575 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2576 // (smulo x, 2) -> (saddo x, x)
2577 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2578 if (C2->getAPIntValue() == 2)
2579 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2580 N->getOperand(0), N->getOperand(0));
2585 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2586 // (umulo x, 2) -> (uaddo x, x)
2587 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2588 if (C2->getAPIntValue() == 2)
2589 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2590 N->getOperand(0), N->getOperand(0));
2595 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2596 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2602 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2603 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2609 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2610 SDValue N0 = N->getOperand(0);
2611 SDValue N1 = N->getOperand(1);
2612 EVT VT = N0.getValueType();
2616 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2619 // fold (add c1, c2) -> c1+c2
2620 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2621 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2623 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2625 // canonicalize constant to RHS
2626 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2627 !isConstantIntBuildVectorOrConstantInt(N1))
2628 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2633 /// If this is a binary operator with two operands of the same opcode, try to
2635 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2636 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2637 EVT VT = N0.getValueType();
2638 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2640 // Bail early if none of these transforms apply.
2641 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2643 // For each of OP in AND/OR/XOR:
2644 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2645 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2646 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2647 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2648 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2650 // do not sink logical op inside of a vector extend, since it may combine
2652 EVT Op0VT = N0.getOperand(0).getValueType();
2653 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2654 N0.getOpcode() == ISD::SIGN_EXTEND ||
2655 N0.getOpcode() == ISD::BSWAP ||
2656 // Avoid infinite looping with PromoteIntBinOp.
2657 (N0.getOpcode() == ISD::ANY_EXTEND &&
2658 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2659 (N0.getOpcode() == ISD::TRUNCATE &&
2660 (!TLI.isZExtFree(VT, Op0VT) ||
2661 !TLI.isTruncateFree(Op0VT, VT)) &&
2662 TLI.isTypeLegal(Op0VT))) &&
2664 Op0VT == N1.getOperand(0).getValueType() &&
2665 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2666 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2667 N0.getOperand(0).getValueType(),
2668 N0.getOperand(0), N1.getOperand(0));
2669 AddToWorklist(ORNode.getNode());
2670 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2673 // For each of OP in SHL/SRL/SRA/AND...
2674 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2675 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2676 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2677 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2678 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2679 N0.getOperand(1) == N1.getOperand(1)) {
2680 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2681 N0.getOperand(0).getValueType(),
2682 N0.getOperand(0), N1.getOperand(0));
2683 AddToWorklist(ORNode.getNode());
2684 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2685 ORNode, N0.getOperand(1));
2688 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2689 // Only perform this optimization after type legalization and before
2690 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2691 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2692 // we don't want to undo this promotion.
2693 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2695 if ((N0.getOpcode() == ISD::BITCAST ||
2696 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2697 Level == AfterLegalizeTypes) {
2698 SDValue In0 = N0.getOperand(0);
2699 SDValue In1 = N1.getOperand(0);
2700 EVT In0Ty = In0.getValueType();
2701 EVT In1Ty = In1.getValueType();
2703 // If both incoming values are integers, and the original types are the
2705 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2706 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2707 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2708 AddToWorklist(Op.getNode());
2713 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2714 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2715 // If both shuffles use the same mask, and both shuffle within a single
2716 // vector, then it is worthwhile to move the swizzle after the operation.
2717 // The type-legalizer generates this pattern when loading illegal
2718 // vector types from memory. In many cases this allows additional shuffle
2720 // There are other cases where moving the shuffle after the xor/and/or
2721 // is profitable even if shuffles don't perform a swizzle.
2722 // If both shuffles use the same mask, and both shuffles have the same first
2723 // or second operand, then it might still be profitable to move the shuffle
2724 // after the xor/and/or operation.
2725 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2726 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2727 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2729 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2730 "Inputs to shuffles are not the same type");
2732 // Check that both shuffles use the same mask. The masks are known to be of
2733 // the same length because the result vector type is the same.
2734 // Check also that shuffles have only one use to avoid introducing extra
2736 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2737 SVN0->getMask().equals(SVN1->getMask())) {
2738 SDValue ShOp = N0->getOperand(1);
2740 // Don't try to fold this node if it requires introducing a
2741 // build vector of all zeros that might be illegal at this stage.
2742 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2744 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2749 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2750 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2751 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2752 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2753 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2754 N0->getOperand(0), N1->getOperand(0));
2755 AddToWorklist(NewNode.getNode());
2756 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2757 &SVN0->getMask()[0]);
2760 // Don't try to fold this node if it requires introducing a
2761 // build vector of all zeros that might be illegal at this stage.
2762 ShOp = N0->getOperand(0);
2763 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2765 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2770 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2771 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2772 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2773 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2774 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2775 N0->getOperand(1), N1->getOperand(1));
2776 AddToWorklist(NewNode.getNode());
2777 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2778 &SVN0->getMask()[0]);
2786 /// This contains all DAGCombine rules which reduce two values combined by
2787 /// an And operation to a single value. This makes them reusable in the context
2788 /// of visitSELECT(). Rules involving constants are not included as
2789 /// visitSELECT() already handles those cases.
2790 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2791 SDNode *LocReference) {
2792 EVT VT = N1.getValueType();
2794 // fold (and x, undef) -> 0
2795 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2796 return DAG.getConstant(0, SDLoc(LocReference), VT);
2797 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2798 SDValue LL, LR, RL, RR, CC0, CC1;
2799 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2800 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2801 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2803 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2804 LL.getValueType().isInteger()) {
2805 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2806 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2807 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2808 LR.getValueType(), LL, RL);
2809 AddToWorklist(ORNode.getNode());
2810 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2812 if (isAllOnesConstant(LR)) {
2813 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2814 if (Op1 == ISD::SETEQ) {
2815 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2816 LR.getValueType(), LL, RL);
2817 AddToWorklist(ANDNode.getNode());
2818 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2820 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2821 if (Op1 == ISD::SETGT) {
2822 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2823 LR.getValueType(), LL, RL);
2824 AddToWorklist(ORNode.getNode());
2825 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2829 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2830 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2831 Op0 == Op1 && LL.getValueType().isInteger() &&
2832 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2833 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2835 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2836 LL, DAG.getConstant(1, DL,
2837 LL.getValueType()));
2838 AddToWorklist(ADDNode.getNode());
2839 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2840 DAG.getConstant(2, DL, LL.getValueType()),
2843 // canonicalize equivalent to ll == rl
2844 if (LL == RR && LR == RL) {
2845 Op1 = ISD::getSetCCSwappedOperands(Op1);
2848 if (LL == RL && LR == RR) {
2849 bool isInteger = LL.getValueType().isInteger();
2850 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2851 if (Result != ISD::SETCC_INVALID &&
2852 (!LegalOperations ||
2853 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2854 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2855 EVT CCVT = getSetCCResultType(LL.getValueType());
2856 if (N0.getValueType() == CCVT ||
2857 (!LegalOperations && N0.getValueType() == MVT::i1))
2858 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2864 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2865 VT.getSizeInBits() <= 64) {
2866 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2867 APInt ADDC = ADDI->getAPIntValue();
2868 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2869 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2870 // immediate for an add, but it is legal if its top c2 bits are set,
2871 // transform the ADD so the immediate doesn't need to be materialized
2873 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2874 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2875 SRLI->getZExtValue());
2876 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2878 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2881 DAG.getNode(ISD::ADD, DL, VT,
2882 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2883 CombineTo(N0.getNode(), NewAdd);
2884 // Return N so it doesn't get rechecked!
2885 return SDValue(LocReference, 0);
2896 SDValue DAGCombiner::visitAND(SDNode *N) {
2897 SDValue N0 = N->getOperand(0);
2898 SDValue N1 = N->getOperand(1);
2899 EVT VT = N1.getValueType();
2902 if (VT.isVector()) {
2903 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2906 // fold (and x, 0) -> 0, vector edition
2907 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2908 // do not return N0, because undef node may exist in N0
2909 return DAG.getConstant(
2910 APInt::getNullValue(
2911 N0.getValueType().getScalarType().getSizeInBits()),
2912 SDLoc(N), N0.getValueType());
2913 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2914 // do not return N1, because undef node may exist in N1
2915 return DAG.getConstant(
2916 APInt::getNullValue(
2917 N1.getValueType().getScalarType().getSizeInBits()),
2918 SDLoc(N), N1.getValueType());
2920 // fold (and x, -1) -> x, vector edition
2921 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2923 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2927 // fold (and c1, c2) -> c1&c2
2928 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2929 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2930 if (N0C && N1C && !N1C->isOpaque())
2931 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2932 // canonicalize constant to RHS
2933 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2934 !isConstantIntBuildVectorOrConstantInt(N1))
2935 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2936 // fold (and x, -1) -> x
2937 if (isAllOnesConstant(N1))
2939 // if (and x, c) is known to be zero, return 0
2940 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2941 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2942 APInt::getAllOnesValue(BitWidth)))
2943 return DAG.getConstant(0, SDLoc(N), VT);
2945 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2947 // fold (and (or x, C), D) -> D if (C & D) == D
2948 if (N1C && N0.getOpcode() == ISD::OR)
2949 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2950 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2952 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2953 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2954 SDValue N0Op0 = N0.getOperand(0);
2955 APInt Mask = ~N1C->getAPIntValue();
2956 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2957 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2958 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2959 N0.getValueType(), N0Op0);
2961 // Replace uses of the AND with uses of the Zero extend node.
2964 // We actually want to replace all uses of the any_extend with the
2965 // zero_extend, to avoid duplicating things. This will later cause this
2966 // AND to be folded.
2967 CombineTo(N0.getNode(), Zext);
2968 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2971 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2972 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2973 // already be zero by virtue of the width of the base type of the load.
2975 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2977 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2978 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2979 N0.getOpcode() == ISD::LOAD) {
2980 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2981 N0 : N0.getOperand(0) );
2983 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2984 // This can be a pure constant or a vector splat, in which case we treat the
2985 // vector as a scalar and use the splat value.
2986 APInt Constant = APInt::getNullValue(1);
2987 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2988 Constant = C->getAPIntValue();
2989 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2990 APInt SplatValue, SplatUndef;
2991 unsigned SplatBitSize;
2993 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2994 SplatBitSize, HasAnyUndefs);
2996 // Undef bits can contribute to a possible optimisation if set, so
2998 SplatValue |= SplatUndef;
3000 // The splat value may be something like "0x00FFFFFF", which means 0 for
3001 // the first vector value and FF for the rest, repeating. We need a mask
3002 // that will apply equally to all members of the vector, so AND all the
3003 // lanes of the constant together.
3004 EVT VT = Vector->getValueType(0);
3005 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3007 // If the splat value has been compressed to a bitlength lower
3008 // than the size of the vector lane, we need to re-expand it to
3010 if (BitWidth > SplatBitSize)
3011 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3012 SplatBitSize < BitWidth;
3013 SplatBitSize = SplatBitSize * 2)
3014 SplatValue |= SplatValue.shl(SplatBitSize);
3016 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3017 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3018 if (SplatBitSize % BitWidth == 0) {
3019 Constant = APInt::getAllOnesValue(BitWidth);
3020 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3021 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3026 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3027 // actually legal and isn't going to get expanded, else this is a false
3029 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3030 Load->getValueType(0),
3031 Load->getMemoryVT());
3033 // Resize the constant to the same size as the original memory access before
3034 // extension. If it is still the AllOnesValue then this AND is completely
3037 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3040 switch (Load->getExtensionType()) {
3041 default: B = false; break;
3042 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3044 case ISD::NON_EXTLOAD: B = true; break;
3047 if (B && Constant.isAllOnesValue()) {
3048 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3049 // preserve semantics once we get rid of the AND.
3050 SDValue NewLoad(Load, 0);
3051 if (Load->getExtensionType() == ISD::EXTLOAD) {
3052 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3053 Load->getValueType(0), SDLoc(Load),
3054 Load->getChain(), Load->getBasePtr(),
3055 Load->getOffset(), Load->getMemoryVT(),
3056 Load->getMemOperand());
3057 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3058 if (Load->getNumValues() == 3) {
3059 // PRE/POST_INC loads have 3 values.
3060 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3061 NewLoad.getValue(2) };
3062 CombineTo(Load, To, 3, true);
3064 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3068 // Fold the AND away, taking care not to fold to the old load node if we
3070 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3072 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3076 // fold (and (load x), 255) -> (zextload x, i8)
3077 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3078 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3079 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3080 (N0.getOpcode() == ISD::ANY_EXTEND &&
3081 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3082 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3083 LoadSDNode *LN0 = HasAnyExt
3084 ? cast<LoadSDNode>(N0.getOperand(0))
3085 : cast<LoadSDNode>(N0);
3086 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3087 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3088 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3089 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3090 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3091 EVT LoadedVT = LN0->getMemoryVT();
3092 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3094 if (ExtVT == LoadedVT &&
3095 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3099 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3100 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3101 LN0->getMemOperand());
3103 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3104 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3107 // Do not change the width of a volatile load.
3108 // Do not generate loads of non-round integer types since these can
3109 // be expensive (and would be wrong if the type is not byte sized).
3110 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3111 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3113 EVT PtrType = LN0->getOperand(1).getValueType();
3115 unsigned Alignment = LN0->getAlignment();
3116 SDValue NewPtr = LN0->getBasePtr();
3118 // For big endian targets, we need to add an offset to the pointer
3119 // to load the correct bytes. For little endian systems, we merely
3120 // need to read fewer bytes from the same pointer.
3121 if (DAG.getDataLayout().isBigEndian()) {
3122 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3123 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3124 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3126 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3127 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3128 Alignment = MinAlign(Alignment, PtrOff);
3131 AddToWorklist(NewPtr.getNode());
3134 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3135 LN0->getChain(), NewPtr,
3136 LN0->getPointerInfo(),
3137 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3138 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3140 CombineTo(LN0, Load, Load.getValue(1));
3141 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3147 if (SDValue Combined = visitANDLike(N0, N1, N))
3150 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3151 if (N0.getOpcode() == N1.getOpcode())
3152 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3155 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3156 // fold (and (sra)) -> (and (srl)) when possible.
3157 if (!VT.isVector() &&
3158 SimplifyDemandedBits(SDValue(N, 0)))
3159 return SDValue(N, 0);
3161 // fold (zext_inreg (extload x)) -> (zextload x)
3162 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3163 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3164 EVT MemVT = LN0->getMemoryVT();
3165 // If we zero all the possible extended bits, then we can turn this into
3166 // a zextload if we are running before legalize or the operation is legal.
3167 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3168 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3169 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3170 ((!LegalOperations && !LN0->isVolatile()) ||
3171 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3172 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3173 LN0->getChain(), LN0->getBasePtr(),
3174 MemVT, LN0->getMemOperand());
3176 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3177 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3180 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3181 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3183 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3184 EVT MemVT = LN0->getMemoryVT();
3185 // If we zero all the possible extended bits, then we can turn this into
3186 // a zextload if we are running before legalize or the operation is legal.
3187 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3188 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3189 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3190 ((!LegalOperations && !LN0->isVolatile()) ||
3191 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3192 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3193 LN0->getChain(), LN0->getBasePtr(),
3194 MemVT, LN0->getMemOperand());
3196 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3197 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3200 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3201 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3202 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3203 N0.getOperand(1), false);
3204 if (BSwap.getNode())
3211 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3212 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3213 bool DemandHighBits) {
3214 if (!LegalOperations)
3217 EVT VT = N->getValueType(0);
3218 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3220 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3223 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3224 bool LookPassAnd0 = false;
3225 bool LookPassAnd1 = false;
3226 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3228 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3230 if (N0.getOpcode() == ISD::AND) {
3231 if (!N0.getNode()->hasOneUse())
3233 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3234 if (!N01C || N01C->getZExtValue() != 0xFF00)
3236 N0 = N0.getOperand(0);
3237 LookPassAnd0 = true;
3240 if (N1.getOpcode() == ISD::AND) {
3241 if (!N1.getNode()->hasOneUse())
3243 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3244 if (!N11C || N11C->getZExtValue() != 0xFF)
3246 N1 = N1.getOperand(0);
3247 LookPassAnd1 = true;
3250 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3252 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3254 if (!N0.getNode()->hasOneUse() ||
3255 !N1.getNode()->hasOneUse())
3258 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3259 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3262 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3265 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3266 SDValue N00 = N0->getOperand(0);
3267 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3268 if (!N00.getNode()->hasOneUse())
3270 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3271 if (!N001C || N001C->getZExtValue() != 0xFF)
3273 N00 = N00.getOperand(0);
3274 LookPassAnd0 = true;
3277 SDValue N10 = N1->getOperand(0);
3278 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3279 if (!N10.getNode()->hasOneUse())
3281 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3282 if (!N101C || N101C->getZExtValue() != 0xFF00)
3284 N10 = N10.getOperand(0);
3285 LookPassAnd1 = true;
3291 // Make sure everything beyond the low halfword gets set to zero since the SRL
3292 // 16 will clear the top bits.
3293 unsigned OpSizeInBits = VT.getSizeInBits();
3294 if (DemandHighBits && OpSizeInBits > 16) {
3295 // If the left-shift isn't masked out then the only way this is a bswap is
3296 // if all bits beyond the low 8 are 0. In that case the entire pattern
3297 // reduces to a left shift anyway: leave it for other parts of the combiner.
3301 // However, if the right shift isn't masked out then it might be because
3302 // it's not needed. See if we can spot that too.
3303 if (!LookPassAnd1 &&
3304 !DAG.MaskedValueIsZero(
3305 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3309 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3310 if (OpSizeInBits > 16) {
3312 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3313 DAG.getConstant(OpSizeInBits - 16, DL,
3314 getShiftAmountTy(VT)));
3319 /// Return true if the specified node is an element that makes up a 32-bit
3320 /// packed halfword byteswap.
3321 /// ((x & 0x000000ff) << 8) |
3322 /// ((x & 0x0000ff00) >> 8) |
3323 /// ((x & 0x00ff0000) << 8) |
3324 /// ((x & 0xff000000) >> 8)
3325 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3326 if (!N.getNode()->hasOneUse())
3329 unsigned Opc = N.getOpcode();
3330 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3333 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3338 switch (N1C->getZExtValue()) {
3341 case 0xFF: Num = 0; break;
3342 case 0xFF00: Num = 1; break;
3343 case 0xFF0000: Num = 2; break;
3344 case 0xFF000000: Num = 3; break;
3347 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3348 SDValue N0 = N.getOperand(0);
3349 if (Opc == ISD::AND) {
3350 if (Num == 0 || Num == 2) {
3352 // (x >> 8) & 0xff0000
3353 if (N0.getOpcode() != ISD::SRL)
3355 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3356 if (!C || C->getZExtValue() != 8)
3359 // (x << 8) & 0xff00
3360 // (x << 8) & 0xff000000
3361 if (N0.getOpcode() != ISD::SHL)
3363 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3364 if (!C || C->getZExtValue() != 8)
3367 } else if (Opc == ISD::SHL) {
3369 // (x & 0xff0000) << 8
3370 if (Num != 0 && Num != 2)
3372 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3373 if (!C || C->getZExtValue() != 8)
3375 } else { // Opc == ISD::SRL
3376 // (x & 0xff00) >> 8
3377 // (x & 0xff000000) >> 8
3378 if (Num != 1 && Num != 3)
3380 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3381 if (!C || C->getZExtValue() != 8)
3388 Parts[Num] = N0.getOperand(0).getNode();
3392 /// Match a 32-bit packed halfword bswap. That is
3393 /// ((x & 0x000000ff) << 8) |
3394 /// ((x & 0x0000ff00) >> 8) |
3395 /// ((x & 0x00ff0000) << 8) |
3396 /// ((x & 0xff000000) >> 8)
3397 /// => (rotl (bswap x), 16)
3398 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3399 if (!LegalOperations)
3402 EVT VT = N->getValueType(0);
3405 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3409 // (or (or (and), (and)), (or (and), (and)))
3410 // (or (or (or (and), (and)), (and)), (and))
3411 if (N0.getOpcode() != ISD::OR)
3413 SDValue N00 = N0.getOperand(0);
3414 SDValue N01 = N0.getOperand(1);
3415 SDNode *Parts[4] = {};
3417 if (N1.getOpcode() == ISD::OR &&
3418 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3419 // (or (or (and), (and)), (or (and), (and)))
3420 SDValue N000 = N00.getOperand(0);
3421 if (!isBSwapHWordElement(N000, Parts))
3424 SDValue N001 = N00.getOperand(1);
3425 if (!isBSwapHWordElement(N001, Parts))
3427 SDValue N010 = N01.getOperand(0);
3428 if (!isBSwapHWordElement(N010, Parts))
3430 SDValue N011 = N01.getOperand(1);
3431 if (!isBSwapHWordElement(N011, Parts))
3434 // (or (or (or (and), (and)), (and)), (and))
3435 if (!isBSwapHWordElement(N1, Parts))
3437 if (!isBSwapHWordElement(N01, Parts))
3439 if (N00.getOpcode() != ISD::OR)
3441 SDValue N000 = N00.getOperand(0);
3442 if (!isBSwapHWordElement(N000, Parts))
3444 SDValue N001 = N00.getOperand(1);
3445 if (!isBSwapHWordElement(N001, Parts))
3449 // Make sure the parts are all coming from the same node.
3450 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3454 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3455 SDValue(Parts[0], 0));
3457 // Result of the bswap should be rotated by 16. If it's not legal, then
3458 // do (x << 16) | (x >> 16).
3459 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3460 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3461 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3462 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3463 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3464 return DAG.getNode(ISD::OR, DL, VT,
3465 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3466 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3469 /// This contains all DAGCombine rules which reduce two values combined by
3470 /// an Or operation to a single value \see visitANDLike().
3471 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3472 EVT VT = N1.getValueType();
3473 // fold (or x, undef) -> -1
3474 if (!LegalOperations &&
3475 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3476 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3477 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3478 SDLoc(LocReference), VT);
3480 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3481 SDValue LL, LR, RL, RR, CC0, CC1;
3482 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3483 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3484 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3486 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3487 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3488 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3489 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3490 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3491 LR.getValueType(), LL, RL);
3492 AddToWorklist(ORNode.getNode());
3493 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3495 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3496 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3497 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3498 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3499 LR.getValueType(), LL, RL);
3500 AddToWorklist(ANDNode.getNode());
3501 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3504 // canonicalize equivalent to ll == rl
3505 if (LL == RR && LR == RL) {
3506 Op1 = ISD::getSetCCSwappedOperands(Op1);
3509 if (LL == RL && LR == RR) {
3510 bool isInteger = LL.getValueType().isInteger();
3511 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3512 if (Result != ISD::SETCC_INVALID &&
3513 (!LegalOperations ||
3514 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3515 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3516 EVT CCVT = getSetCCResultType(LL.getValueType());
3517 if (N0.getValueType() == CCVT ||
3518 (!LegalOperations && N0.getValueType() == MVT::i1))
3519 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3525 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3526 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3527 // Don't increase # computations.
3528 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3529 // We can only do this xform if we know that bits from X that are set in C2
3530 // but not in C1 are already zero. Likewise for Y.
3531 if (const ConstantSDNode *N0O1C =
3532 getAsNonOpaqueConstant(N0.getOperand(1))) {
3533 if (const ConstantSDNode *N1O1C =
3534 getAsNonOpaqueConstant(N1.getOperand(1))) {
3535 // We can only do this xform if we know that bits from X that are set in
3536 // C2 but not in C1 are already zero. Likewise for Y.
3537 const APInt &LHSMask = N0O1C->getAPIntValue();
3538 const APInt &RHSMask = N1O1C->getAPIntValue();
3540 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3541 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3542 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3543 N0.getOperand(0), N1.getOperand(0));
3544 SDLoc DL(LocReference);
3545 return DAG.getNode(ISD::AND, DL, VT, X,
3546 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3552 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3553 if (N0.getOpcode() == ISD::AND &&
3554 N1.getOpcode() == ISD::AND &&
3555 N0.getOperand(0) == N1.getOperand(0) &&
3556 // Don't increase # computations.
3557 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3558 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3559 N0.getOperand(1), N1.getOperand(1));
3560 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3566 SDValue DAGCombiner::visitOR(SDNode *N) {
3567 SDValue N0 = N->getOperand(0);
3568 SDValue N1 = N->getOperand(1);
3569 EVT VT = N1.getValueType();
3572 if (VT.isVector()) {
3573 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3576 // fold (or x, 0) -> x, vector edition
3577 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3579 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3582 // fold (or x, -1) -> -1, vector edition
3583 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3584 // do not return N0, because undef node may exist in N0
3585 return DAG.getConstant(
3586 APInt::getAllOnesValue(
3587 N0.getValueType().getScalarType().getSizeInBits()),
3588 SDLoc(N), N0.getValueType());
3589 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3590 // do not return N1, because undef node may exist in N1
3591 return DAG.getConstant(
3592 APInt::getAllOnesValue(
3593 N1.getValueType().getScalarType().getSizeInBits()),
3594 SDLoc(N), N1.getValueType());
3596 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3597 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3598 // Do this only if the resulting shuffle is legal.
3599 if (isa<ShuffleVectorSDNode>(N0) &&
3600 isa<ShuffleVectorSDNode>(N1) &&
3601 // Avoid folding a node with illegal type.
3602 TLI.isTypeLegal(VT) &&
3603 N0->getOperand(1) == N1->getOperand(1) &&
3604 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3605 bool CanFold = true;
3606 unsigned NumElts = VT.getVectorNumElements();
3607 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3608 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3609 // We construct two shuffle masks:
3610 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3611 // and N1 as the second operand.
3612 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3613 // and N0 as the second operand.
3614 // We do this because OR is commutable and therefore there might be
3615 // two ways to fold this node into a shuffle.
3616 SmallVector<int,4> Mask1;
3617 SmallVector<int,4> Mask2;
3619 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3620 int M0 = SV0->getMaskElt(i);
3621 int M1 = SV1->getMaskElt(i);
3623 // Both shuffle indexes are undef. Propagate Undef.
3624 if (M0 < 0 && M1 < 0) {
3625 Mask1.push_back(M0);
3626 Mask2.push_back(M0);
3630 if (M0 < 0 || M1 < 0 ||
3631 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3632 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3637 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3638 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3642 // Fold this sequence only if the resulting shuffle is 'legal'.
3643 if (TLI.isShuffleMaskLegal(Mask1, VT))
3644 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3645 N1->getOperand(0), &Mask1[0]);
3646 if (TLI.isShuffleMaskLegal(Mask2, VT))
3647 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3648 N0->getOperand(0), &Mask2[0]);
3653 // fold (or c1, c2) -> c1|c2
3654 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3655 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3656 if (N0C && N1C && !N1C->isOpaque())
3657 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3658 // canonicalize constant to RHS
3659 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3660 !isConstantIntBuildVectorOrConstantInt(N1))
3661 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3662 // fold (or x, 0) -> x
3663 if (isNullConstant(N1))
3665 // fold (or x, -1) -> -1
3666 if (isAllOnesConstant(N1))
3668 // fold (or x, c) -> c iff (x & ~c) == 0
3669 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3672 if (SDValue Combined = visitORLike(N0, N1, N))
3675 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3676 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3678 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3682 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3684 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3685 // iff (c1 & c2) == 0.
3686 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3687 isa<ConstantSDNode>(N0.getOperand(1))) {
3688 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3689 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3690 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3693 ISD::AND, SDLoc(N), VT,
3694 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3698 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3699 if (N0.getOpcode() == N1.getOpcode())
3700 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3703 // See if this is some rotate idiom.
3704 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3705 return SDValue(Rot, 0);
3707 // Simplify the operands using demanded-bits information.
3708 if (!VT.isVector() &&
3709 SimplifyDemandedBits(SDValue(N, 0)))
3710 return SDValue(N, 0);
3715 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3716 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3717 if (Op.getOpcode() == ISD::AND) {
3718 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3719 Mask = Op.getOperand(1);
3720 Op = Op.getOperand(0);
3726 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3734 // Return true if we can prove that, whenever Neg and Pos are both in the
3735 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3736 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3738 // (or (shift1 X, Neg), (shift2 X, Pos))
3740 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3741 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3742 // to consider shift amounts with defined behavior.
3743 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3744 // If OpSize is a power of 2 then:
3746 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3747 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3749 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3750 // for the stronger condition:
3752 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3754 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3755 // we can just replace Neg with Neg' for the rest of the function.
3757 // In other cases we check for the even stronger condition:
3759 // Neg == OpSize - Pos [B]
3761 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3762 // behavior if Pos == 0 (and consequently Neg == OpSize).
3764 // We could actually use [A] whenever OpSize is a power of 2, but the
3765 // only extra cases that it would match are those uninteresting ones
3766 // where Neg and Pos are never in range at the same time. E.g. for
3767 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3768 // as well as (sub 32, Pos), but:
3770 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3772 // always invokes undefined behavior for 32-bit X.
3774 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3775 unsigned MaskLoBits = 0;
3776 if (Neg.getOpcode() == ISD::AND &&
3777 isPowerOf2_64(OpSize) &&
3778 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3779 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3780 Neg = Neg.getOperand(0);
3781 MaskLoBits = Log2_64(OpSize);
3784 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3785 if (Neg.getOpcode() != ISD::SUB)
3787 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3790 SDValue NegOp1 = Neg.getOperand(1);
3792 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3793 // Pos'. The truncation is redundant for the purpose of the equality.
3795 Pos.getOpcode() == ISD::AND &&
3796 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3797 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3798 Pos = Pos.getOperand(0);
3800 // The condition we need is now:
3802 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3804 // If NegOp1 == Pos then we need:
3806 // OpSize & Mask == NegC & Mask
3808 // (because "x & Mask" is a truncation and distributes through subtraction).
3811 Width = NegC->getAPIntValue();
3812 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3813 // Then the condition we want to prove becomes:
3815 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3817 // which, again because "x & Mask" is a truncation, becomes:
3819 // NegC & Mask == (OpSize - PosC) & Mask
3820 // OpSize & Mask == (NegC + PosC) & Mask
3821 else if (Pos.getOpcode() == ISD::ADD &&
3822 Pos.getOperand(0) == NegOp1 &&
3823 Pos.getOperand(1).getOpcode() == ISD::Constant)
3824 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3825 NegC->getAPIntValue());
3829 // Now we just need to check that OpSize & Mask == Width & Mask.
3831 // Opsize & Mask is 0 since Mask is Opsize - 1.
3832 return Width.getLoBits(MaskLoBits) == 0;
3833 return Width == OpSize;
3836 // A subroutine of MatchRotate used once we have found an OR of two opposite
3837 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3838 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3839 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3840 // Neg with outer conversions stripped away.
3841 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3842 SDValue Neg, SDValue InnerPos,
3843 SDValue InnerNeg, unsigned PosOpcode,
3844 unsigned NegOpcode, SDLoc DL) {
3845 // fold (or (shl x, (*ext y)),
3846 // (srl x, (*ext (sub 32, y)))) ->
3847 // (rotl x, y) or (rotr x, (sub 32, y))
3849 // fold (or (shl x, (*ext (sub 32, y))),
3850 // (srl x, (*ext y))) ->
3851 // (rotr x, y) or (rotl x, (sub 32, y))
3852 EVT VT = Shifted.getValueType();
3853 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3854 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3855 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3856 HasPos ? Pos : Neg).getNode();
3862 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3863 // idioms for rotate, and if the target supports rotation instructions, generate
3865 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3866 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3867 EVT VT = LHS.getValueType();
3868 if (!TLI.isTypeLegal(VT)) return nullptr;
3870 // The target must have at least one rotate flavor.
3871 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3872 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3873 if (!HasROTL && !HasROTR) return nullptr;
3875 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3876 SDValue LHSShift; // The shift.
3877 SDValue LHSMask; // AND value if any.
3878 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3879 return nullptr; // Not part of a rotate.
3881 SDValue RHSShift; // The shift.
3882 SDValue RHSMask; // AND value if any.
3883 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3884 return nullptr; // Not part of a rotate.
3886 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3887 return nullptr; // Not shifting the same value.
3889 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3890 return nullptr; // Shifts must disagree.
3892 // Canonicalize shl to left side in a shl/srl pair.
3893 if (RHSShift.getOpcode() == ISD::SHL) {
3894 std::swap(LHS, RHS);
3895 std::swap(LHSShift, RHSShift);
3896 std::swap(LHSMask , RHSMask );
3899 unsigned OpSizeInBits = VT.getSizeInBits();
3900 SDValue LHSShiftArg = LHSShift.getOperand(0);
3901 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3902 SDValue RHSShiftArg = RHSShift.getOperand(0);
3903 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3905 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3906 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3907 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3908 RHSShiftAmt.getOpcode() == ISD::Constant) {
3909 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3910 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3911 if ((LShVal + RShVal) != OpSizeInBits)
3914 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3915 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3917 // If there is an AND of either shifted operand, apply it to the result.
3918 if (LHSMask.getNode() || RHSMask.getNode()) {
3919 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3921 if (LHSMask.getNode()) {
3922 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3923 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3925 if (RHSMask.getNode()) {
3926 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3927 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3930 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3933 return Rot.getNode();
3936 // If there is a mask here, and we have a variable shift, we can't be sure
3937 // that we're masking out the right stuff.
3938 if (LHSMask.getNode() || RHSMask.getNode())
3941 // If the shift amount is sign/zext/any-extended just peel it off.
3942 SDValue LExtOp0 = LHSShiftAmt;
3943 SDValue RExtOp0 = RHSShiftAmt;
3944 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3945 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3946 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3947 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3948 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3949 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3950 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3951 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3952 LExtOp0 = LHSShiftAmt.getOperand(0);
3953 RExtOp0 = RHSShiftAmt.getOperand(0);
3956 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3957 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3961 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3962 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3969 SDValue DAGCombiner::visitXOR(SDNode *N) {
3970 SDValue N0 = N->getOperand(0);
3971 SDValue N1 = N->getOperand(1);
3972 EVT VT = N0.getValueType();
3975 if (VT.isVector()) {
3976 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3979 // fold (xor x, 0) -> x, vector edition
3980 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3982 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3986 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3987 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3988 return DAG.getConstant(0, SDLoc(N), VT);
3989 // fold (xor x, undef) -> undef
3990 if (N0.getOpcode() == ISD::UNDEF)
3992 if (N1.getOpcode() == ISD::UNDEF)
3994 // fold (xor c1, c2) -> c1^c2
3995 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3996 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3998 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3999 // canonicalize constant to RHS
4000 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4001 !isConstantIntBuildVectorOrConstantInt(N1))
4002 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4003 // fold (xor x, 0) -> x
4004 if (isNullConstant(N1))
4007 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4010 // fold !(x cc y) -> (x !cc y)
4011 SDValue LHS, RHS, CC;
4012 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4013 bool isInt = LHS.getValueType().isInteger();
4014 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4017 if (!LegalOperations ||
4018 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4019 switch (N0.getOpcode()) {
4021 llvm_unreachable("Unhandled SetCC Equivalent!");
4023 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4024 case ISD::SELECT_CC:
4025 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4026 N0.getOperand(3), NotCC);
4031 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4032 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4033 N0.getNode()->hasOneUse() &&
4034 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4035 SDValue V = N0.getOperand(0);
4037 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4038 DAG.getConstant(1, DL, V.getValueType()));
4039 AddToWorklist(V.getNode());
4040 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4043 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4044 if (isOneConstant(N1) && VT == MVT::i1 &&
4045 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4046 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4047 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4048 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4049 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4050 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4051 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4052 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4055 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4056 if (isAllOnesConstant(N1) &&
4057 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4058 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4059 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4060 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4061 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4062 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4063 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4064 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4067 // fold (xor (and x, y), y) -> (and (not x), y)
4068 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4069 N0->getOperand(1) == N1) {
4070 SDValue X = N0->getOperand(0);
4071 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4072 AddToWorklist(NotX.getNode());
4073 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4075 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4076 if (N1C && N0.getOpcode() == ISD::XOR) {
4077 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4079 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4080 DAG.getConstant(N1C->getAPIntValue() ^
4081 N00C->getAPIntValue(), DL, VT));
4083 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4085 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4086 DAG.getConstant(N1C->getAPIntValue() ^
4087 N01C->getAPIntValue(), DL, VT));
4090 // fold (xor x, x) -> 0
4092 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4094 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4095 // Here is a concrete example of this equivalence:
4097 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4098 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4102 // i16 ~1 == 0b1111111111111110
4103 // i16 rol(~1, 14) == 0b1011111111111111
4105 // Some additional tips to help conceptualize this transform:
4106 // - Try to see the operation as placing a single zero in a value of all ones.
4107 // - There exists no value for x which would allow the result to contain zero.
4108 // - Values of x larger than the bitwidth are undefined and do not require a
4109 // consistent result.
4110 // - Pushing the zero left requires shifting one bits in from the right.
4111 // A rotate left of ~1 is a nice way of achieving the desired result.
4112 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4113 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4115 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4119 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4120 if (N0.getOpcode() == N1.getOpcode())
4121 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4124 // Simplify the expression using non-local knowledge.
4125 if (!VT.isVector() &&
4126 SimplifyDemandedBits(SDValue(N, 0)))
4127 return SDValue(N, 0);
4132 /// Handle transforms common to the three shifts, when the shift amount is a
4134 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4135 SDNode *LHS = N->getOperand(0).getNode();
4136 if (!LHS->hasOneUse()) return SDValue();
4138 // We want to pull some binops through shifts, so that we have (and (shift))
4139 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4140 // thing happens with address calculations, so it's important to canonicalize
4142 bool HighBitSet = false; // Can we transform this if the high bit is set?
4144 switch (LHS->getOpcode()) {
4145 default: return SDValue();
4148 HighBitSet = false; // We can only transform sra if the high bit is clear.
4151 HighBitSet = true; // We can only transform sra if the high bit is set.
4154 if (N->getOpcode() != ISD::SHL)
4155 return SDValue(); // only shl(add) not sr[al](add).
4156 HighBitSet = false; // We can only transform sra if the high bit is clear.
4160 // We require the RHS of the binop to be a constant and not opaque as well.
4161 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4162 if (!BinOpCst) return SDValue();
4164 // FIXME: disable this unless the input to the binop is a shift by a constant.
4165 // If it is not a shift, it pessimizes some common cases like:
4167 // void foo(int *X, int i) { X[i & 1235] = 1; }
4168 // int bar(int *X, int i) { return X[i & 255]; }
4169 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4170 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4171 BinOpLHSVal->getOpcode() != ISD::SRA &&
4172 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4173 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4176 EVT VT = N->getValueType(0);
4178 // If this is a signed shift right, and the high bit is modified by the
4179 // logical operation, do not perform the transformation. The highBitSet
4180 // boolean indicates the value of the high bit of the constant which would
4181 // cause it to be modified for this operation.
4182 if (N->getOpcode() == ISD::SRA) {
4183 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4184 if (BinOpRHSSignSet != HighBitSet)
4188 if (!TLI.isDesirableToCommuteWithShift(LHS))
4191 // Fold the constants, shifting the binop RHS by the shift amount.
4192 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4194 LHS->getOperand(1), N->getOperand(1));
4195 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4197 // Create the new shift.
4198 SDValue NewShift = DAG.getNode(N->getOpcode(),
4199 SDLoc(LHS->getOperand(0)),
4200 VT, LHS->getOperand(0), N->getOperand(1));
4202 // Create the new binop.
4203 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4206 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4207 assert(N->getOpcode() == ISD::TRUNCATE);
4208 assert(N->getOperand(0).getOpcode() == ISD::AND);
4210 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4211 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4212 SDValue N01 = N->getOperand(0).getOperand(1);
4214 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4215 if (!N01C->isOpaque()) {
4216 EVT TruncVT = N->getValueType(0);
4217 SDValue N00 = N->getOperand(0).getOperand(0);
4218 APInt TruncC = N01C->getAPIntValue();
4219 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4222 return DAG.getNode(ISD::AND, DL, TruncVT,
4223 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4224 DAG.getConstant(TruncC, DL, TruncVT));
4232 SDValue DAGCombiner::visitRotate(SDNode *N) {
4233 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4234 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4235 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4236 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4237 if (NewOp1.getNode())
4238 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4239 N->getOperand(0), NewOp1);
4244 SDValue DAGCombiner::visitSHL(SDNode *N) {
4245 SDValue N0 = N->getOperand(0);
4246 SDValue N1 = N->getOperand(1);
4247 EVT VT = N0.getValueType();
4248 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4251 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4252 if (VT.isVector()) {
4253 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4256 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4257 // If setcc produces all-one true value then:
4258 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4259 if (N1CV && N1CV->isConstant()) {
4260 if (N0.getOpcode() == ISD::AND) {
4261 SDValue N00 = N0->getOperand(0);
4262 SDValue N01 = N0->getOperand(1);
4263 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4265 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4266 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4267 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4268 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4270 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4273 N1C = isConstOrConstSplat(N1);
4278 // fold (shl c1, c2) -> c1<<c2
4279 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4280 if (N0C && N1C && !N1C->isOpaque())
4281 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4282 // fold (shl 0, x) -> 0
4283 if (isNullConstant(N0))
4285 // fold (shl x, c >= size(x)) -> undef
4286 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4287 return DAG.getUNDEF(VT);
4288 // fold (shl x, 0) -> x
4289 if (N1C && N1C->isNullValue())
4291 // fold (shl undef, x) -> 0
4292 if (N0.getOpcode() == ISD::UNDEF)
4293 return DAG.getConstant(0, SDLoc(N), VT);
4294 // if (shl x, c) is known to be zero, return 0
4295 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4296 APInt::getAllOnesValue(OpSizeInBits)))
4297 return DAG.getConstant(0, SDLoc(N), VT);
4298 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4299 if (N1.getOpcode() == ISD::TRUNCATE &&
4300 N1.getOperand(0).getOpcode() == ISD::AND) {
4301 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4302 if (NewOp1.getNode())
4303 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4306 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4307 return SDValue(N, 0);
4309 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4310 if (N1C && N0.getOpcode() == ISD::SHL) {
4311 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4312 uint64_t c1 = N0C1->getZExtValue();
4313 uint64_t c2 = N1C->getZExtValue();
4315 if (c1 + c2 >= OpSizeInBits)
4316 return DAG.getConstant(0, DL, VT);
4317 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4318 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4322 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4323 // For this to be valid, the second form must not preserve any of the bits
4324 // that are shifted out by the inner shift in the first form. This means
4325 // the outer shift size must be >= the number of bits added by the ext.
4326 // As a corollary, we don't care what kind of ext it is.
4327 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4328 N0.getOpcode() == ISD::ANY_EXTEND ||
4329 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4330 N0.getOperand(0).getOpcode() == ISD::SHL) {
4331 SDValue N0Op0 = N0.getOperand(0);
4332 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4333 uint64_t c1 = N0Op0C1->getZExtValue();
4334 uint64_t c2 = N1C->getZExtValue();
4335 EVT InnerShiftVT = N0Op0.getValueType();
4336 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4337 if (c2 >= OpSizeInBits - InnerShiftSize) {
4339 if (c1 + c2 >= OpSizeInBits)
4340 return DAG.getConstant(0, DL, VT);
4341 return DAG.getNode(ISD::SHL, DL, VT,
4342 DAG.getNode(N0.getOpcode(), DL, VT,
4343 N0Op0->getOperand(0)),
4344 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4349 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4350 // Only fold this if the inner zext has no other uses to avoid increasing
4351 // the total number of instructions.
4352 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4353 N0.getOperand(0).getOpcode() == ISD::SRL) {
4354 SDValue N0Op0 = N0.getOperand(0);
4355 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4356 uint64_t c1 = N0Op0C1->getZExtValue();
4357 if (c1 < VT.getScalarSizeInBits()) {
4358 uint64_t c2 = N1C->getZExtValue();
4360 SDValue NewOp0 = N0.getOperand(0);
4361 EVT CountVT = NewOp0.getOperand(1).getValueType();
4363 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4365 DAG.getConstant(c2, DL, CountVT));
4366 AddToWorklist(NewSHL.getNode());
4367 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4373 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4374 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4375 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4376 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4377 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4378 uint64_t C1 = N0C1->getZExtValue();
4379 uint64_t C2 = N1C->getZExtValue();
4382 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4383 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4384 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4385 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4389 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4390 // (and (srl x, (sub c1, c2), MASK)
4391 // Only fold this if the inner shift has no other uses -- if it does, folding
4392 // this will increase the total number of instructions.
4393 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4394 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4395 uint64_t c1 = N0C1->getZExtValue();
4396 if (c1 < OpSizeInBits) {
4397 uint64_t c2 = N1C->getZExtValue();
4398 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4401 Mask = Mask.shl(c2 - c1);
4403 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4404 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4406 Mask = Mask.lshr(c1 - c2);
4408 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4409 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4412 return DAG.getNode(ISD::AND, DL, VT, Shift,
4413 DAG.getConstant(Mask, DL, VT));
4417 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4418 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4419 unsigned BitSize = VT.getScalarSizeInBits();
4421 SDValue HiBitsMask =
4422 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4423 BitSize - N1C->getZExtValue()),
4425 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4429 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4430 // Variant of version done on multiply, except mul by a power of 2 is turned
4433 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4434 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4435 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4436 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4437 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4438 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4441 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4442 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4443 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4444 if (SDValue Folded =
4445 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4446 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4450 if (N1C && !N1C->isOpaque())
4451 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4457 SDValue DAGCombiner::visitSRA(SDNode *N) {
4458 SDValue N0 = N->getOperand(0);
4459 SDValue N1 = N->getOperand(1);
4460 EVT VT = N0.getValueType();
4461 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4464 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4465 if (VT.isVector()) {
4466 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4469 N1C = isConstOrConstSplat(N1);
4472 // fold (sra c1, c2) -> (sra c1, c2)
4473 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4474 if (N0C && N1C && !N1C->isOpaque())
4475 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4476 // fold (sra 0, x) -> 0
4477 if (isNullConstant(N0))
4479 // fold (sra -1, x) -> -1
4480 if (isAllOnesConstant(N0))
4482 // fold (sra x, (setge c, size(x))) -> undef
4483 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4484 return DAG.getUNDEF(VT);
4485 // fold (sra x, 0) -> x
4486 if (N1C && N1C->isNullValue())
4488 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4490 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4491 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4492 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4494 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4495 ExtVT, VT.getVectorNumElements());
4496 if ((!LegalOperations ||
4497 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4498 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4499 N0.getOperand(0), DAG.getValueType(ExtVT));
4502 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4503 if (N1C && N0.getOpcode() == ISD::SRA) {
4504 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4505 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4506 if (Sum >= OpSizeInBits)
4507 Sum = OpSizeInBits - 1;
4509 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4510 DAG.getConstant(Sum, DL, N1.getValueType()));
4514 // fold (sra (shl X, m), (sub result_size, n))
4515 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4516 // result_size - n != m.
4517 // If truncate is free for the target sext(shl) is likely to result in better
4519 if (N0.getOpcode() == ISD::SHL && N1C) {
4520 // Get the two constanst of the shifts, CN0 = m, CN = n.
4521 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4523 LLVMContext &Ctx = *DAG.getContext();
4524 // Determine what the truncate's result bitsize and type would be.
4525 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4528 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4530 // Determine the residual right-shift amount.
4531 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4533 // If the shift is not a no-op (in which case this should be just a sign
4534 // extend already), the truncated to type is legal, sign_extend is legal
4535 // on that type, and the truncate to that type is both legal and free,
4536 // perform the transform.
4537 if ((ShiftAmt > 0) &&
4538 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4539 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4540 TLI.isTruncateFree(VT, TruncVT)) {
4543 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4544 getShiftAmountTy(N0.getOperand(0).getValueType()));
4545 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4546 N0.getOperand(0), Amt);
4547 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4549 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4550 N->getValueType(0), Trunc);
4555 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4556 if (N1.getOpcode() == ISD::TRUNCATE &&
4557 N1.getOperand(0).getOpcode() == ISD::AND) {
4558 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4559 if (NewOp1.getNode())
4560 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4563 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4564 // if c1 is equal to the number of bits the trunc removes
4565 if (N0.getOpcode() == ISD::TRUNCATE &&
4566 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4567 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4568 N0.getOperand(0).hasOneUse() &&
4569 N0.getOperand(0).getOperand(1).hasOneUse() &&
4571 SDValue N0Op0 = N0.getOperand(0);
4572 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4573 unsigned LargeShiftVal = LargeShift->getZExtValue();
4574 EVT LargeVT = N0Op0.getValueType();
4576 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4579 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4580 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4581 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4582 N0Op0.getOperand(0), Amt);
4583 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4588 // Simplify, based on bits shifted out of the LHS.
4589 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4590 return SDValue(N, 0);
4593 // If the sign bit is known to be zero, switch this to a SRL.
4594 if (DAG.SignBitIsZero(N0))
4595 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4597 if (N1C && !N1C->isOpaque())
4598 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4604 SDValue DAGCombiner::visitSRL(SDNode *N) {
4605 SDValue N0 = N->getOperand(0);
4606 SDValue N1 = N->getOperand(1);
4607 EVT VT = N0.getValueType();
4608 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4611 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4612 if (VT.isVector()) {
4613 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4616 N1C = isConstOrConstSplat(N1);
4619 // fold (srl c1, c2) -> c1 >>u c2
4620 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4621 if (N0C && N1C && !N1C->isOpaque())
4622 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4623 // fold (srl 0, x) -> 0
4624 if (isNullConstant(N0))
4626 // fold (srl x, c >= size(x)) -> undef
4627 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4628 return DAG.getUNDEF(VT);
4629 // fold (srl x, 0) -> x
4630 if (N1C && N1C->isNullValue())
4632 // if (srl x, c) is known to be zero, return 0
4633 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4634 APInt::getAllOnesValue(OpSizeInBits)))
4635 return DAG.getConstant(0, SDLoc(N), VT);
4637 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4638 if (N1C && N0.getOpcode() == ISD::SRL) {
4639 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4640 uint64_t c1 = N01C->getZExtValue();
4641 uint64_t c2 = N1C->getZExtValue();
4643 if (c1 + c2 >= OpSizeInBits)
4644 return DAG.getConstant(0, DL, VT);
4645 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4646 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4650 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4651 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4652 N0.getOperand(0).getOpcode() == ISD::SRL &&
4653 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4655 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4656 uint64_t c2 = N1C->getZExtValue();
4657 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4658 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4659 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4660 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4661 if (c1 + OpSizeInBits == InnerShiftSize) {
4663 if (c1 + c2 >= InnerShiftSize)
4664 return DAG.getConstant(0, DL, VT);
4665 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4666 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4667 N0.getOperand(0)->getOperand(0),
4668 DAG.getConstant(c1 + c2, DL,
4673 // fold (srl (shl x, c), c) -> (and x, cst2)
4674 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4675 unsigned BitSize = N0.getScalarValueSizeInBits();
4676 if (BitSize <= 64) {
4677 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4679 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4680 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4684 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4685 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4686 // Shifting in all undef bits?
4687 EVT SmallVT = N0.getOperand(0).getValueType();
4688 unsigned BitSize = SmallVT.getScalarSizeInBits();
4689 if (N1C->getZExtValue() >= BitSize)
4690 return DAG.getUNDEF(VT);
4692 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4693 uint64_t ShiftAmt = N1C->getZExtValue();
4695 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4697 DAG.getConstant(ShiftAmt, DL0,
4698 getShiftAmountTy(SmallVT)));
4699 AddToWorklist(SmallShift.getNode());
4700 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4702 return DAG.getNode(ISD::AND, DL, VT,
4703 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4704 DAG.getConstant(Mask, DL, VT));
4708 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4709 // bit, which is unmodified by sra.
4710 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4711 if (N0.getOpcode() == ISD::SRA)
4712 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4715 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4716 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4717 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4718 APInt KnownZero, KnownOne;
4719 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4721 // If any of the input bits are KnownOne, then the input couldn't be all
4722 // zeros, thus the result of the srl will always be zero.
4723 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4725 // If all of the bits input the to ctlz node are known to be zero, then
4726 // the result of the ctlz is "32" and the result of the shift is one.
4727 APInt UnknownBits = ~KnownZero;
4728 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4730 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4731 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4732 // Okay, we know that only that the single bit specified by UnknownBits
4733 // could be set on input to the CTLZ node. If this bit is set, the SRL
4734 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4735 // to an SRL/XOR pair, which is likely to simplify more.
4736 unsigned ShAmt = UnknownBits.countTrailingZeros();
4737 SDValue Op = N0.getOperand(0);
4741 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4742 DAG.getConstant(ShAmt, DL,
4743 getShiftAmountTy(Op.getValueType())));
4744 AddToWorklist(Op.getNode());
4748 return DAG.getNode(ISD::XOR, DL, VT,
4749 Op, DAG.getConstant(1, DL, VT));
4753 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4754 if (N1.getOpcode() == ISD::TRUNCATE &&
4755 N1.getOperand(0).getOpcode() == ISD::AND) {
4756 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4757 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4760 // fold operands of srl based on knowledge that the low bits are not
4762 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4763 return SDValue(N, 0);
4765 if (N1C && !N1C->isOpaque())
4766 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4769 // Attempt to convert a srl of a load into a narrower zero-extending load.
4770 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4773 // Here is a common situation. We want to optimize:
4776 // %b = and i32 %a, 2
4777 // %c = srl i32 %b, 1
4778 // brcond i32 %c ...
4784 // %c = setcc eq %b, 0
4787 // However when after the source operand of SRL is optimized into AND, the SRL
4788 // itself may not be optimized further. Look for it and add the BRCOND into
4790 if (N->hasOneUse()) {
4791 SDNode *Use = *N->use_begin();
4792 if (Use->getOpcode() == ISD::BRCOND)
4794 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4795 // Also look pass the truncate.
4796 Use = *Use->use_begin();
4797 if (Use->getOpcode() == ISD::BRCOND)
4805 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4806 SDValue N0 = N->getOperand(0);
4807 EVT VT = N->getValueType(0);
4809 // fold (bswap c1) -> c2
4810 if (isConstantIntBuildVectorOrConstantInt(N0))
4811 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4812 // fold (bswap (bswap x)) -> x
4813 if (N0.getOpcode() == ISD::BSWAP)
4814 return N0->getOperand(0);
4818 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4819 SDValue N0 = N->getOperand(0);
4820 EVT VT = N->getValueType(0);
4822 // fold (ctlz c1) -> c2
4823 if (isConstantIntBuildVectorOrConstantInt(N0))
4824 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4828 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4829 SDValue N0 = N->getOperand(0);
4830 EVT VT = N->getValueType(0);
4832 // fold (ctlz_zero_undef c1) -> c2
4833 if (isConstantIntBuildVectorOrConstantInt(N0))
4834 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4838 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4839 SDValue N0 = N->getOperand(0);
4840 EVT VT = N->getValueType(0);
4842 // fold (cttz c1) -> c2
4843 if (isConstantIntBuildVectorOrConstantInt(N0))
4844 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4848 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4849 SDValue N0 = N->getOperand(0);
4850 EVT VT = N->getValueType(0);
4852 // fold (cttz_zero_undef c1) -> c2
4853 if (isConstantIntBuildVectorOrConstantInt(N0))
4854 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4858 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4859 SDValue N0 = N->getOperand(0);
4860 EVT VT = N->getValueType(0);
4862 // fold (ctpop c1) -> c2
4863 if (isConstantIntBuildVectorOrConstantInt(N0))
4864 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4869 /// \brief Generate Min/Max node
4870 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4871 SDValue True, SDValue False,
4872 ISD::CondCode CC, const TargetLowering &TLI,
4873 SelectionDAG &DAG) {
4874 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4884 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4885 if (TLI.isOperationLegal(Opcode, VT))
4886 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4895 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4896 if (TLI.isOperationLegal(Opcode, VT))
4897 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4905 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4906 SDValue N0 = N->getOperand(0);
4907 SDValue N1 = N->getOperand(1);
4908 SDValue N2 = N->getOperand(2);
4909 EVT VT = N->getValueType(0);
4910 EVT VT0 = N0.getValueType();
4912 // fold (select C, X, X) -> X
4915 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4916 // fold (select true, X, Y) -> X
4917 // fold (select false, X, Y) -> Y
4918 return !N0C->isNullValue() ? N1 : N2;
4920 // fold (select C, 1, X) -> (or C, X)
4921 if (VT == MVT::i1 && isOneConstant(N1))
4922 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4923 // fold (select C, 0, 1) -> (xor C, 1)
4924 // We can't do this reliably if integer based booleans have different contents
4925 // to floating point based booleans. This is because we can't tell whether we
4926 // have an integer-based boolean or a floating-point-based boolean unless we
4927 // can find the SETCC that produced it and inspect its operands. This is
4928 // fairly easy if C is the SETCC node, but it can potentially be
4929 // undiscoverable (or not reasonably discoverable). For example, it could be
4930 // in another basic block or it could require searching a complicated
4932 if (VT.isInteger() &&
4933 (VT0 == MVT::i1 || (VT0.isInteger() &&
4934 TLI.getBooleanContents(false, false) ==
4935 TLI.getBooleanContents(false, true) &&
4936 TLI.getBooleanContents(false, false) ==
4937 TargetLowering::ZeroOrOneBooleanContent)) &&
4938 isNullConstant(N1) && isOneConstant(N2)) {
4942 return DAG.getNode(ISD::XOR, DL, VT0,
4943 N0, DAG.getConstant(1, DL, VT0));
4946 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4947 N0, DAG.getConstant(1, DL0, VT0));
4948 AddToWorklist(XORNode.getNode());
4950 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4951 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4953 // fold (select C, 0, X) -> (and (not C), X)
4954 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4955 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4956 AddToWorklist(NOTNode.getNode());
4957 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4959 // fold (select C, X, 1) -> (or (not C), X)
4960 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4961 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4962 AddToWorklist(NOTNode.getNode());
4963 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4965 // fold (select C, X, 0) -> (and C, X)
4966 if (VT == MVT::i1 && isNullConstant(N2))
4967 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4968 // fold (select X, X, Y) -> (or X, Y)
4969 // fold (select X, 1, Y) -> (or X, Y)
4970 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4971 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4972 // fold (select X, Y, X) -> (and X, Y)
4973 // fold (select X, Y, 0) -> (and X, Y)
4974 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4975 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4977 // If we can fold this based on the true/false value, do so.
4978 if (SimplifySelectOps(N, N1, N2))
4979 return SDValue(N, 0); // Don't revisit N.
4981 if (VT0 == MVT::i1) {
4982 // The code in this block deals with the following 2 equivalences:
4983 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
4984 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
4985 // The target can specify its prefered form with the
4986 // shouldNormalizeToSelectSequence() callback. However we always transform
4987 // to the right anyway if we find the inner select exists in the DAG anyway
4988 // and we always transform to the left side if we know that we can further
4989 // optimize the combination of the conditions.
4990 bool normalizeToSequence
4991 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
4992 // select (and Cond0, Cond1), X, Y
4993 // -> select Cond0, (select Cond1, X, Y), Y
4994 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4995 SDValue Cond0 = N0->getOperand(0);
4996 SDValue Cond1 = N0->getOperand(1);
4997 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4998 N1.getValueType(), Cond1, N1, N2);
4999 if (normalizeToSequence || !InnerSelect.use_empty())
5000 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5003 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5004 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5005 SDValue Cond0 = N0->getOperand(0);
5006 SDValue Cond1 = N0->getOperand(1);
5007 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5008 N1.getValueType(), Cond1, N1, N2);
5009 if (normalizeToSequence || !InnerSelect.use_empty())
5010 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5014 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5015 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5016 SDValue N1_0 = N1->getOperand(0);
5017 SDValue N1_1 = N1->getOperand(1);
5018 SDValue N1_2 = N1->getOperand(2);
5019 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5020 // Create the actual and node if we can generate good code for it.
5021 if (!normalizeToSequence) {
5022 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5024 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5027 // Otherwise see if we can optimize the "and" to a better pattern.
5028 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5029 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5033 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5034 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5035 SDValue N2_0 = N2->getOperand(0);
5036 SDValue N2_1 = N2->getOperand(1);
5037 SDValue N2_2 = N2->getOperand(2);
5038 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5039 // Create the actual or node if we can generate good code for it.
5040 if (!normalizeToSequence) {
5041 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5043 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5046 // Otherwise see if we can optimize to a better pattern.
5047 if (SDValue Combined = visitORLike(N0, N2_0, N))
5048 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5054 // fold selects based on a setcc into other things, such as min/max/abs
5055 if (N0.getOpcode() == ISD::SETCC) {
5056 // select x, y (fcmp lt x, y) -> fminnum x, y
5057 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5059 // This is OK if we don't care about what happens if either operand is a
5063 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5064 // no signed zeros as well as no nans.
5065 const TargetOptions &Options = DAG.getTarget().Options;
5066 if (Options.UnsafeFPMath &&
5067 VT.isFloatingPoint() && N0.hasOneUse() &&
5068 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5069 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5071 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5072 N0.getOperand(1), N1, N2, CC,
5077 if ((!LegalOperations &&
5078 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5079 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5080 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5081 N0.getOperand(0), N0.getOperand(1),
5082 N1, N2, N0.getOperand(2));
5083 return SimplifySelect(SDLoc(N), N0, N1, N2);
5090 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5093 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5095 // Split the inputs.
5096 SDValue Lo, Hi, LL, LH, RL, RH;
5097 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5098 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5100 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5101 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5103 return std::make_pair(Lo, Hi);
5106 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5107 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5108 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5110 SDValue Cond = N->getOperand(0);
5111 SDValue LHS = N->getOperand(1);
5112 SDValue RHS = N->getOperand(2);
5113 EVT VT = N->getValueType(0);
5114 int NumElems = VT.getVectorNumElements();
5115 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5116 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5117 Cond.getOpcode() == ISD::BUILD_VECTOR);
5119 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5120 // binary ones here.
5121 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5124 // We're sure we have an even number of elements due to the
5125 // concat_vectors we have as arguments to vselect.
5126 // Skip BV elements until we find one that's not an UNDEF
5127 // After we find an UNDEF element, keep looping until we get to half the
5128 // length of the BV and see if all the non-undef nodes are the same.
5129 ConstantSDNode *BottomHalf = nullptr;
5130 for (int i = 0; i < NumElems / 2; ++i) {
5131 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5134 if (BottomHalf == nullptr)
5135 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5136 else if (Cond->getOperand(i).getNode() != BottomHalf)
5140 // Do the same for the second half of the BuildVector
5141 ConstantSDNode *TopHalf = nullptr;
5142 for (int i = NumElems / 2; i < NumElems; ++i) {
5143 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5146 if (TopHalf == nullptr)
5147 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5148 else if (Cond->getOperand(i).getNode() != TopHalf)
5152 assert(TopHalf && BottomHalf &&
5153 "One half of the selector was all UNDEFs and the other was all the "
5154 "same value. This should have been addressed before this function.");
5156 ISD::CONCAT_VECTORS, dl, VT,
5157 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5158 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5161 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5163 if (Level >= AfterLegalizeTypes)
5166 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5167 SDValue Mask = MSC->getMask();
5168 SDValue Data = MSC->getValue();
5171 // If the MSCATTER data type requires splitting and the mask is provided by a
5172 // SETCC, then split both nodes and its operands before legalization. This
5173 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5174 // and enables future optimizations (e.g. min/max pattern matching on X86).
5175 if (Mask.getOpcode() != ISD::SETCC)
5178 // Check if any splitting is required.
5179 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5180 TargetLowering::TypeSplitVector)
5182 SDValue MaskLo, MaskHi, Lo, Hi;
5183 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5186 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5188 SDValue Chain = MSC->getChain();
5190 EVT MemoryVT = MSC->getMemoryVT();
5191 unsigned Alignment = MSC->getOriginalAlignment();
5193 EVT LoMemVT, HiMemVT;
5194 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5196 SDValue DataLo, DataHi;
5197 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5199 SDValue BasePtr = MSC->getBasePtr();
5200 SDValue IndexLo, IndexHi;
5201 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5203 MachineMemOperand *MMO = DAG.getMachineFunction().
5204 getMachineMemOperand(MSC->getPointerInfo(),
5205 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5206 Alignment, MSC->getAAInfo(), MSC->getRanges());
5208 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5209 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5212 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5213 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5216 AddToWorklist(Lo.getNode());
5217 AddToWorklist(Hi.getNode());
5219 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5222 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5224 if (Level >= AfterLegalizeTypes)
5227 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5228 SDValue Mask = MST->getMask();
5229 SDValue Data = MST->getValue();
5232 // If the MSTORE data type requires splitting and the mask is provided by a
5233 // SETCC, then split both nodes and its operands before legalization. This
5234 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5235 // and enables future optimizations (e.g. min/max pattern matching on X86).
5236 if (Mask.getOpcode() == ISD::SETCC) {
5238 // Check if any splitting is required.
5239 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5240 TargetLowering::TypeSplitVector)
5243 SDValue MaskLo, MaskHi, Lo, Hi;
5244 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5247 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5249 SDValue Chain = MST->getChain();
5250 SDValue Ptr = MST->getBasePtr();
5252 EVT MemoryVT = MST->getMemoryVT();
5253 unsigned Alignment = MST->getOriginalAlignment();
5255 // if Alignment is equal to the vector size,
5256 // take the half of it for the second part
5257 unsigned SecondHalfAlignment =
5258 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5259 Alignment/2 : Alignment;
5261 EVT LoMemVT, HiMemVT;
5262 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5264 SDValue DataLo, DataHi;
5265 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5267 MachineMemOperand *MMO = DAG.getMachineFunction().
5268 getMachineMemOperand(MST->getPointerInfo(),
5269 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5270 Alignment, MST->getAAInfo(), MST->getRanges());
5272 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5273 MST->isTruncatingStore());
5275 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5276 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5277 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5279 MMO = DAG.getMachineFunction().
5280 getMachineMemOperand(MST->getPointerInfo(),
5281 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5282 SecondHalfAlignment, MST->getAAInfo(),
5285 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5286 MST->isTruncatingStore());
5288 AddToWorklist(Lo.getNode());
5289 AddToWorklist(Hi.getNode());
5291 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5296 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5298 if (Level >= AfterLegalizeTypes)
5301 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5302 SDValue Mask = MGT->getMask();
5305 // If the MGATHER result requires splitting and the mask is provided by a
5306 // SETCC, then split both nodes and its operands before legalization. This
5307 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5308 // and enables future optimizations (e.g. min/max pattern matching on X86).
5310 if (Mask.getOpcode() != ISD::SETCC)
5313 EVT VT = N->getValueType(0);
5315 // Check if any splitting is required.
5316 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5317 TargetLowering::TypeSplitVector)
5320 SDValue MaskLo, MaskHi, Lo, Hi;
5321 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5323 SDValue Src0 = MGT->getValue();
5324 SDValue Src0Lo, Src0Hi;
5325 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5328 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5330 SDValue Chain = MGT->getChain();
5331 EVT MemoryVT = MGT->getMemoryVT();
5332 unsigned Alignment = MGT->getOriginalAlignment();
5334 EVT LoMemVT, HiMemVT;
5335 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5337 SDValue BasePtr = MGT->getBasePtr();
5338 SDValue Index = MGT->getIndex();
5339 SDValue IndexLo, IndexHi;
5340 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5342 MachineMemOperand *MMO = DAG.getMachineFunction().
5343 getMachineMemOperand(MGT->getPointerInfo(),
5344 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5345 Alignment, MGT->getAAInfo(), MGT->getRanges());
5347 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5348 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5351 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5352 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5355 AddToWorklist(Lo.getNode());
5356 AddToWorklist(Hi.getNode());
5358 // Build a factor node to remember that this load is independent of the
5360 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5363 // Legalized the chain result - switch anything that used the old chain to
5365 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5367 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5369 SDValue RetOps[] = { GatherRes, Chain };
5370 return DAG.getMergeValues(RetOps, DL);
5373 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5375 if (Level >= AfterLegalizeTypes)
5378 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5379 SDValue Mask = MLD->getMask();
5382 // If the MLOAD result requires splitting and the mask is provided by a
5383 // SETCC, then split both nodes and its operands before legalization. This
5384 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5385 // and enables future optimizations (e.g. min/max pattern matching on X86).
5387 if (Mask.getOpcode() == ISD::SETCC) {
5388 EVT VT = N->getValueType(0);
5390 // Check if any splitting is required.
5391 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5392 TargetLowering::TypeSplitVector)
5395 SDValue MaskLo, MaskHi, Lo, Hi;
5396 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5398 SDValue Src0 = MLD->getSrc0();
5399 SDValue Src0Lo, Src0Hi;
5400 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5403 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5405 SDValue Chain = MLD->getChain();
5406 SDValue Ptr = MLD->getBasePtr();
5407 EVT MemoryVT = MLD->getMemoryVT();
5408 unsigned Alignment = MLD->getOriginalAlignment();
5410 // if Alignment is equal to the vector size,
5411 // take the half of it for the second part
5412 unsigned SecondHalfAlignment =
5413 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5414 Alignment/2 : Alignment;
5416 EVT LoMemVT, HiMemVT;
5417 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5419 MachineMemOperand *MMO = DAG.getMachineFunction().
5420 getMachineMemOperand(MLD->getPointerInfo(),
5421 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5422 Alignment, MLD->getAAInfo(), MLD->getRanges());
5424 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5427 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5428 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5429 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5431 MMO = DAG.getMachineFunction().
5432 getMachineMemOperand(MLD->getPointerInfo(),
5433 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5434 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5436 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5439 AddToWorklist(Lo.getNode());
5440 AddToWorklist(Hi.getNode());
5442 // Build a factor node to remember that this load is independent of the
5444 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5447 // Legalized the chain result - switch anything that used the old chain to
5449 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5451 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5453 SDValue RetOps[] = { LoadRes, Chain };
5454 return DAG.getMergeValues(RetOps, DL);
5459 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5460 SDValue N0 = N->getOperand(0);
5461 SDValue N1 = N->getOperand(1);
5462 SDValue N2 = N->getOperand(2);
5465 // Canonicalize integer abs.
5466 // vselect (setg[te] X, 0), X, -X ->
5467 // vselect (setgt X, -1), X, -X ->
5468 // vselect (setl[te] X, 0), -X, X ->
5469 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5470 if (N0.getOpcode() == ISD::SETCC) {
5471 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5472 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5474 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5476 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5477 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5478 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5479 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5480 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5481 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5482 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5485 EVT VT = LHS.getValueType();
5486 SDValue Shift = DAG.getNode(
5487 ISD::SRA, DL, VT, LHS,
5488 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5489 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5490 AddToWorklist(Shift.getNode());
5491 AddToWorklist(Add.getNode());
5492 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5496 if (SimplifySelectOps(N, N1, N2))
5497 return SDValue(N, 0); // Don't revisit N.
5499 // If the VSELECT result requires splitting and the mask is provided by a
5500 // SETCC, then split both nodes and its operands before legalization. This
5501 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5502 // and enables future optimizations (e.g. min/max pattern matching on X86).
5503 if (N0.getOpcode() == ISD::SETCC) {
5504 EVT VT = N->getValueType(0);
5506 // Check if any splitting is required.
5507 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5508 TargetLowering::TypeSplitVector)
5511 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5512 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5513 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5514 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5516 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5517 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5519 // Add the new VSELECT nodes to the work list in case they need to be split
5521 AddToWorklist(Lo.getNode());
5522 AddToWorklist(Hi.getNode());
5524 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5527 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5528 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5530 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5531 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5534 // The ConvertSelectToConcatVector function is assuming both the above
5535 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5537 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5538 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5539 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5540 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5547 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5548 SDValue N0 = N->getOperand(0);
5549 SDValue N1 = N->getOperand(1);
5550 SDValue N2 = N->getOperand(2);
5551 SDValue N3 = N->getOperand(3);
5552 SDValue N4 = N->getOperand(4);
5553 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5555 // fold select_cc lhs, rhs, x, x, cc -> x
5559 // Determine if the condition we're dealing with is constant
5560 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5561 N0, N1, CC, SDLoc(N), false);
5562 if (SCC.getNode()) {
5563 AddToWorklist(SCC.getNode());
5565 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5566 if (!SCCC->isNullValue())
5567 return N2; // cond always true -> true val
5569 return N3; // cond always false -> false val
5570 } else if (SCC->getOpcode() == ISD::UNDEF) {
5571 // When the condition is UNDEF, just return the first operand. This is
5572 // coherent the DAG creation, no setcc node is created in this case
5574 } else if (SCC.getOpcode() == ISD::SETCC) {
5575 // Fold to a simpler select_cc
5576 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5577 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5582 // If we can fold this based on the true/false value, do so.
5583 if (SimplifySelectOps(N, N2, N3))
5584 return SDValue(N, 0); // Don't revisit N.
5586 // fold select_cc into other things, such as min/max/abs
5587 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5590 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5591 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5592 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5596 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5597 /// a build_vector of constants.
5598 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5599 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5600 /// Vector extends are not folded if operations are legal; this is to
5601 /// avoid introducing illegal build_vector dag nodes.
5602 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5603 SelectionDAG &DAG, bool LegalTypes,
5604 bool LegalOperations) {
5605 unsigned Opcode = N->getOpcode();
5606 SDValue N0 = N->getOperand(0);
5607 EVT VT = N->getValueType(0);
5609 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5610 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5611 && "Expected EXTEND dag node in input!");
5613 // fold (sext c1) -> c1
5614 // fold (zext c1) -> c1
5615 // fold (aext c1) -> c1
5616 if (isa<ConstantSDNode>(N0))
5617 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5619 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5620 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5621 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5622 EVT SVT = VT.getScalarType();
5623 if (!(VT.isVector() &&
5624 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5625 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5628 // We can fold this node into a build_vector.
5629 unsigned VTBits = SVT.getSizeInBits();
5630 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5631 SmallVector<SDValue, 8> Elts;
5632 unsigned NumElts = VT.getVectorNumElements();
5635 for (unsigned i=0; i != NumElts; ++i) {
5636 SDValue Op = N0->getOperand(i);
5637 if (Op->getOpcode() == ISD::UNDEF) {
5638 Elts.push_back(DAG.getUNDEF(SVT));
5643 // Get the constant value and if needed trunc it to the size of the type.
5644 // Nodes like build_vector might have constants wider than the scalar type.
5645 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5646 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5647 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5649 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5652 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5655 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5656 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5657 // transformation. Returns true if extension are possible and the above
5658 // mentioned transformation is profitable.
5659 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5661 SmallVectorImpl<SDNode *> &ExtendNodes,
5662 const TargetLowering &TLI) {
5663 bool HasCopyToRegUses = false;
5664 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5665 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5666 UE = N0.getNode()->use_end();
5671 if (UI.getUse().getResNo() != N0.getResNo())
5673 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5674 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5675 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5676 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5677 // Sign bits will be lost after a zext.
5680 for (unsigned i = 0; i != 2; ++i) {
5681 SDValue UseOp = User->getOperand(i);
5684 if (!isa<ConstantSDNode>(UseOp))
5689 ExtendNodes.push_back(User);
5692 // If truncates aren't free and there are users we can't
5693 // extend, it isn't worthwhile.
5696 // Remember if this value is live-out.
5697 if (User->getOpcode() == ISD::CopyToReg)
5698 HasCopyToRegUses = true;
5701 if (HasCopyToRegUses) {
5702 bool BothLiveOut = false;
5703 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5705 SDUse &Use = UI.getUse();
5706 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5712 // Both unextended and extended values are live out. There had better be
5713 // a good reason for the transformation.
5714 return ExtendNodes.size();
5719 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5720 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5721 ISD::NodeType ExtType) {
5722 // Extend SetCC uses if necessary.
5723 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5724 SDNode *SetCC = SetCCs[i];
5725 SmallVector<SDValue, 4> Ops;
5727 for (unsigned j = 0; j != 2; ++j) {
5728 SDValue SOp = SetCC->getOperand(j);
5730 Ops.push_back(ExtLoad);
5732 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5735 Ops.push_back(SetCC->getOperand(2));
5736 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5740 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5741 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5742 SDValue N0 = N->getOperand(0);
5743 EVT DstVT = N->getValueType(0);
5744 EVT SrcVT = N0.getValueType();
5746 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5747 N->getOpcode() == ISD::ZERO_EXTEND) &&
5748 "Unexpected node type (not an extend)!");
5750 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5751 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5752 // (v8i32 (sext (v8i16 (load x))))
5754 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5755 // (v4i32 (sextload (x + 16)))))
5756 // Where uses of the original load, i.e.:
5758 // are replaced with:
5760 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5761 // (v4i32 (sextload (x + 16)))))))
5763 // This combine is only applicable to illegal, but splittable, vectors.
5764 // All legal types, and illegal non-vector types, are handled elsewhere.
5765 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5767 if (N0->getOpcode() != ISD::LOAD)
5770 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5772 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5773 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5774 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5777 SmallVector<SDNode *, 4> SetCCs;
5778 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5781 ISD::LoadExtType ExtType =
5782 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5784 // Try to split the vector types to get down to legal types.
5785 EVT SplitSrcVT = SrcVT;
5786 EVT SplitDstVT = DstVT;
5787 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5788 SplitSrcVT.getVectorNumElements() > 1) {
5789 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5790 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5793 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5797 const unsigned NumSplits =
5798 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5799 const unsigned Stride = SplitSrcVT.getStoreSize();
5800 SmallVector<SDValue, 4> Loads;
5801 SmallVector<SDValue, 4> Chains;
5803 SDValue BasePtr = LN0->getBasePtr();
5804 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5805 const unsigned Offset = Idx * Stride;
5806 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5808 SDValue SplitLoad = DAG.getExtLoad(
5809 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5810 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5811 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5812 Align, LN0->getAAInfo());
5814 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5815 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5817 Loads.push_back(SplitLoad.getValue(0));
5818 Chains.push_back(SplitLoad.getValue(1));
5821 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5822 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5824 CombineTo(N, NewValue);
5826 // Replace uses of the original load (before extension)
5827 // with a truncate of the concatenated sextloaded vectors.
5829 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5830 CombineTo(N0.getNode(), Trunc, NewChain);
5831 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5832 (ISD::NodeType)N->getOpcode());
5833 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5836 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5837 SDValue N0 = N->getOperand(0);
5838 EVT VT = N->getValueType(0);
5840 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5842 return SDValue(Res, 0);
5844 // fold (sext (sext x)) -> (sext x)
5845 // fold (sext (aext x)) -> (sext x)
5846 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5847 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5850 if (N0.getOpcode() == ISD::TRUNCATE) {
5851 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5852 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5853 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5854 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5855 if (NarrowLoad.getNode() != N0.getNode()) {
5856 CombineTo(N0.getNode(), NarrowLoad);
5857 // CombineTo deleted the truncate, if needed, but not what's under it.
5860 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5863 // See if the value being truncated is already sign extended. If so, just
5864 // eliminate the trunc/sext pair.
5865 SDValue Op = N0.getOperand(0);
5866 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5867 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5868 unsigned DestBits = VT.getScalarType().getSizeInBits();
5869 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5871 if (OpBits == DestBits) {
5872 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5873 // bits, it is already ready.
5874 if (NumSignBits > DestBits-MidBits)
5876 } else if (OpBits < DestBits) {
5877 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5878 // bits, just sext from i32.
5879 if (NumSignBits > OpBits-MidBits)
5880 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5882 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5883 // bits, just truncate to i32.
5884 if (NumSignBits > OpBits-MidBits)
5885 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5888 // fold (sext (truncate x)) -> (sextinreg x).
5889 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5890 N0.getValueType())) {
5891 if (OpBits < DestBits)
5892 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5893 else if (OpBits > DestBits)
5894 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5895 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5896 DAG.getValueType(N0.getValueType()));
5900 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5901 // Only generate vector extloads when 1) they're legal, and 2) they are
5902 // deemed desirable by the target.
5903 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5904 ((!LegalOperations && !VT.isVector() &&
5905 !cast<LoadSDNode>(N0)->isVolatile()) ||
5906 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5907 bool DoXform = true;
5908 SmallVector<SDNode*, 4> SetCCs;
5909 if (!N0.hasOneUse())
5910 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5912 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5914 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5915 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5917 LN0->getBasePtr(), N0.getValueType(),
5918 LN0->getMemOperand());
5919 CombineTo(N, ExtLoad);
5920 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5921 N0.getValueType(), ExtLoad);
5922 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5923 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5925 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5929 // fold (sext (load x)) to multiple smaller sextloads.
5930 // Only on illegal but splittable vectors.
5931 if (SDValue ExtLoad = CombineExtLoad(N))
5934 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5935 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5936 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5937 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5938 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5939 EVT MemVT = LN0->getMemoryVT();
5940 if ((!LegalOperations && !LN0->isVolatile()) ||
5941 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5942 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5944 LN0->getBasePtr(), MemVT,
5945 LN0->getMemOperand());
5946 CombineTo(N, ExtLoad);
5947 CombineTo(N0.getNode(),
5948 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5949 N0.getValueType(), ExtLoad),
5950 ExtLoad.getValue(1));
5951 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5955 // fold (sext (and/or/xor (load x), cst)) ->
5956 // (and/or/xor (sextload x), (sext cst))
5957 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5958 N0.getOpcode() == ISD::XOR) &&
5959 isa<LoadSDNode>(N0.getOperand(0)) &&
5960 N0.getOperand(1).getOpcode() == ISD::Constant &&
5961 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5962 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5963 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5964 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5965 bool DoXform = true;
5966 SmallVector<SDNode*, 4> SetCCs;
5967 if (!N0.hasOneUse())
5968 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5971 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5972 LN0->getChain(), LN0->getBasePtr(),
5974 LN0->getMemOperand());
5975 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5976 Mask = Mask.sext(VT.getSizeInBits());
5978 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5979 ExtLoad, DAG.getConstant(Mask, DL, VT));
5980 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5981 SDLoc(N0.getOperand(0)),
5982 N0.getOperand(0).getValueType(), ExtLoad);
5984 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5985 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5987 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5992 if (N0.getOpcode() == ISD::SETCC) {
5993 EVT N0VT = N0.getOperand(0).getValueType();
5994 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5995 // Only do this before legalize for now.
5996 if (VT.isVector() && !LegalOperations &&
5997 TLI.getBooleanContents(N0VT) ==
5998 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5999 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6000 // of the same size as the compared operands. Only optimize sext(setcc())
6001 // if this is the case.
6002 EVT SVT = getSetCCResultType(N0VT);
6004 // We know that the # elements of the results is the same as the
6005 // # elements of the compare (and the # elements of the compare result
6006 // for that matter). Check to see that they are the same size. If so,
6007 // we know that the element size of the sext'd result matches the
6008 // element size of the compare operands.
6009 if (VT.getSizeInBits() == SVT.getSizeInBits())
6010 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6012 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6014 // If the desired elements are smaller or larger than the source
6015 // elements we can use a matching integer vector type and then
6016 // truncate/sign extend
6017 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6018 if (SVT == MatchingVectorType) {
6019 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6020 N0.getOperand(0), N0.getOperand(1),
6021 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6022 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6026 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6027 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6030 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6032 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6033 NegOne, DAG.getConstant(0, DL, VT),
6034 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6035 if (SCC.getNode()) return SCC;
6037 if (!VT.isVector()) {
6038 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6039 if (!LegalOperations ||
6040 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6042 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6043 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6044 N0.getOperand(0), N0.getOperand(1), CC);
6045 return DAG.getSelect(DL, VT, SetCC,
6046 NegOne, DAG.getConstant(0, DL, VT));
6051 // fold (sext x) -> (zext x) if the sign bit is known zero.
6052 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6053 DAG.SignBitIsZero(N0))
6054 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6059 // isTruncateOf - If N is a truncate of some other value, return true, record
6060 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6061 // This function computes KnownZero to avoid a duplicated call to
6062 // computeKnownBits in the caller.
6063 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6066 if (N->getOpcode() == ISD::TRUNCATE) {
6067 Op = N->getOperand(0);
6068 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6072 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6073 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6076 SDValue Op0 = N->getOperand(0);
6077 SDValue Op1 = N->getOperand(1);
6078 assert(Op0.getValueType() == Op1.getValueType());
6080 if (isNullConstant(Op0))
6082 else if (isNullConstant(Op1))
6087 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6089 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6095 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6096 SDValue N0 = N->getOperand(0);
6097 EVT VT = N->getValueType(0);
6099 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6101 return SDValue(Res, 0);
6103 // fold (zext (zext x)) -> (zext x)
6104 // fold (zext (aext x)) -> (zext x)
6105 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6106 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6109 // fold (zext (truncate x)) -> (zext x) or
6110 // (zext (truncate x)) -> (truncate x)
6111 // This is valid when the truncated bits of x are already zero.
6112 // FIXME: We should extend this to work for vectors too.
6115 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6116 APInt TruncatedBits =
6117 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6118 APInt(Op.getValueSizeInBits(), 0) :
6119 APInt::getBitsSet(Op.getValueSizeInBits(),
6120 N0.getValueSizeInBits(),
6121 std::min(Op.getValueSizeInBits(),
6122 VT.getSizeInBits()));
6123 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6124 if (VT.bitsGT(Op.getValueType()))
6125 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6126 if (VT.bitsLT(Op.getValueType()))
6127 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6133 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6134 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6135 if (N0.getOpcode() == ISD::TRUNCATE) {
6136 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6137 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6138 if (NarrowLoad.getNode() != N0.getNode()) {
6139 CombineTo(N0.getNode(), NarrowLoad);
6140 // CombineTo deleted the truncate, if needed, but not what's under it.
6143 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6147 // fold (zext (truncate x)) -> (and x, mask)
6148 if (N0.getOpcode() == ISD::TRUNCATE) {
6149 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6150 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6151 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6152 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6153 if (NarrowLoad.getNode() != N0.getNode()) {
6154 CombineTo(N0.getNode(), NarrowLoad);
6155 // CombineTo deleted the truncate, if needed, but not what's under it.
6158 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6161 EVT SrcVT = N0.getOperand(0).getValueType();
6162 EVT MinVT = N0.getValueType();
6164 // Try to mask before the extension to avoid having to generate a larger mask,
6165 // possibly over several sub-vectors.
6166 if (SrcVT.bitsLT(VT)) {
6167 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6168 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6169 SDValue Op = N0.getOperand(0);
6170 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6171 AddToWorklist(Op.getNode());
6172 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6176 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6177 SDValue Op = N0.getOperand(0);
6178 if (SrcVT.bitsLT(VT)) {
6179 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6180 AddToWorklist(Op.getNode());
6181 } else if (SrcVT.bitsGT(VT)) {
6182 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6183 AddToWorklist(Op.getNode());
6185 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6189 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6190 // if either of the casts is not free.
6191 if (N0.getOpcode() == ISD::AND &&
6192 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6193 N0.getOperand(1).getOpcode() == ISD::Constant &&
6194 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6195 N0.getValueType()) ||
6196 !TLI.isZExtFree(N0.getValueType(), VT))) {
6197 SDValue X = N0.getOperand(0).getOperand(0);
6198 if (X.getValueType().bitsLT(VT)) {
6199 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6200 } else if (X.getValueType().bitsGT(VT)) {
6201 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6203 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6204 Mask = Mask.zext(VT.getSizeInBits());
6206 return DAG.getNode(ISD::AND, DL, VT,
6207 X, DAG.getConstant(Mask, DL, VT));
6210 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6211 // Only generate vector extloads when 1) they're legal, and 2) they are
6212 // deemed desirable by the target.
6213 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6214 ((!LegalOperations && !VT.isVector() &&
6215 !cast<LoadSDNode>(N0)->isVolatile()) ||
6216 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6217 bool DoXform = true;
6218 SmallVector<SDNode*, 4> SetCCs;
6219 if (!N0.hasOneUse())
6220 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6222 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6224 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6225 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6227 LN0->getBasePtr(), N0.getValueType(),
6228 LN0->getMemOperand());
6229 CombineTo(N, ExtLoad);
6230 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6231 N0.getValueType(), ExtLoad);
6232 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6234 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6236 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6240 // fold (zext (load x)) to multiple smaller zextloads.
6241 // Only on illegal but splittable vectors.
6242 if (SDValue ExtLoad = CombineExtLoad(N))
6245 // fold (zext (and/or/xor (load x), cst)) ->
6246 // (and/or/xor (zextload x), (zext cst))
6247 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6248 N0.getOpcode() == ISD::XOR) &&
6249 isa<LoadSDNode>(N0.getOperand(0)) &&
6250 N0.getOperand(1).getOpcode() == ISD::Constant &&
6251 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6252 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6253 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6254 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6255 bool DoXform = true;
6256 SmallVector<SDNode*, 4> SetCCs;
6257 if (!N0.hasOneUse())
6258 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6261 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6262 LN0->getChain(), LN0->getBasePtr(),
6264 LN0->getMemOperand());
6265 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6266 Mask = Mask.zext(VT.getSizeInBits());
6268 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6269 ExtLoad, DAG.getConstant(Mask, DL, VT));
6270 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6271 SDLoc(N0.getOperand(0)),
6272 N0.getOperand(0).getValueType(), ExtLoad);
6274 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6275 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6277 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6282 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6283 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6284 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6285 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6286 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6287 EVT MemVT = LN0->getMemoryVT();
6288 if ((!LegalOperations && !LN0->isVolatile()) ||
6289 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6290 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6292 LN0->getBasePtr(), MemVT,
6293 LN0->getMemOperand());
6294 CombineTo(N, ExtLoad);
6295 CombineTo(N0.getNode(),
6296 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6298 ExtLoad.getValue(1));
6299 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6303 if (N0.getOpcode() == ISD::SETCC) {
6304 if (!LegalOperations && VT.isVector() &&
6305 N0.getValueType().getVectorElementType() == MVT::i1) {
6306 EVT N0VT = N0.getOperand(0).getValueType();
6307 if (getSetCCResultType(N0VT) == N0.getValueType())
6310 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6311 // Only do this before legalize for now.
6312 EVT EltVT = VT.getVectorElementType();
6314 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6315 DAG.getConstant(1, DL, EltVT));
6316 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6317 // We know that the # elements of the results is the same as the
6318 // # elements of the compare (and the # elements of the compare result
6319 // for that matter). Check to see that they are the same size. If so,
6320 // we know that the element size of the sext'd result matches the
6321 // element size of the compare operands.
6322 return DAG.getNode(ISD::AND, DL, VT,
6323 DAG.getSetCC(DL, VT, N0.getOperand(0),
6325 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6326 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6329 // If the desired elements are smaller or larger than the source
6330 // elements we can use a matching integer vector type and then
6331 // truncate/sign extend
6332 EVT MatchingElementType =
6333 EVT::getIntegerVT(*DAG.getContext(),
6334 N0VT.getScalarType().getSizeInBits());
6335 EVT MatchingVectorType =
6336 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6337 N0VT.getVectorNumElements());
6339 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6341 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6342 return DAG.getNode(ISD::AND, DL, VT,
6343 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6344 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6347 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6350 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6351 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6352 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6353 if (SCC.getNode()) return SCC;
6356 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6357 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6358 isa<ConstantSDNode>(N0.getOperand(1)) &&
6359 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6361 SDValue ShAmt = N0.getOperand(1);
6362 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6363 if (N0.getOpcode() == ISD::SHL) {
6364 SDValue InnerZExt = N0.getOperand(0);
6365 // If the original shl may be shifting out bits, do not perform this
6367 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6368 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6369 if (ShAmtVal > KnownZeroBits)
6375 // Ensure that the shift amount is wide enough for the shifted value.
6376 if (VT.getSizeInBits() >= 256)
6377 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6379 return DAG.getNode(N0.getOpcode(), DL, VT,
6380 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6387 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6388 SDValue N0 = N->getOperand(0);
6389 EVT VT = N->getValueType(0);
6391 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6393 return SDValue(Res, 0);
6395 // fold (aext (aext x)) -> (aext x)
6396 // fold (aext (zext x)) -> (zext x)
6397 // fold (aext (sext x)) -> (sext x)
6398 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6399 N0.getOpcode() == ISD::ZERO_EXTEND ||
6400 N0.getOpcode() == ISD::SIGN_EXTEND)
6401 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6403 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6404 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6405 if (N0.getOpcode() == ISD::TRUNCATE) {
6406 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6407 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6408 if (NarrowLoad.getNode() != N0.getNode()) {
6409 CombineTo(N0.getNode(), NarrowLoad);
6410 // CombineTo deleted the truncate, if needed, but not what's under it.
6413 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6417 // fold (aext (truncate x))
6418 if (N0.getOpcode() == ISD::TRUNCATE) {
6419 SDValue TruncOp = N0.getOperand(0);
6420 if (TruncOp.getValueType() == VT)
6421 return TruncOp; // x iff x size == zext size.
6422 if (TruncOp.getValueType().bitsGT(VT))
6423 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6424 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6427 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6428 // if the trunc is not free.
6429 if (N0.getOpcode() == ISD::AND &&
6430 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6431 N0.getOperand(1).getOpcode() == ISD::Constant &&
6432 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6433 N0.getValueType())) {
6434 SDValue X = N0.getOperand(0).getOperand(0);
6435 if (X.getValueType().bitsLT(VT)) {
6436 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6437 } else if (X.getValueType().bitsGT(VT)) {
6438 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6440 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6441 Mask = Mask.zext(VT.getSizeInBits());
6443 return DAG.getNode(ISD::AND, DL, VT,
6444 X, DAG.getConstant(Mask, DL, VT));
6447 // fold (aext (load x)) -> (aext (truncate (extload x)))
6448 // None of the supported targets knows how to perform load and any_ext
6449 // on vectors in one instruction. We only perform this transformation on
6451 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6452 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6453 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6454 bool DoXform = true;
6455 SmallVector<SDNode*, 4> SetCCs;
6456 if (!N0.hasOneUse())
6457 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6459 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6460 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6462 LN0->getBasePtr(), N0.getValueType(),
6463 LN0->getMemOperand());
6464 CombineTo(N, ExtLoad);
6465 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6466 N0.getValueType(), ExtLoad);
6467 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6468 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6470 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6474 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6475 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6476 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6477 if (N0.getOpcode() == ISD::LOAD &&
6478 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6480 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6481 ISD::LoadExtType ExtType = LN0->getExtensionType();
6482 EVT MemVT = LN0->getMemoryVT();
6483 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6484 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6485 VT, LN0->getChain(), LN0->getBasePtr(),
6486 MemVT, LN0->getMemOperand());
6487 CombineTo(N, ExtLoad);
6488 CombineTo(N0.getNode(),
6489 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6490 N0.getValueType(), ExtLoad),
6491 ExtLoad.getValue(1));
6492 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6496 if (N0.getOpcode() == ISD::SETCC) {
6498 // aext(setcc) -> vsetcc
6499 // aext(setcc) -> truncate(vsetcc)
6500 // aext(setcc) -> aext(vsetcc)
6501 // Only do this before legalize for now.
6502 if (VT.isVector() && !LegalOperations) {
6503 EVT N0VT = N0.getOperand(0).getValueType();
6504 // We know that the # elements of the results is the same as the
6505 // # elements of the compare (and the # elements of the compare result
6506 // for that matter). Check to see that they are the same size. If so,
6507 // we know that the element size of the sext'd result matches the
6508 // element size of the compare operands.
6509 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6510 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6512 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6513 // If the desired elements are smaller or larger than the source
6514 // elements we can use a matching integer vector type and then
6515 // truncate/any extend
6517 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6519 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6521 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6522 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6526 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6529 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6530 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6531 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6539 /// See if the specified operand can be simplified with the knowledge that only
6540 /// the bits specified by Mask are used. If so, return the simpler operand,
6541 /// otherwise return a null SDValue.
6542 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6543 switch (V.getOpcode()) {
6545 case ISD::Constant: {
6546 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6547 assert(CV && "Const value should be ConstSDNode.");
6548 const APInt &CVal = CV->getAPIntValue();
6549 APInt NewVal = CVal & Mask;
6551 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6556 // If the LHS or RHS don't contribute bits to the or, drop them.
6557 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6558 return V.getOperand(1);
6559 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6560 return V.getOperand(0);
6563 // Only look at single-use SRLs.
6564 if (!V.getNode()->hasOneUse())
6566 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6567 // See if we can recursively simplify the LHS.
6568 unsigned Amt = RHSC->getZExtValue();
6570 // Watch out for shift count overflow though.
6571 if (Amt >= Mask.getBitWidth()) break;
6572 APInt NewMask = Mask << Amt;
6573 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6574 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6575 SimplifyLHS, V.getOperand(1));
6581 /// If the result of a wider load is shifted to right of N bits and then
6582 /// truncated to a narrower type and where N is a multiple of number of bits of
6583 /// the narrower type, transform it to a narrower load from address + N / num of
6584 /// bits of new type. If the result is to be extended, also fold the extension
6585 /// to form a extending load.
6586 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6587 unsigned Opc = N->getOpcode();
6589 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6590 SDValue N0 = N->getOperand(0);
6591 EVT VT = N->getValueType(0);
6594 // This transformation isn't valid for vector loads.
6598 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6600 if (Opc == ISD::SIGN_EXTEND_INREG) {
6601 ExtType = ISD::SEXTLOAD;
6602 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6603 } else if (Opc == ISD::SRL) {
6604 // Another special-case: SRL is basically zero-extending a narrower value.
6605 ExtType = ISD::ZEXTLOAD;
6607 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6608 if (!N01) return SDValue();
6609 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6610 VT.getSizeInBits() - N01->getZExtValue());
6612 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6615 unsigned EVTBits = ExtVT.getSizeInBits();
6617 // Do not generate loads of non-round integer types since these can
6618 // be expensive (and would be wrong if the type is not byte sized).
6619 if (!ExtVT.isRound())
6623 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6624 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6625 ShAmt = N01->getZExtValue();
6626 // Is the shift amount a multiple of size of VT?
6627 if ((ShAmt & (EVTBits-1)) == 0) {
6628 N0 = N0.getOperand(0);
6629 // Is the load width a multiple of size of VT?
6630 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6634 // At this point, we must have a load or else we can't do the transform.
6635 if (!isa<LoadSDNode>(N0)) return SDValue();
6637 // Because a SRL must be assumed to *need* to zero-extend the high bits
6638 // (as opposed to anyext the high bits), we can't combine the zextload
6639 // lowering of SRL and an sextload.
6640 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6643 // If the shift amount is larger than the input type then we're not
6644 // accessing any of the loaded bytes. If the load was a zextload/extload
6645 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6646 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6651 // If the load is shifted left (and the result isn't shifted back right),
6652 // we can fold the truncate through the shift.
6653 unsigned ShLeftAmt = 0;
6654 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6655 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6656 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6657 ShLeftAmt = N01->getZExtValue();
6658 N0 = N0.getOperand(0);
6662 // If we haven't found a load, we can't narrow it. Don't transform one with
6663 // multiple uses, this would require adding a new load.
6664 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6667 // Don't change the width of a volatile load.
6668 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6669 if (LN0->isVolatile())
6672 // Verify that we are actually reducing a load width here.
6673 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6676 // For the transform to be legal, the load must produce only two values
6677 // (the value loaded and the chain). Don't transform a pre-increment
6678 // load, for example, which produces an extra value. Otherwise the
6679 // transformation is not equivalent, and the downstream logic to replace
6680 // uses gets things wrong.
6681 if (LN0->getNumValues() > 2)
6684 // If the load that we're shrinking is an extload and we're not just
6685 // discarding the extension we can't simply shrink the load. Bail.
6686 // TODO: It would be possible to merge the extensions in some cases.
6687 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6688 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6691 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6694 EVT PtrType = N0.getOperand(1).getValueType();
6696 if (PtrType == MVT::Untyped || PtrType.isExtended())
6697 // It's not possible to generate a constant of extended or untyped type.
6700 // For big endian targets, we need to adjust the offset to the pointer to
6701 // load the correct bytes.
6702 if (DAG.getDataLayout().isBigEndian()) {
6703 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6704 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6705 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6708 uint64_t PtrOff = ShAmt / 8;
6709 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6711 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6712 PtrType, LN0->getBasePtr(),
6713 DAG.getConstant(PtrOff, DL, PtrType));
6714 AddToWorklist(NewPtr.getNode());
6717 if (ExtType == ISD::NON_EXTLOAD)
6718 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6719 LN0->getPointerInfo().getWithOffset(PtrOff),
6720 LN0->isVolatile(), LN0->isNonTemporal(),
6721 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6723 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6724 LN0->getPointerInfo().getWithOffset(PtrOff),
6725 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6726 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6728 // Replace the old load's chain with the new load's chain.
6729 WorklistRemover DeadNodes(*this);
6730 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6732 // Shift the result left, if we've swallowed a left shift.
6733 SDValue Result = Load;
6734 if (ShLeftAmt != 0) {
6735 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6736 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6738 // If the shift amount is as large as the result size (but, presumably,
6739 // no larger than the source) then the useful bits of the result are
6740 // zero; we can't simply return the shortened shift, because the result
6741 // of that operation is undefined.
6743 if (ShLeftAmt >= VT.getSizeInBits())
6744 Result = DAG.getConstant(0, DL, VT);
6746 Result = DAG.getNode(ISD::SHL, DL, VT,
6747 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6750 // Return the new loaded value.
6754 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6755 SDValue N0 = N->getOperand(0);
6756 SDValue N1 = N->getOperand(1);
6757 EVT VT = N->getValueType(0);
6758 EVT EVT = cast<VTSDNode>(N1)->getVT();
6759 unsigned VTBits = VT.getScalarType().getSizeInBits();
6760 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6763 return DAG.getUNDEF(VT);
6765 // fold (sext_in_reg c1) -> c1
6766 if (isConstantIntBuildVectorOrConstantInt(N0))
6767 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6769 // If the input is already sign extended, just drop the extension.
6770 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6773 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6774 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6775 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6776 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6777 N0.getOperand(0), N1);
6779 // fold (sext_in_reg (sext x)) -> (sext x)
6780 // fold (sext_in_reg (aext x)) -> (sext x)
6781 // if x is small enough.
6782 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6783 SDValue N00 = N0.getOperand(0);
6784 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6785 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6786 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6789 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6790 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6791 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6793 // fold operands of sext_in_reg based on knowledge that the top bits are not
6795 if (SimplifyDemandedBits(SDValue(N, 0)))
6796 return SDValue(N, 0);
6798 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6799 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6800 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6803 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6804 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6805 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6806 if (N0.getOpcode() == ISD::SRL) {
6807 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6808 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6809 // We can turn this into an SRA iff the input to the SRL is already sign
6811 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6812 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6813 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6814 N0.getOperand(0), N0.getOperand(1));
6818 // fold (sext_inreg (extload x)) -> (sextload x)
6819 if (ISD::isEXTLoad(N0.getNode()) &&
6820 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6821 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6822 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6823 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6824 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6825 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6827 LN0->getBasePtr(), EVT,
6828 LN0->getMemOperand());
6829 CombineTo(N, ExtLoad);
6830 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6831 AddToWorklist(ExtLoad.getNode());
6832 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6834 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6835 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6837 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6838 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6839 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6840 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6841 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6843 LN0->getBasePtr(), EVT,
6844 LN0->getMemOperand());
6845 CombineTo(N, ExtLoad);
6846 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6847 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6850 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6851 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6852 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6853 N0.getOperand(1), false);
6854 if (BSwap.getNode())
6855 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6862 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6863 SDValue N0 = N->getOperand(0);
6864 EVT VT = N->getValueType(0);
6866 if (N0.getOpcode() == ISD::UNDEF)
6867 return DAG.getUNDEF(VT);
6869 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6871 return SDValue(Res, 0);
6876 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6877 SDValue N0 = N->getOperand(0);
6878 EVT VT = N->getValueType(0);
6879 bool isLE = DAG.getDataLayout().isLittleEndian();
6882 if (N0.getValueType() == N->getValueType(0))
6884 // fold (truncate c1) -> c1
6885 if (isConstantIntBuildVectorOrConstantInt(N0))
6886 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6887 // fold (truncate (truncate x)) -> (truncate x)
6888 if (N0.getOpcode() == ISD::TRUNCATE)
6889 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6890 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6891 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6892 N0.getOpcode() == ISD::SIGN_EXTEND ||
6893 N0.getOpcode() == ISD::ANY_EXTEND) {
6894 if (N0.getOperand(0).getValueType().bitsLT(VT))
6895 // if the source is smaller than the dest, we still need an extend
6896 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6898 if (N0.getOperand(0).getValueType().bitsGT(VT))
6899 // if the source is larger than the dest, than we just need the truncate
6900 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6901 // if the source and dest are the same type, we can drop both the extend
6902 // and the truncate.
6903 return N0.getOperand(0);
6906 // Fold extract-and-trunc into a narrow extract. For example:
6907 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6908 // i32 y = TRUNCATE(i64 x)
6910 // v16i8 b = BITCAST (v2i64 val)
6911 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6913 // Note: We only run this optimization after type legalization (which often
6914 // creates this pattern) and before operation legalization after which
6915 // we need to be more careful about the vector instructions that we generate.
6916 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6917 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6919 EVT VecTy = N0.getOperand(0).getValueType();
6920 EVT ExTy = N0.getValueType();
6921 EVT TrTy = N->getValueType(0);
6923 unsigned NumElem = VecTy.getVectorNumElements();
6924 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6926 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6927 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6929 SDValue EltNo = N0->getOperand(1);
6930 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6931 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6932 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6933 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6935 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6936 NVT, N0.getOperand(0));
6939 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6941 DAG.getConstant(Index, DL, IndexTy));
6945 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6946 if (N0.getOpcode() == ISD::SELECT) {
6947 EVT SrcVT = N0.getValueType();
6948 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6949 TLI.isTruncateFree(SrcVT, VT)) {
6951 SDValue Cond = N0.getOperand(0);
6952 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6953 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6954 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6958 // Fold a series of buildvector, bitcast, and truncate if possible.
6960 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6961 // (2xi32 (buildvector x, y)).
6962 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6963 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6964 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6965 N0.getOperand(0).hasOneUse()) {
6967 SDValue BuildVect = N0.getOperand(0);
6968 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6969 EVT TruncVecEltTy = VT.getVectorElementType();
6971 // Check that the element types match.
6972 if (BuildVectEltTy == TruncVecEltTy) {
6973 // Now we only need to compute the offset of the truncated elements.
6974 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6975 unsigned TruncVecNumElts = VT.getVectorNumElements();
6976 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6978 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6979 "Invalid number of elements");
6981 SmallVector<SDValue, 8> Opnds;
6982 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6983 Opnds.push_back(BuildVect.getOperand(i));
6985 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6989 // See if we can simplify the input to this truncate through knowledge that
6990 // only the low bits are being used.
6991 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6992 // Currently we only perform this optimization on scalars because vectors
6993 // may have different active low bits.
6994 if (!VT.isVector()) {
6996 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6997 VT.getSizeInBits()));
6998 if (Shorter.getNode())
6999 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7001 // fold (truncate (load x)) -> (smaller load x)
7002 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7003 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7004 if (SDValue Reduced = ReduceLoadWidth(N))
7007 // Handle the case where the load remains an extending load even
7008 // after truncation.
7009 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7010 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7011 if (!LN0->isVolatile() &&
7012 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7013 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7014 VT, LN0->getChain(), LN0->getBasePtr(),
7016 LN0->getMemOperand());
7017 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7022 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7023 // where ... are all 'undef'.
7024 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7025 SmallVector<EVT, 8> VTs;
7028 unsigned NumDefs = 0;
7030 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7031 SDValue X = N0.getOperand(i);
7032 if (X.getOpcode() != ISD::UNDEF) {
7037 // Stop if more than one members are non-undef.
7040 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7041 VT.getVectorElementType(),
7042 X.getValueType().getVectorNumElements()));
7046 return DAG.getUNDEF(VT);
7049 assert(V.getNode() && "The single defined operand is empty!");
7050 SmallVector<SDValue, 8> Opnds;
7051 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7053 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7056 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7057 AddToWorklist(NV.getNode());
7058 Opnds.push_back(NV);
7060 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7064 // Simplify the operands using demanded-bits information.
7065 if (!VT.isVector() &&
7066 SimplifyDemandedBits(SDValue(N, 0)))
7067 return SDValue(N, 0);
7072 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7073 SDValue Elt = N->getOperand(i);
7074 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7075 return Elt.getNode();
7076 return Elt.getOperand(Elt.getResNo()).getNode();
7079 /// build_pair (load, load) -> load
7080 /// if load locations are consecutive.
7081 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7082 assert(N->getOpcode() == ISD::BUILD_PAIR);
7084 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7085 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7086 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7087 LD1->getAddressSpace() != LD2->getAddressSpace())
7089 EVT LD1VT = LD1->getValueType(0);
7091 if (ISD::isNON_EXTLoad(LD2) &&
7093 // If both are volatile this would reduce the number of volatile loads.
7094 // If one is volatile it might be ok, but play conservative and bail out.
7095 !LD1->isVolatile() &&
7096 !LD2->isVolatile() &&
7097 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7098 unsigned Align = LD1->getAlignment();
7099 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7100 VT.getTypeForEVT(*DAG.getContext()));
7102 if (NewAlign <= Align &&
7103 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7104 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7105 LD1->getBasePtr(), LD1->getPointerInfo(),
7106 false, false, false, Align);
7112 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7113 SDValue N0 = N->getOperand(0);
7114 EVT VT = N->getValueType(0);
7116 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7117 // Only do this before legalize, since afterward the target may be depending
7118 // on the bitconvert.
7119 // First check to see if this is all constant.
7121 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7123 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7125 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7126 assert(!DestEltVT.isVector() &&
7127 "Element type of vector ValueType must not be vector!");
7129 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7132 // If the input is a constant, let getNode fold it.
7133 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7134 // If we can't allow illegal operations, we need to check that this is just
7135 // a fp -> int or int -> conversion and that the resulting operation will
7137 if (!LegalOperations ||
7138 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7139 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7140 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7141 TLI.isOperationLegal(ISD::Constant, VT)))
7142 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7145 // (conv (conv x, t1), t2) -> (conv x, t2)
7146 if (N0.getOpcode() == ISD::BITCAST)
7147 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7150 // fold (conv (load x)) -> (load (conv*)x)
7151 // If the resultant load doesn't need a higher alignment than the original!
7152 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7153 // Do not change the width of a volatile load.
7154 !cast<LoadSDNode>(N0)->isVolatile() &&
7155 // Do not remove the cast if the types differ in endian layout.
7156 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7157 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7158 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7159 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7160 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7161 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7162 VT.getTypeForEVT(*DAG.getContext()));
7163 unsigned OrigAlign = LN0->getAlignment();
7165 if (Align <= OrigAlign) {
7166 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7167 LN0->getBasePtr(), LN0->getPointerInfo(),
7168 LN0->isVolatile(), LN0->isNonTemporal(),
7169 LN0->isInvariant(), OrigAlign,
7171 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7176 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7177 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7178 // This often reduces constant pool loads.
7179 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7180 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7181 N0.getNode()->hasOneUse() && VT.isInteger() &&
7182 !VT.isVector() && !N0.getValueType().isVector()) {
7183 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7185 AddToWorklist(NewConv.getNode());
7188 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7189 if (N0.getOpcode() == ISD::FNEG)
7190 return DAG.getNode(ISD::XOR, DL, VT,
7191 NewConv, DAG.getConstant(SignBit, DL, VT));
7192 assert(N0.getOpcode() == ISD::FABS);
7193 return DAG.getNode(ISD::AND, DL, VT,
7194 NewConv, DAG.getConstant(~SignBit, DL, VT));
7197 // fold (bitconvert (fcopysign cst, x)) ->
7198 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7199 // Note that we don't handle (copysign x, cst) because this can always be
7200 // folded to an fneg or fabs.
7201 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7202 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7203 VT.isInteger() && !VT.isVector()) {
7204 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7205 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7206 if (isTypeLegal(IntXVT)) {
7207 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7208 IntXVT, N0.getOperand(1));
7209 AddToWorklist(X.getNode());
7211 // If X has a different width than the result/lhs, sext it or truncate it.
7212 unsigned VTWidth = VT.getSizeInBits();
7213 if (OrigXWidth < VTWidth) {
7214 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7215 AddToWorklist(X.getNode());
7216 } else if (OrigXWidth > VTWidth) {
7217 // To get the sign bit in the right place, we have to shift it right
7218 // before truncating.
7220 X = DAG.getNode(ISD::SRL, DL,
7221 X.getValueType(), X,
7222 DAG.getConstant(OrigXWidth-VTWidth, DL,
7224 AddToWorklist(X.getNode());
7225 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7226 AddToWorklist(X.getNode());
7229 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7230 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7231 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7232 AddToWorklist(X.getNode());
7234 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7235 VT, N0.getOperand(0));
7236 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7237 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7238 AddToWorklist(Cst.getNode());
7240 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7244 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7245 if (N0.getOpcode() == ISD::BUILD_PAIR)
7246 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7249 // Remove double bitcasts from shuffles - this is often a legacy of
7250 // XformToShuffleWithZero being used to combine bitmaskings (of
7251 // float vectors bitcast to integer vectors) into shuffles.
7252 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7253 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7254 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7255 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7256 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7257 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7259 // If operands are a bitcast, peek through if it casts the original VT.
7260 // If operands are a constant, just bitcast back to original VT.
7261 auto PeekThroughBitcast = [&](SDValue Op) {
7262 if (Op.getOpcode() == ISD::BITCAST &&
7263 Op.getOperand(0).getValueType() == VT)
7264 return SDValue(Op.getOperand(0));
7265 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7266 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7267 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7271 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7272 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7277 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7278 SmallVector<int, 8> NewMask;
7279 for (int M : SVN->getMask())
7280 for (int i = 0; i != MaskScale; ++i)
7281 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7283 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7285 std::swap(SV0, SV1);
7286 ShuffleVectorSDNode::commuteMask(NewMask);
7287 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7291 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7297 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7298 EVT VT = N->getValueType(0);
7299 return CombineConsecutiveLoads(N, VT);
7302 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7303 /// operands. DstEltVT indicates the destination element value type.
7304 SDValue DAGCombiner::
7305 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7306 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7308 // If this is already the right type, we're done.
7309 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7311 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7312 unsigned DstBitSize = DstEltVT.getSizeInBits();
7314 // If this is a conversion of N elements of one type to N elements of another
7315 // type, convert each element. This handles FP<->INT cases.
7316 if (SrcBitSize == DstBitSize) {
7317 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7318 BV->getValueType(0).getVectorNumElements());
7320 // Due to the FP element handling below calling this routine recursively,
7321 // we can end up with a scalar-to-vector node here.
7322 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7323 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7324 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7325 DstEltVT, BV->getOperand(0)));
7327 SmallVector<SDValue, 8> Ops;
7328 for (SDValue Op : BV->op_values()) {
7329 // If the vector element type is not legal, the BUILD_VECTOR operands
7330 // are promoted and implicitly truncated. Make that explicit here.
7331 if (Op.getValueType() != SrcEltVT)
7332 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7333 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7335 AddToWorklist(Ops.back().getNode());
7337 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7340 // Otherwise, we're growing or shrinking the elements. To avoid having to
7341 // handle annoying details of growing/shrinking FP values, we convert them to
7343 if (SrcEltVT.isFloatingPoint()) {
7344 // Convert the input float vector to a int vector where the elements are the
7346 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7347 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7351 // Now we know the input is an integer vector. If the output is a FP type,
7352 // convert to integer first, then to FP of the right size.
7353 if (DstEltVT.isFloatingPoint()) {
7354 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7355 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7357 // Next, convert to FP elements of the same size.
7358 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7363 // Okay, we know the src/dst types are both integers of differing types.
7364 // Handling growing first.
7365 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7366 if (SrcBitSize < DstBitSize) {
7367 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7369 SmallVector<SDValue, 8> Ops;
7370 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7371 i += NumInputsPerOutput) {
7372 bool isLE = DAG.getDataLayout().isLittleEndian();
7373 APInt NewBits = APInt(DstBitSize, 0);
7374 bool EltIsUndef = true;
7375 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7376 // Shift the previously computed bits over.
7377 NewBits <<= SrcBitSize;
7378 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7379 if (Op.getOpcode() == ISD::UNDEF) continue;
7382 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7383 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7387 Ops.push_back(DAG.getUNDEF(DstEltVT));
7389 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7392 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7393 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7396 // Finally, this must be the case where we are shrinking elements: each input
7397 // turns into multiple outputs.
7398 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7399 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7400 NumOutputsPerInput*BV->getNumOperands());
7401 SmallVector<SDValue, 8> Ops;
7403 for (const SDValue &Op : BV->op_values()) {
7404 if (Op.getOpcode() == ISD::UNDEF) {
7405 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7409 APInt OpVal = cast<ConstantSDNode>(Op)->
7410 getAPIntValue().zextOrTrunc(SrcBitSize);
7412 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7413 APInt ThisVal = OpVal.trunc(DstBitSize);
7414 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7415 OpVal = OpVal.lshr(DstBitSize);
7418 // For big endian targets, swap the order of the pieces of each element.
7419 if (DAG.getDataLayout().isBigEndian())
7420 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7423 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7426 /// Try to perform FMA combining on a given FADD node.
7427 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7428 SDValue N0 = N->getOperand(0);
7429 SDValue N1 = N->getOperand(1);
7430 EVT VT = N->getValueType(0);
7433 const TargetOptions &Options = DAG.getTarget().Options;
7435 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7437 // Floating-point multiply-add with intermediate rounding.
7438 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7440 // Floating-point multiply-add without intermediate rounding.
7442 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7443 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7445 // No valid opcode, do not combine.
7446 if (!HasFMAD && !HasFMA)
7449 // Always prefer FMAD to FMA for precision.
7450 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7451 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7452 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7454 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7455 // prefer to fold the multiply with fewer uses.
7456 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7457 N1.getOpcode() == ISD::FMUL) {
7458 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7462 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7463 if (N0.getOpcode() == ISD::FMUL &&
7464 (Aggressive || N0->hasOneUse())) {
7465 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7466 N0.getOperand(0), N0.getOperand(1), N1);
7469 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7470 // Note: Commutes FADD operands.
7471 if (N1.getOpcode() == ISD::FMUL &&
7472 (Aggressive || N1->hasOneUse())) {
7473 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7474 N1.getOperand(0), N1.getOperand(1), N0);
7477 // Look through FP_EXTEND nodes to do more combining.
7478 if (AllowFusion && LookThroughFPExt) {
7479 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7480 if (N0.getOpcode() == ISD::FP_EXTEND) {
7481 SDValue N00 = N0.getOperand(0);
7482 if (N00.getOpcode() == ISD::FMUL)
7483 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7484 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7486 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7487 N00.getOperand(1)), N1);
7490 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7491 // Note: Commutes FADD operands.
7492 if (N1.getOpcode() == ISD::FP_EXTEND) {
7493 SDValue N10 = N1.getOperand(0);
7494 if (N10.getOpcode() == ISD::FMUL)
7495 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7496 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7498 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7499 N10.getOperand(1)), N0);
7503 // More folding opportunities when target permits.
7504 if ((AllowFusion || HasFMAD) && Aggressive) {
7505 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7506 if (N0.getOpcode() == PreferredFusedOpcode &&
7507 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7508 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7509 N0.getOperand(0), N0.getOperand(1),
7510 DAG.getNode(PreferredFusedOpcode, SL, VT,
7511 N0.getOperand(2).getOperand(0),
7512 N0.getOperand(2).getOperand(1),
7516 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7517 if (N1->getOpcode() == PreferredFusedOpcode &&
7518 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7519 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7520 N1.getOperand(0), N1.getOperand(1),
7521 DAG.getNode(PreferredFusedOpcode, SL, VT,
7522 N1.getOperand(2).getOperand(0),
7523 N1.getOperand(2).getOperand(1),
7527 if (AllowFusion && LookThroughFPExt) {
7528 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7529 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7530 auto FoldFAddFMAFPExtFMul = [&] (
7531 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7532 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7533 DAG.getNode(PreferredFusedOpcode, SL, VT,
7534 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7535 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7538 if (N0.getOpcode() == PreferredFusedOpcode) {
7539 SDValue N02 = N0.getOperand(2);
7540 if (N02.getOpcode() == ISD::FP_EXTEND) {
7541 SDValue N020 = N02.getOperand(0);
7542 if (N020.getOpcode() == ISD::FMUL)
7543 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7544 N020.getOperand(0), N020.getOperand(1),
7549 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7550 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7551 // FIXME: This turns two single-precision and one double-precision
7552 // operation into two double-precision operations, which might not be
7553 // interesting for all targets, especially GPUs.
7554 auto FoldFAddFPExtFMAFMul = [&] (
7555 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7556 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7557 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7558 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7559 DAG.getNode(PreferredFusedOpcode, SL, VT,
7560 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7561 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7564 if (N0.getOpcode() == ISD::FP_EXTEND) {
7565 SDValue N00 = N0.getOperand(0);
7566 if (N00.getOpcode() == PreferredFusedOpcode) {
7567 SDValue N002 = N00.getOperand(2);
7568 if (N002.getOpcode() == ISD::FMUL)
7569 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7570 N002.getOperand(0), N002.getOperand(1),
7575 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7576 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7577 if (N1.getOpcode() == PreferredFusedOpcode) {
7578 SDValue N12 = N1.getOperand(2);
7579 if (N12.getOpcode() == ISD::FP_EXTEND) {
7580 SDValue N120 = N12.getOperand(0);
7581 if (N120.getOpcode() == ISD::FMUL)
7582 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7583 N120.getOperand(0), N120.getOperand(1),
7588 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7589 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7590 // FIXME: This turns two single-precision and one double-precision
7591 // operation into two double-precision operations, which might not be
7592 // interesting for all targets, especially GPUs.
7593 if (N1.getOpcode() == ISD::FP_EXTEND) {
7594 SDValue N10 = N1.getOperand(0);
7595 if (N10.getOpcode() == PreferredFusedOpcode) {
7596 SDValue N102 = N10.getOperand(2);
7597 if (N102.getOpcode() == ISD::FMUL)
7598 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7599 N102.getOperand(0), N102.getOperand(1),
7609 /// Try to perform FMA combining on a given FSUB node.
7610 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7611 SDValue N0 = N->getOperand(0);
7612 SDValue N1 = N->getOperand(1);
7613 EVT VT = N->getValueType(0);
7616 const TargetOptions &Options = DAG.getTarget().Options;
7618 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7620 // Floating-point multiply-add with intermediate rounding.
7621 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7623 // Floating-point multiply-add without intermediate rounding.
7625 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7626 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7628 // No valid opcode, do not combine.
7629 if (!HasFMAD && !HasFMA)
7632 // Always prefer FMAD to FMA for precision.
7633 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7634 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7635 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7637 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7638 if (N0.getOpcode() == ISD::FMUL &&
7639 (Aggressive || N0->hasOneUse())) {
7640 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7641 N0.getOperand(0), N0.getOperand(1),
7642 DAG.getNode(ISD::FNEG, SL, VT, N1));
7645 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7646 // Note: Commutes FSUB operands.
7647 if (N1.getOpcode() == ISD::FMUL &&
7648 (Aggressive || N1->hasOneUse()))
7649 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7650 DAG.getNode(ISD::FNEG, SL, VT,
7652 N1.getOperand(1), N0);
7654 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7655 if (N0.getOpcode() == ISD::FNEG &&
7656 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7657 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7658 SDValue N00 = N0.getOperand(0).getOperand(0);
7659 SDValue N01 = N0.getOperand(0).getOperand(1);
7660 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7661 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7662 DAG.getNode(ISD::FNEG, SL, VT, N1));
7665 // Look through FP_EXTEND nodes to do more combining.
7666 if (AllowFusion && LookThroughFPExt) {
7667 // fold (fsub (fpext (fmul x, y)), z)
7668 // -> (fma (fpext x), (fpext y), (fneg z))
7669 if (N0.getOpcode() == ISD::FP_EXTEND) {
7670 SDValue N00 = N0.getOperand(0);
7671 if (N00.getOpcode() == ISD::FMUL)
7672 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7673 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7675 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7677 DAG.getNode(ISD::FNEG, SL, VT, N1));
7680 // fold (fsub x, (fpext (fmul y, z)))
7681 // -> (fma (fneg (fpext y)), (fpext z), x)
7682 // Note: Commutes FSUB operands.
7683 if (N1.getOpcode() == ISD::FP_EXTEND) {
7684 SDValue N10 = N1.getOperand(0);
7685 if (N10.getOpcode() == ISD::FMUL)
7686 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7687 DAG.getNode(ISD::FNEG, SL, VT,
7688 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7689 N10.getOperand(0))),
7690 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7695 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7696 // -> (fneg (fma (fpext x), (fpext y), z))
7697 // Note: This could be removed with appropriate canonicalization of the
7698 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7699 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7700 // from implementing the canonicalization in visitFSUB.
7701 if (N0.getOpcode() == ISD::FP_EXTEND) {
7702 SDValue N00 = N0.getOperand(0);
7703 if (N00.getOpcode() == ISD::FNEG) {
7704 SDValue N000 = N00.getOperand(0);
7705 if (N000.getOpcode() == ISD::FMUL) {
7706 return DAG.getNode(ISD::FNEG, SL, VT,
7707 DAG.getNode(PreferredFusedOpcode, SL, VT,
7708 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7709 N000.getOperand(0)),
7710 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7711 N000.getOperand(1)),
7717 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7718 // -> (fneg (fma (fpext x)), (fpext y), z)
7719 // Note: This could be removed with appropriate canonicalization of the
7720 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7721 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7722 // from implementing the canonicalization in visitFSUB.
7723 if (N0.getOpcode() == ISD::FNEG) {
7724 SDValue N00 = N0.getOperand(0);
7725 if (N00.getOpcode() == ISD::FP_EXTEND) {
7726 SDValue N000 = N00.getOperand(0);
7727 if (N000.getOpcode() == ISD::FMUL) {
7728 return DAG.getNode(ISD::FNEG, SL, VT,
7729 DAG.getNode(PreferredFusedOpcode, SL, VT,
7730 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7731 N000.getOperand(0)),
7732 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7733 N000.getOperand(1)),
7741 // More folding opportunities when target permits.
7742 if ((AllowFusion || HasFMAD) && Aggressive) {
7743 // fold (fsub (fma x, y, (fmul u, v)), z)
7744 // -> (fma x, y (fma u, v, (fneg z)))
7745 if (N0.getOpcode() == PreferredFusedOpcode &&
7746 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7747 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7748 N0.getOperand(0), N0.getOperand(1),
7749 DAG.getNode(PreferredFusedOpcode, SL, VT,
7750 N0.getOperand(2).getOperand(0),
7751 N0.getOperand(2).getOperand(1),
7752 DAG.getNode(ISD::FNEG, SL, VT,
7756 // fold (fsub x, (fma y, z, (fmul u, v)))
7757 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7758 if (N1.getOpcode() == PreferredFusedOpcode &&
7759 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7760 SDValue N20 = N1.getOperand(2).getOperand(0);
7761 SDValue N21 = N1.getOperand(2).getOperand(1);
7762 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7763 DAG.getNode(ISD::FNEG, SL, VT,
7766 DAG.getNode(PreferredFusedOpcode, SL, VT,
7767 DAG.getNode(ISD::FNEG, SL, VT, N20),
7772 if (AllowFusion && LookThroughFPExt) {
7773 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7774 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7775 if (N0.getOpcode() == PreferredFusedOpcode) {
7776 SDValue N02 = N0.getOperand(2);
7777 if (N02.getOpcode() == ISD::FP_EXTEND) {
7778 SDValue N020 = N02.getOperand(0);
7779 if (N020.getOpcode() == ISD::FMUL)
7780 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7781 N0.getOperand(0), N0.getOperand(1),
7782 DAG.getNode(PreferredFusedOpcode, SL, VT,
7783 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7784 N020.getOperand(0)),
7785 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7786 N020.getOperand(1)),
7787 DAG.getNode(ISD::FNEG, SL, VT,
7792 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7793 // -> (fma (fpext x), (fpext y),
7794 // (fma (fpext u), (fpext v), (fneg z)))
7795 // FIXME: This turns two single-precision and one double-precision
7796 // operation into two double-precision operations, which might not be
7797 // interesting for all targets, especially GPUs.
7798 if (N0.getOpcode() == ISD::FP_EXTEND) {
7799 SDValue N00 = N0.getOperand(0);
7800 if (N00.getOpcode() == PreferredFusedOpcode) {
7801 SDValue N002 = N00.getOperand(2);
7802 if (N002.getOpcode() == ISD::FMUL)
7803 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7804 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7806 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7808 DAG.getNode(PreferredFusedOpcode, SL, VT,
7809 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7810 N002.getOperand(0)),
7811 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7812 N002.getOperand(1)),
7813 DAG.getNode(ISD::FNEG, SL, VT,
7818 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7819 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7820 if (N1.getOpcode() == PreferredFusedOpcode &&
7821 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7822 SDValue N120 = N1.getOperand(2).getOperand(0);
7823 if (N120.getOpcode() == ISD::FMUL) {
7824 SDValue N1200 = N120.getOperand(0);
7825 SDValue N1201 = N120.getOperand(1);
7826 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7827 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7829 DAG.getNode(PreferredFusedOpcode, SL, VT,
7830 DAG.getNode(ISD::FNEG, SL, VT,
7831 DAG.getNode(ISD::FP_EXTEND, SL,
7833 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7839 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7840 // -> (fma (fneg (fpext y)), (fpext z),
7841 // (fma (fneg (fpext u)), (fpext v), x))
7842 // FIXME: This turns two single-precision and one double-precision
7843 // operation into two double-precision operations, which might not be
7844 // interesting for all targets, especially GPUs.
7845 if (N1.getOpcode() == ISD::FP_EXTEND &&
7846 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7847 SDValue N100 = N1.getOperand(0).getOperand(0);
7848 SDValue N101 = N1.getOperand(0).getOperand(1);
7849 SDValue N102 = N1.getOperand(0).getOperand(2);
7850 if (N102.getOpcode() == ISD::FMUL) {
7851 SDValue N1020 = N102.getOperand(0);
7852 SDValue N1021 = N102.getOperand(1);
7853 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7854 DAG.getNode(ISD::FNEG, SL, VT,
7855 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7857 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7858 DAG.getNode(PreferredFusedOpcode, SL, VT,
7859 DAG.getNode(ISD::FNEG, SL, VT,
7860 DAG.getNode(ISD::FP_EXTEND, SL,
7862 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7873 /// Try to perform FMA combining on a given FMUL node.
7874 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7875 SDValue N0 = N->getOperand(0);
7876 SDValue N1 = N->getOperand(1);
7877 EVT VT = N->getValueType(0);
7880 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7882 const TargetOptions &Options = DAG.getTarget().Options;
7884 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7886 // Floating-point multiply-add with intermediate rounding.
7887 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7889 // Floating-point multiply-add without intermediate rounding.
7891 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7892 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7894 // No valid opcode, do not combine.
7895 if (!HasFMAD && !HasFMA)
7898 // Always prefer FMAD to FMA for precision.
7899 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7900 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7902 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7903 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7904 auto FuseFADD = [&](SDValue X, SDValue Y) {
7905 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7906 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7907 if (XC1 && XC1->isExactlyValue(+1.0))
7908 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7909 if (XC1 && XC1->isExactlyValue(-1.0))
7910 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7911 DAG.getNode(ISD::FNEG, SL, VT, Y));
7916 if (SDValue FMA = FuseFADD(N0, N1))
7918 if (SDValue FMA = FuseFADD(N1, N0))
7921 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
7922 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
7923 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
7924 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
7925 auto FuseFSUB = [&](SDValue X, SDValue Y) {
7926 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
7927 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
7928 if (XC0 && XC0->isExactlyValue(+1.0))
7929 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7930 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7932 if (XC0 && XC0->isExactlyValue(-1.0))
7933 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7934 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7935 DAG.getNode(ISD::FNEG, SL, VT, Y));
7937 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7938 if (XC1 && XC1->isExactlyValue(+1.0))
7939 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7940 DAG.getNode(ISD::FNEG, SL, VT, Y));
7941 if (XC1 && XC1->isExactlyValue(-1.0))
7942 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7947 if (SDValue FMA = FuseFSUB(N0, N1))
7949 if (SDValue FMA = FuseFSUB(N1, N0))
7955 SDValue DAGCombiner::visitFADD(SDNode *N) {
7956 SDValue N0 = N->getOperand(0);
7957 SDValue N1 = N->getOperand(1);
7958 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
7959 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
7960 EVT VT = N->getValueType(0);
7962 const TargetOptions &Options = DAG.getTarget().Options;
7963 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
7967 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7970 // fold (fadd c1, c2) -> c1 + c2
7972 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
7974 // canonicalize constant to RHS
7975 if (N0CFP && !N1CFP)
7976 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
7978 // fold (fadd A, (fneg B)) -> (fsub A, B)
7979 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7980 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7981 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7982 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
7984 // fold (fadd (fneg A), B) -> (fsub B, A)
7985 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7986 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7987 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7988 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
7990 // If 'unsafe math' is enabled, fold lots of things.
7991 if (Options.UnsafeFPMath) {
7992 // No FP constant should be created after legalization as Instruction
7993 // Selection pass has a hard time dealing with FP constants.
7994 bool AllowNewConst = (Level < AfterLegalizeDAG);
7996 // fold (fadd A, 0) -> A
7997 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8001 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8002 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8003 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8004 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8005 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8009 // If allowed, fold (fadd (fneg x), x) -> 0.0
8010 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8011 return DAG.getConstantFP(0.0, DL, VT);
8013 // If allowed, fold (fadd x, (fneg x)) -> 0.0
8014 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8015 return DAG.getConstantFP(0.0, DL, VT);
8017 // We can fold chains of FADD's of the same value into multiplications.
8018 // This transform is not safe in general because we are reducing the number
8019 // of rounding steps.
8020 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8021 if (N0.getOpcode() == ISD::FMUL) {
8022 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8023 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8025 // (fadd (fmul x, c), x) -> (fmul x, c+1)
8026 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8027 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8028 DAG.getConstantFP(1.0, DL, VT), Flags);
8029 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8032 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8033 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8034 N1.getOperand(0) == N1.getOperand(1) &&
8035 N0.getOperand(0) == N1.getOperand(0)) {
8036 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8037 DAG.getConstantFP(2.0, DL, VT), Flags);
8038 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8042 if (N1.getOpcode() == ISD::FMUL) {
8043 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8044 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8046 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8047 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8048 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8049 DAG.getConstantFP(1.0, DL, VT), Flags);
8050 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8053 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8054 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8055 N0.getOperand(0) == N0.getOperand(1) &&
8056 N1.getOperand(0) == N0.getOperand(0)) {
8057 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8058 DAG.getConstantFP(2.0, DL, VT), Flags);
8059 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8063 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8064 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8065 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8066 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8067 (N0.getOperand(0) == N1)) {
8068 return DAG.getNode(ISD::FMUL, DL, VT,
8069 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8073 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8074 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8075 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8076 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8077 N1.getOperand(0) == N0) {
8078 return DAG.getNode(ISD::FMUL, DL, VT,
8079 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8083 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8084 if (AllowNewConst &&
8085 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8086 N0.getOperand(0) == N0.getOperand(1) &&
8087 N1.getOperand(0) == N1.getOperand(1) &&
8088 N0.getOperand(0) == N1.getOperand(0)) {
8089 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8090 DAG.getConstantFP(4.0, DL, VT), Flags);
8093 } // enable-unsafe-fp-math
8095 // FADD -> FMA combines:
8096 if (SDValue Fused = visitFADDForFMACombine(N)) {
8097 AddToWorklist(Fused.getNode());
8104 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8105 SDValue N0 = N->getOperand(0);
8106 SDValue N1 = N->getOperand(1);
8107 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8108 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8109 EVT VT = N->getValueType(0);
8111 const TargetOptions &Options = DAG.getTarget().Options;
8112 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8116 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8119 // fold (fsub c1, c2) -> c1-c2
8121 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8123 // fold (fsub A, (fneg B)) -> (fadd A, B)
8124 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8125 return DAG.getNode(ISD::FADD, dl, VT, N0,
8126 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8128 // If 'unsafe math' is enabled, fold lots of things.
8129 if (Options.UnsafeFPMath) {
8131 if (N1CFP && N1CFP->isZero())
8134 // (fsub 0, B) -> -B
8135 if (N0CFP && N0CFP->isZero()) {
8136 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8137 return GetNegatedExpression(N1, DAG, LegalOperations);
8138 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8139 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8142 // (fsub x, x) -> 0.0
8144 return DAG.getConstantFP(0.0f, dl, VT);
8146 // (fsub x, (fadd x, y)) -> (fneg y)
8147 // (fsub x, (fadd y, x)) -> (fneg y)
8148 if (N1.getOpcode() == ISD::FADD) {
8149 SDValue N10 = N1->getOperand(0);
8150 SDValue N11 = N1->getOperand(1);
8152 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8153 return GetNegatedExpression(N11, DAG, LegalOperations);
8155 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8156 return GetNegatedExpression(N10, DAG, LegalOperations);
8160 // FSUB -> FMA combines:
8161 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8162 AddToWorklist(Fused.getNode());
8169 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8170 SDValue N0 = N->getOperand(0);
8171 SDValue N1 = N->getOperand(1);
8172 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8173 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8174 EVT VT = N->getValueType(0);
8176 const TargetOptions &Options = DAG.getTarget().Options;
8177 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8180 if (VT.isVector()) {
8181 // This just handles C1 * C2 for vectors. Other vector folds are below.
8182 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8186 // fold (fmul c1, c2) -> c1*c2
8188 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8190 // canonicalize constant to RHS
8191 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8192 !isConstantFPBuildVectorOrConstantFP(N1))
8193 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8195 // fold (fmul A, 1.0) -> A
8196 if (N1CFP && N1CFP->isExactlyValue(1.0))
8199 if (Options.UnsafeFPMath) {
8200 // fold (fmul A, 0) -> 0
8201 if (N1CFP && N1CFP->isZero())
8204 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8205 if (N0.getOpcode() == ISD::FMUL) {
8206 // Fold scalars or any vector constants (not just splats).
8207 // This fold is done in general by InstCombine, but extra fmul insts
8208 // may have been generated during lowering.
8209 SDValue N00 = N0.getOperand(0);
8210 SDValue N01 = N0.getOperand(1);
8211 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8212 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8213 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8215 // Check 1: Make sure that the first operand of the inner multiply is NOT
8216 // a constant. Otherwise, we may induce infinite looping.
8217 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8218 // Check 2: Make sure that the second operand of the inner multiply and
8219 // the second operand of the outer multiply are constants.
8220 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8221 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8222 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8223 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8228 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8229 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8230 // during an early run of DAGCombiner can prevent folding with fmuls
8231 // inserted during lowering.
8232 if (N0.getOpcode() == ISD::FADD &&
8233 (N0.getOperand(0) == N0.getOperand(1)) &&
8235 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8236 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8237 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8241 // fold (fmul X, 2.0) -> (fadd X, X)
8242 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8243 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8245 // fold (fmul X, -1.0) -> (fneg X)
8246 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8247 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8248 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8250 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8251 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8252 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8253 // Both can be negated for free, check to see if at least one is cheaper
8255 if (LHSNeg == 2 || RHSNeg == 2)
8256 return DAG.getNode(ISD::FMUL, DL, VT,
8257 GetNegatedExpression(N0, DAG, LegalOperations),
8258 GetNegatedExpression(N1, DAG, LegalOperations),
8263 // FMUL -> FMA combines:
8264 if (SDValue Fused = visitFMULForFMACombine(N)) {
8265 AddToWorklist(Fused.getNode());
8272 SDValue DAGCombiner::visitFMA(SDNode *N) {
8273 SDValue N0 = N->getOperand(0);
8274 SDValue N1 = N->getOperand(1);
8275 SDValue N2 = N->getOperand(2);
8276 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8277 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8278 EVT VT = N->getValueType(0);
8280 const TargetOptions &Options = DAG.getTarget().Options;
8282 // Constant fold FMA.
8283 if (isa<ConstantFPSDNode>(N0) &&
8284 isa<ConstantFPSDNode>(N1) &&
8285 isa<ConstantFPSDNode>(N2)) {
8286 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8289 if (Options.UnsafeFPMath) {
8290 if (N0CFP && N0CFP->isZero())
8292 if (N1CFP && N1CFP->isZero())
8295 // TODO: The FMA node should have flags that propagate to these nodes.
8296 if (N0CFP && N0CFP->isExactlyValue(1.0))
8297 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8298 if (N1CFP && N1CFP->isExactlyValue(1.0))
8299 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8301 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8302 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8303 !isConstantFPBuildVectorOrConstantFP(N1))
8304 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8306 // TODO: FMA nodes should have flags that propagate to the created nodes.
8307 // For now, create a Flags object for use with all unsafe math transforms.
8309 Flags.setUnsafeAlgebra(true);
8311 if (Options.UnsafeFPMath) {
8312 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8313 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8314 isConstantFPBuildVectorOrConstantFP(N1) &&
8315 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8316 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8317 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8321 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8322 if (N0.getOpcode() == ISD::FMUL &&
8323 isConstantFPBuildVectorOrConstantFP(N1) &&
8324 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8325 return DAG.getNode(ISD::FMA, dl, VT,
8327 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8333 // (fma x, 1, y) -> (fadd x, y)
8334 // (fma x, -1, y) -> (fadd (fneg x), y)
8336 if (N1CFP->isExactlyValue(1.0))
8337 // TODO: The FMA node should have flags that propagate to this node.
8338 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8340 if (N1CFP->isExactlyValue(-1.0) &&
8341 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8342 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8343 AddToWorklist(RHSNeg.getNode());
8344 // TODO: The FMA node should have flags that propagate to this node.
8345 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8349 if (Options.UnsafeFPMath) {
8350 // (fma x, c, x) -> (fmul x, (c+1))
8351 if (N1CFP && N0 == N2) {
8352 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8353 DAG.getNode(ISD::FADD, dl, VT,
8354 N1, DAG.getConstantFP(1.0, dl, VT),
8358 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8359 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8360 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8361 DAG.getNode(ISD::FADD, dl, VT,
8362 N1, DAG.getConstantFP(-1.0, dl, VT),
8370 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8372 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8373 // Notice that this is not always beneficial. One reason is different target
8374 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8375 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8376 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8377 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8378 if (!DAG.getTarget().Options.UnsafeFPMath)
8381 // Skip if current node is a reciprocal.
8382 SDValue N0 = N->getOperand(0);
8383 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8384 if (N0CFP && N0CFP->isExactlyValue(1.0))
8387 // Exit early if the target does not want this transform or if there can't
8388 // possibly be enough uses of the divisor to make the transform worthwhile.
8389 SDValue N1 = N->getOperand(1);
8390 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8391 if (!MinUses || N1->use_size() < MinUses)
8394 // Find all FDIV users of the same divisor.
8395 // Use a set because duplicates may be present in the user list.
8396 SetVector<SDNode *> Users;
8397 for (auto *U : N1->uses())
8398 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8401 // Now that we have the actual number of divisor uses, make sure it meets
8402 // the minimum threshold specified by the target.
8403 if (Users.size() < MinUses)
8406 EVT VT = N->getValueType(0);
8408 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8409 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8410 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8412 // Dividend / Divisor -> Dividend * Reciprocal
8413 for (auto *U : Users) {
8414 SDValue Dividend = U->getOperand(0);
8415 if (Dividend != FPOne) {
8416 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8418 CombineTo(U, NewNode);
8419 } else if (U != Reciprocal.getNode()) {
8420 // In the absence of fast-math-flags, this user node is always the
8421 // same node as Reciprocal, but with FMF they may be different nodes.
8422 CombineTo(U, Reciprocal);
8425 return SDValue(N, 0); // N was replaced.
8428 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8429 SDValue N0 = N->getOperand(0);
8430 SDValue N1 = N->getOperand(1);
8431 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8432 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8433 EVT VT = N->getValueType(0);
8435 const TargetOptions &Options = DAG.getTarget().Options;
8436 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8440 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8443 // fold (fdiv c1, c2) -> c1/c2
8445 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8447 if (Options.UnsafeFPMath) {
8448 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8450 // Compute the reciprocal 1.0 / c2.
8451 APFloat N1APF = N1CFP->getValueAPF();
8452 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8453 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8454 // Only do the transform if the reciprocal is a legal fp immediate that
8455 // isn't too nasty (eg NaN, denormal, ...).
8456 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8457 (!LegalOperations ||
8458 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8459 // backend)... we should handle this gracefully after Legalize.
8460 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8461 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8462 TLI.isFPImmLegal(Recip, VT)))
8463 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8464 DAG.getConstantFP(Recip, DL, VT), Flags);
8467 // If this FDIV is part of a reciprocal square root, it may be folded
8468 // into a target-specific square root estimate instruction.
8469 if (N1.getOpcode() == ISD::FSQRT) {
8470 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8471 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8473 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8474 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8475 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8477 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8478 AddToWorklist(RV.getNode());
8479 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8481 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8482 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8483 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8485 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8486 AddToWorklist(RV.getNode());
8487 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8489 } else if (N1.getOpcode() == ISD::FMUL) {
8490 // Look through an FMUL. Even though this won't remove the FDIV directly,
8491 // it's still worthwhile to get rid of the FSQRT if possible.
8494 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8495 SqrtOp = N1.getOperand(0);
8496 OtherOp = N1.getOperand(1);
8497 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8498 SqrtOp = N1.getOperand(1);
8499 OtherOp = N1.getOperand(0);
8501 if (SqrtOp.getNode()) {
8502 // We found a FSQRT, so try to make this fold:
8503 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8504 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8505 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8506 AddToWorklist(RV.getNode());
8507 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8512 // Fold into a reciprocal estimate and multiply instead of a real divide.
8513 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8514 AddToWorklist(RV.getNode());
8515 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8519 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8520 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8521 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8522 // Both can be negated for free, check to see if at least one is cheaper
8524 if (LHSNeg == 2 || RHSNeg == 2)
8525 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8526 GetNegatedExpression(N0, DAG, LegalOperations),
8527 GetNegatedExpression(N1, DAG, LegalOperations),
8532 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8533 return CombineRepeatedDivisors;
8538 SDValue DAGCombiner::visitFREM(SDNode *N) {
8539 SDValue N0 = N->getOperand(0);
8540 SDValue N1 = N->getOperand(1);
8541 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8542 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8543 EVT VT = N->getValueType(0);
8545 // fold (frem c1, c2) -> fmod(c1,c2)
8547 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8548 &cast<BinaryWithFlagsSDNode>(N)->Flags);
8553 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8554 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8557 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8558 // For now, create a Flags object for use with all unsafe math transforms.
8560 Flags.setUnsafeAlgebra(true);
8562 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8563 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8567 EVT VT = RV.getValueType();
8569 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8570 AddToWorklist(RV.getNode());
8572 // Unfortunately, RV is now NaN if the input was exactly 0.
8573 // Select out this case and force the answer to 0.
8574 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8575 EVT CCVT = getSetCCResultType(VT);
8576 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8577 AddToWorklist(ZeroCmp.getNode());
8578 AddToWorklist(RV.getNode());
8580 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8584 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8585 SDValue N0 = N->getOperand(0);
8586 SDValue N1 = N->getOperand(1);
8587 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8588 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8589 EVT VT = N->getValueType(0);
8591 if (N0CFP && N1CFP) // Constant fold
8592 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8595 const APFloat& V = N1CFP->getValueAPF();
8596 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8597 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8598 if (!V.isNegative()) {
8599 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8600 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8602 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8603 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8604 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8608 // copysign(fabs(x), y) -> copysign(x, y)
8609 // copysign(fneg(x), y) -> copysign(x, y)
8610 // copysign(copysign(x,z), y) -> copysign(x, y)
8611 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8612 N0.getOpcode() == ISD::FCOPYSIGN)
8613 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8614 N0.getOperand(0), N1);
8616 // copysign(x, abs(y)) -> abs(x)
8617 if (N1.getOpcode() == ISD::FABS)
8618 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8620 // copysign(x, copysign(y,z)) -> copysign(x, z)
8621 if (N1.getOpcode() == ISD::FCOPYSIGN)
8622 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8623 N0, N1.getOperand(1));
8625 // copysign(x, fp_extend(y)) -> copysign(x, y)
8626 // copysign(x, fp_round(y)) -> copysign(x, y)
8627 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8628 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8629 N0, N1.getOperand(0));
8634 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8635 SDValue N0 = N->getOperand(0);
8636 EVT VT = N->getValueType(0);
8637 EVT OpVT = N0.getValueType();
8639 // fold (sint_to_fp c1) -> c1fp
8640 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8641 // ...but only if the target supports immediate floating-point values
8642 (!LegalOperations ||
8643 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8644 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8646 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8647 // but UINT_TO_FP is legal on this target, try to convert.
8648 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8649 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8650 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8651 if (DAG.SignBitIsZero(N0))
8652 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8655 // The next optimizations are desirable only if SELECT_CC can be lowered.
8656 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8657 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8658 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8660 (!LegalOperations ||
8661 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8664 { N0.getOperand(0), N0.getOperand(1),
8665 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8667 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8670 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8671 // (select_cc x, y, 1.0, 0.0,, cc)
8672 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8673 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8674 (!LegalOperations ||
8675 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8678 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8679 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8680 N0.getOperand(0).getOperand(2) };
8681 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8688 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8689 SDValue N0 = N->getOperand(0);
8690 EVT VT = N->getValueType(0);
8691 EVT OpVT = N0.getValueType();
8693 // fold (uint_to_fp c1) -> c1fp
8694 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8695 // ...but only if the target supports immediate floating-point values
8696 (!LegalOperations ||
8697 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8698 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8700 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8701 // but SINT_TO_FP is legal on this target, try to convert.
8702 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8703 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8704 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8705 if (DAG.SignBitIsZero(N0))
8706 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8709 // The next optimizations are desirable only if SELECT_CC can be lowered.
8710 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8711 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8713 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8714 (!LegalOperations ||
8715 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8718 { N0.getOperand(0), N0.getOperand(1),
8719 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8721 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8728 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8729 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8730 SDValue N0 = N->getOperand(0);
8731 EVT VT = N->getValueType(0);
8733 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8736 SDValue Src = N0.getOperand(0);
8737 EVT SrcVT = Src.getValueType();
8738 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8739 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8741 // We can safely assume the conversion won't overflow the output range,
8742 // because (for example) (uint8_t)18293.f is undefined behavior.
8744 // Since we can assume the conversion won't overflow, our decision as to
8745 // whether the input will fit in the float should depend on the minimum
8746 // of the input range and output range.
8748 // This means this is also safe for a signed input and unsigned output, since
8749 // a negative input would lead to undefined behavior.
8750 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8751 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8752 unsigned ActualSize = std::min(InputSize, OutputSize);
8753 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8755 // We can only fold away the float conversion if the input range can be
8756 // represented exactly in the float range.
8757 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8758 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8759 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8761 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8763 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8764 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8767 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8772 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8773 SDValue N0 = N->getOperand(0);
8774 EVT VT = N->getValueType(0);
8776 // fold (fp_to_sint c1fp) -> c1
8777 if (isConstantFPBuildVectorOrConstantFP(N0))
8778 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8780 return FoldIntToFPToInt(N, DAG);
8783 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8784 SDValue N0 = N->getOperand(0);
8785 EVT VT = N->getValueType(0);
8787 // fold (fp_to_uint c1fp) -> c1
8788 if (isConstantFPBuildVectorOrConstantFP(N0))
8789 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8791 return FoldIntToFPToInt(N, DAG);
8794 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8795 SDValue N0 = N->getOperand(0);
8796 SDValue N1 = N->getOperand(1);
8797 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8798 EVT VT = N->getValueType(0);
8800 // fold (fp_round c1fp) -> c1fp
8802 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8804 // fold (fp_round (fp_extend x)) -> x
8805 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8806 return N0.getOperand(0);
8808 // fold (fp_round (fp_round x)) -> (fp_round x)
8809 if (N0.getOpcode() == ISD::FP_ROUND) {
8810 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8811 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8812 // If the first fp_round isn't a value preserving truncation, it might
8813 // introduce a tie in the second fp_round, that wouldn't occur in the
8814 // single-step fp_round we want to fold to.
8815 // In other words, double rounding isn't the same as rounding.
8816 // Also, this is a value preserving truncation iff both fp_round's are.
8817 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8819 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8820 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8824 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8825 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8826 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8827 N0.getOperand(0), N1);
8828 AddToWorklist(Tmp.getNode());
8829 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8830 Tmp, N0.getOperand(1));
8836 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8837 SDValue N0 = N->getOperand(0);
8838 EVT VT = N->getValueType(0);
8839 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8840 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8842 // fold (fp_round_inreg c1fp) -> c1fp
8843 if (N0CFP && isTypeLegal(EVT)) {
8845 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8846 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8852 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8853 SDValue N0 = N->getOperand(0);
8854 EVT VT = N->getValueType(0);
8856 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8857 if (N->hasOneUse() &&
8858 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8861 // fold (fp_extend c1fp) -> c1fp
8862 if (isConstantFPBuildVectorOrConstantFP(N0))
8863 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8865 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8866 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8867 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8868 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8870 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8872 if (N0.getOpcode() == ISD::FP_ROUND
8873 && N0.getNode()->getConstantOperandVal(1) == 1) {
8874 SDValue In = N0.getOperand(0);
8875 if (In.getValueType() == VT) return In;
8876 if (VT.bitsLT(In.getValueType()))
8877 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8878 In, N0.getOperand(1));
8879 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8882 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8883 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8884 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8885 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8886 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8888 LN0->getBasePtr(), N0.getValueType(),
8889 LN0->getMemOperand());
8890 CombineTo(N, ExtLoad);
8891 CombineTo(N0.getNode(),
8892 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8893 N0.getValueType(), ExtLoad,
8894 DAG.getIntPtrConstant(1, SDLoc(N0))),
8895 ExtLoad.getValue(1));
8896 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8902 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8903 SDValue N0 = N->getOperand(0);
8904 EVT VT = N->getValueType(0);
8906 // fold (fceil c1) -> fceil(c1)
8907 if (isConstantFPBuildVectorOrConstantFP(N0))
8908 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8913 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8914 SDValue N0 = N->getOperand(0);
8915 EVT VT = N->getValueType(0);
8917 // fold (ftrunc c1) -> ftrunc(c1)
8918 if (isConstantFPBuildVectorOrConstantFP(N0))
8919 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8924 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8925 SDValue N0 = N->getOperand(0);
8926 EVT VT = N->getValueType(0);
8928 // fold (ffloor c1) -> ffloor(c1)
8929 if (isConstantFPBuildVectorOrConstantFP(N0))
8930 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8935 // FIXME: FNEG and FABS have a lot in common; refactor.
8936 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8937 SDValue N0 = N->getOperand(0);
8938 EVT VT = N->getValueType(0);
8940 // Constant fold FNEG.
8941 if (isConstantFPBuildVectorOrConstantFP(N0))
8942 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8944 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8945 &DAG.getTarget().Options))
8946 return GetNegatedExpression(N0, DAG, LegalOperations);
8948 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8949 // constant pool values.
8950 if (!TLI.isFNegFree(VT) &&
8951 N0.getOpcode() == ISD::BITCAST &&
8952 N0.getNode()->hasOneUse()) {
8953 SDValue Int = N0.getOperand(0);
8954 EVT IntVT = Int.getValueType();
8955 if (IntVT.isInteger() && !IntVT.isVector()) {
8957 if (N0.getValueType().isVector()) {
8958 // For a vector, get a mask such as 0x80... per scalar element
8960 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8961 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8963 // For a scalar, just generate 0x80...
8964 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8967 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8968 DAG.getConstant(SignMask, DL0, IntVT));
8969 AddToWorklist(Int.getNode());
8970 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8974 // (fneg (fmul c, x)) -> (fmul -c, x)
8975 if (N0.getOpcode() == ISD::FMUL &&
8976 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8977 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8979 APFloat CVal = CFP1->getValueAPF();
8981 if (Level >= AfterLegalizeDAG &&
8982 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8983 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8984 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8985 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8987 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
8994 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8995 SDValue N0 = N->getOperand(0);
8996 SDValue N1 = N->getOperand(1);
8997 EVT VT = N->getValueType(0);
8998 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8999 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9001 if (N0CFP && N1CFP) {
9002 const APFloat &C0 = N0CFP->getValueAPF();
9003 const APFloat &C1 = N1CFP->getValueAPF();
9004 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9007 // Canonicalize to constant on RHS.
9008 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9009 !isConstantFPBuildVectorOrConstantFP(N1))
9010 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9015 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9016 SDValue N0 = N->getOperand(0);
9017 SDValue N1 = N->getOperand(1);
9018 EVT VT = N->getValueType(0);
9019 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9020 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9022 if (N0CFP && N1CFP) {
9023 const APFloat &C0 = N0CFP->getValueAPF();
9024 const APFloat &C1 = N1CFP->getValueAPF();
9025 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9028 // Canonicalize to constant on RHS.
9029 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9030 !isConstantFPBuildVectorOrConstantFP(N1))
9031 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9036 SDValue DAGCombiner::visitFABS(SDNode *N) {
9037 SDValue N0 = N->getOperand(0);
9038 EVT VT = N->getValueType(0);
9040 // fold (fabs c1) -> fabs(c1)
9041 if (isConstantFPBuildVectorOrConstantFP(N0))
9042 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9044 // fold (fabs (fabs x)) -> (fabs x)
9045 if (N0.getOpcode() == ISD::FABS)
9046 return N->getOperand(0);
9048 // fold (fabs (fneg x)) -> (fabs x)
9049 // fold (fabs (fcopysign x, y)) -> (fabs x)
9050 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9051 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9053 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9054 // constant pool values.
9055 if (!TLI.isFAbsFree(VT) &&
9056 N0.getOpcode() == ISD::BITCAST &&
9057 N0.getNode()->hasOneUse()) {
9058 SDValue Int = N0.getOperand(0);
9059 EVT IntVT = Int.getValueType();
9060 if (IntVT.isInteger() && !IntVT.isVector()) {
9062 if (N0.getValueType().isVector()) {
9063 // For a vector, get a mask such as 0x7f... per scalar element
9065 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9066 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9068 // For a scalar, just generate 0x7f...
9069 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9072 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9073 DAG.getConstant(SignMask, DL, IntVT));
9074 AddToWorklist(Int.getNode());
9075 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9082 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9083 SDValue Chain = N->getOperand(0);
9084 SDValue N1 = N->getOperand(1);
9085 SDValue N2 = N->getOperand(2);
9087 // If N is a constant we could fold this into a fallthrough or unconditional
9088 // branch. However that doesn't happen very often in normal code, because
9089 // Instcombine/SimplifyCFG should have handled the available opportunities.
9090 // If we did this folding here, it would be necessary to update the
9091 // MachineBasicBlock CFG, which is awkward.
9093 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9095 if (N1.getOpcode() == ISD::SETCC &&
9096 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9097 N1.getOperand(0).getValueType())) {
9098 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9099 Chain, N1.getOperand(2),
9100 N1.getOperand(0), N1.getOperand(1), N2);
9103 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9104 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9105 (N1.getOperand(0).hasOneUse() &&
9106 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9107 SDNode *Trunc = nullptr;
9108 if (N1.getOpcode() == ISD::TRUNCATE) {
9109 // Look pass the truncate.
9110 Trunc = N1.getNode();
9111 N1 = N1.getOperand(0);
9114 // Match this pattern so that we can generate simpler code:
9117 // %b = and i32 %a, 2
9118 // %c = srl i32 %b, 1
9119 // brcond i32 %c ...
9124 // %b = and i32 %a, 2
9125 // %c = setcc eq %b, 0
9128 // This applies only when the AND constant value has one bit set and the
9129 // SRL constant is equal to the log2 of the AND constant. The back-end is
9130 // smart enough to convert the result into a TEST/JMP sequence.
9131 SDValue Op0 = N1.getOperand(0);
9132 SDValue Op1 = N1.getOperand(1);
9134 if (Op0.getOpcode() == ISD::AND &&
9135 Op1.getOpcode() == ISD::Constant) {
9136 SDValue AndOp1 = Op0.getOperand(1);
9138 if (AndOp1.getOpcode() == ISD::Constant) {
9139 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9141 if (AndConst.isPowerOf2() &&
9142 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9146 getSetCCResultType(Op0.getValueType()),
9147 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9150 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9151 MVT::Other, Chain, SetCC, N2);
9152 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9153 // will convert it back to (X & C1) >> C2.
9154 CombineTo(N, NewBRCond, false);
9155 // Truncate is dead.
9157 deleteAndRecombine(Trunc);
9158 // Replace the uses of SRL with SETCC
9159 WorklistRemover DeadNodes(*this);
9160 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9161 deleteAndRecombine(N1.getNode());
9162 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9168 // Restore N1 if the above transformation doesn't match.
9169 N1 = N->getOperand(1);
9172 // Transform br(xor(x, y)) -> br(x != y)
9173 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9174 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9175 SDNode *TheXor = N1.getNode();
9176 SDValue Op0 = TheXor->getOperand(0);
9177 SDValue Op1 = TheXor->getOperand(1);
9178 if (Op0.getOpcode() == Op1.getOpcode()) {
9179 // Avoid missing important xor optimizations.
9180 if (SDValue Tmp = visitXOR(TheXor)) {
9181 if (Tmp.getNode() != TheXor) {
9182 DEBUG(dbgs() << "\nReplacing.8 ";
9184 dbgs() << "\nWith: ";
9185 Tmp.getNode()->dump(&DAG);
9187 WorklistRemover DeadNodes(*this);
9188 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9189 deleteAndRecombine(TheXor);
9190 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9191 MVT::Other, Chain, Tmp, N2);
9194 // visitXOR has changed XOR's operands or replaced the XOR completely,
9196 return SDValue(N, 0);
9200 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9202 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9203 Op0.getOpcode() == ISD::XOR) {
9204 TheXor = Op0.getNode();
9208 EVT SetCCVT = N1.getValueType();
9210 SetCCVT = getSetCCResultType(SetCCVT);
9211 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9214 Equal ? ISD::SETEQ : ISD::SETNE);
9215 // Replace the uses of XOR with SETCC
9216 WorklistRemover DeadNodes(*this);
9217 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9218 deleteAndRecombine(N1.getNode());
9219 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9220 MVT::Other, Chain, SetCC, N2);
9227 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9229 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9230 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9231 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9233 // If N is a constant we could fold this into a fallthrough or unconditional
9234 // branch. However that doesn't happen very often in normal code, because
9235 // Instcombine/SimplifyCFG should have handled the available opportunities.
9236 // If we did this folding here, it would be necessary to update the
9237 // MachineBasicBlock CFG, which is awkward.
9239 // Use SimplifySetCC to simplify SETCC's.
9240 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9241 CondLHS, CondRHS, CC->get(), SDLoc(N),
9243 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9245 // fold to a simpler setcc
9246 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9247 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9248 N->getOperand(0), Simp.getOperand(2),
9249 Simp.getOperand(0), Simp.getOperand(1),
9255 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9256 /// and that N may be folded in the load / store addressing mode.
9257 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9259 const TargetLowering &TLI) {
9263 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9264 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9266 VT = LD->getMemoryVT();
9267 AS = LD->getAddressSpace();
9268 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9269 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9271 VT = ST->getMemoryVT();
9272 AS = ST->getAddressSpace();
9276 TargetLowering::AddrMode AM;
9277 if (N->getOpcode() == ISD::ADD) {
9278 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9281 AM.BaseOffs = Offset->getSExtValue();
9285 } else if (N->getOpcode() == ISD::SUB) {
9286 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9289 AM.BaseOffs = -Offset->getSExtValue();
9296 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9297 VT.getTypeForEVT(*DAG.getContext()), AS);
9300 /// Try turning a load/store into a pre-indexed load/store when the base
9301 /// pointer is an add or subtract and it has other uses besides the load/store.
9302 /// After the transformation, the new indexed load/store has effectively folded
9303 /// the add/subtract in and all of its other uses are redirected to the
9305 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9306 if (Level < AfterLegalizeDAG)
9312 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9313 if (LD->isIndexed())
9315 VT = LD->getMemoryVT();
9316 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9317 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9319 Ptr = LD->getBasePtr();
9320 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9321 if (ST->isIndexed())
9323 VT = ST->getMemoryVT();
9324 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9325 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9327 Ptr = ST->getBasePtr();
9333 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9334 // out. There is no reason to make this a preinc/predec.
9335 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9336 Ptr.getNode()->hasOneUse())
9339 // Ask the target to do addressing mode selection.
9342 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9343 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9346 // Backends without true r+i pre-indexed forms may need to pass a
9347 // constant base with a variable offset so that constant coercion
9348 // will work with the patterns in canonical form.
9349 bool Swapped = false;
9350 if (isa<ConstantSDNode>(BasePtr)) {
9351 std::swap(BasePtr, Offset);
9355 // Don't create a indexed load / store with zero offset.
9356 if (isNullConstant(Offset))
9359 // Try turning it into a pre-indexed load / store except when:
9360 // 1) The new base ptr is a frame index.
9361 // 2) If N is a store and the new base ptr is either the same as or is a
9362 // predecessor of the value being stored.
9363 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9364 // that would create a cycle.
9365 // 4) All uses are load / store ops that use it as old base ptr.
9367 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9368 // (plus the implicit offset) to a register to preinc anyway.
9369 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9374 SDValue Val = cast<StoreSDNode>(N)->getValue();
9375 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9379 // If the offset is a constant, there may be other adds of constants that
9380 // can be folded with this one. We should do this to avoid having to keep
9381 // a copy of the original base pointer.
9382 SmallVector<SDNode *, 16> OtherUses;
9383 if (isa<ConstantSDNode>(Offset))
9384 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9385 UE = BasePtr.getNode()->use_end();
9387 SDUse &Use = UI.getUse();
9388 // Skip the use that is Ptr and uses of other results from BasePtr's
9389 // node (important for nodes that return multiple results).
9390 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9393 if (Use.getUser()->isPredecessorOf(N))
9396 if (Use.getUser()->getOpcode() != ISD::ADD &&
9397 Use.getUser()->getOpcode() != ISD::SUB) {
9402 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9403 if (!isa<ConstantSDNode>(Op1)) {
9408 // FIXME: In some cases, we can be smarter about this.
9409 if (Op1.getValueType() != Offset.getValueType()) {
9414 OtherUses.push_back(Use.getUser());
9418 std::swap(BasePtr, Offset);
9420 // Now check for #3 and #4.
9421 bool RealUse = false;
9423 // Caches for hasPredecessorHelper
9424 SmallPtrSet<const SDNode *, 32> Visited;
9425 SmallVector<const SDNode *, 16> Worklist;
9427 for (SDNode *Use : Ptr.getNode()->uses()) {
9430 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9433 // If Ptr may be folded in addressing mode of other use, then it's
9434 // not profitable to do this transformation.
9435 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9444 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9445 BasePtr, Offset, AM);
9447 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9448 BasePtr, Offset, AM);
9451 DEBUG(dbgs() << "\nReplacing.4 ";
9453 dbgs() << "\nWith: ";
9454 Result.getNode()->dump(&DAG);
9456 WorklistRemover DeadNodes(*this);
9458 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9459 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9461 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9464 // Finally, since the node is now dead, remove it from the graph.
9465 deleteAndRecombine(N);
9468 std::swap(BasePtr, Offset);
9470 // Replace other uses of BasePtr that can be updated to use Ptr
9471 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9472 unsigned OffsetIdx = 1;
9473 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9475 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9476 BasePtr.getNode() && "Expected BasePtr operand");
9478 // We need to replace ptr0 in the following expression:
9479 // x0 * offset0 + y0 * ptr0 = t0
9481 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9483 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9484 // indexed load/store and the expresion that needs to be re-written.
9486 // Therefore, we have:
9487 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9489 ConstantSDNode *CN =
9490 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9492 APInt Offset0 = CN->getAPIntValue();
9493 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9495 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9496 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9497 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9498 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9500 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9502 APInt CNV = Offset0;
9503 if (X0 < 0) CNV = -CNV;
9504 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9505 else CNV = CNV - Offset1;
9507 SDLoc DL(OtherUses[i]);
9509 // We can now generate the new expression.
9510 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9511 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9513 SDValue NewUse = DAG.getNode(Opcode,
9515 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9516 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9517 deleteAndRecombine(OtherUses[i]);
9520 // Replace the uses of Ptr with uses of the updated base value.
9521 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9522 deleteAndRecombine(Ptr.getNode());
9527 /// Try to combine a load/store with a add/sub of the base pointer node into a
9528 /// post-indexed load/store. The transformation folded the add/subtract into the
9529 /// new indexed load/store effectively and all of its uses are redirected to the
9531 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9532 if (Level < AfterLegalizeDAG)
9538 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9539 if (LD->isIndexed())
9541 VT = LD->getMemoryVT();
9542 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9543 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9545 Ptr = LD->getBasePtr();
9546 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9547 if (ST->isIndexed())
9549 VT = ST->getMemoryVT();
9550 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9551 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9553 Ptr = ST->getBasePtr();
9559 if (Ptr.getNode()->hasOneUse())
9562 for (SDNode *Op : Ptr.getNode()->uses()) {
9564 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9569 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9570 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9571 // Don't create a indexed load / store with zero offset.
9572 if (isNullConstant(Offset))
9575 // Try turning it into a post-indexed load / store except when
9576 // 1) All uses are load / store ops that use it as base ptr (and
9577 // it may be folded as addressing mmode).
9578 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9579 // nor a successor of N. Otherwise, if Op is folded that would
9582 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9586 bool TryNext = false;
9587 for (SDNode *Use : BasePtr.getNode()->uses()) {
9588 if (Use == Ptr.getNode())
9591 // If all the uses are load / store addresses, then don't do the
9593 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9594 bool RealUse = false;
9595 for (SDNode *UseUse : Use->uses()) {
9596 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9611 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9612 SDValue Result = isLoad
9613 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9614 BasePtr, Offset, AM)
9615 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9616 BasePtr, Offset, AM);
9619 DEBUG(dbgs() << "\nReplacing.5 ";
9621 dbgs() << "\nWith: ";
9622 Result.getNode()->dump(&DAG);
9624 WorklistRemover DeadNodes(*this);
9626 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9627 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9629 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9632 // Finally, since the node is now dead, remove it from the graph.
9633 deleteAndRecombine(N);
9635 // Replace the uses of Use with uses of the updated base value.
9636 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9637 Result.getValue(isLoad ? 1 : 0));
9638 deleteAndRecombine(Op);
9647 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9648 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9649 ISD::MemIndexedMode AM = LD->getAddressingMode();
9650 assert(AM != ISD::UNINDEXED);
9651 SDValue BP = LD->getOperand(1);
9652 SDValue Inc = LD->getOperand(2);
9654 // Some backends use TargetConstants for load offsets, but don't expect
9655 // TargetConstants in general ADD nodes. We can convert these constants into
9656 // regular Constants (if the constant is not opaque).
9657 assert((Inc.getOpcode() != ISD::TargetConstant ||
9658 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9659 "Cannot split out indexing using opaque target constants");
9660 if (Inc.getOpcode() == ISD::TargetConstant) {
9661 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9662 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9663 ConstInc->getValueType(0));
9667 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9668 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9671 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9672 LoadSDNode *LD = cast<LoadSDNode>(N);
9673 SDValue Chain = LD->getChain();
9674 SDValue Ptr = LD->getBasePtr();
9676 // If load is not volatile and there are no uses of the loaded value (and
9677 // the updated indexed value in case of indexed loads), change uses of the
9678 // chain value into uses of the chain input (i.e. delete the dead load).
9679 if (!LD->isVolatile()) {
9680 if (N->getValueType(1) == MVT::Other) {
9682 if (!N->hasAnyUseOfValue(0)) {
9683 // It's not safe to use the two value CombineTo variant here. e.g.
9684 // v1, chain2 = load chain1, loc
9685 // v2, chain3 = load chain2, loc
9687 // Now we replace use of chain2 with chain1. This makes the second load
9688 // isomorphic to the one we are deleting, and thus makes this load live.
9689 DEBUG(dbgs() << "\nReplacing.6 ";
9691 dbgs() << "\nWith chain: ";
9692 Chain.getNode()->dump(&DAG);
9694 WorklistRemover DeadNodes(*this);
9695 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9698 deleteAndRecombine(N);
9700 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9704 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9706 // If this load has an opaque TargetConstant offset, then we cannot split
9707 // the indexing into an add/sub directly (that TargetConstant may not be
9708 // valid for a different type of node, and we cannot convert an opaque
9709 // target constant into a regular constant).
9710 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9711 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9713 if (!N->hasAnyUseOfValue(0) &&
9714 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9715 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9717 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9718 Index = SplitIndexingFromLoad(LD);
9719 // Try to fold the base pointer arithmetic into subsequent loads and
9721 AddUsersToWorklist(N);
9723 Index = DAG.getUNDEF(N->getValueType(1));
9724 DEBUG(dbgs() << "\nReplacing.7 ";
9726 dbgs() << "\nWith: ";
9727 Undef.getNode()->dump(&DAG);
9728 dbgs() << " and 2 other values\n");
9729 WorklistRemover DeadNodes(*this);
9730 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9731 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9732 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9733 deleteAndRecombine(N);
9734 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9739 // If this load is directly stored, replace the load value with the stored
9741 // TODO: Handle store large -> read small portion.
9742 // TODO: Handle TRUNCSTORE/LOADEXT
9743 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9744 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9745 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9746 if (PrevST->getBasePtr() == Ptr &&
9747 PrevST->getValue().getValueType() == N->getValueType(0))
9748 return CombineTo(N, Chain.getOperand(1), Chain);
9752 // Try to infer better alignment information than the load already has.
9753 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9754 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9755 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9757 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9758 LD->getValueType(0),
9759 Chain, Ptr, LD->getPointerInfo(),
9761 LD->isVolatile(), LD->isNonTemporal(),
9762 LD->isInvariant(), Align, LD->getAAInfo());
9763 if (NewLoad.getNode() != N)
9764 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9769 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9770 : DAG.getSubtarget().useAA();
9772 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9773 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9776 if (UseAA && LD->isUnindexed()) {
9777 // Walk up chain skipping non-aliasing memory nodes.
9778 SDValue BetterChain = FindBetterChain(N, Chain);
9780 // If there is a better chain.
9781 if (Chain != BetterChain) {
9784 // Replace the chain to void dependency.
9785 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9786 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9787 BetterChain, Ptr, LD->getMemOperand());
9789 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9790 LD->getValueType(0),
9791 BetterChain, Ptr, LD->getMemoryVT(),
9792 LD->getMemOperand());
9795 // Create token factor to keep old chain connected.
9796 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9797 MVT::Other, Chain, ReplLoad.getValue(1));
9799 // Make sure the new and old chains are cleaned up.
9800 AddToWorklist(Token.getNode());
9802 // Replace uses with load result and token factor. Don't add users
9804 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9808 // Try transforming N to an indexed load.
9809 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9810 return SDValue(N, 0);
9812 // Try to slice up N to more direct loads if the slices are mapped to
9813 // different register banks or pairing can take place.
9815 return SDValue(N, 0);
9821 /// \brief Helper structure used to slice a load in smaller loads.
9822 /// Basically a slice is obtained from the following sequence:
9823 /// Origin = load Ty1, Base
9824 /// Shift = srl Ty1 Origin, CstTy Amount
9825 /// Inst = trunc Shift to Ty2
9827 /// Then, it will be rewriten into:
9828 /// Slice = load SliceTy, Base + SliceOffset
9829 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9831 /// SliceTy is deduced from the number of bits that are actually used to
9833 struct LoadedSlice {
9834 /// \brief Helper structure used to compute the cost of a slice.
9836 /// Are we optimizing for code size.
9841 unsigned CrossRegisterBanksCopies;
9845 Cost(bool ForCodeSize = false)
9846 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9847 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9849 /// \brief Get the cost of one isolated slice.
9850 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9851 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9852 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9853 EVT TruncType = LS.Inst->getValueType(0);
9854 EVT LoadedType = LS.getLoadedType();
9855 if (TruncType != LoadedType &&
9856 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9860 /// \brief Account for slicing gain in the current cost.
9861 /// Slicing provide a few gains like removing a shift or a
9862 /// truncate. This method allows to grow the cost of the original
9863 /// load with the gain from this slice.
9864 void addSliceGain(const LoadedSlice &LS) {
9865 // Each slice saves a truncate.
9866 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9867 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9868 LS.Inst->getValueType(0)))
9870 // If there is a shift amount, this slice gets rid of it.
9873 // If this slice can merge a cross register bank copy, account for it.
9874 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9875 ++CrossRegisterBanksCopies;
9878 Cost &operator+=(const Cost &RHS) {
9880 Truncates += RHS.Truncates;
9881 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9887 bool operator==(const Cost &RHS) const {
9888 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9889 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9890 ZExts == RHS.ZExts && Shift == RHS.Shift;
9893 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9895 bool operator<(const Cost &RHS) const {
9896 // Assume cross register banks copies are as expensive as loads.
9897 // FIXME: Do we want some more target hooks?
9898 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9899 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9900 // Unless we are optimizing for code size, consider the
9901 // expensive operation first.
9902 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9903 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9904 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9905 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9908 bool operator>(const Cost &RHS) const { return RHS < *this; }
9910 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9912 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9914 // The last instruction that represent the slice. This should be a
9915 // truncate instruction.
9917 // The original load instruction.
9919 // The right shift amount in bits from the original load.
9921 // The DAG from which Origin came from.
9922 // This is used to get some contextual information about legal types, etc.
9925 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9926 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9927 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9929 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9930 /// \return Result is \p BitWidth and has used bits set to 1 and
9931 /// not used bits set to 0.
9932 APInt getUsedBits() const {
9933 // Reproduce the trunc(lshr) sequence:
9934 // - Start from the truncated value.
9935 // - Zero extend to the desired bit width.
9937 assert(Origin && "No original load to compare against.");
9938 unsigned BitWidth = Origin->getValueSizeInBits(0);
9939 assert(Inst && "This slice is not bound to an instruction");
9940 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9941 "Extracted slice is bigger than the whole type!");
9942 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9943 UsedBits.setAllBits();
9944 UsedBits = UsedBits.zext(BitWidth);
9949 /// \brief Get the size of the slice to be loaded in bytes.
9950 unsigned getLoadedSize() const {
9951 unsigned SliceSize = getUsedBits().countPopulation();
9952 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9953 return SliceSize / 8;
9956 /// \brief Get the type that will be loaded for this slice.
9957 /// Note: This may not be the final type for the slice.
9958 EVT getLoadedType() const {
9959 assert(DAG && "Missing context");
9960 LLVMContext &Ctxt = *DAG->getContext();
9961 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9964 /// \brief Get the alignment of the load used for this slice.
9965 unsigned getAlignment() const {
9966 unsigned Alignment = Origin->getAlignment();
9967 unsigned Offset = getOffsetFromBase();
9969 Alignment = MinAlign(Alignment, Alignment + Offset);
9973 /// \brief Check if this slice can be rewritten with legal operations.
9974 bool isLegal() const {
9975 // An invalid slice is not legal.
9976 if (!Origin || !Inst || !DAG)
9979 // Offsets are for indexed load only, we do not handle that.
9980 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9983 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9985 // Check that the type is legal.
9986 EVT SliceType = getLoadedType();
9987 if (!TLI.isTypeLegal(SliceType))
9990 // Check that the load is legal for this type.
9991 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9994 // Check that the offset can be computed.
9995 // 1. Check its type.
9996 EVT PtrType = Origin->getBasePtr().getValueType();
9997 if (PtrType == MVT::Untyped || PtrType.isExtended())
10000 // 2. Check that it fits in the immediate.
10001 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10004 // 3. Check that the computation is legal.
10005 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10008 // Check that the zext is legal if it needs one.
10009 EVT TruncateType = Inst->getValueType(0);
10010 if (TruncateType != SliceType &&
10011 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10017 /// \brief Get the offset in bytes of this slice in the original chunk of
10019 /// \pre DAG != nullptr.
10020 uint64_t getOffsetFromBase() const {
10021 assert(DAG && "Missing context.");
10022 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10023 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10024 uint64_t Offset = Shift / 8;
10025 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10026 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10027 "The size of the original loaded type is not a multiple of a"
10029 // If Offset is bigger than TySizeInBytes, it means we are loading all
10030 // zeros. This should have been optimized before in the process.
10031 assert(TySizeInBytes > Offset &&
10032 "Invalid shift amount for given loaded size");
10034 Offset = TySizeInBytes - Offset - getLoadedSize();
10038 /// \brief Generate the sequence of instructions to load the slice
10039 /// represented by this object and redirect the uses of this slice to
10040 /// this new sequence of instructions.
10041 /// \pre this->Inst && this->Origin are valid Instructions and this
10042 /// object passed the legal check: LoadedSlice::isLegal returned true.
10043 /// \return The last instruction of the sequence used to load the slice.
10044 SDValue loadSlice() const {
10045 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10046 const SDValue &OldBaseAddr = Origin->getBasePtr();
10047 SDValue BaseAddr = OldBaseAddr;
10048 // Get the offset in that chunk of bytes w.r.t. the endianess.
10049 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10050 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10052 // BaseAddr = BaseAddr + Offset.
10053 EVT ArithType = BaseAddr.getValueType();
10055 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10056 DAG->getConstant(Offset, DL, ArithType));
10059 // Create the type of the loaded slice according to its size.
10060 EVT SliceType = getLoadedType();
10062 // Create the load for the slice.
10063 SDValue LastInst = DAG->getLoad(
10064 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10065 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10066 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10067 // If the final type is not the same as the loaded type, this means that
10068 // we have to pad with zero. Create a zero extend for that.
10069 EVT FinalType = Inst->getValueType(0);
10070 if (SliceType != FinalType)
10072 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10076 /// \brief Check if this slice can be merged with an expensive cross register
10077 /// bank copy. E.g.,
10079 /// f = bitcast i32 i to float
10080 bool canMergeExpensiveCrossRegisterBankCopy() const {
10081 if (!Inst || !Inst->hasOneUse())
10083 SDNode *Use = *Inst->use_begin();
10084 if (Use->getOpcode() != ISD::BITCAST)
10086 assert(DAG && "Missing context");
10087 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10088 EVT ResVT = Use->getValueType(0);
10089 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10090 const TargetRegisterClass *ArgRC =
10091 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10092 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10095 // At this point, we know that we perform a cross-register-bank copy.
10096 // Check if it is expensive.
10097 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10098 // Assume bitcasts are cheap, unless both register classes do not
10099 // explicitly share a common sub class.
10100 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10103 // Check if it will be merged with the load.
10104 // 1. Check the alignment constraint.
10105 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10106 ResVT.getTypeForEVT(*DAG->getContext()));
10108 if (RequiredAlignment > getAlignment())
10111 // 2. Check that the load is a legal operation for that type.
10112 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10115 // 3. Check that we do not have a zext in the way.
10116 if (Inst->getValueType(0) != getLoadedType())
10124 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10125 /// \p UsedBits looks like 0..0 1..1 0..0.
10126 static bool areUsedBitsDense(const APInt &UsedBits) {
10127 // If all the bits are one, this is dense!
10128 if (UsedBits.isAllOnesValue())
10131 // Get rid of the unused bits on the right.
10132 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10133 // Get rid of the unused bits on the left.
10134 if (NarrowedUsedBits.countLeadingZeros())
10135 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10136 // Check that the chunk of bits is completely used.
10137 return NarrowedUsedBits.isAllOnesValue();
10140 /// \brief Check whether or not \p First and \p Second are next to each other
10141 /// in memory. This means that there is no hole between the bits loaded
10142 /// by \p First and the bits loaded by \p Second.
10143 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10144 const LoadedSlice &Second) {
10145 assert(First.Origin == Second.Origin && First.Origin &&
10146 "Unable to match different memory origins.");
10147 APInt UsedBits = First.getUsedBits();
10148 assert((UsedBits & Second.getUsedBits()) == 0 &&
10149 "Slices are not supposed to overlap.");
10150 UsedBits |= Second.getUsedBits();
10151 return areUsedBitsDense(UsedBits);
10154 /// \brief Adjust the \p GlobalLSCost according to the target
10155 /// paring capabilities and the layout of the slices.
10156 /// \pre \p GlobalLSCost should account for at least as many loads as
10157 /// there is in the slices in \p LoadedSlices.
10158 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10159 LoadedSlice::Cost &GlobalLSCost) {
10160 unsigned NumberOfSlices = LoadedSlices.size();
10161 // If there is less than 2 elements, no pairing is possible.
10162 if (NumberOfSlices < 2)
10165 // Sort the slices so that elements that are likely to be next to each
10166 // other in memory are next to each other in the list.
10167 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10168 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10169 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10170 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10172 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10173 // First (resp. Second) is the first (resp. Second) potentially candidate
10174 // to be placed in a paired load.
10175 const LoadedSlice *First = nullptr;
10176 const LoadedSlice *Second = nullptr;
10177 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10178 // Set the beginning of the pair.
10181 Second = &LoadedSlices[CurrSlice];
10183 // If First is NULL, it means we start a new pair.
10184 // Get to the next slice.
10188 EVT LoadedType = First->getLoadedType();
10190 // If the types of the slices are different, we cannot pair them.
10191 if (LoadedType != Second->getLoadedType())
10194 // Check if the target supplies paired loads for this type.
10195 unsigned RequiredAlignment = 0;
10196 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10197 // move to the next pair, this type is hopeless.
10201 // Check if we meet the alignment requirement.
10202 if (RequiredAlignment > First->getAlignment())
10205 // Check that both loads are next to each other in memory.
10206 if (!areSlicesNextToEachOther(*First, *Second))
10209 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10210 --GlobalLSCost.Loads;
10211 // Move to the next pair.
10216 /// \brief Check the profitability of all involved LoadedSlice.
10217 /// Currently, it is considered profitable if there is exactly two
10218 /// involved slices (1) which are (2) next to each other in memory, and
10219 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10221 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10222 /// the elements themselves.
10224 /// FIXME: When the cost model will be mature enough, we can relax
10225 /// constraints (1) and (2).
10226 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10227 const APInt &UsedBits, bool ForCodeSize) {
10228 unsigned NumberOfSlices = LoadedSlices.size();
10229 if (StressLoadSlicing)
10230 return NumberOfSlices > 1;
10233 if (NumberOfSlices != 2)
10237 if (!areUsedBitsDense(UsedBits))
10241 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10242 // The original code has one big load.
10243 OrigCost.Loads = 1;
10244 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10245 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10246 // Accumulate the cost of all the slices.
10247 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10248 GlobalSlicingCost += SliceCost;
10250 // Account as cost in the original configuration the gain obtained
10251 // with the current slices.
10252 OrigCost.addSliceGain(LS);
10255 // If the target supports paired load, adjust the cost accordingly.
10256 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10257 return OrigCost > GlobalSlicingCost;
10260 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10261 /// operations, split it in the various pieces being extracted.
10263 /// This sort of thing is introduced by SROA.
10264 /// This slicing takes care not to insert overlapping loads.
10265 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10266 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10267 if (Level < AfterLegalizeDAG)
10270 LoadSDNode *LD = cast<LoadSDNode>(N);
10271 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10272 !LD->getValueType(0).isInteger())
10275 // Keep track of already used bits to detect overlapping values.
10276 // In that case, we will just abort the transformation.
10277 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10279 SmallVector<LoadedSlice, 4> LoadedSlices;
10281 // Check if this load is used as several smaller chunks of bits.
10282 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10283 // of computation for each trunc.
10284 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10285 UI != UIEnd; ++UI) {
10286 // Skip the uses of the chain.
10287 if (UI.getUse().getResNo() != 0)
10290 SDNode *User = *UI;
10291 unsigned Shift = 0;
10293 // Check if this is a trunc(lshr).
10294 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10295 isa<ConstantSDNode>(User->getOperand(1))) {
10296 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10297 User = *User->use_begin();
10300 // At this point, User is a Truncate, iff we encountered, trunc or
10302 if (User->getOpcode() != ISD::TRUNCATE)
10305 // The width of the type must be a power of 2 and greater than 8-bits.
10306 // Otherwise the load cannot be represented in LLVM IR.
10307 // Moreover, if we shifted with a non-8-bits multiple, the slice
10308 // will be across several bytes. We do not support that.
10309 unsigned Width = User->getValueSizeInBits(0);
10310 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10313 // Build the slice for this chain of computations.
10314 LoadedSlice LS(User, LD, Shift, &DAG);
10315 APInt CurrentUsedBits = LS.getUsedBits();
10317 // Check if this slice overlaps with another.
10318 if ((CurrentUsedBits & UsedBits) != 0)
10320 // Update the bits used globally.
10321 UsedBits |= CurrentUsedBits;
10323 // Check if the new slice would be legal.
10327 // Record the slice.
10328 LoadedSlices.push_back(LS);
10331 // Abort slicing if it does not seem to be profitable.
10332 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10337 // Rewrite each chain to use an independent load.
10338 // By construction, each chain can be represented by a unique load.
10340 // Prepare the argument for the new token factor for all the slices.
10341 SmallVector<SDValue, 8> ArgChains;
10342 for (SmallVectorImpl<LoadedSlice>::const_iterator
10343 LSIt = LoadedSlices.begin(),
10344 LSItEnd = LoadedSlices.end();
10345 LSIt != LSItEnd; ++LSIt) {
10346 SDValue SliceInst = LSIt->loadSlice();
10347 CombineTo(LSIt->Inst, SliceInst, true);
10348 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10349 SliceInst = SliceInst.getOperand(0);
10350 assert(SliceInst->getOpcode() == ISD::LOAD &&
10351 "It takes more than a zext to get to the loaded slice!!");
10352 ArgChains.push_back(SliceInst.getValue(1));
10355 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10357 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10361 /// Check to see if V is (and load (ptr), imm), where the load is having
10362 /// specific bytes cleared out. If so, return the byte size being masked out
10363 /// and the shift amount.
10364 static std::pair<unsigned, unsigned>
10365 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10366 std::pair<unsigned, unsigned> Result(0, 0);
10368 // Check for the structure we're looking for.
10369 if (V->getOpcode() != ISD::AND ||
10370 !isa<ConstantSDNode>(V->getOperand(1)) ||
10371 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10374 // Check the chain and pointer.
10375 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10376 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10378 // The store should be chained directly to the load or be an operand of a
10380 if (LD == Chain.getNode())
10382 else if (Chain->getOpcode() != ISD::TokenFactor)
10383 return Result; // Fail.
10386 for (const SDValue &ChainOp : Chain->op_values())
10387 if (ChainOp.getNode() == LD) {
10391 if (!isOk) return Result;
10394 // This only handles simple types.
10395 if (V.getValueType() != MVT::i16 &&
10396 V.getValueType() != MVT::i32 &&
10397 V.getValueType() != MVT::i64)
10400 // Check the constant mask. Invert it so that the bits being masked out are
10401 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10402 // follow the sign bit for uniformity.
10403 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10404 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10405 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10406 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10407 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10408 if (NotMaskLZ == 64) return Result; // All zero mask.
10410 // See if we have a continuous run of bits. If so, we have 0*1+0*
10411 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10414 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10415 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10416 NotMaskLZ -= 64-V.getValueSizeInBits();
10418 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10419 switch (MaskedBytes) {
10423 default: return Result; // All one mask, or 5-byte mask.
10426 // Verify that the first bit starts at a multiple of mask so that the access
10427 // is aligned the same as the access width.
10428 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10430 Result.first = MaskedBytes;
10431 Result.second = NotMaskTZ/8;
10436 /// Check to see if IVal is something that provides a value as specified by
10437 /// MaskInfo. If so, replace the specified store with a narrower store of
10438 /// truncated IVal.
10440 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10441 SDValue IVal, StoreSDNode *St,
10443 unsigned NumBytes = MaskInfo.first;
10444 unsigned ByteShift = MaskInfo.second;
10445 SelectionDAG &DAG = DC->getDAG();
10447 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10448 // that uses this. If not, this is not a replacement.
10449 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10450 ByteShift*8, (ByteShift+NumBytes)*8);
10451 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10453 // Check that it is legal on the target to do this. It is legal if the new
10454 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10456 MVT VT = MVT::getIntegerVT(NumBytes*8);
10457 if (!DC->isTypeLegal(VT))
10460 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10461 // shifted by ByteShift and truncated down to NumBytes.
10464 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10465 DAG.getConstant(ByteShift*8, DL,
10466 DC->getShiftAmountTy(IVal.getValueType())));
10469 // Figure out the offset for the store and the alignment of the access.
10471 unsigned NewAlign = St->getAlignment();
10473 if (DAG.getDataLayout().isLittleEndian())
10474 StOffset = ByteShift;
10476 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10478 SDValue Ptr = St->getBasePtr();
10481 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10482 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10483 NewAlign = MinAlign(NewAlign, StOffset);
10486 // Truncate down to the new size.
10487 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10490 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10491 St->getPointerInfo().getWithOffset(StOffset),
10492 false, false, NewAlign).getNode();
10496 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10497 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10498 /// narrowing the load and store if it would end up being a win for performance
10500 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10501 StoreSDNode *ST = cast<StoreSDNode>(N);
10502 if (ST->isVolatile())
10505 SDValue Chain = ST->getChain();
10506 SDValue Value = ST->getValue();
10507 SDValue Ptr = ST->getBasePtr();
10508 EVT VT = Value.getValueType();
10510 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10513 unsigned Opc = Value.getOpcode();
10515 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10516 // is a byte mask indicating a consecutive number of bytes, check to see if
10517 // Y is known to provide just those bytes. If so, we try to replace the
10518 // load + replace + store sequence with a single (narrower) store, which makes
10520 if (Opc == ISD::OR) {
10521 std::pair<unsigned, unsigned> MaskedLoad;
10522 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10523 if (MaskedLoad.first)
10524 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10525 Value.getOperand(1), ST,this))
10526 return SDValue(NewST, 0);
10528 // Or is commutative, so try swapping X and Y.
10529 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10530 if (MaskedLoad.first)
10531 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10532 Value.getOperand(0), ST,this))
10533 return SDValue(NewST, 0);
10536 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10537 Value.getOperand(1).getOpcode() != ISD::Constant)
10540 SDValue N0 = Value.getOperand(0);
10541 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10542 Chain == SDValue(N0.getNode(), 1)) {
10543 LoadSDNode *LD = cast<LoadSDNode>(N0);
10544 if (LD->getBasePtr() != Ptr ||
10545 LD->getPointerInfo().getAddrSpace() !=
10546 ST->getPointerInfo().getAddrSpace())
10549 // Find the type to narrow it the load / op / store to.
10550 SDValue N1 = Value.getOperand(1);
10551 unsigned BitWidth = N1.getValueSizeInBits();
10552 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10553 if (Opc == ISD::AND)
10554 Imm ^= APInt::getAllOnesValue(BitWidth);
10555 if (Imm == 0 || Imm.isAllOnesValue())
10557 unsigned ShAmt = Imm.countTrailingZeros();
10558 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10559 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10560 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10561 // The narrowing should be profitable, the load/store operation should be
10562 // legal (or custom) and the store size should be equal to the NewVT width.
10563 while (NewBW < BitWidth &&
10564 (NewVT.getStoreSizeInBits() != NewBW ||
10565 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10566 !TLI.isNarrowingProfitable(VT, NewVT))) {
10567 NewBW = NextPowerOf2(NewBW);
10568 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10570 if (NewBW >= BitWidth)
10573 // If the lsb changed does not start at the type bitwidth boundary,
10574 // start at the previous one.
10576 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10577 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10578 std::min(BitWidth, ShAmt + NewBW));
10579 if ((Imm & Mask) == Imm) {
10580 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10581 if (Opc == ISD::AND)
10582 NewImm ^= APInt::getAllOnesValue(NewBW);
10583 uint64_t PtrOff = ShAmt / 8;
10584 // For big endian targets, we need to adjust the offset to the pointer to
10585 // load the correct bytes.
10586 if (DAG.getDataLayout().isBigEndian())
10587 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10589 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10590 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10591 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10594 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10595 Ptr.getValueType(), Ptr,
10596 DAG.getConstant(PtrOff, SDLoc(LD),
10597 Ptr.getValueType()));
10598 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10599 LD->getChain(), NewPtr,
10600 LD->getPointerInfo().getWithOffset(PtrOff),
10601 LD->isVolatile(), LD->isNonTemporal(),
10602 LD->isInvariant(), NewAlign,
10604 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10605 DAG.getConstant(NewImm, SDLoc(Value),
10607 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10609 ST->getPointerInfo().getWithOffset(PtrOff),
10610 false, false, NewAlign);
10612 AddToWorklist(NewPtr.getNode());
10613 AddToWorklist(NewLD.getNode());
10614 AddToWorklist(NewVal.getNode());
10615 WorklistRemover DeadNodes(*this);
10616 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10625 /// For a given floating point load / store pair, if the load value isn't used
10626 /// by any other operations, then consider transforming the pair to integer
10627 /// load / store operations if the target deems the transformation profitable.
10628 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10629 StoreSDNode *ST = cast<StoreSDNode>(N);
10630 SDValue Chain = ST->getChain();
10631 SDValue Value = ST->getValue();
10632 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10633 Value.hasOneUse() &&
10634 Chain == SDValue(Value.getNode(), 1)) {
10635 LoadSDNode *LD = cast<LoadSDNode>(Value);
10636 EVT VT = LD->getMemoryVT();
10637 if (!VT.isFloatingPoint() ||
10638 VT != ST->getMemoryVT() ||
10639 LD->isNonTemporal() ||
10640 ST->isNonTemporal() ||
10641 LD->getPointerInfo().getAddrSpace() != 0 ||
10642 ST->getPointerInfo().getAddrSpace() != 0)
10645 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10646 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10647 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10648 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10649 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10652 unsigned LDAlign = LD->getAlignment();
10653 unsigned STAlign = ST->getAlignment();
10654 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10655 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10656 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10659 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10660 LD->getChain(), LD->getBasePtr(),
10661 LD->getPointerInfo(),
10662 false, false, false, LDAlign);
10664 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10665 NewLD, ST->getBasePtr(),
10666 ST->getPointerInfo(),
10667 false, false, STAlign);
10669 AddToWorklist(NewLD.getNode());
10670 AddToWorklist(NewST.getNode());
10671 WorklistRemover DeadNodes(*this);
10672 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10681 /// Helper struct to parse and store a memory address as base + index + offset.
10682 /// We ignore sign extensions when it is safe to do so.
10683 /// The following two expressions are not equivalent. To differentiate we need
10684 /// to store whether there was a sign extension involved in the index
10686 /// (load (i64 add (i64 copyfromreg %c)
10687 /// (i64 signextend (add (i8 load %index)
10691 /// (load (i64 add (i64 copyfromreg %c)
10692 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10694 struct BaseIndexOffset {
10698 bool IsIndexSignExt;
10700 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10702 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10703 bool IsIndexSignExt) :
10704 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10706 bool equalBaseIndex(const BaseIndexOffset &Other) {
10707 return Other.Base == Base && Other.Index == Index &&
10708 Other.IsIndexSignExt == IsIndexSignExt;
10711 /// Parses tree in Ptr for base, index, offset addresses.
10712 static BaseIndexOffset match(SDValue Ptr) {
10713 bool IsIndexSignExt = false;
10715 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10716 // instruction, then it could be just the BASE or everything else we don't
10717 // know how to handle. Just use Ptr as BASE and give up.
10718 if (Ptr->getOpcode() != ISD::ADD)
10719 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10721 // We know that we have at least an ADD instruction. Try to pattern match
10722 // the simple case of BASE + OFFSET.
10723 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10724 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10725 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10729 // Inside a loop the current BASE pointer is calculated using an ADD and a
10730 // MUL instruction. In this case Ptr is the actual BASE pointer.
10731 // (i64 add (i64 %array_ptr)
10732 // (i64 mul (i64 %induction_var)
10733 // (i64 %element_size)))
10734 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10735 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10737 // Look at Base + Index + Offset cases.
10738 SDValue Base = Ptr->getOperand(0);
10739 SDValue IndexOffset = Ptr->getOperand(1);
10741 // Skip signextends.
10742 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10743 IndexOffset = IndexOffset->getOperand(0);
10744 IsIndexSignExt = true;
10747 // Either the case of Base + Index (no offset) or something else.
10748 if (IndexOffset->getOpcode() != ISD::ADD)
10749 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10751 // Now we have the case of Base + Index + offset.
10752 SDValue Index = IndexOffset->getOperand(0);
10753 SDValue Offset = IndexOffset->getOperand(1);
10755 if (!isa<ConstantSDNode>(Offset))
10756 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10758 // Ignore signextends.
10759 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10760 Index = Index->getOperand(0);
10761 IsIndexSignExt = true;
10762 } else IsIndexSignExt = false;
10764 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10765 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10770 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10772 ArrayRef<MemOpLink> Stores,
10773 SmallVectorImpl<SDValue> &Chains,
10775 SmallVector<SDValue, 8> BuildVector;
10777 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10778 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10779 Chains.push_back(St->getChain());
10780 BuildVector.push_back(St->getValue());
10783 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10786 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10787 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10788 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10789 // Make sure we have something to merge.
10793 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10794 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10795 unsigned LatestNodeUsed = 0;
10797 for (unsigned i=0; i < NumStores; ++i) {
10798 // Find a chain for the new wide-store operand. Notice that some
10799 // of the store nodes that we found may not be selected for inclusion
10800 // in the wide store. The chain we use needs to be the chain of the
10801 // latest store node which is *used* and replaced by the wide store.
10802 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10803 LatestNodeUsed = i;
10806 SmallVector<SDValue, 8> Chains;
10808 // The latest Node in the DAG.
10809 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10810 SDLoc DL(StoreNodes[0].MemNode);
10814 bool IsVec = MemVT.isVector();
10815 unsigned Elts = NumStores;
10817 // When merging vector stores, get the total number of elements.
10818 Elts *= MemVT.getVectorNumElements();
10820 // Get the type for the merged vector store.
10821 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10822 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10824 if (IsConstantSrc) {
10825 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10827 SmallVector<SDValue, 8> Ops;
10828 for (unsigned i = 0; i < NumStores; ++i) {
10829 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10830 SDValue Val = St->getValue();
10831 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10832 if (Val.getValueType() != MemVT)
10834 Ops.push_back(Val);
10835 Chains.push_back(St->getChain());
10838 // Build the extracted vector elements back into a vector.
10839 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10842 // We should always use a vector store when merging extracted vector
10843 // elements, so this path implies a store of constants.
10844 assert(IsConstantSrc && "Merged vector elements should use vector store");
10846 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10847 APInt StoreInt(SizeInBits, 0);
10849 // Construct a single integer constant which is made of the smaller
10850 // constant inputs.
10851 bool IsLE = DAG.getDataLayout().isLittleEndian();
10852 for (unsigned i = 0; i < NumStores; ++i) {
10853 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10854 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10855 Chains.push_back(St->getChain());
10857 SDValue Val = St->getValue();
10858 StoreInt <<= ElementSizeBytes * 8;
10859 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10860 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10861 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10862 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10864 llvm_unreachable("Invalid constant element type");
10868 // Create the new Load and Store operations.
10869 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10870 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10873 assert(!Chains.empty());
10875 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10876 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
10877 FirstInChain->getBasePtr(),
10878 FirstInChain->getPointerInfo(),
10880 FirstInChain->getAlignment());
10882 // Replace the last store with the new store
10883 CombineTo(LatestOp, NewStore);
10884 // Erase all other stores.
10885 for (unsigned i = 0; i < NumStores; ++i) {
10886 if (StoreNodes[i].MemNode == LatestOp)
10888 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10889 // ReplaceAllUsesWith will replace all uses that existed when it was
10890 // called, but graph optimizations may cause new ones to appear. For
10891 // example, the case in pr14333 looks like
10893 // St's chain -> St -> another store -> X
10895 // And the only difference from St to the other store is the chain.
10896 // When we change it's chain to be St's chain they become identical,
10897 // get CSEed and the net result is that X is now a use of St.
10898 // Since we know that St is redundant, just iterate.
10899 while (!St->use_empty())
10900 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10901 deleteAndRecombine(St);
10907 void DAGCombiner::getStoreMergeAndAliasCandidates(
10908 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10909 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10910 // This holds the base pointer, index, and the offset in bytes from the base
10912 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10914 // We must have a base and an offset.
10915 if (!BasePtr.Base.getNode())
10918 // Do not handle stores to undef base pointers.
10919 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10922 // Walk up the chain and look for nodes with offsets from the same
10923 // base pointer. Stop when reaching an instruction with a different kind
10924 // or instruction which has a different base pointer.
10925 EVT MemVT = St->getMemoryVT();
10927 StoreSDNode *Index = St;
10930 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10931 : DAG.getSubtarget().useAA();
10934 // Look at other users of the same chain. Stores on the same chain do not
10935 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10936 // to be on the same chain, so don't bother looking at adjacent chains.
10938 SDValue Chain = St->getChain();
10939 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10940 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10941 if (I.getOperandNo() != 0)
10944 if (OtherST->isVolatile() || OtherST->isIndexed())
10947 if (OtherST->getMemoryVT() != MemVT)
10950 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10952 if (Ptr.equalBaseIndex(BasePtr))
10953 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
10961 // If the chain has more than one use, then we can't reorder the mem ops.
10962 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10965 // Find the base pointer and offset for this memory node.
10966 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10968 // Check that the base pointer is the same as the original one.
10969 if (!Ptr.equalBaseIndex(BasePtr))
10972 // The memory operands must not be volatile.
10973 if (Index->isVolatile() || Index->isIndexed())
10977 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10978 if (St->isTruncatingStore())
10981 // The stored memory type must be the same.
10982 if (Index->getMemoryVT() != MemVT)
10985 // We found a potential memory operand to merge.
10986 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10988 // Find the next memory operand in the chain. If the next operand in the
10989 // chain is a store then move up and continue the scan with the next
10990 // memory operand. If the next operand is a load save it and use alias
10991 // information to check if it interferes with anything.
10992 SDNode *NextInChain = Index->getChain().getNode();
10994 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10995 // We found a store node. Use it for the next iteration.
10998 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10999 if (Ldn->isVolatile()) {
11004 // Save the load node for later. Continue the scan.
11005 AliasLoadNodes.push_back(Ldn);
11006 NextInChain = Ldn->getChain().getNode();
11016 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11017 if (OptLevel == CodeGenOpt::None)
11020 EVT MemVT = St->getMemoryVT();
11021 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11022 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11023 Attribute::NoImplicitFloat);
11025 // This function cannot currently deal with non-byte-sized memory sizes.
11026 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11029 if (!MemVT.isSimple())
11032 // Perform an early exit check. Do not bother looking at stored values that
11033 // are not constants, loads, or extracted vector elements.
11034 SDValue StoredVal = St->getValue();
11035 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11036 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11037 isa<ConstantFPSDNode>(StoredVal);
11038 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11039 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11041 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11044 // Don't merge vectors into wider vectors if the source data comes from loads.
11045 // TODO: This restriction can be lifted by using logic similar to the
11046 // ExtractVecSrc case.
11047 if (MemVT.isVector() && IsLoadSrc)
11050 // Only look at ends of store sequences.
11051 SDValue Chain = SDValue(St, 0);
11052 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11055 // Save the LoadSDNodes that we find in the chain.
11056 // We need to make sure that these nodes do not interfere with
11057 // any of the store nodes.
11058 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11060 // Save the StoreSDNodes that we find in the chain.
11061 SmallVector<MemOpLink, 8> StoreNodes;
11063 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11065 // Check if there is anything to merge.
11066 if (StoreNodes.size() < 2)
11069 // Sort the memory operands according to their distance from the base pointer.
11070 std::sort(StoreNodes.begin(), StoreNodes.end(),
11071 [](MemOpLink LHS, MemOpLink RHS) {
11072 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11073 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11074 LHS.SequenceNum > RHS.SequenceNum);
11077 // Scan the memory operations on the chain and find the first non-consecutive
11078 // store memory address.
11079 unsigned LastConsecutiveStore = 0;
11080 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11081 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11083 // Check that the addresses are consecutive starting from the second
11084 // element in the list of stores.
11086 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11087 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11091 bool Alias = false;
11092 // Check if this store interferes with any of the loads that we found.
11093 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11094 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11098 // We found a load that alias with this store. Stop the sequence.
11102 // Mark this node as useful.
11103 LastConsecutiveStore = i;
11106 // The node with the lowest store address.
11107 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11108 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11109 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11110 LLVMContext &Context = *DAG.getContext();
11111 const DataLayout &DL = DAG.getDataLayout();
11113 // Store the constants into memory as one consecutive store.
11114 if (IsConstantSrc) {
11115 unsigned LastLegalType = 0;
11116 unsigned LastLegalVectorType = 0;
11117 bool NonZero = false;
11118 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11119 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11120 SDValue StoredVal = St->getValue();
11122 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11123 NonZero |= !C->isNullValue();
11124 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11125 NonZero |= !C->getConstantFPValue()->isNullValue();
11131 // Find a legal type for the constant store.
11132 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11133 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11135 if (TLI.isTypeLegal(StoreTy) &&
11136 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11137 FirstStoreAlign, &IsFast) && IsFast) {
11138 LastLegalType = i+1;
11139 // Or check whether a truncstore is legal.
11140 } else if (TLI.getTypeAction(Context, StoreTy) ==
11141 TargetLowering::TypePromoteInteger) {
11142 EVT LegalizedStoredValueTy =
11143 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11144 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11145 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11146 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11148 LastLegalType = i + 1;
11152 // We only use vectors if the constant is known to be zero or the target
11153 // allows it and the function is not marked with the noimplicitfloat
11155 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11158 // Find a legal type for the vector store.
11159 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11160 if (TLI.isTypeLegal(Ty) &&
11161 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11162 FirstStoreAlign, &IsFast) && IsFast)
11163 LastLegalVectorType = i + 1;
11167 // Check if we found a legal integer type to store.
11168 if (LastLegalType == 0 && LastLegalVectorType == 0)
11171 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11172 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11174 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11178 // When extracting multiple vector elements, try to store them
11179 // in one vector store rather than a sequence of scalar stores.
11180 if (IsExtractVecSrc) {
11181 unsigned NumStoresToMerge = 0;
11182 bool IsVec = MemVT.isVector();
11183 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11184 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11185 unsigned StoreValOpcode = St->getValue().getOpcode();
11186 // This restriction could be loosened.
11187 // Bail out if any stored values are not elements extracted from a vector.
11188 // It should be possible to handle mixed sources, but load sources need
11189 // more careful handling (see the block of code below that handles
11190 // consecutive loads).
11191 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11192 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11195 // Find a legal type for the vector store.
11196 unsigned Elts = i + 1;
11198 // When merging vector stores, get the total number of elements.
11199 Elts *= MemVT.getVectorNumElements();
11201 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11203 if (TLI.isTypeLegal(Ty) &&
11204 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11205 FirstStoreAlign, &IsFast) && IsFast)
11206 NumStoresToMerge = i + 1;
11209 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11213 // Below we handle the case of multiple consecutive stores that
11214 // come from multiple consecutive loads. We merge them into a single
11215 // wide load and a single wide store.
11217 // Look for load nodes which are used by the stored values.
11218 SmallVector<MemOpLink, 8> LoadNodes;
11220 // Find acceptable loads. Loads need to have the same chain (token factor),
11221 // must not be zext, volatile, indexed, and they must be consecutive.
11222 BaseIndexOffset LdBasePtr;
11223 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11224 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11225 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11228 // Loads must only have one use.
11229 if (!Ld->hasNUsesOfValue(1, 0))
11232 // The memory operands must not be volatile.
11233 if (Ld->isVolatile() || Ld->isIndexed())
11236 // We do not accept ext loads.
11237 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11240 // The stored memory type must be the same.
11241 if (Ld->getMemoryVT() != MemVT)
11244 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11245 // If this is not the first ptr that we check.
11246 if (LdBasePtr.Base.getNode()) {
11247 // The base ptr must be the same.
11248 if (!LdPtr.equalBaseIndex(LdBasePtr))
11251 // Check that all other base pointers are the same as this one.
11255 // We found a potential memory operand to merge.
11256 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11259 if (LoadNodes.size() < 2)
11262 // If we have load/store pair instructions and we only have two values,
11264 unsigned RequiredAlignment;
11265 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11266 St->getAlignment() >= RequiredAlignment)
11269 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11270 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11271 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11273 // Scan the memory operations on the chain and find the first non-consecutive
11274 // load memory address. These variables hold the index in the store node
11276 unsigned LastConsecutiveLoad = 0;
11277 // This variable refers to the size and not index in the array.
11278 unsigned LastLegalVectorType = 0;
11279 unsigned LastLegalIntegerType = 0;
11280 StartAddress = LoadNodes[0].OffsetFromBase;
11281 SDValue FirstChain = FirstLoad->getChain();
11282 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11283 // All loads much share the same chain.
11284 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11287 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11288 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11290 LastConsecutiveLoad = i;
11291 // Find a legal type for the vector store.
11292 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11293 bool IsFastSt, IsFastLd;
11294 if (TLI.isTypeLegal(StoreTy) &&
11295 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11296 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11297 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11298 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11299 LastLegalVectorType = i + 1;
11302 // Find a legal type for the integer store.
11303 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11304 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11305 if (TLI.isTypeLegal(StoreTy) &&
11306 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11307 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11308 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11309 FirstLoadAlign, &IsFastLd) && IsFastLd)
11310 LastLegalIntegerType = i + 1;
11311 // Or check whether a truncstore and extload is legal.
11312 else if (TLI.getTypeAction(Context, StoreTy) ==
11313 TargetLowering::TypePromoteInteger) {
11314 EVT LegalizedStoredValueTy =
11315 TLI.getTypeToTransformTo(Context, StoreTy);
11316 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11317 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11318 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11319 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11320 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11321 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11323 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11324 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11326 LastLegalIntegerType = i+1;
11330 // Only use vector types if the vector type is larger than the integer type.
11331 // If they are the same, use integers.
11332 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11333 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11335 // We add +1 here because the LastXXX variables refer to location while
11336 // the NumElem refers to array/index size.
11337 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11338 NumElem = std::min(LastLegalType, NumElem);
11343 // Collect the chains from all merged stores.
11344 SmallVector<SDValue, 8> MergeStoreChains;
11345 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11347 // The latest Node in the DAG.
11348 unsigned LatestNodeUsed = 0;
11349 for (unsigned i=1; i<NumElem; ++i) {
11350 // Find a chain for the new wide-store operand. Notice that some
11351 // of the store nodes that we found may not be selected for inclusion
11352 // in the wide store. The chain we use needs to be the chain of the
11353 // latest store node which is *used* and replaced by the wide store.
11354 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11355 LatestNodeUsed = i;
11357 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11360 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11362 // Find if it is better to use vectors or integers to load and store
11366 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11368 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11369 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11372 SDLoc LoadDL(LoadNodes[0].MemNode);
11373 SDLoc StoreDL(StoreNodes[0].MemNode);
11375 // The merged loads are required to have the same chain, so using the first's
11376 // chain is acceptable.
11377 SDValue NewLoad = DAG.getLoad(
11378 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11379 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11381 SDValue NewStoreChain =
11382 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11384 SDValue NewStore = DAG.getStore(
11385 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11386 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11388 // Replace one of the loads with the new load.
11389 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11390 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11391 SDValue(NewLoad.getNode(), 1));
11393 // Remove the rest of the load chains.
11394 for (unsigned i = 1; i < NumElem ; ++i) {
11395 // Replace all chain users of the old load nodes with the chain of the new
11397 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11398 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11401 // Replace the last store with the new store.
11402 CombineTo(LatestOp, NewStore);
11403 // Erase all other stores.
11404 for (unsigned i = 0; i < NumElem ; ++i) {
11405 // Remove all Store nodes.
11406 if (StoreNodes[i].MemNode == LatestOp)
11408 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11409 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11410 deleteAndRecombine(St);
11416 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11420 // Replace the chain to avoid dependency.
11421 if (ST->isTruncatingStore()) {
11422 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11423 ST->getBasePtr(), ST->getMemoryVT(),
11424 ST->getMemOperand());
11426 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11427 ST->getMemOperand());
11430 // Create token to keep both nodes around.
11431 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11432 MVT::Other, ST->getChain(), ReplStore);
11434 // Make sure the new and old chains are cleaned up.
11435 AddToWorklist(Token.getNode());
11437 // Don't add users to work list.
11438 return CombineTo(ST, Token, false);
11441 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11442 SDValue Value = ST->getValue();
11443 if (Value.getOpcode() == ISD::TargetConstantFP)
11448 SDValue Chain = ST->getChain();
11449 SDValue Ptr = ST->getBasePtr();
11451 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11453 // NOTE: If the original store is volatile, this transform must not increase
11454 // the number of stores. For example, on x86-32 an f64 can be stored in one
11455 // processor operation but an i64 (which is not legal) requires two. So the
11456 // transform should not be done in this case.
11459 switch (CFP->getSimpleValueType(0).SimpleTy) {
11461 llvm_unreachable("Unknown FP type");
11462 case MVT::f16: // We don't do this for these yet.
11468 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11469 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11471 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11472 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11474 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11479 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11480 !ST->isVolatile()) ||
11481 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11483 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11484 getZExtValue(), SDLoc(CFP), MVT::i64);
11485 return DAG.getStore(Chain, DL, Tmp,
11486 Ptr, ST->getMemOperand());
11489 if (!ST->isVolatile() &&
11490 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11491 // Many FP stores are not made apparent until after legalize, e.g. for
11492 // argument passing. Since this is so common, custom legalize the
11493 // 64-bit integer store into two 32-bit stores.
11494 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11495 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11496 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11497 if (DAG.getDataLayout().isBigEndian())
11500 unsigned Alignment = ST->getAlignment();
11501 bool isVolatile = ST->isVolatile();
11502 bool isNonTemporal = ST->isNonTemporal();
11503 AAMDNodes AAInfo = ST->getAAInfo();
11505 SDValue St0 = DAG.getStore(Chain, DL, Lo,
11506 Ptr, ST->getPointerInfo(),
11507 isVolatile, isNonTemporal,
11508 ST->getAlignment(), AAInfo);
11509 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11510 DAG.getConstant(4, DL, Ptr.getValueType()));
11511 Alignment = MinAlign(Alignment, 4U);
11512 SDValue St1 = DAG.getStore(Chain, DL, Hi,
11513 Ptr, ST->getPointerInfo().getWithOffset(4),
11514 isVolatile, isNonTemporal,
11515 Alignment, AAInfo);
11516 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11524 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11525 StoreSDNode *ST = cast<StoreSDNode>(N);
11526 SDValue Chain = ST->getChain();
11527 SDValue Value = ST->getValue();
11528 SDValue Ptr = ST->getBasePtr();
11530 // If this is a store of a bit convert, store the input value if the
11531 // resultant store does not need a higher alignment than the original.
11532 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11533 ST->isUnindexed()) {
11534 unsigned OrigAlign = ST->getAlignment();
11535 EVT SVT = Value.getOperand(0).getValueType();
11536 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11537 SVT.getTypeForEVT(*DAG.getContext()));
11538 if (Align <= OrigAlign &&
11539 ((!LegalOperations && !ST->isVolatile()) ||
11540 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11541 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11542 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11543 ST->isNonTemporal(), OrigAlign,
11547 // Turn 'store undef, Ptr' -> nothing.
11548 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11551 // Try to infer better alignment information than the store already has.
11552 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11553 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11554 if (Align > ST->getAlignment()) {
11556 DAG.getTruncStore(Chain, SDLoc(N), Value,
11557 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11558 ST->isVolatile(), ST->isNonTemporal(), Align,
11560 if (NewStore.getNode() != N)
11561 return CombineTo(ST, NewStore, true);
11566 // Try transforming a pair floating point load / store ops to integer
11567 // load / store ops.
11568 if (SDValue NewST = TransformFPLoadStorePair(N))
11571 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11572 : DAG.getSubtarget().useAA();
11574 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11575 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11578 if (UseAA && ST->isUnindexed()) {
11579 // FIXME: We should do this even without AA enabled. AA will just allow
11580 // FindBetterChain to work in more situations. The problem with this is that
11581 // any combine that expects memory operations to be on consecutive chains
11582 // first needs to be updated to look for users of the same chain.
11584 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11585 // adjacent stores.
11586 if (findBetterNeighborChains(ST)) {
11587 // replaceStoreChain uses CombineTo, which handled all of the worklist
11588 // manipulation. Return the original node to not do anything else.
11589 return SDValue(ST, 0);
11593 // Try transforming N to an indexed store.
11594 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11595 return SDValue(N, 0);
11597 // FIXME: is there such a thing as a truncating indexed store?
11598 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11599 Value.getValueType().isInteger()) {
11600 // See if we can simplify the input to this truncstore with knowledge that
11601 // only the low bits are being used. For example:
11602 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11604 GetDemandedBits(Value,
11605 APInt::getLowBitsSet(
11606 Value.getValueType().getScalarType().getSizeInBits(),
11607 ST->getMemoryVT().getScalarType().getSizeInBits()));
11608 AddToWorklist(Value.getNode());
11609 if (Shorter.getNode())
11610 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11611 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11613 // Otherwise, see if we can simplify the operation with
11614 // SimplifyDemandedBits, which only works if the value has a single use.
11615 if (SimplifyDemandedBits(Value,
11616 APInt::getLowBitsSet(
11617 Value.getValueType().getScalarType().getSizeInBits(),
11618 ST->getMemoryVT().getScalarType().getSizeInBits())))
11619 return SDValue(N, 0);
11622 // If this is a load followed by a store to the same location, then the store
11624 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11625 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11626 ST->isUnindexed() && !ST->isVolatile() &&
11627 // There can't be any side effects between the load and store, such as
11628 // a call or store.
11629 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11630 // The store is dead, remove it.
11635 // If this is a store followed by a store with the same value to the same
11636 // location, then the store is dead/noop.
11637 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11638 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11639 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11640 ST1->isUnindexed() && !ST1->isVolatile()) {
11641 // The store is dead, remove it.
11646 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11647 // truncating store. We can do this even if this is already a truncstore.
11648 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11649 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11650 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11651 ST->getMemoryVT())) {
11652 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11653 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11656 // Only perform this optimization before the types are legal, because we
11657 // don't want to perform this optimization on every DAGCombine invocation.
11659 bool EverChanged = false;
11662 // There can be multiple store sequences on the same chain.
11663 // Keep trying to merge store sequences until we are unable to do so
11664 // or until we merge the last store on the chain.
11665 bool Changed = MergeConsecutiveStores(ST);
11666 EverChanged |= Changed;
11667 if (!Changed) break;
11668 } while (ST->getOpcode() != ISD::DELETED_NODE);
11671 return SDValue(N, 0);
11674 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11676 // Make sure to do this only after attempting to merge stores in order to
11677 // avoid changing the types of some subset of stores due to visit order,
11678 // preventing their merging.
11679 if (isa<ConstantFPSDNode>(Value)) {
11680 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11684 return ReduceLoadOpStoreWidth(N);
11687 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11688 SDValue InVec = N->getOperand(0);
11689 SDValue InVal = N->getOperand(1);
11690 SDValue EltNo = N->getOperand(2);
11693 // If the inserted element is an UNDEF, just use the input vector.
11694 if (InVal.getOpcode() == ISD::UNDEF)
11697 EVT VT = InVec.getValueType();
11699 // If we can't generate a legal BUILD_VECTOR, exit
11700 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11703 // Check that we know which element is being inserted
11704 if (!isa<ConstantSDNode>(EltNo))
11706 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11708 // Canonicalize insert_vector_elt dag nodes.
11710 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11711 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11713 // Do this only if the child insert_vector node has one use; also
11714 // do this only if indices are both constants and Idx1 < Idx0.
11715 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11716 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11717 unsigned OtherElt =
11718 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11719 if (Elt < OtherElt) {
11721 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11722 InVec.getOperand(0), InVal, EltNo);
11723 AddToWorklist(NewOp.getNode());
11724 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11725 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11729 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11730 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11731 // vector elements.
11732 SmallVector<SDValue, 8> Ops;
11733 // Do not combine these two vectors if the output vector will not replace
11734 // the input vector.
11735 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11736 Ops.append(InVec.getNode()->op_begin(),
11737 InVec.getNode()->op_end());
11738 } else if (InVec.getOpcode() == ISD::UNDEF) {
11739 unsigned NElts = VT.getVectorNumElements();
11740 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11745 // Insert the element
11746 if (Elt < Ops.size()) {
11747 // All the operands of BUILD_VECTOR must have the same type;
11748 // we enforce that here.
11749 EVT OpVT = Ops[0].getValueType();
11750 if (InVal.getValueType() != OpVT)
11751 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11752 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11753 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11757 // Return the new vector
11758 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11761 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11762 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11763 EVT ResultVT = EVE->getValueType(0);
11764 EVT VecEltVT = InVecVT.getVectorElementType();
11765 unsigned Align = OriginalLoad->getAlignment();
11766 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11767 VecEltVT.getTypeForEVT(*DAG.getContext()));
11769 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11774 SDValue NewPtr = OriginalLoad->getBasePtr();
11776 EVT PtrType = NewPtr.getValueType();
11777 MachinePointerInfo MPI;
11779 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11780 int Elt = ConstEltNo->getZExtValue();
11781 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11782 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11783 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11785 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11786 Offset = DAG.getNode(
11787 ISD::MUL, DL, PtrType, Offset,
11788 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11789 MPI = OriginalLoad->getPointerInfo();
11791 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11793 // The replacement we need to do here is a little tricky: we need to
11794 // replace an extractelement of a load with a load.
11795 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11796 // Note that this replacement assumes that the extractvalue is the only
11797 // use of the load; that's okay because we don't want to perform this
11798 // transformation in other cases anyway.
11801 if (ResultVT.bitsGT(VecEltVT)) {
11802 // If the result type of vextract is wider than the load, then issue an
11803 // extending load instead.
11804 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11808 Load = DAG.getExtLoad(
11809 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11810 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11811 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11812 Chain = Load.getValue(1);
11814 Load = DAG.getLoad(
11815 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11816 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11817 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11818 Chain = Load.getValue(1);
11819 if (ResultVT.bitsLT(VecEltVT))
11820 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11822 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11824 WorklistRemover DeadNodes(*this);
11825 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11826 SDValue To[] = { Load, Chain };
11827 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11828 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11829 // worklist explicitly as well.
11830 AddToWorklist(Load.getNode());
11831 AddUsersToWorklist(Load.getNode()); // Add users too
11832 // Make sure to revisit this node to clean it up; it will usually be dead.
11833 AddToWorklist(EVE);
11835 return SDValue(EVE, 0);
11838 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11839 // (vextract (scalar_to_vector val, 0) -> val
11840 SDValue InVec = N->getOperand(0);
11841 EVT VT = InVec.getValueType();
11842 EVT NVT = N->getValueType(0);
11844 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11845 // Check if the result type doesn't match the inserted element type. A
11846 // SCALAR_TO_VECTOR may truncate the inserted element and the
11847 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11848 SDValue InOp = InVec.getOperand(0);
11849 if (InOp.getValueType() != NVT) {
11850 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11851 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11856 SDValue EltNo = N->getOperand(1);
11857 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
11859 // extract_vector_elt (build_vector x, y), 1 -> y
11861 InVec.getOpcode() == ISD::BUILD_VECTOR &&
11862 TLI.isTypeLegal(VT) &&
11863 (InVec.hasOneUse() ||
11864 TLI.aggressivelyPreferBuildVectorSources(VT))) {
11865 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
11866 EVT InEltVT = Elt.getValueType();
11868 // Sometimes build_vector's scalar input types do not match result type.
11869 if (NVT == InEltVT)
11872 // TODO: It may be useful to truncate if free if the build_vector implicitly
11876 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11877 // We only perform this optimization before the op legalization phase because
11878 // we may introduce new vector instructions which are not backed by TD
11879 // patterns. For example on AVX, extracting elements from a wide vector
11880 // without using extract_subvector. However, if we can find an underlying
11881 // scalar value, then we can always use that.
11882 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
11883 int NumElem = VT.getVectorNumElements();
11884 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11885 // Find the new index to extract from.
11886 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
11888 // Extracting an undef index is undef.
11890 return DAG.getUNDEF(NVT);
11892 // Select the right vector half to extract from.
11894 if (OrigElt < NumElem) {
11895 SVInVec = InVec->getOperand(0);
11897 SVInVec = InVec->getOperand(1);
11898 OrigElt -= NumElem;
11901 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11902 SDValue InOp = SVInVec.getOperand(OrigElt);
11903 if (InOp.getValueType() != NVT) {
11904 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11905 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11911 // FIXME: We should handle recursing on other vector shuffles and
11912 // scalar_to_vector here as well.
11914 if (!LegalOperations) {
11915 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11916 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11917 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11921 bool BCNumEltsChanged = false;
11922 EVT ExtVT = VT.getVectorElementType();
11925 // If the result of load has to be truncated, then it's not necessarily
11927 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11930 if (InVec.getOpcode() == ISD::BITCAST) {
11931 // Don't duplicate a load with other uses.
11932 if (!InVec.hasOneUse())
11935 EVT BCVT = InVec.getOperand(0).getValueType();
11936 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11938 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11939 BCNumEltsChanged = true;
11940 InVec = InVec.getOperand(0);
11941 ExtVT = BCVT.getVectorElementType();
11944 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11945 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11946 ISD::isNormalLoad(InVec.getNode()) &&
11947 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11948 SDValue Index = N->getOperand(1);
11949 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11950 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11954 // Perform only after legalization to ensure build_vector / vector_shuffle
11955 // optimizations have already been done.
11956 if (!LegalOperations) return SDValue();
11958 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11959 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11960 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11963 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11965 LoadSDNode *LN0 = nullptr;
11966 const ShuffleVectorSDNode *SVN = nullptr;
11967 if (ISD::isNormalLoad(InVec.getNode())) {
11968 LN0 = cast<LoadSDNode>(InVec);
11969 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11970 InVec.getOperand(0).getValueType() == ExtVT &&
11971 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11972 // Don't duplicate a load with other uses.
11973 if (!InVec.hasOneUse())
11976 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11977 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11978 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11980 // (load $addr+1*size)
11982 // Don't duplicate a load with other uses.
11983 if (!InVec.hasOneUse())
11986 // If the bit convert changed the number of elements, it is unsafe
11987 // to examine the mask.
11988 if (BCNumEltsChanged)
11991 // Select the input vector, guarding against out of range extract vector.
11992 unsigned NumElems = VT.getVectorNumElements();
11993 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11994 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11996 if (InVec.getOpcode() == ISD::BITCAST) {
11997 // Don't duplicate a load with other uses.
11998 if (!InVec.hasOneUse())
12001 InVec = InVec.getOperand(0);
12003 if (ISD::isNormalLoad(InVec.getNode())) {
12004 LN0 = cast<LoadSDNode>(InVec);
12005 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12006 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12010 // Make sure we found a non-volatile load and the extractelement is
12012 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12015 // If Idx was -1 above, Elt is going to be -1, so just return undef.
12017 return DAG.getUNDEF(LVT);
12019 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12025 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12026 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12027 // We perform this optimization post type-legalization because
12028 // the type-legalizer often scalarizes integer-promoted vectors.
12029 // Performing this optimization before may create bit-casts which
12030 // will be type-legalized to complex code sequences.
12031 // We perform this optimization only before the operation legalizer because we
12032 // may introduce illegal operations.
12033 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12036 unsigned NumInScalars = N->getNumOperands();
12038 EVT VT = N->getValueType(0);
12040 // Check to see if this is a BUILD_VECTOR of a bunch of values
12041 // which come from any_extend or zero_extend nodes. If so, we can create
12042 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12043 // optimizations. We do not handle sign-extend because we can't fill the sign
12045 EVT SourceType = MVT::Other;
12046 bool AllAnyExt = true;
12048 for (unsigned i = 0; i != NumInScalars; ++i) {
12049 SDValue In = N->getOperand(i);
12050 // Ignore undef inputs.
12051 if (In.getOpcode() == ISD::UNDEF) continue;
12053 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
12054 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12056 // Abort if the element is not an extension.
12057 if (!ZeroExt && !AnyExt) {
12058 SourceType = MVT::Other;
12062 // The input is a ZeroExt or AnyExt. Check the original type.
12063 EVT InTy = In.getOperand(0).getValueType();
12065 // Check that all of the widened source types are the same.
12066 if (SourceType == MVT::Other)
12069 else if (InTy != SourceType) {
12070 // Multiple income types. Abort.
12071 SourceType = MVT::Other;
12075 // Check if all of the extends are ANY_EXTENDs.
12076 AllAnyExt &= AnyExt;
12079 // In order to have valid types, all of the inputs must be extended from the
12080 // same source type and all of the inputs must be any or zero extend.
12081 // Scalar sizes must be a power of two.
12082 EVT OutScalarTy = VT.getScalarType();
12083 bool ValidTypes = SourceType != MVT::Other &&
12084 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12085 isPowerOf2_32(SourceType.getSizeInBits());
12087 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12088 // turn into a single shuffle instruction.
12092 bool isLE = DAG.getDataLayout().isLittleEndian();
12093 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12094 assert(ElemRatio > 1 && "Invalid element size ratio");
12095 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12096 DAG.getConstant(0, SDLoc(N), SourceType);
12098 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12099 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12101 // Populate the new build_vector
12102 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12103 SDValue Cast = N->getOperand(i);
12104 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12105 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12106 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12108 if (Cast.getOpcode() == ISD::UNDEF)
12109 In = DAG.getUNDEF(SourceType);
12111 In = Cast->getOperand(0);
12112 unsigned Index = isLE ? (i * ElemRatio) :
12113 (i * ElemRatio + (ElemRatio - 1));
12115 assert(Index < Ops.size() && "Invalid index");
12119 // The type of the new BUILD_VECTOR node.
12120 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12121 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12122 "Invalid vector size");
12123 // Check if the new vector type is legal.
12124 if (!isTypeLegal(VecVT)) return SDValue();
12126 // Make the new BUILD_VECTOR.
12127 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12129 // The new BUILD_VECTOR node has the potential to be further optimized.
12130 AddToWorklist(BV.getNode());
12131 // Bitcast to the desired type.
12132 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12135 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12136 EVT VT = N->getValueType(0);
12138 unsigned NumInScalars = N->getNumOperands();
12141 EVT SrcVT = MVT::Other;
12142 unsigned Opcode = ISD::DELETED_NODE;
12143 unsigned NumDefs = 0;
12145 for (unsigned i = 0; i != NumInScalars; ++i) {
12146 SDValue In = N->getOperand(i);
12147 unsigned Opc = In.getOpcode();
12149 if (Opc == ISD::UNDEF)
12152 // If all scalar values are floats and converted from integers.
12153 if (Opcode == ISD::DELETED_NODE &&
12154 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12161 EVT InVT = In.getOperand(0).getValueType();
12163 // If all scalar values are typed differently, bail out. It's chosen to
12164 // simplify BUILD_VECTOR of integer types.
12165 if (SrcVT == MVT::Other)
12172 // If the vector has just one element defined, it's not worth to fold it into
12173 // a vectorized one.
12177 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12178 && "Should only handle conversion from integer to float.");
12179 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12181 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12183 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12186 // Just because the floating-point vector type is legal does not necessarily
12187 // mean that the corresponding integer vector type is.
12188 if (!isTypeLegal(NVT))
12191 SmallVector<SDValue, 8> Opnds;
12192 for (unsigned i = 0; i != NumInScalars; ++i) {
12193 SDValue In = N->getOperand(i);
12195 if (In.getOpcode() == ISD::UNDEF)
12196 Opnds.push_back(DAG.getUNDEF(SrcVT));
12198 Opnds.push_back(In.getOperand(0));
12200 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12201 AddToWorklist(BV.getNode());
12203 return DAG.getNode(Opcode, dl, VT, BV);
12206 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12207 unsigned NumInScalars = N->getNumOperands();
12209 EVT VT = N->getValueType(0);
12211 // A vector built entirely of undefs is undef.
12212 if (ISD::allOperandsUndef(N))
12213 return DAG.getUNDEF(VT);
12215 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12218 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12221 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12222 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12223 // at most two distinct vectors, turn this into a shuffle node.
12225 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12226 if (!isTypeLegal(VT))
12229 // May only combine to shuffle after legalize if shuffle is legal.
12230 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12233 SDValue VecIn1, VecIn2;
12234 bool UsesZeroVector = false;
12235 for (unsigned i = 0; i != NumInScalars; ++i) {
12236 SDValue Op = N->getOperand(i);
12237 // Ignore undef inputs.
12238 if (Op.getOpcode() == ISD::UNDEF) continue;
12240 // See if we can combine this build_vector into a blend with a zero vector.
12241 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12242 UsesZeroVector = true;
12246 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12247 // constant index, bail out.
12248 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12249 !isa<ConstantSDNode>(Op.getOperand(1))) {
12250 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12254 // We allow up to two distinct input vectors.
12255 SDValue ExtractedFromVec = Op.getOperand(0);
12256 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12259 if (!VecIn1.getNode()) {
12260 VecIn1 = ExtractedFromVec;
12261 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12262 VecIn2 = ExtractedFromVec;
12264 // Too many inputs.
12265 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12270 // If everything is good, we can make a shuffle operation.
12271 if (VecIn1.getNode()) {
12272 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12273 SmallVector<int, 8> Mask;
12274 for (unsigned i = 0; i != NumInScalars; ++i) {
12275 unsigned Opcode = N->getOperand(i).getOpcode();
12276 if (Opcode == ISD::UNDEF) {
12277 Mask.push_back(-1);
12281 // Operands can also be zero.
12282 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12283 assert(UsesZeroVector &&
12284 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12285 "Unexpected node found!");
12286 Mask.push_back(NumInScalars+i);
12290 // If extracting from the first vector, just use the index directly.
12291 SDValue Extract = N->getOperand(i);
12292 SDValue ExtVal = Extract.getOperand(1);
12293 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12294 if (Extract.getOperand(0) == VecIn1) {
12295 Mask.push_back(ExtIndex);
12299 // Otherwise, use InIdx + InputVecSize
12300 Mask.push_back(InNumElements + ExtIndex);
12303 // Avoid introducing illegal shuffles with zero.
12304 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12307 // We can't generate a shuffle node with mismatched input and output types.
12308 // Attempt to transform a single input vector to the correct type.
12309 if ((VT != VecIn1.getValueType())) {
12310 // If the input vector type has a different base type to the output
12311 // vector type, bail out.
12312 EVT VTElemType = VT.getVectorElementType();
12313 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12314 (VecIn2.getNode() &&
12315 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12318 // If the input vector is too small, widen it.
12319 // We only support widening of vectors which are half the size of the
12320 // output registers. For example XMM->YMM widening on X86 with AVX.
12321 EVT VecInT = VecIn1.getValueType();
12322 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12323 // If we only have one small input, widen it by adding undef values.
12324 if (!VecIn2.getNode())
12325 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12326 DAG.getUNDEF(VecIn1.getValueType()));
12327 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12328 // If we have two small inputs of the same type, try to concat them.
12329 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12330 VecIn2 = SDValue(nullptr, 0);
12333 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12334 // If the input vector is too large, try to split it.
12335 // We don't support having two input vectors that are too large.
12336 // If the zero vector was used, we can not split the vector,
12337 // since we'd need 3 inputs.
12338 if (UsesZeroVector || VecIn2.getNode())
12341 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12344 // Try to replace VecIn1 with two extract_subvectors
12345 // No need to update the masks, they should still be correct.
12346 VecIn2 = DAG.getNode(
12347 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12348 DAG.getConstant(VT.getVectorNumElements(), dl,
12349 TLI.getVectorIdxTy(DAG.getDataLayout())));
12350 VecIn1 = DAG.getNode(
12351 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12352 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12357 if (UsesZeroVector)
12358 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12359 DAG.getConstantFP(0.0, dl, VT);
12361 // If VecIn2 is unused then change it to undef.
12362 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12364 // Check that we were able to transform all incoming values to the same
12366 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12367 VecIn1.getValueType() != VT)
12370 // Return the new VECTOR_SHUFFLE node.
12374 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12380 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12381 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12382 EVT OpVT = N->getOperand(0).getValueType();
12384 // If the operands are legal vectors, leave them alone.
12385 if (TLI.isTypeLegal(OpVT))
12389 EVT VT = N->getValueType(0);
12390 SmallVector<SDValue, 8> Ops;
12392 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12393 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12395 // Keep track of what we encounter.
12396 bool AnyInteger = false;
12397 bool AnyFP = false;
12398 for (const SDValue &Op : N->ops()) {
12399 if (ISD::BITCAST == Op.getOpcode() &&
12400 !Op.getOperand(0).getValueType().isVector())
12401 Ops.push_back(Op.getOperand(0));
12402 else if (ISD::UNDEF == Op.getOpcode())
12403 Ops.push_back(ScalarUndef);
12407 // Note whether we encounter an integer or floating point scalar.
12408 // If it's neither, bail out, it could be something weird like x86mmx.
12409 EVT LastOpVT = Ops.back().getValueType();
12410 if (LastOpVT.isFloatingPoint())
12412 else if (LastOpVT.isInteger())
12418 // If any of the operands is a floating point scalar bitcast to a vector,
12419 // use floating point types throughout, and bitcast everything.
12420 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12422 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12423 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12425 for (SDValue &Op : Ops) {
12426 if (Op.getValueType() == SVT)
12428 if (Op.getOpcode() == ISD::UNDEF)
12431 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12436 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12437 VT.getSizeInBits() / SVT.getSizeInBits());
12438 return DAG.getNode(ISD::BITCAST, DL, VT,
12439 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12442 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12443 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12444 // most two distinct vectors the same size as the result, attempt to turn this
12445 // into a legal shuffle.
12446 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12447 EVT VT = N->getValueType(0);
12448 EVT OpVT = N->getOperand(0).getValueType();
12449 int NumElts = VT.getVectorNumElements();
12450 int NumOpElts = OpVT.getVectorNumElements();
12452 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12453 SmallVector<int, 8> Mask;
12455 for (SDValue Op : N->ops()) {
12456 // Peek through any bitcast.
12457 while (Op.getOpcode() == ISD::BITCAST)
12458 Op = Op.getOperand(0);
12460 // UNDEF nodes convert to UNDEF shuffle mask values.
12461 if (Op.getOpcode() == ISD::UNDEF) {
12462 Mask.append((unsigned)NumOpElts, -1);
12466 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12469 // What vector are we extracting the subvector from and at what index?
12470 SDValue ExtVec = Op.getOperand(0);
12472 // We want the EVT of the original extraction to correctly scale the
12473 // extraction index.
12474 EVT ExtVT = ExtVec.getValueType();
12476 // Peek through any bitcast.
12477 while (ExtVec.getOpcode() == ISD::BITCAST)
12478 ExtVec = ExtVec.getOperand(0);
12480 // UNDEF nodes convert to UNDEF shuffle mask values.
12481 if (ExtVec.getOpcode() == ISD::UNDEF) {
12482 Mask.append((unsigned)NumOpElts, -1);
12486 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12488 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12490 // Ensure that we are extracting a subvector from a vector the same
12491 // size as the result.
12492 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12495 // Scale the subvector index to account for any bitcast.
12496 int NumExtElts = ExtVT.getVectorNumElements();
12497 if (0 == (NumExtElts % NumElts))
12498 ExtIdx /= (NumExtElts / NumElts);
12499 else if (0 == (NumElts % NumExtElts))
12500 ExtIdx *= (NumElts / NumExtElts);
12504 // At most we can reference 2 inputs in the final shuffle.
12505 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12507 for (int i = 0; i != NumOpElts; ++i)
12508 Mask.push_back(i + ExtIdx);
12509 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12511 for (int i = 0; i != NumOpElts; ++i)
12512 Mask.push_back(i + ExtIdx + NumElts);
12518 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12521 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12522 DAG.getBitcast(VT, SV1), Mask);
12525 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12526 // If we only have one input vector, we don't need to do any concatenation.
12527 if (N->getNumOperands() == 1)
12528 return N->getOperand(0);
12530 // Check if all of the operands are undefs.
12531 EVT VT = N->getValueType(0);
12532 if (ISD::allOperandsUndef(N))
12533 return DAG.getUNDEF(VT);
12535 // Optimize concat_vectors where all but the first of the vectors are undef.
12536 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12537 return Op.getOpcode() == ISD::UNDEF;
12539 SDValue In = N->getOperand(0);
12540 assert(In.getValueType().isVector() && "Must concat vectors");
12542 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12543 if (In->getOpcode() == ISD::BITCAST &&
12544 !In->getOperand(0)->getValueType(0).isVector()) {
12545 SDValue Scalar = In->getOperand(0);
12547 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12548 // look through the trunc so we can still do the transform:
12549 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12550 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12551 !TLI.isTypeLegal(Scalar.getValueType()) &&
12552 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12553 Scalar = Scalar->getOperand(0);
12555 EVT SclTy = Scalar->getValueType(0);
12557 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12560 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12561 VT.getSizeInBits() / SclTy.getSizeInBits());
12562 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12565 SDLoc dl = SDLoc(N);
12566 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12567 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12571 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12572 // We have already tested above for an UNDEF only concatenation.
12573 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12574 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12575 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12576 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12578 bool AllBuildVectorsOrUndefs =
12579 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12580 if (AllBuildVectorsOrUndefs) {
12581 SmallVector<SDValue, 8> Opnds;
12582 EVT SVT = VT.getScalarType();
12585 if (!SVT.isFloatingPoint()) {
12586 // If BUILD_VECTOR are from built from integer, they may have different
12587 // operand types. Get the smallest type and truncate all operands to it.
12588 bool FoundMinVT = false;
12589 for (const SDValue &Op : N->ops())
12590 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12591 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12592 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12595 assert(FoundMinVT && "Concat vector type mismatch");
12598 for (const SDValue &Op : N->ops()) {
12599 EVT OpVT = Op.getValueType();
12600 unsigned NumElts = OpVT.getVectorNumElements();
12602 if (ISD::UNDEF == Op.getOpcode())
12603 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12605 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12606 if (SVT.isFloatingPoint()) {
12607 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12608 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12610 for (unsigned i = 0; i != NumElts; ++i)
12612 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12617 assert(VT.getVectorNumElements() == Opnds.size() &&
12618 "Concat vector type mismatch");
12619 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12622 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12623 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12626 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12627 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12628 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12631 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12632 // nodes often generate nop CONCAT_VECTOR nodes.
12633 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12634 // place the incoming vectors at the exact same location.
12635 SDValue SingleSource = SDValue();
12636 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12638 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12639 SDValue Op = N->getOperand(i);
12641 if (Op.getOpcode() == ISD::UNDEF)
12644 // Check if this is the identity extract:
12645 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12648 // Find the single incoming vector for the extract_subvector.
12649 if (SingleSource.getNode()) {
12650 if (Op.getOperand(0) != SingleSource)
12653 SingleSource = Op.getOperand(0);
12655 // Check the source type is the same as the type of the result.
12656 // If not, this concat may extend the vector, so we can not
12657 // optimize it away.
12658 if (SingleSource.getValueType() != N->getValueType(0))
12662 unsigned IdentityIndex = i * PartNumElem;
12663 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12664 // The extract index must be constant.
12668 // Check that we are reading from the identity index.
12669 if (CS->getZExtValue() != IdentityIndex)
12673 if (SingleSource.getNode())
12674 return SingleSource;
12679 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12680 EVT NVT = N->getValueType(0);
12681 SDValue V = N->getOperand(0);
12683 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12685 // (extract_subvec (concat V1, V2, ...), i)
12688 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12690 if (V->getOperand(0).getValueType() != NVT)
12692 unsigned Idx = N->getConstantOperandVal(1);
12693 unsigned NumElems = NVT.getVectorNumElements();
12694 assert((Idx % NumElems) == 0 &&
12695 "IDX in concat is not a multiple of the result vector length.");
12696 return V->getOperand(Idx / NumElems);
12700 if (V->getOpcode() == ISD::BITCAST)
12701 V = V.getOperand(0);
12703 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12705 // Handle only simple case where vector being inserted and vector
12706 // being extracted are of same type, and are half size of larger vectors.
12707 EVT BigVT = V->getOperand(0).getValueType();
12708 EVT SmallVT = V->getOperand(1).getValueType();
12709 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12712 // Only handle cases where both indexes are constants with the same type.
12713 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12714 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12716 if (InsIdx && ExtIdx &&
12717 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12718 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12720 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12722 // indices are equal or bit offsets are equal => V1
12723 // otherwise => (extract_subvec V1, ExtIdx)
12724 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12725 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12726 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12727 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12728 DAG.getNode(ISD::BITCAST, dl,
12729 N->getOperand(0).getValueType(),
12730 V->getOperand(0)), N->getOperand(1));
12737 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12738 SDValue V, SelectionDAG &DAG) {
12740 EVT VT = V.getValueType();
12742 switch (V.getOpcode()) {
12746 case ISD::CONCAT_VECTORS: {
12747 EVT OpVT = V->getOperand(0).getValueType();
12748 int OpSize = OpVT.getVectorNumElements();
12749 SmallBitVector OpUsedElements(OpSize, false);
12750 bool FoundSimplification = false;
12751 SmallVector<SDValue, 4> NewOps;
12752 NewOps.reserve(V->getNumOperands());
12753 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12754 SDValue Op = V->getOperand(i);
12755 bool OpUsed = false;
12756 for (int j = 0; j < OpSize; ++j)
12757 if (UsedElements[i * OpSize + j]) {
12758 OpUsedElements[j] = true;
12762 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12763 : DAG.getUNDEF(OpVT));
12764 FoundSimplification |= Op == NewOps.back();
12765 OpUsedElements.reset();
12767 if (FoundSimplification)
12768 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12772 case ISD::INSERT_SUBVECTOR: {
12773 SDValue BaseV = V->getOperand(0);
12774 SDValue SubV = V->getOperand(1);
12775 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12779 int SubSize = SubV.getValueType().getVectorNumElements();
12780 int Idx = IdxN->getZExtValue();
12781 bool SubVectorUsed = false;
12782 SmallBitVector SubUsedElements(SubSize, false);
12783 for (int i = 0; i < SubSize; ++i)
12784 if (UsedElements[i + Idx]) {
12785 SubVectorUsed = true;
12786 SubUsedElements[i] = true;
12787 UsedElements[i + Idx] = false;
12790 // Now recurse on both the base and sub vectors.
12791 SDValue SimplifiedSubV =
12793 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12794 : DAG.getUNDEF(SubV.getValueType());
12795 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12796 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12797 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12798 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12804 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12805 SDValue N1, SelectionDAG &DAG) {
12806 EVT VT = SVN->getValueType(0);
12807 int NumElts = VT.getVectorNumElements();
12808 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12809 for (int M : SVN->getMask())
12810 if (M >= 0 && M < NumElts)
12811 N0UsedElements[M] = true;
12812 else if (M >= NumElts)
12813 N1UsedElements[M - NumElts] = true;
12815 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12816 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12817 if (S0 == N0 && S1 == N1)
12820 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12823 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12824 // or turn a shuffle of a single concat into simpler shuffle then concat.
12825 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12826 EVT VT = N->getValueType(0);
12827 unsigned NumElts = VT.getVectorNumElements();
12829 SDValue N0 = N->getOperand(0);
12830 SDValue N1 = N->getOperand(1);
12831 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12833 SmallVector<SDValue, 4> Ops;
12834 EVT ConcatVT = N0.getOperand(0).getValueType();
12835 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12836 unsigned NumConcats = NumElts / NumElemsPerConcat;
12838 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12839 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12840 // half vector elements.
12841 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12842 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12843 SVN->getMask().end(), [](int i) { return i == -1; })) {
12844 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12845 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
12846 N1 = DAG.getUNDEF(ConcatVT);
12847 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12850 // Look at every vector that's inserted. We're looking for exact
12851 // subvector-sized copies from a concatenated vector
12852 for (unsigned I = 0; I != NumConcats; ++I) {
12853 // Make sure we're dealing with a copy.
12854 unsigned Begin = I * NumElemsPerConcat;
12855 bool AllUndef = true, NoUndef = true;
12856 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12857 if (SVN->getMaskElt(J) >= 0)
12864 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12867 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12868 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12871 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12872 if (FirstElt < N0.getNumOperands())
12873 Ops.push_back(N0.getOperand(FirstElt));
12875 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12877 } else if (AllUndef) {
12878 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12879 } else { // Mixed with general masks and undefs, can't do optimization.
12884 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12887 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12888 EVT VT = N->getValueType(0);
12889 unsigned NumElts = VT.getVectorNumElements();
12891 SDValue N0 = N->getOperand(0);
12892 SDValue N1 = N->getOperand(1);
12894 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12896 // Canonicalize shuffle undef, undef -> undef
12897 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12898 return DAG.getUNDEF(VT);
12900 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12902 // Canonicalize shuffle v, v -> v, undef
12904 SmallVector<int, 8> NewMask;
12905 for (unsigned i = 0; i != NumElts; ++i) {
12906 int Idx = SVN->getMaskElt(i);
12907 if (Idx >= (int)NumElts) Idx -= NumElts;
12908 NewMask.push_back(Idx);
12910 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12914 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12915 if (N0.getOpcode() == ISD::UNDEF) {
12916 SmallVector<int, 8> NewMask;
12917 for (unsigned i = 0; i != NumElts; ++i) {
12918 int Idx = SVN->getMaskElt(i);
12920 if (Idx >= (int)NumElts)
12923 Idx = -1; // remove reference to lhs
12925 NewMask.push_back(Idx);
12927 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12931 // Remove references to rhs if it is undef
12932 if (N1.getOpcode() == ISD::UNDEF) {
12933 bool Changed = false;
12934 SmallVector<int, 8> NewMask;
12935 for (unsigned i = 0; i != NumElts; ++i) {
12936 int Idx = SVN->getMaskElt(i);
12937 if (Idx >= (int)NumElts) {
12941 NewMask.push_back(Idx);
12944 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12947 // If it is a splat, check if the argument vector is another splat or a
12949 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12950 SDNode *V = N0.getNode();
12952 // If this is a bit convert that changes the element type of the vector but
12953 // not the number of vector elements, look through it. Be careful not to
12954 // look though conversions that change things like v4f32 to v2f64.
12955 if (V->getOpcode() == ISD::BITCAST) {
12956 SDValue ConvInput = V->getOperand(0);
12957 if (ConvInput.getValueType().isVector() &&
12958 ConvInput.getValueType().getVectorNumElements() == NumElts)
12959 V = ConvInput.getNode();
12962 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12963 assert(V->getNumOperands() == NumElts &&
12964 "BUILD_VECTOR has wrong number of operands");
12966 bool AllSame = true;
12967 for (unsigned i = 0; i != NumElts; ++i) {
12968 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12969 Base = V->getOperand(i);
12973 // Splat of <u, u, u, u>, return <u, u, u, u>
12974 if (!Base.getNode())
12976 for (unsigned i = 0; i != NumElts; ++i) {
12977 if (V->getOperand(i) != Base) {
12982 // Splat of <x, x, x, x>, return <x, x, x, x>
12986 // Canonicalize any other splat as a build_vector.
12987 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12988 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12989 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12990 V->getValueType(0), Ops);
12992 // We may have jumped through bitcasts, so the type of the
12993 // BUILD_VECTOR may not match the type of the shuffle.
12994 if (V->getValueType(0) != VT)
12995 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13000 // There are various patterns used to build up a vector from smaller vectors,
13001 // subvectors, or elements. Scan chains of these and replace unused insertions
13002 // or components with undef.
13003 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13006 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13007 Level < AfterLegalizeVectorOps &&
13008 (N1.getOpcode() == ISD::UNDEF ||
13009 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13010 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13011 SDValue V = partitionShuffleOfConcats(N, DAG);
13017 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13018 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13019 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13020 SmallVector<SDValue, 8> Ops;
13021 for (int M : SVN->getMask()) {
13022 SDValue Op = DAG.getUNDEF(VT.getScalarType());
13024 int Idx = M % NumElts;
13025 SDValue &S = (M < (int)NumElts ? N0 : N1);
13026 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13027 Op = S.getOperand(Idx);
13028 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13030 Op = S.getOperand(0);
13032 // Operand can't be combined - bail out.
13038 if (Ops.size() == VT.getVectorNumElements()) {
13039 // BUILD_VECTOR requires all inputs to be of the same type, find the
13040 // maximum type and extend them all.
13041 EVT SVT = VT.getScalarType();
13042 if (SVT.isInteger())
13043 for (SDValue &Op : Ops)
13044 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13045 if (SVT != VT.getScalarType())
13046 for (SDValue &Op : Ops)
13047 Op = TLI.isZExtFree(Op.getValueType(), SVT)
13048 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13049 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13050 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13054 // If this shuffle only has a single input that is a bitcasted shuffle,
13055 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13056 // back to their original types.
13057 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13058 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13059 TLI.isTypeLegal(VT)) {
13061 // Peek through the bitcast only if there is one user.
13063 while (BC0.getOpcode() == ISD::BITCAST) {
13064 if (!BC0.hasOneUse())
13066 BC0 = BC0.getOperand(0);
13069 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13071 return SmallVector<int, 8>(Mask.begin(), Mask.end());
13073 SmallVector<int, 8> NewMask;
13075 for (int s = 0; s != Scale; ++s)
13076 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13080 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13081 EVT SVT = VT.getScalarType();
13082 EVT InnerVT = BC0->getValueType(0);
13083 EVT InnerSVT = InnerVT.getScalarType();
13085 // Determine which shuffle works with the smaller scalar type.
13086 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13087 EVT ScaleSVT = ScaleVT.getScalarType();
13089 if (TLI.isTypeLegal(ScaleVT) &&
13090 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13091 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13093 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13094 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13096 // Scale the shuffle masks to the smaller scalar type.
13097 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13098 SmallVector<int, 8> InnerMask =
13099 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13100 SmallVector<int, 8> OuterMask =
13101 ScaleShuffleMask(SVN->getMask(), OuterScale);
13103 // Merge the shuffle masks.
13104 SmallVector<int, 8> NewMask;
13105 for (int M : OuterMask)
13106 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13108 // Test for shuffle mask legality over both commutations.
13109 SDValue SV0 = BC0->getOperand(0);
13110 SDValue SV1 = BC0->getOperand(1);
13111 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13113 std::swap(SV0, SV1);
13114 ShuffleVectorSDNode::commuteMask(NewMask);
13115 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13119 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13120 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13121 return DAG.getNode(
13122 ISD::BITCAST, SDLoc(N), VT,
13123 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13129 // Canonicalize shuffles according to rules:
13130 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13131 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13132 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13133 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13134 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13135 TLI.isTypeLegal(VT)) {
13136 // The incoming shuffle must be of the same type as the result of the
13137 // current shuffle.
13138 assert(N1->getOperand(0).getValueType() == VT &&
13139 "Shuffle types don't match");
13141 SDValue SV0 = N1->getOperand(0);
13142 SDValue SV1 = N1->getOperand(1);
13143 bool HasSameOp0 = N0 == SV0;
13144 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13145 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13146 // Commute the operands of this shuffle so that next rule
13148 return DAG.getCommutedVectorShuffle(*SVN);
13151 // Try to fold according to rules:
13152 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13153 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13154 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13155 // Don't try to fold shuffles with illegal type.
13156 // Only fold if this shuffle is the only user of the other shuffle.
13157 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13158 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13159 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13161 // The incoming shuffle must be of the same type as the result of the
13162 // current shuffle.
13163 assert(OtherSV->getOperand(0).getValueType() == VT &&
13164 "Shuffle types don't match");
13167 SmallVector<int, 4> Mask;
13168 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13169 // operand, and SV1 as the second operand.
13170 for (unsigned i = 0; i != NumElts; ++i) {
13171 int Idx = SVN->getMaskElt(i);
13173 // Propagate Undef.
13174 Mask.push_back(Idx);
13178 SDValue CurrentVec;
13179 if (Idx < (int)NumElts) {
13180 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13181 // shuffle mask to identify which vector is actually referenced.
13182 Idx = OtherSV->getMaskElt(Idx);
13184 // Propagate Undef.
13185 Mask.push_back(Idx);
13189 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13190 : OtherSV->getOperand(1);
13192 // This shuffle index references an element within N1.
13196 // Simple case where 'CurrentVec' is UNDEF.
13197 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13198 Mask.push_back(-1);
13202 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13203 // will be the first or second operand of the combined shuffle.
13204 Idx = Idx % NumElts;
13205 if (!SV0.getNode() || SV0 == CurrentVec) {
13206 // Ok. CurrentVec is the left hand side.
13207 // Update the mask accordingly.
13209 Mask.push_back(Idx);
13213 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13214 if (SV1.getNode() && SV1 != CurrentVec)
13217 // Ok. CurrentVec is the right hand side.
13218 // Update the mask accordingly.
13220 Mask.push_back(Idx + NumElts);
13223 // Check if all indices in Mask are Undef. In case, propagate Undef.
13224 bool isUndefMask = true;
13225 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13226 isUndefMask &= Mask[i] < 0;
13229 return DAG.getUNDEF(VT);
13231 if (!SV0.getNode())
13232 SV0 = DAG.getUNDEF(VT);
13233 if (!SV1.getNode())
13234 SV1 = DAG.getUNDEF(VT);
13236 // Avoid introducing shuffles with illegal mask.
13237 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13238 ShuffleVectorSDNode::commuteMask(Mask);
13240 if (!TLI.isShuffleMaskLegal(Mask, VT))
13243 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13244 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13245 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13246 std::swap(SV0, SV1);
13249 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13250 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13251 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13252 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13258 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13259 SDValue InVal = N->getOperand(0);
13260 EVT VT = N->getValueType(0);
13262 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13263 // with a VECTOR_SHUFFLE.
13264 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13265 SDValue InVec = InVal->getOperand(0);
13266 SDValue EltNo = InVal->getOperand(1);
13268 // FIXME: We could support implicit truncation if the shuffle can be
13269 // scaled to a smaller vector scalar type.
13270 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13271 if (C0 && VT == InVec.getValueType() &&
13272 VT.getScalarType() == InVal.getValueType()) {
13273 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13274 int Elt = C0->getZExtValue();
13277 if (TLI.isShuffleMaskLegal(NewMask, VT))
13278 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13286 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13287 SDValue N0 = N->getOperand(0);
13288 SDValue N2 = N->getOperand(2);
13290 // If the input vector is a concatenation, and the insert replaces
13291 // one of the halves, we can optimize into a single concat_vectors.
13292 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13293 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13294 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13295 EVT VT = N->getValueType(0);
13297 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13298 // (concat_vectors Z, Y)
13300 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13301 N->getOperand(1), N0.getOperand(1));
13303 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13304 // (concat_vectors X, Z)
13305 if (InsIdx == VT.getVectorNumElements()/2)
13306 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13307 N0.getOperand(0), N->getOperand(1));
13313 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13314 SDValue N0 = N->getOperand(0);
13316 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13317 if (N0->getOpcode() == ISD::FP16_TO_FP)
13318 return N0->getOperand(0);
13323 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13324 SDValue N0 = N->getOperand(0);
13326 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13327 if (N0->getOpcode() == ISD::AND) {
13328 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13329 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13330 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13338 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13339 /// with the destination vector and a zero vector.
13340 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13341 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13342 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13343 EVT VT = N->getValueType(0);
13344 SDValue LHS = N->getOperand(0);
13345 SDValue RHS = N->getOperand(1);
13348 // Make sure we're not running after operation legalization where it
13349 // may have custom lowered the vector shuffles.
13350 if (LegalOperations)
13353 if (N->getOpcode() != ISD::AND)
13356 if (RHS.getOpcode() == ISD::BITCAST)
13357 RHS = RHS.getOperand(0);
13359 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13362 EVT RVT = RHS.getValueType();
13363 unsigned NumElts = RHS.getNumOperands();
13365 // Attempt to create a valid clear mask, splitting the mask into
13366 // sub elements and checking to see if each is
13367 // all zeros or all ones - suitable for shuffle masking.
13368 auto BuildClearMask = [&](int Split) {
13369 int NumSubElts = NumElts * Split;
13370 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13372 SmallVector<int, 8> Indices;
13373 for (int i = 0; i != NumSubElts; ++i) {
13374 int EltIdx = i / Split;
13375 int SubIdx = i % Split;
13376 SDValue Elt = RHS.getOperand(EltIdx);
13377 if (Elt.getOpcode() == ISD::UNDEF) {
13378 Indices.push_back(-1);
13383 if (isa<ConstantSDNode>(Elt))
13384 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13385 else if (isa<ConstantFPSDNode>(Elt))
13386 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13390 // Extract the sub element from the constant bit mask.
13391 if (DAG.getDataLayout().isBigEndian()) {
13392 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13394 Bits = Bits.lshr(SubIdx * NumSubBits);
13398 Bits = Bits.trunc(NumSubBits);
13400 if (Bits.isAllOnesValue())
13401 Indices.push_back(i);
13402 else if (Bits == 0)
13403 Indices.push_back(i + NumSubElts);
13408 // Let's see if the target supports this vector_shuffle.
13409 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13410 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13411 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13414 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13415 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13416 DAG.getBitcast(ClearVT, LHS),
13417 Zero, &Indices[0]));
13420 // Determine maximum split level (byte level masking).
13422 if (RVT.getScalarSizeInBits() % 8 == 0)
13423 MaxSplit = RVT.getScalarSizeInBits() / 8;
13425 for (int Split = 1; Split <= MaxSplit; ++Split)
13426 if (RVT.getScalarSizeInBits() % Split == 0)
13427 if (SDValue S = BuildClearMask(Split))
13433 /// Visit a binary vector operation, like ADD.
13434 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13435 assert(N->getValueType(0).isVector() &&
13436 "SimplifyVBinOp only works on vectors!");
13438 SDValue LHS = N->getOperand(0);
13439 SDValue RHS = N->getOperand(1);
13440 SDValue Ops[] = {LHS, RHS};
13442 // See if we can constant fold the vector operation.
13443 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13444 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13447 // Try to convert a constant mask AND into a shuffle clear mask.
13448 if (SDValue Shuffle = XformToShuffleWithZero(N))
13451 // Type legalization might introduce new shuffles in the DAG.
13452 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13453 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13454 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13455 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13456 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13457 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13458 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13459 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13461 if (SVN0->getMask().equals(SVN1->getMask())) {
13462 EVT VT = N->getValueType(0);
13463 SDValue UndefVector = LHS.getOperand(1);
13464 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13465 LHS.getOperand(0), RHS.getOperand(0),
13467 AddUsersToWorklist(N);
13468 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13469 &SVN0->getMask()[0]);
13476 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13477 SDValue N1, SDValue N2){
13478 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13480 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13481 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13483 // If we got a simplified select_cc node back from SimplifySelectCC, then
13484 // break it down into a new SETCC node, and a new SELECT node, and then return
13485 // the SELECT node, since we were called with a SELECT node.
13486 if (SCC.getNode()) {
13487 // Check to see if we got a select_cc back (to turn into setcc/select).
13488 // Otherwise, just return whatever node we got back, like fabs.
13489 if (SCC.getOpcode() == ISD::SELECT_CC) {
13490 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13492 SCC.getOperand(0), SCC.getOperand(1),
13493 SCC.getOperand(4));
13494 AddToWorklist(SETCC.getNode());
13495 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13496 SCC.getOperand(2), SCC.getOperand(3));
13504 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13505 /// being selected between, see if we can simplify the select. Callers of this
13506 /// should assume that TheSelect is deleted if this returns true. As such, they
13507 /// should return the appropriate thing (e.g. the node) back to the top-level of
13508 /// the DAG combiner loop to avoid it being looked at.
13509 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13512 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13513 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13514 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13515 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13516 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13517 SDValue Sqrt = RHS;
13520 const ConstantFPSDNode *NegZero = nullptr;
13522 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13523 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13524 CmpLHS = TheSelect->getOperand(0);
13525 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13527 // SELECT or VSELECT
13528 SDValue Cmp = TheSelect->getOperand(0);
13529 if (Cmp.getOpcode() == ISD::SETCC) {
13530 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13531 CmpLHS = Cmp.getOperand(0);
13532 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13535 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13536 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13537 CC == ISD::SETULT || CC == ISD::SETLT)) {
13538 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13539 CombineTo(TheSelect, Sqrt);
13544 // Cannot simplify select with vector condition
13545 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13547 // If this is a select from two identical things, try to pull the operation
13548 // through the select.
13549 if (LHS.getOpcode() != RHS.getOpcode() ||
13550 !LHS.hasOneUse() || !RHS.hasOneUse())
13553 // If this is a load and the token chain is identical, replace the select
13554 // of two loads with a load through a select of the address to load from.
13555 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13556 // constants have been dropped into the constant pool.
13557 if (LHS.getOpcode() == ISD::LOAD) {
13558 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13559 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13561 // Token chains must be identical.
13562 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13563 // Do not let this transformation reduce the number of volatile loads.
13564 LLD->isVolatile() || RLD->isVolatile() ||
13565 // FIXME: If either is a pre/post inc/dec load,
13566 // we'd need to split out the address adjustment.
13567 LLD->isIndexed() || RLD->isIndexed() ||
13568 // If this is an EXTLOAD, the VT's must match.
13569 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13570 // If this is an EXTLOAD, the kind of extension must match.
13571 (LLD->getExtensionType() != RLD->getExtensionType() &&
13572 // The only exception is if one of the extensions is anyext.
13573 LLD->getExtensionType() != ISD::EXTLOAD &&
13574 RLD->getExtensionType() != ISD::EXTLOAD) ||
13575 // FIXME: this discards src value information. This is
13576 // over-conservative. It would be beneficial to be able to remember
13577 // both potential memory locations. Since we are discarding
13578 // src value info, don't do the transformation if the memory
13579 // locations are not in the default address space.
13580 LLD->getPointerInfo().getAddrSpace() != 0 ||
13581 RLD->getPointerInfo().getAddrSpace() != 0 ||
13582 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13583 LLD->getBasePtr().getValueType()))
13586 // Check that the select condition doesn't reach either load. If so,
13587 // folding this will induce a cycle into the DAG. If not, this is safe to
13588 // xform, so create a select of the addresses.
13590 if (TheSelect->getOpcode() == ISD::SELECT) {
13591 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13592 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13593 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13595 // The loads must not depend on one another.
13596 if (LLD->isPredecessorOf(RLD) ||
13597 RLD->isPredecessorOf(LLD))
13599 Addr = DAG.getSelect(SDLoc(TheSelect),
13600 LLD->getBasePtr().getValueType(),
13601 TheSelect->getOperand(0), LLD->getBasePtr(),
13602 RLD->getBasePtr());
13603 } else { // Otherwise SELECT_CC
13604 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13605 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13607 if ((LLD->hasAnyUseOfValue(1) &&
13608 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13609 (RLD->hasAnyUseOfValue(1) &&
13610 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13613 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13614 LLD->getBasePtr().getValueType(),
13615 TheSelect->getOperand(0),
13616 TheSelect->getOperand(1),
13617 LLD->getBasePtr(), RLD->getBasePtr(),
13618 TheSelect->getOperand(4));
13622 // It is safe to replace the two loads if they have different alignments,
13623 // but the new load must be the minimum (most restrictive) alignment of the
13625 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13626 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13627 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13628 Load = DAG.getLoad(TheSelect->getValueType(0),
13630 // FIXME: Discards pointer and AA info.
13631 LLD->getChain(), Addr, MachinePointerInfo(),
13632 LLD->isVolatile(), LLD->isNonTemporal(),
13633 isInvariant, Alignment);
13635 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13636 RLD->getExtensionType() : LLD->getExtensionType(),
13638 TheSelect->getValueType(0),
13639 // FIXME: Discards pointer and AA info.
13640 LLD->getChain(), Addr, MachinePointerInfo(),
13641 LLD->getMemoryVT(), LLD->isVolatile(),
13642 LLD->isNonTemporal(), isInvariant, Alignment);
13645 // Users of the select now use the result of the load.
13646 CombineTo(TheSelect, Load);
13648 // Users of the old loads now use the new load's chain. We know the
13649 // old-load value is dead now.
13650 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13651 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13658 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13659 /// where 'cond' is the comparison specified by CC.
13660 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13661 SDValue N2, SDValue N3,
13662 ISD::CondCode CC, bool NotExtCompare) {
13663 // (x ? y : y) -> y.
13664 if (N2 == N3) return N2;
13666 EVT VT = N2.getValueType();
13667 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13668 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13670 // Determine if the condition we're dealing with is constant
13671 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13672 N0, N1, CC, DL, false);
13673 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13675 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13676 // fold select_cc true, x, y -> x
13677 // fold select_cc false, x, y -> y
13678 return !SCCC->isNullValue() ? N2 : N3;
13681 // Check to see if we can simplify the select into an fabs node
13682 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13683 // Allow either -0.0 or 0.0
13684 if (CFP->isZero()) {
13685 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13686 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13687 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13688 N2 == N3.getOperand(0))
13689 return DAG.getNode(ISD::FABS, DL, VT, N0);
13691 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13692 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13693 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13694 N2.getOperand(0) == N3)
13695 return DAG.getNode(ISD::FABS, DL, VT, N3);
13699 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13700 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13701 // in it. This is a win when the constant is not otherwise available because
13702 // it replaces two constant pool loads with one. We only do this if the FP
13703 // type is known to be legal, because if it isn't, then we are before legalize
13704 // types an we want the other legalization to happen first (e.g. to avoid
13705 // messing with soft float) and if the ConstantFP is not legal, because if
13706 // it is legal, we may not need to store the FP constant in a constant pool.
13707 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13708 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13709 if (TLI.isTypeLegal(N2.getValueType()) &&
13710 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13711 TargetLowering::Legal &&
13712 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13713 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13714 // If both constants have multiple uses, then we won't need to do an
13715 // extra load, they are likely around in registers for other users.
13716 (TV->hasOneUse() || FV->hasOneUse())) {
13717 Constant *Elts[] = {
13718 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13719 const_cast<ConstantFP*>(TV->getConstantFPValue())
13721 Type *FPTy = Elts[0]->getType();
13722 const DataLayout &TD = DAG.getDataLayout();
13724 // Create a ConstantArray of the two constants.
13725 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13727 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13728 TD.getPrefTypeAlignment(FPTy));
13729 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13731 // Get the offsets to the 0 and 1 element of the array so that we can
13732 // select between them.
13733 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13734 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13735 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13737 SDValue Cond = DAG.getSetCC(DL,
13738 getSetCCResultType(N0.getValueType()),
13740 AddToWorklist(Cond.getNode());
13741 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13743 AddToWorklist(CstOffset.getNode());
13744 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13746 AddToWorklist(CPIdx.getNode());
13747 return DAG.getLoad(
13748 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13749 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13750 false, false, false, Alignment);
13754 // Check to see if we can perform the "gzip trick", transforming
13755 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13756 if (isNullConstant(N3) && CC == ISD::SETLT &&
13757 (isNullConstant(N1) || // (a < 0) ? b : 0
13758 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13759 EVT XType = N0.getValueType();
13760 EVT AType = N2.getValueType();
13761 if (XType.bitsGE(AType)) {
13762 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13763 // single-bit constant.
13764 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13765 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13766 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13767 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13768 getShiftAmountTy(N0.getValueType()));
13769 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13771 AddToWorklist(Shift.getNode());
13773 if (XType.bitsGT(AType)) {
13774 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13775 AddToWorklist(Shift.getNode());
13778 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13781 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13783 DAG.getConstant(XType.getSizeInBits() - 1,
13785 getShiftAmountTy(N0.getValueType())));
13786 AddToWorklist(Shift.getNode());
13788 if (XType.bitsGT(AType)) {
13789 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13790 AddToWorklist(Shift.getNode());
13793 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13797 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13798 // where y is has a single bit set.
13799 // A plaintext description would be, we can turn the SELECT_CC into an AND
13800 // when the condition can be materialized as an all-ones register. Any
13801 // single bit-test can be materialized as an all-ones register with
13802 // shift-left and shift-right-arith.
13803 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13804 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13805 SDValue AndLHS = N0->getOperand(0);
13806 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13807 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13808 // Shift the tested bit over the sign bit.
13809 APInt AndMask = ConstAndRHS->getAPIntValue();
13811 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13812 getShiftAmountTy(AndLHS.getValueType()));
13813 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13815 // Now arithmetic right shift it all the way over, so the result is either
13816 // all-ones, or zero.
13818 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13819 getShiftAmountTy(Shl.getValueType()));
13820 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13822 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13826 // fold select C, 16, 0 -> shl C, 4
13827 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13828 TLI.getBooleanContents(N0.getValueType()) ==
13829 TargetLowering::ZeroOrOneBooleanContent) {
13831 // If the caller doesn't want us to simplify this into a zext of a compare,
13833 if (NotExtCompare && N2C->isOne())
13836 // Get a SetCC of the condition
13837 // NOTE: Don't create a SETCC if it's not legal on this target.
13838 if (!LegalOperations ||
13839 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13841 // cast from setcc result type to select result type
13843 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13845 if (N2.getValueType().bitsLT(SCC.getValueType()))
13846 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13847 N2.getValueType());
13849 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13850 N2.getValueType(), SCC);
13852 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13853 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13854 N2.getValueType(), SCC);
13857 AddToWorklist(SCC.getNode());
13858 AddToWorklist(Temp.getNode());
13863 // shl setcc result by log2 n2c
13864 return DAG.getNode(
13865 ISD::SHL, DL, N2.getValueType(), Temp,
13866 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13867 getShiftAmountTy(Temp.getValueType())));
13871 // Check to see if this is an integer abs.
13872 // select_cc setg[te] X, 0, X, -X ->
13873 // select_cc setgt X, -1, X, -X ->
13874 // select_cc setl[te] X, 0, -X, X ->
13875 // select_cc setlt X, 1, -X, X ->
13876 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13878 ConstantSDNode *SubC = nullptr;
13879 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13880 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13881 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13882 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13883 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13884 (N1C->isOne() && CC == ISD::SETLT)) &&
13885 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13886 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13888 EVT XType = N0.getValueType();
13889 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13891 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13893 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13894 getShiftAmountTy(N0.getValueType())));
13895 SDValue Add = DAG.getNode(ISD::ADD, DL,
13897 AddToWorklist(Shift.getNode());
13898 AddToWorklist(Add.getNode());
13899 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13906 /// This is a stub for TargetLowering::SimplifySetCC.
13907 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13908 SDValue N1, ISD::CondCode Cond,
13909 SDLoc DL, bool foldBooleans) {
13910 TargetLowering::DAGCombinerInfo
13911 DagCombineInfo(DAG, Level, false, this);
13912 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13915 /// Given an ISD::SDIV node expressing a divide by constant, return
13916 /// a DAG expression to select that will generate the same value by multiplying
13917 /// by a magic number.
13918 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13919 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13920 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13924 // Avoid division by zero.
13925 if (C->isNullValue())
13928 std::vector<SDNode*> Built;
13930 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13932 for (SDNode *N : Built)
13937 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13938 /// DAG expression that will generate the same value by right shifting.
13939 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13940 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13944 // Avoid division by zero.
13945 if (C->isNullValue())
13948 std::vector<SDNode *> Built;
13949 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13951 for (SDNode *N : Built)
13956 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13957 /// expression that will generate the same value by multiplying by a magic
13959 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13960 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13961 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13965 // Avoid division by zero.
13966 if (C->isNullValue())
13969 std::vector<SDNode*> Built;
13971 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13973 for (SDNode *N : Built)
13978 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
13979 if (Level >= AfterLegalizeDAG)
13982 // Expose the DAG combiner to the target combiner implementations.
13983 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13985 unsigned Iterations = 0;
13986 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13988 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13989 // For the reciprocal, we need to find the zero of the function:
13990 // F(X) = A X - 1 [which has a zero at X = 1/A]
13992 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13993 // does not require additional intermediate precision]
13994 EVT VT = Op.getValueType();
13996 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13998 AddToWorklist(Est.getNode());
14000 // Newton iterations: Est = Est + Est (1 - Arg * Est)
14001 for (unsigned i = 0; i < Iterations; ++i) {
14002 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14003 AddToWorklist(NewEst.getNode());
14005 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14006 AddToWorklist(NewEst.getNode());
14008 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14009 AddToWorklist(NewEst.getNode());
14011 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14012 AddToWorklist(Est.getNode());
14021 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14022 /// For the reciprocal sqrt, we need to find the zero of the function:
14023 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14025 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14026 /// As a result, we precompute A/2 prior to the iteration loop.
14027 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14028 unsigned Iterations,
14029 SDNodeFlags *Flags) {
14030 EVT VT = Arg.getValueType();
14032 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14034 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14035 // this entire sequence requires only one FP constant.
14036 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14037 AddToWorklist(HalfArg.getNode());
14039 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14040 AddToWorklist(HalfArg.getNode());
14042 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14043 for (unsigned i = 0; i < Iterations; ++i) {
14044 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14045 AddToWorklist(NewEst.getNode());
14047 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14048 AddToWorklist(NewEst.getNode());
14050 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14051 AddToWorklist(NewEst.getNode());
14053 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14054 AddToWorklist(Est.getNode());
14059 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14060 /// For the reciprocal sqrt, we need to find the zero of the function:
14061 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14063 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14064 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14065 unsigned Iterations,
14066 SDNodeFlags *Flags) {
14067 EVT VT = Arg.getValueType();
14069 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14070 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14072 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14073 for (unsigned i = 0; i < Iterations; ++i) {
14074 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14075 AddToWorklist(HalfEst.getNode());
14077 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14078 AddToWorklist(Est.getNode());
14080 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14081 AddToWorklist(Est.getNode());
14083 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14084 AddToWorklist(Est.getNode());
14086 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14087 AddToWorklist(Est.getNode());
14092 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14093 if (Level >= AfterLegalizeDAG)
14096 // Expose the DAG combiner to the target combiner implementations.
14097 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14098 unsigned Iterations = 0;
14099 bool UseOneConstNR = false;
14100 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14101 AddToWorklist(Est.getNode());
14103 Est = UseOneConstNR ?
14104 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14105 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14113 /// Return true if base is a frame index, which is known not to alias with
14114 /// anything but itself. Provides base object and offset as results.
14115 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14116 const GlobalValue *&GV, const void *&CV) {
14117 // Assume it is a primitive operation.
14118 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14120 // If it's an adding a simple constant then integrate the offset.
14121 if (Base.getOpcode() == ISD::ADD) {
14122 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14123 Base = Base.getOperand(0);
14124 Offset += C->getZExtValue();
14128 // Return the underlying GlobalValue, and update the Offset. Return false
14129 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14130 // by multiple nodes with different offsets.
14131 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14132 GV = G->getGlobal();
14133 Offset += G->getOffset();
14137 // Return the underlying Constant value, and update the Offset. Return false
14138 // for ConstantSDNodes since the same constant pool entry may be represented
14139 // by multiple nodes with different offsets.
14140 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14141 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14142 : (const void *)C->getConstVal();
14143 Offset += C->getOffset();
14146 // If it's any of the following then it can't alias with anything but itself.
14147 return isa<FrameIndexSDNode>(Base);
14150 /// Return true if there is any possibility that the two addresses overlap.
14151 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14152 // If they are the same then they must be aliases.
14153 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14155 // If they are both volatile then they cannot be reordered.
14156 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14158 // If one operation reads from invariant memory, and the other may store, they
14159 // cannot alias. These should really be checking the equivalent of mayWrite,
14160 // but it only matters for memory nodes other than load /store.
14161 if (Op0->isInvariant() && Op1->writeMem())
14164 if (Op1->isInvariant() && Op0->writeMem())
14167 // Gather base node and offset information.
14168 SDValue Base1, Base2;
14169 int64_t Offset1, Offset2;
14170 const GlobalValue *GV1, *GV2;
14171 const void *CV1, *CV2;
14172 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14173 Base1, Offset1, GV1, CV1);
14174 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14175 Base2, Offset2, GV2, CV2);
14177 // If they have a same base address then check to see if they overlap.
14178 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14179 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14180 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14182 // It is possible for different frame indices to alias each other, mostly
14183 // when tail call optimization reuses return address slots for arguments.
14184 // To catch this case, look up the actual index of frame indices to compute
14185 // the real alias relationship.
14186 if (isFrameIndex1 && isFrameIndex2) {
14187 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14188 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14189 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14190 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14191 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14194 // Otherwise, if we know what the bases are, and they aren't identical, then
14195 // we know they cannot alias.
14196 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14199 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14200 // compared to the size and offset of the access, we may be able to prove they
14201 // do not alias. This check is conservative for now to catch cases created by
14202 // splitting vector types.
14203 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14204 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14205 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14206 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14207 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14208 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14209 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14211 // There is no overlap between these relatively aligned accesses of similar
14212 // size, return no alias.
14213 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14214 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14218 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14220 : DAG.getSubtarget().useAA();
14222 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14223 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14227 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14228 // Use alias analysis information.
14229 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14230 Op1->getSrcValueOffset());
14231 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14232 Op0->getSrcValueOffset() - MinOffset;
14233 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14234 Op1->getSrcValueOffset() - MinOffset;
14235 AliasResult AAResult =
14236 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14237 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14238 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14239 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14240 if (AAResult == NoAlias)
14244 // Otherwise we have to assume they alias.
14248 /// Walk up chain skipping non-aliasing memory nodes,
14249 /// looking for aliasing nodes and adding them to the Aliases vector.
14250 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14251 SmallVectorImpl<SDValue> &Aliases) {
14252 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14253 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14255 // Get alias information for node.
14256 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14259 Chains.push_back(OriginalChain);
14260 unsigned Depth = 0;
14262 // Look at each chain and determine if it is an alias. If so, add it to the
14263 // aliases list. If not, then continue up the chain looking for the next
14265 while (!Chains.empty()) {
14266 SDValue Chain = Chains.pop_back_val();
14268 // For TokenFactor nodes, look at each operand and only continue up the
14269 // chain until we reach the depth limit.
14271 // FIXME: The depth check could be made to return the last non-aliasing
14272 // chain we found before we hit a tokenfactor rather than the original
14276 Aliases.push_back(OriginalChain);
14280 // Don't bother if we've been before.
14281 if (!Visited.insert(Chain.getNode()).second)
14284 switch (Chain.getOpcode()) {
14285 case ISD::EntryToken:
14286 // Entry token is ideal chain operand, but handled in FindBetterChain.
14291 // Get alias information for Chain.
14292 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14293 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14295 // If chain is alias then stop here.
14296 if (!(IsLoad && IsOpLoad) &&
14297 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14298 Aliases.push_back(Chain);
14300 // Look further up the chain.
14301 Chains.push_back(Chain.getOperand(0));
14307 case ISD::TokenFactor:
14308 // We have to check each of the operands of the token factor for "small"
14309 // token factors, so we queue them up. Adding the operands to the queue
14310 // (stack) in reverse order maintains the original order and increases the
14311 // likelihood that getNode will find a matching token factor (CSE.)
14312 if (Chain.getNumOperands() > 16) {
14313 Aliases.push_back(Chain);
14316 for (unsigned n = Chain.getNumOperands(); n;)
14317 Chains.push_back(Chain.getOperand(--n));
14322 // For all other instructions we will just have to take what we can get.
14323 Aliases.push_back(Chain);
14328 // We need to be careful here to also search for aliases through the
14329 // value operand of a store, etc. Consider the following situation:
14331 // L1 = load Token1, %52
14332 // S1 = store Token1, L1, %51
14333 // L2 = load Token1, %52+8
14334 // S2 = store Token1, L2, %51+8
14335 // Token2 = Token(S1, S2)
14336 // L3 = load Token2, %53
14337 // S3 = store Token2, L3, %52
14338 // L4 = load Token2, %53+8
14339 // S4 = store Token2, L4, %52+8
14340 // If we search for aliases of S3 (which loads address %52), and we look
14341 // only through the chain, then we'll miss the trivial dependence on L1
14342 // (which also loads from %52). We then might change all loads and
14343 // stores to use Token1 as their chain operand, which could result in
14344 // copying %53 into %52 before copying %52 into %51 (which should
14347 // The problem is, however, that searching for such data dependencies
14348 // can become expensive, and the cost is not directly related to the
14349 // chain depth. Instead, we'll rule out such configurations here by
14350 // insisting that we've visited all chain users (except for users
14351 // of the original chain, which is not necessary). When doing this,
14352 // we need to look through nodes we don't care about (otherwise, things
14353 // like register copies will interfere with trivial cases).
14355 SmallVector<const SDNode *, 16> Worklist;
14356 for (const SDNode *N : Visited)
14357 if (N != OriginalChain.getNode())
14358 Worklist.push_back(N);
14360 while (!Worklist.empty()) {
14361 const SDNode *M = Worklist.pop_back_val();
14363 // We have already visited M, and want to make sure we've visited any uses
14364 // of M that we care about. For uses that we've not visisted, and don't
14365 // care about, queue them to the worklist.
14367 for (SDNode::use_iterator UI = M->use_begin(),
14368 UIE = M->use_end(); UI != UIE; ++UI)
14369 if (UI.getUse().getValueType() == MVT::Other &&
14370 Visited.insert(*UI).second) {
14371 if (isa<MemSDNode>(*UI)) {
14372 // We've not visited this use, and we care about it (it could have an
14373 // ordering dependency with the original node).
14375 Aliases.push_back(OriginalChain);
14379 // We've not visited this use, but we don't care about it. Mark it as
14380 // visited and enqueue it to the worklist.
14381 Worklist.push_back(*UI);
14386 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14387 /// (aliasing node.)
14388 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14389 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14391 // Accumulate all the aliases to this node.
14392 GatherAllAliases(N, OldChain, Aliases);
14394 // If no operands then chain to entry token.
14395 if (Aliases.size() == 0)
14396 return DAG.getEntryNode();
14398 // If a single operand then chain to it. We don't need to revisit it.
14399 if (Aliases.size() == 1)
14402 // Construct a custom tailored token factor.
14403 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14406 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14407 // This holds the base pointer, index, and the offset in bytes from the base
14409 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14411 // We must have a base and an offset.
14412 if (!BasePtr.Base.getNode())
14415 // Do not handle stores to undef base pointers.
14416 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14419 SmallVector<StoreSDNode *, 8> ChainedStores;
14420 ChainedStores.push_back(St);
14422 // Walk up the chain and look for nodes with offsets from the same
14423 // base pointer. Stop when reaching an instruction with a different kind
14424 // or instruction which has a different base pointer.
14425 StoreSDNode *Index = St;
14427 // If the chain has more than one use, then we can't reorder the mem ops.
14428 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14431 if (Index->isVolatile() || Index->isIndexed())
14434 // Find the base pointer and offset for this memory node.
14435 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14437 // Check that the base pointer is the same as the original one.
14438 if (!Ptr.equalBaseIndex(BasePtr))
14441 // Find the next memory operand in the chain. If the next operand in the
14442 // chain is a store then move up and continue the scan with the next
14443 // memory operand. If the next operand is a load save it and use alias
14444 // information to check if it interferes with anything.
14445 SDNode *NextInChain = Index->getChain().getNode();
14447 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14448 // We found a store node. Use it for the next iteration.
14449 ChainedStores.push_back(STn);
14452 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14453 NextInChain = Ldn->getChain().getNode();
14462 bool MadeChange = false;
14463 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14465 for (StoreSDNode *ChainedStore : ChainedStores) {
14466 SDValue Chain = ChainedStore->getChain();
14467 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14469 if (Chain != BetterChain) {
14471 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14475 // Do all replacements after finding the replacements to make to avoid making
14476 // the chains more complicated by introducing new TokenFactors.
14477 for (auto Replacement : BetterChains)
14478 replaceStoreChain(Replacement.first, Replacement.second);
14483 /// This is the entry point for the file.
14484 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14485 CodeGenOpt::Level OptLevel) {
14486 /// This is the main entry point to this class.
14487 DAGCombiner(*this, AA, OptLevel).Run(Level);