1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitIMINMAX(SDNode *N);
249 SDValue visitAND(SDNode *N);
250 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
251 SDValue visitOR(SDNode *N);
252 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
253 SDValue visitXOR(SDNode *N);
254 SDValue SimplifyVBinOp(SDNode *N);
255 SDValue visitSHL(SDNode *N);
256 SDValue visitSRA(SDNode *N);
257 SDValue visitSRL(SDNode *N);
258 SDValue visitRotate(SDNode *N);
259 SDValue visitBSWAP(SDNode *N);
260 SDValue visitCTLZ(SDNode *N);
261 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
262 SDValue visitCTTZ(SDNode *N);
263 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
264 SDValue visitCTPOP(SDNode *N);
265 SDValue visitSELECT(SDNode *N);
266 SDValue visitVSELECT(SDNode *N);
267 SDValue visitSELECT_CC(SDNode *N);
268 SDValue visitSETCC(SDNode *N);
269 SDValue visitSIGN_EXTEND(SDNode *N);
270 SDValue visitZERO_EXTEND(SDNode *N);
271 SDValue visitANY_EXTEND(SDNode *N);
272 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
273 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
274 SDValue visitTRUNCATE(SDNode *N);
275 SDValue visitBITCAST(SDNode *N);
276 SDValue visitBUILD_PAIR(SDNode *N);
277 SDValue visitFADD(SDNode *N);
278 SDValue visitFSUB(SDNode *N);
279 SDValue visitFMUL(SDNode *N);
280 SDValue visitFMA(SDNode *N);
281 SDValue visitFDIV(SDNode *N);
282 SDValue visitFREM(SDNode *N);
283 SDValue visitFSQRT(SDNode *N);
284 SDValue visitFCOPYSIGN(SDNode *N);
285 SDValue visitSINT_TO_FP(SDNode *N);
286 SDValue visitUINT_TO_FP(SDNode *N);
287 SDValue visitFP_TO_SINT(SDNode *N);
288 SDValue visitFP_TO_UINT(SDNode *N);
289 SDValue visitFP_ROUND(SDNode *N);
290 SDValue visitFP_ROUND_INREG(SDNode *N);
291 SDValue visitFP_EXTEND(SDNode *N);
292 SDValue visitFNEG(SDNode *N);
293 SDValue visitFABS(SDNode *N);
294 SDValue visitFCEIL(SDNode *N);
295 SDValue visitFTRUNC(SDNode *N);
296 SDValue visitFFLOOR(SDNode *N);
297 SDValue visitFMINNUM(SDNode *N);
298 SDValue visitFMAXNUM(SDNode *N);
299 SDValue visitBRCOND(SDNode *N);
300 SDValue visitBR_CC(SDNode *N);
301 SDValue visitLOAD(SDNode *N);
303 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
304 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
306 SDValue visitSTORE(SDNode *N);
307 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
308 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
309 SDValue visitBUILD_VECTOR(SDNode *N);
310 SDValue visitCONCAT_VECTORS(SDNode *N);
311 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
312 SDValue visitVECTOR_SHUFFLE(SDNode *N);
313 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
314 SDValue visitINSERT_SUBVECTOR(SDNode *N);
315 SDValue visitMLOAD(SDNode *N);
316 SDValue visitMSTORE(SDNode *N);
317 SDValue visitMGATHER(SDNode *N);
318 SDValue visitMSCATTER(SDNode *N);
319 SDValue visitFP_TO_FP16(SDNode *N);
320 SDValue visitFP16_TO_FP(SDNode *N);
322 SDValue visitFADDForFMACombine(SDNode *N);
323 SDValue visitFSUBForFMACombine(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,
411 /// This is a helper function for MergeConsecutiveStores. When the source
412 /// elements of the consecutive stores are all constants or all extracted
413 /// vector elements, try to merge them into one larger store.
414 /// \return True if a merged store was created.
415 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
416 EVT MemVT, unsigned NumStores,
417 bool IsConstantSrc, bool UseVector);
419 /// This is a helper function for MergeConsecutiveStores.
420 /// Stores that may be merged are placed in StoreNodes.
421 /// Loads that may alias with those stores are placed in AliasLoadNodes.
422 void getStoreMergeAndAliasCandidates(
423 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
424 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
426 /// Merge consecutive store operations into a wide store.
427 /// This optimization uses wide integers or vectors when possible.
428 /// \return True if some memory operations were changed.
429 bool MergeConsecutiveStores(StoreSDNode *N);
431 /// \brief Try to transform a truncation where C is a constant:
432 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
434 /// \p N needs to be a truncation and its first operand an AND. Other
435 /// requirements are checked by the function (e.g. that trunc is
436 /// single-use) and if missed an empty SDValue is returned.
437 SDValue distributeTruncateThroughAnd(SDNode *N);
440 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
441 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
442 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
443 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
446 /// Runs the dag combiner on all nodes in the work list
447 void Run(CombineLevel AtLevel);
449 SelectionDAG &getDAG() const { return DAG; }
451 /// Returns a type large enough to hold any valid shift amount - before type
452 /// legalization these can be huge.
453 EVT getShiftAmountTy(EVT LHSTy) {
454 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
455 if (LHSTy.isVector())
457 auto &DL = DAG.getDataLayout();
458 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
459 : TLI.getPointerTy(DL);
462 /// This method returns true if we are running before type legalization or
463 /// if the specified VT is legal.
464 bool isTypeLegal(const EVT &VT) {
465 if (!LegalTypes) return true;
466 return TLI.isTypeLegal(VT);
469 /// Convenience wrapper around TargetLowering::getSetCCResultType
470 EVT getSetCCResultType(EVT VT) const {
471 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
478 /// This class is a DAGUpdateListener that removes any deleted
479 /// nodes from the worklist.
480 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
483 explicit WorklistRemover(DAGCombiner &dc)
484 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
486 void NodeDeleted(SDNode *N, SDNode *E) override {
487 DC.removeFromWorklist(N);
492 //===----------------------------------------------------------------------===//
493 // TargetLowering::DAGCombinerInfo implementation
494 //===----------------------------------------------------------------------===//
496 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
497 ((DAGCombiner*)DC)->AddToWorklist(N);
500 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
501 ((DAGCombiner*)DC)->removeFromWorklist(N);
504 SDValue TargetLowering::DAGCombinerInfo::
505 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
506 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
509 SDValue TargetLowering::DAGCombinerInfo::
510 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
511 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
515 SDValue TargetLowering::DAGCombinerInfo::
516 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
517 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
520 void TargetLowering::DAGCombinerInfo::
521 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
522 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
525 //===----------------------------------------------------------------------===//
527 //===----------------------------------------------------------------------===//
529 void DAGCombiner::deleteAndRecombine(SDNode *N) {
530 removeFromWorklist(N);
532 // If the operands of this node are only used by the node, they will now be
533 // dead. Make sure to re-visit them and recursively delete dead nodes.
534 for (const SDValue &Op : N->ops())
535 // For an operand generating multiple values, one of the values may
536 // become dead allowing further simplification (e.g. split index
537 // arithmetic from an indexed load).
538 if (Op->hasOneUse() || Op->getNumValues() > 1)
539 AddToWorklist(Op.getNode());
544 /// Return 1 if we can compute the negated form of the specified expression for
545 /// the same cost as the expression itself, or 2 if we can compute the negated
546 /// form more cheaply than the expression itself.
547 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
548 const TargetLowering &TLI,
549 const TargetOptions *Options,
550 unsigned Depth = 0) {
551 // fneg is removable even if it has multiple uses.
552 if (Op.getOpcode() == ISD::FNEG) return 2;
554 // Don't allow anything with multiple uses.
555 if (!Op.hasOneUse()) return 0;
557 // Don't recurse exponentially.
558 if (Depth > 6) return 0;
560 switch (Op.getOpcode()) {
561 default: return false;
562 case ISD::ConstantFP:
563 // Don't invert constant FP values after legalize. The negated constant
564 // isn't necessarily legal.
565 return LegalOperations ? 0 : 1;
567 // FIXME: determine better conditions for this xform.
568 if (!Options->UnsafeFPMath) return 0;
570 // After operation legalization, it might not be legal to create new FSUBs.
571 if (LegalOperations &&
572 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
575 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
576 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
579 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
580 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
583 // We can't turn -(A-B) into B-A when we honor signed zeros.
584 if (!Options->UnsafeFPMath) return 0;
586 // fold (fneg (fsub A, B)) -> (fsub B, A)
591 if (Options->HonorSignDependentRoundingFPMath()) return 0;
593 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
594 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
598 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
604 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
609 /// If isNegatibleForFree returns true, return the newly negated expression.
610 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
611 bool LegalOperations, unsigned Depth = 0) {
612 const TargetOptions &Options = DAG.getTarget().Options;
613 // fneg is removable even if it has multiple uses.
614 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
616 // Don't allow anything with multiple uses.
617 assert(Op.hasOneUse() && "Unknown reuse!");
619 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
621 const SDNodeFlags *Flags = Op.getNode()->getFlags();
623 switch (Op.getOpcode()) {
624 default: llvm_unreachable("Unknown code");
625 case ISD::ConstantFP: {
626 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
628 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
631 // FIXME: determine better conditions for this xform.
632 assert(Options.UnsafeFPMath);
634 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
635 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
636 DAG.getTargetLoweringInfo(), &Options, Depth+1))
637 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
638 GetNegatedExpression(Op.getOperand(0), DAG,
639 LegalOperations, Depth+1),
640 Op.getOperand(1), Flags);
641 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
642 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
643 GetNegatedExpression(Op.getOperand(1), DAG,
644 LegalOperations, Depth+1),
645 Op.getOperand(0), Flags);
647 // We can't turn -(A-B) into B-A when we honor signed zeros.
648 assert(Options.UnsafeFPMath);
650 // fold (fneg (fsub 0, B)) -> B
651 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
653 return Op.getOperand(1);
655 // fold (fneg (fsub A, B)) -> (fsub B, A)
656 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
657 Op.getOperand(1), Op.getOperand(0), Flags);
661 assert(!Options.HonorSignDependentRoundingFPMath());
663 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
664 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
665 DAG.getTargetLoweringInfo(), &Options, Depth+1))
666 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
667 GetNegatedExpression(Op.getOperand(0), DAG,
668 LegalOperations, Depth+1),
669 Op.getOperand(1), Flags);
671 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
672 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
674 GetNegatedExpression(Op.getOperand(1), DAG,
675 LegalOperations, Depth+1), Flags);
679 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
680 GetNegatedExpression(Op.getOperand(0), DAG,
681 LegalOperations, Depth+1));
683 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
684 GetNegatedExpression(Op.getOperand(0), DAG,
685 LegalOperations, Depth+1),
690 // Return true if this node is a setcc, or is a select_cc
691 // that selects between the target values used for true and false, making it
692 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
693 // the appropriate nodes based on the type of node we are checking. This
694 // simplifies life a bit for the callers.
695 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
697 if (N.getOpcode() == ISD::SETCC) {
698 LHS = N.getOperand(0);
699 RHS = N.getOperand(1);
700 CC = N.getOperand(2);
704 if (N.getOpcode() != ISD::SELECT_CC ||
705 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
706 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
709 if (TLI.getBooleanContents(N.getValueType()) ==
710 TargetLowering::UndefinedBooleanContent)
713 LHS = N.getOperand(0);
714 RHS = N.getOperand(1);
715 CC = N.getOperand(4);
719 /// Return true if this is a SetCC-equivalent operation with only one use.
720 /// If this is true, it allows the users to invert the operation for free when
721 /// it is profitable to do so.
722 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
724 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
729 /// Returns true if N is a BUILD_VECTOR node whose
730 /// elements are all the same constant or undefined.
731 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
732 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
737 unsigned SplatBitSize;
739 EVT EltVT = N->getValueType(0).getVectorElementType();
740 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
742 EltVT.getSizeInBits() >= SplatBitSize);
745 // \brief Returns the SDNode if it is a constant integer BuildVector
746 // or constant integer.
747 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
748 if (isa<ConstantSDNode>(N))
750 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
755 // \brief Returns the SDNode if it is a constant float BuildVector
756 // or constant float.
757 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
758 if (isa<ConstantFPSDNode>(N))
760 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
765 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
767 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
768 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
771 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
772 BitVector UndefElements;
773 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
775 // BuildVectors can truncate their operands. Ignore that case here.
776 // FIXME: We blindly ignore splats which include undef which is overly
778 if (CN && UndefElements.none() &&
779 CN->getValueType(0) == N.getValueType().getScalarType())
786 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
788 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
789 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
792 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
793 BitVector UndefElements;
794 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
796 if (CN && UndefElements.none())
803 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
804 SDValue N0, SDValue N1) {
805 EVT VT = N0.getValueType();
806 if (N0.getOpcode() == Opc) {
807 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
808 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
809 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
810 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
811 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
814 if (N0.hasOneUse()) {
815 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
817 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
818 if (!OpNode.getNode())
820 AddToWorklist(OpNode.getNode());
821 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
826 if (N1.getOpcode() == Opc) {
827 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
828 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
829 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
830 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
831 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
834 if (N1.hasOneUse()) {
835 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
837 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
838 if (!OpNode.getNode())
840 AddToWorklist(OpNode.getNode());
841 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
849 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
851 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
853 DEBUG(dbgs() << "\nReplacing.1 ";
855 dbgs() << "\nWith: ";
856 To[0].getNode()->dump(&DAG);
857 dbgs() << " and " << NumTo-1 << " other values\n");
858 for (unsigned i = 0, e = NumTo; i != e; ++i)
859 assert((!To[i].getNode() ||
860 N->getValueType(i) == To[i].getValueType()) &&
861 "Cannot combine value to value of different type!");
863 WorklistRemover DeadNodes(*this);
864 DAG.ReplaceAllUsesWith(N, To);
866 // Push the new nodes and any users onto the worklist
867 for (unsigned i = 0, e = NumTo; i != e; ++i) {
868 if (To[i].getNode()) {
869 AddToWorklist(To[i].getNode());
870 AddUsersToWorklist(To[i].getNode());
875 // Finally, if the node is now dead, remove it from the graph. The node
876 // may not be dead if the replacement process recursively simplified to
877 // something else needing this node.
879 deleteAndRecombine(N);
880 return SDValue(N, 0);
884 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
885 // Replace all uses. If any nodes become isomorphic to other nodes and
886 // are deleted, make sure to remove them from our worklist.
887 WorklistRemover DeadNodes(*this);
888 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
890 // Push the new node and any (possibly new) users onto the worklist.
891 AddToWorklist(TLO.New.getNode());
892 AddUsersToWorklist(TLO.New.getNode());
894 // Finally, if the node is now dead, remove it from the graph. The node
895 // may not be dead if the replacement process recursively simplified to
896 // something else needing this node.
897 if (TLO.Old.getNode()->use_empty())
898 deleteAndRecombine(TLO.Old.getNode());
901 /// Check the specified integer node value to see if it can be simplified or if
902 /// things it uses can be simplified by bit propagation. If so, return true.
903 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
904 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
905 APInt KnownZero, KnownOne;
906 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
910 AddToWorklist(Op.getNode());
912 // Replace the old value with the new one.
914 DEBUG(dbgs() << "\nReplacing.2 ";
915 TLO.Old.getNode()->dump(&DAG);
916 dbgs() << "\nWith: ";
917 TLO.New.getNode()->dump(&DAG);
920 CommitTargetLoweringOpt(TLO);
924 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
926 EVT VT = Load->getValueType(0);
927 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
929 DEBUG(dbgs() << "\nReplacing.9 ";
931 dbgs() << "\nWith: ";
932 Trunc.getNode()->dump(&DAG);
934 WorklistRemover DeadNodes(*this);
935 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
936 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
937 deleteAndRecombine(Load);
938 AddToWorklist(Trunc.getNode());
941 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
944 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
945 EVT MemVT = LD->getMemoryVT();
946 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
947 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
949 : LD->getExtensionType();
951 return DAG.getExtLoad(ExtType, dl, PVT,
952 LD->getChain(), LD->getBasePtr(),
953 MemVT, LD->getMemOperand());
956 unsigned Opc = Op.getOpcode();
959 case ISD::AssertSext:
960 return DAG.getNode(ISD::AssertSext, dl, PVT,
961 SExtPromoteOperand(Op.getOperand(0), PVT),
963 case ISD::AssertZext:
964 return DAG.getNode(ISD::AssertZext, dl, PVT,
965 ZExtPromoteOperand(Op.getOperand(0), PVT),
967 case ISD::Constant: {
969 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
970 return DAG.getNode(ExtOpc, dl, PVT, Op);
974 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
976 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
979 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
980 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
982 EVT OldVT = Op.getValueType();
984 bool Replace = false;
985 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
986 if (!NewOp.getNode())
988 AddToWorklist(NewOp.getNode());
991 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
992 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
993 DAG.getValueType(OldVT));
996 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
997 EVT OldVT = Op.getValueType();
999 bool Replace = false;
1000 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1001 if (!NewOp.getNode())
1003 AddToWorklist(NewOp.getNode());
1006 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1007 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1010 /// Promote the specified integer binary operation if the target indicates it is
1011 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1012 /// i32 since i16 instructions are longer.
1013 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1014 if (!LegalOperations)
1017 EVT VT = Op.getValueType();
1018 if (VT.isVector() || !VT.isInteger())
1021 // If operation type is 'undesirable', e.g. i16 on x86, consider
1023 unsigned Opc = Op.getOpcode();
1024 if (TLI.isTypeDesirableForOp(Opc, VT))
1028 // Consult target whether it is a good idea to promote this operation and
1029 // what's the right type to promote it to.
1030 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1031 assert(PVT != VT && "Don't know what type to promote to!");
1033 bool Replace0 = false;
1034 SDValue N0 = Op.getOperand(0);
1035 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1039 bool Replace1 = false;
1040 SDValue N1 = Op.getOperand(1);
1045 NN1 = PromoteOperand(N1, PVT, Replace1);
1050 AddToWorklist(NN0.getNode());
1052 AddToWorklist(NN1.getNode());
1055 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1057 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1059 DEBUG(dbgs() << "\nPromoting ";
1060 Op.getNode()->dump(&DAG));
1062 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1063 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1068 /// Promote the specified integer shift operation if the target indicates it is
1069 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1070 /// i32 since i16 instructions are longer.
1071 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1072 if (!LegalOperations)
1075 EVT VT = Op.getValueType();
1076 if (VT.isVector() || !VT.isInteger())
1079 // If operation type is 'undesirable', e.g. i16 on x86, consider
1081 unsigned Opc = Op.getOpcode();
1082 if (TLI.isTypeDesirableForOp(Opc, VT))
1086 // Consult target whether it is a good idea to promote this operation and
1087 // what's the right type to promote it to.
1088 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1089 assert(PVT != VT && "Don't know what type to promote to!");
1091 bool Replace = false;
1092 SDValue N0 = Op.getOperand(0);
1093 if (Opc == ISD::SRA)
1094 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1095 else if (Opc == ISD::SRL)
1096 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1098 N0 = PromoteOperand(N0, PVT, Replace);
1102 AddToWorklist(N0.getNode());
1104 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1106 DEBUG(dbgs() << "\nPromoting ";
1107 Op.getNode()->dump(&DAG));
1109 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1110 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1115 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1116 if (!LegalOperations)
1119 EVT VT = Op.getValueType();
1120 if (VT.isVector() || !VT.isInteger())
1123 // If operation type is 'undesirable', e.g. i16 on x86, consider
1125 unsigned Opc = Op.getOpcode();
1126 if (TLI.isTypeDesirableForOp(Opc, VT))
1130 // Consult target whether it is a good idea to promote this operation and
1131 // what's the right type to promote it to.
1132 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1133 assert(PVT != VT && "Don't know what type to promote to!");
1134 // fold (aext (aext x)) -> (aext x)
1135 // fold (aext (zext x)) -> (zext x)
1136 // fold (aext (sext x)) -> (sext x)
1137 DEBUG(dbgs() << "\nPromoting ";
1138 Op.getNode()->dump(&DAG));
1139 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1144 bool DAGCombiner::PromoteLoad(SDValue Op) {
1145 if (!LegalOperations)
1148 EVT VT = Op.getValueType();
1149 if (VT.isVector() || !VT.isInteger())
1152 // If operation type is 'undesirable', e.g. i16 on x86, consider
1154 unsigned Opc = Op.getOpcode();
1155 if (TLI.isTypeDesirableForOp(Opc, VT))
1159 // Consult target whether it is a good idea to promote this operation and
1160 // what's the right type to promote it to.
1161 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1162 assert(PVT != VT && "Don't know what type to promote to!");
1165 SDNode *N = Op.getNode();
1166 LoadSDNode *LD = cast<LoadSDNode>(N);
1167 EVT MemVT = LD->getMemoryVT();
1168 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1169 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1171 : LD->getExtensionType();
1172 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1173 LD->getChain(), LD->getBasePtr(),
1174 MemVT, LD->getMemOperand());
1175 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1177 DEBUG(dbgs() << "\nPromoting ";
1180 Result.getNode()->dump(&DAG);
1182 WorklistRemover DeadNodes(*this);
1183 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1184 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1185 deleteAndRecombine(N);
1186 AddToWorklist(Result.getNode());
1192 /// \brief Recursively delete a node which has no uses and any operands for
1193 /// which it is the only use.
1195 /// Note that this both deletes the nodes and removes them from the worklist.
1196 /// It also adds any nodes who have had a user deleted to the worklist as they
1197 /// may now have only one use and subject to other combines.
1198 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1199 if (!N->use_empty())
1202 SmallSetVector<SDNode *, 16> Nodes;
1205 N = Nodes.pop_back_val();
1209 if (N->use_empty()) {
1210 for (const SDValue &ChildN : N->op_values())
1211 Nodes.insert(ChildN.getNode());
1213 removeFromWorklist(N);
1218 } while (!Nodes.empty());
1222 //===----------------------------------------------------------------------===//
1223 // Main DAG Combiner implementation
1224 //===----------------------------------------------------------------------===//
1226 void DAGCombiner::Run(CombineLevel AtLevel) {
1227 // set the instance variables, so that the various visit routines may use it.
1229 LegalOperations = Level >= AfterLegalizeVectorOps;
1230 LegalTypes = Level >= AfterLegalizeTypes;
1232 // Add all the dag nodes to the worklist.
1233 for (SDNode &Node : DAG.allnodes())
1234 AddToWorklist(&Node);
1236 // Create a dummy node (which is not added to allnodes), that adds a reference
1237 // to the root node, preventing it from being deleted, and tracking any
1238 // changes of the root.
1239 HandleSDNode Dummy(DAG.getRoot());
1241 // while the worklist isn't empty, find a node and
1242 // try and combine it.
1243 while (!WorklistMap.empty()) {
1245 // The Worklist holds the SDNodes in order, but it may contain null entries.
1247 N = Worklist.pop_back_val();
1250 bool GoodWorklistEntry = WorklistMap.erase(N);
1251 (void)GoodWorklistEntry;
1252 assert(GoodWorklistEntry &&
1253 "Found a worklist entry without a corresponding map entry!");
1255 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1256 // N is deleted from the DAG, since they too may now be dead or may have a
1257 // reduced number of uses, allowing other xforms.
1258 if (recursivelyDeleteUnusedNodes(N))
1261 WorklistRemover DeadNodes(*this);
1263 // If this combine is running after legalizing the DAG, re-legalize any
1264 // nodes pulled off the worklist.
1265 if (Level == AfterLegalizeDAG) {
1266 SmallSetVector<SDNode *, 16> UpdatedNodes;
1267 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1269 for (SDNode *LN : UpdatedNodes) {
1271 AddUsersToWorklist(LN);
1277 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1279 // Add any operands of the new node which have not yet been combined to the
1280 // worklist as well. Because the worklist uniques things already, this
1281 // won't repeatedly process the same operand.
1282 CombinedNodes.insert(N);
1283 for (const SDValue &ChildN : N->op_values())
1284 if (!CombinedNodes.count(ChildN.getNode()))
1285 AddToWorklist(ChildN.getNode());
1287 SDValue RV = combine(N);
1294 // If we get back the same node we passed in, rather than a new node or
1295 // zero, we know that the node must have defined multiple values and
1296 // CombineTo was used. Since CombineTo takes care of the worklist
1297 // mechanics for us, we have no work to do in this case.
1298 if (RV.getNode() == N)
1301 assert(N->getOpcode() != ISD::DELETED_NODE &&
1302 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1303 "Node was deleted but visit returned new node!");
1305 DEBUG(dbgs() << " ... into: ";
1306 RV.getNode()->dump(&DAG));
1308 // Transfer debug value.
1309 DAG.TransferDbgValues(SDValue(N, 0), RV);
1310 if (N->getNumValues() == RV.getNode()->getNumValues())
1311 DAG.ReplaceAllUsesWith(N, RV.getNode());
1313 assert(N->getValueType(0) == RV.getValueType() &&
1314 N->getNumValues() == 1 && "Type mismatch");
1316 DAG.ReplaceAllUsesWith(N, &OpV);
1319 // Push the new node and any users onto the worklist
1320 AddToWorklist(RV.getNode());
1321 AddUsersToWorklist(RV.getNode());
1323 // Finally, if the node is now dead, remove it from the graph. The node
1324 // may not be dead if the replacement process recursively simplified to
1325 // something else needing this node. This will also take care of adding any
1326 // operands which have lost a user to the worklist.
1327 recursivelyDeleteUnusedNodes(N);
1330 // If the root changed (e.g. it was a dead load, update the root).
1331 DAG.setRoot(Dummy.getValue());
1332 DAG.RemoveDeadNodes();
1335 SDValue DAGCombiner::visit(SDNode *N) {
1336 switch (N->getOpcode()) {
1338 case ISD::TokenFactor: return visitTokenFactor(N);
1339 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1340 case ISD::ADD: return visitADD(N);
1341 case ISD::SUB: return visitSUB(N);
1342 case ISD::ADDC: return visitADDC(N);
1343 case ISD::SUBC: return visitSUBC(N);
1344 case ISD::ADDE: return visitADDE(N);
1345 case ISD::SUBE: return visitSUBE(N);
1346 case ISD::MUL: return visitMUL(N);
1347 case ISD::SDIV: return visitSDIV(N);
1348 case ISD::UDIV: return visitUDIV(N);
1349 case ISD::SREM: return visitSREM(N);
1350 case ISD::UREM: return visitUREM(N);
1351 case ISD::MULHU: return visitMULHU(N);
1352 case ISD::MULHS: return visitMULHS(N);
1353 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1354 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1355 case ISD::SMULO: return visitSMULO(N);
1356 case ISD::UMULO: return visitUMULO(N);
1357 case ISD::SDIVREM: return visitSDIVREM(N);
1358 case ISD::UDIVREM: return visitUDIVREM(N);
1362 case ISD::UMAX: return visitIMINMAX(N);
1363 case ISD::AND: return visitAND(N);
1364 case ISD::OR: return visitOR(N);
1365 case ISD::XOR: return visitXOR(N);
1366 case ISD::SHL: return visitSHL(N);
1367 case ISD::SRA: return visitSRA(N);
1368 case ISD::SRL: return visitSRL(N);
1370 case ISD::ROTL: return visitRotate(N);
1371 case ISD::BSWAP: return visitBSWAP(N);
1372 case ISD::CTLZ: return visitCTLZ(N);
1373 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1374 case ISD::CTTZ: return visitCTTZ(N);
1375 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1376 case ISD::CTPOP: return visitCTPOP(N);
1377 case ISD::SELECT: return visitSELECT(N);
1378 case ISD::VSELECT: return visitVSELECT(N);
1379 case ISD::SELECT_CC: return visitSELECT_CC(N);
1380 case ISD::SETCC: return visitSETCC(N);
1381 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1382 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1383 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1384 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1385 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1386 case ISD::TRUNCATE: return visitTRUNCATE(N);
1387 case ISD::BITCAST: return visitBITCAST(N);
1388 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1389 case ISD::FADD: return visitFADD(N);
1390 case ISD::FSUB: return visitFSUB(N);
1391 case ISD::FMUL: return visitFMUL(N);
1392 case ISD::FMA: return visitFMA(N);
1393 case ISD::FDIV: return visitFDIV(N);
1394 case ISD::FREM: return visitFREM(N);
1395 case ISD::FSQRT: return visitFSQRT(N);
1396 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1397 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1398 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1399 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1400 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1401 case ISD::FP_ROUND: return visitFP_ROUND(N);
1402 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1403 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1404 case ISD::FNEG: return visitFNEG(N);
1405 case ISD::FABS: return visitFABS(N);
1406 case ISD::FFLOOR: return visitFFLOOR(N);
1407 case ISD::FMINNUM: return visitFMINNUM(N);
1408 case ISD::FMAXNUM: return visitFMAXNUM(N);
1409 case ISD::FCEIL: return visitFCEIL(N);
1410 case ISD::FTRUNC: return visitFTRUNC(N);
1411 case ISD::BRCOND: return visitBRCOND(N);
1412 case ISD::BR_CC: return visitBR_CC(N);
1413 case ISD::LOAD: return visitLOAD(N);
1414 case ISD::STORE: return visitSTORE(N);
1415 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1416 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1417 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1418 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1419 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1420 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1421 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1422 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1423 case ISD::MGATHER: return visitMGATHER(N);
1424 case ISD::MLOAD: return visitMLOAD(N);
1425 case ISD::MSCATTER: return visitMSCATTER(N);
1426 case ISD::MSTORE: return visitMSTORE(N);
1427 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1428 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1433 SDValue DAGCombiner::combine(SDNode *N) {
1434 SDValue RV = visit(N);
1436 // If nothing happened, try a target-specific DAG combine.
1437 if (!RV.getNode()) {
1438 assert(N->getOpcode() != ISD::DELETED_NODE &&
1439 "Node was deleted but visit returned NULL!");
1441 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1442 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1444 // Expose the DAG combiner to the target combiner impls.
1445 TargetLowering::DAGCombinerInfo
1446 DagCombineInfo(DAG, Level, false, this);
1448 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1452 // If nothing happened still, try promoting the operation.
1453 if (!RV.getNode()) {
1454 switch (N->getOpcode()) {
1462 RV = PromoteIntBinOp(SDValue(N, 0));
1467 RV = PromoteIntShiftOp(SDValue(N, 0));
1469 case ISD::SIGN_EXTEND:
1470 case ISD::ZERO_EXTEND:
1471 case ISD::ANY_EXTEND:
1472 RV = PromoteExtend(SDValue(N, 0));
1475 if (PromoteLoad(SDValue(N, 0)))
1481 // If N is a commutative binary node, try commuting it to enable more
1483 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1484 N->getNumValues() == 1) {
1485 SDValue N0 = N->getOperand(0);
1486 SDValue N1 = N->getOperand(1);
1488 // Constant operands are canonicalized to RHS.
1489 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1490 SDValue Ops[] = {N1, N0};
1491 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1494 return SDValue(CSENode, 0);
1501 /// Given a node, return its input chain if it has one, otherwise return a null
1503 static SDValue getInputChainForNode(SDNode *N) {
1504 if (unsigned NumOps = N->getNumOperands()) {
1505 if (N->getOperand(0).getValueType() == MVT::Other)
1506 return N->getOperand(0);
1507 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1508 return N->getOperand(NumOps-1);
1509 for (unsigned i = 1; i < NumOps-1; ++i)
1510 if (N->getOperand(i).getValueType() == MVT::Other)
1511 return N->getOperand(i);
1516 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1517 // If N has two operands, where one has an input chain equal to the other,
1518 // the 'other' chain is redundant.
1519 if (N->getNumOperands() == 2) {
1520 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1521 return N->getOperand(0);
1522 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1523 return N->getOperand(1);
1526 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1527 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1528 SmallPtrSet<SDNode*, 16> SeenOps;
1529 bool Changed = false; // If we should replace this token factor.
1531 // Start out with this token factor.
1534 // Iterate through token factors. The TFs grows when new token factors are
1536 for (unsigned i = 0; i < TFs.size(); ++i) {
1537 SDNode *TF = TFs[i];
1539 // Check each of the operands.
1540 for (const SDValue &Op : TF->op_values()) {
1542 switch (Op.getOpcode()) {
1543 case ISD::EntryToken:
1544 // Entry tokens don't need to be added to the list. They are
1549 case ISD::TokenFactor:
1550 if (Op.hasOneUse() &&
1551 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1552 // Queue up for processing.
1553 TFs.push_back(Op.getNode());
1554 // Clean up in case the token factor is removed.
1555 AddToWorklist(Op.getNode());
1562 // Only add if it isn't already in the list.
1563 if (SeenOps.insert(Op.getNode()).second)
1574 // If we've changed things around then replace token factor.
1577 // The entry token is the only possible outcome.
1578 Result = DAG.getEntryNode();
1580 // New and improved token factor.
1581 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1584 // Add users to worklist if AA is enabled, since it may introduce
1585 // a lot of new chained token factors while removing memory deps.
1586 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1587 : DAG.getSubtarget().useAA();
1588 return CombineTo(N, Result, UseAA /*add to worklist*/);
1594 /// MERGE_VALUES can always be eliminated.
1595 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1596 WorklistRemover DeadNodes(*this);
1597 // Replacing results may cause a different MERGE_VALUES to suddenly
1598 // be CSE'd with N, and carry its uses with it. Iterate until no
1599 // uses remain, to ensure that the node can be safely deleted.
1600 // First add the users of this node to the work list so that they
1601 // can be tried again once they have new operands.
1602 AddUsersToWorklist(N);
1604 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1605 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1606 } while (!N->use_empty());
1607 deleteAndRecombine(N);
1608 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1611 static bool isNullConstant(SDValue V) {
1612 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1613 return Const != nullptr && Const->isNullValue();
1616 static bool isNullFPConstant(SDValue V) {
1617 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1618 return Const != nullptr && Const->isZero() && !Const->isNegative();
1621 static bool isAllOnesConstant(SDValue V) {
1622 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1623 return Const != nullptr && Const->isAllOnesValue();
1626 static bool isOneConstant(SDValue V) {
1627 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1628 return Const != nullptr && Const->isOne();
1631 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1632 /// ContantSDNode pointer else nullptr.
1633 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1634 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1635 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1638 SDValue DAGCombiner::visitADD(SDNode *N) {
1639 SDValue N0 = N->getOperand(0);
1640 SDValue N1 = N->getOperand(1);
1641 EVT VT = N0.getValueType();
1644 if (VT.isVector()) {
1645 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1648 // fold (add x, 0) -> x, vector edition
1649 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1651 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1655 // fold (add x, undef) -> undef
1656 if (N0.getOpcode() == ISD::UNDEF)
1658 if (N1.getOpcode() == ISD::UNDEF)
1660 // fold (add c1, c2) -> c1+c2
1661 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1662 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1664 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1665 // canonicalize constant to RHS
1666 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1667 !isConstantIntBuildVectorOrConstantInt(N1))
1668 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1669 // fold (add x, 0) -> x
1670 if (isNullConstant(N1))
1672 // fold (add Sym, c) -> Sym+c
1673 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1674 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1675 GA->getOpcode() == ISD::GlobalAddress)
1676 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1678 (uint64_t)N1C->getSExtValue());
1679 // fold ((c1-A)+c2) -> (c1+c2)-A
1680 if (N1C && N0.getOpcode() == ISD::SUB)
1681 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1683 return DAG.getNode(ISD::SUB, DL, VT,
1684 DAG.getConstant(N1C->getAPIntValue()+
1685 N0C->getAPIntValue(), DL, VT),
1689 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1691 // fold ((0-A) + B) -> B-A
1692 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1693 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1694 // fold (A + (0-B)) -> A-B
1695 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1696 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1697 // fold (A+(B-A)) -> B
1698 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1699 return N1.getOperand(0);
1700 // fold ((B-A)+A) -> B
1701 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1702 return N0.getOperand(0);
1703 // fold (A+(B-(A+C))) to (B-C)
1704 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1705 N0 == N1.getOperand(1).getOperand(0))
1706 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1707 N1.getOperand(1).getOperand(1));
1708 // fold (A+(B-(C+A))) to (B-C)
1709 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1710 N0 == N1.getOperand(1).getOperand(1))
1711 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1712 N1.getOperand(1).getOperand(0));
1713 // fold (A+((B-A)+or-C)) to (B+or-C)
1714 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1715 N1.getOperand(0).getOpcode() == ISD::SUB &&
1716 N0 == N1.getOperand(0).getOperand(1))
1717 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1718 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1720 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1721 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1722 SDValue N00 = N0.getOperand(0);
1723 SDValue N01 = N0.getOperand(1);
1724 SDValue N10 = N1.getOperand(0);
1725 SDValue N11 = N1.getOperand(1);
1727 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1728 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1729 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1730 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1733 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1734 return SDValue(N, 0);
1736 // fold (a+b) -> (a|b) iff a and b share no bits.
1737 if (VT.isInteger() && !VT.isVector()) {
1738 APInt LHSZero, LHSOne;
1739 APInt RHSZero, RHSOne;
1740 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1742 if (LHSZero.getBoolValue()) {
1743 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1745 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1746 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1747 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1748 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1749 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1754 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1755 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1756 isNullConstant(N1.getOperand(0).getOperand(0)))
1757 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1758 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1759 N1.getOperand(0).getOperand(1),
1761 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1762 isNullConstant(N0.getOperand(0).getOperand(0)))
1763 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1764 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1765 N0.getOperand(0).getOperand(1),
1768 if (N1.getOpcode() == ISD::AND) {
1769 SDValue AndOp0 = N1.getOperand(0);
1770 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1771 unsigned DestBits = VT.getScalarType().getSizeInBits();
1773 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1774 // and similar xforms where the inner op is either ~0 or 0.
1775 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1777 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1781 // add (sext i1), X -> sub X, (zext i1)
1782 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1783 N0.getOperand(0).getValueType() == MVT::i1 &&
1784 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1786 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1787 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1790 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1791 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1792 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1793 if (TN->getVT() == MVT::i1) {
1795 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1796 DAG.getConstant(1, DL, VT));
1797 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1804 SDValue DAGCombiner::visitADDC(SDNode *N) {
1805 SDValue N0 = N->getOperand(0);
1806 SDValue N1 = N->getOperand(1);
1807 EVT VT = N0.getValueType();
1809 // If the flag result is dead, turn this into an ADD.
1810 if (!N->hasAnyUseOfValue(1))
1811 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1812 DAG.getNode(ISD::CARRY_FALSE,
1813 SDLoc(N), MVT::Glue));
1815 // canonicalize constant to RHS.
1816 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1817 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1819 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1821 // fold (addc x, 0) -> x + no carry out
1822 if (isNullConstant(N1))
1823 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1824 SDLoc(N), MVT::Glue));
1826 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1827 APInt LHSZero, LHSOne;
1828 APInt RHSZero, RHSOne;
1829 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1831 if (LHSZero.getBoolValue()) {
1832 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1834 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1835 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1836 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1837 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1838 DAG.getNode(ISD::CARRY_FALSE,
1839 SDLoc(N), MVT::Glue));
1845 SDValue DAGCombiner::visitADDE(SDNode *N) {
1846 SDValue N0 = N->getOperand(0);
1847 SDValue N1 = N->getOperand(1);
1848 SDValue CarryIn = N->getOperand(2);
1850 // canonicalize constant to RHS
1851 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1852 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1854 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1857 // fold (adde x, y, false) -> (addc x, y)
1858 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1859 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1864 // Since it may not be valid to emit a fold to zero for vector initializers
1865 // check if we can before folding.
1866 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1868 bool LegalOperations, bool LegalTypes) {
1870 return DAG.getConstant(0, DL, VT);
1871 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1872 return DAG.getConstant(0, DL, VT);
1876 SDValue DAGCombiner::visitSUB(SDNode *N) {
1877 SDValue N0 = N->getOperand(0);
1878 SDValue N1 = N->getOperand(1);
1879 EVT VT = N0.getValueType();
1882 if (VT.isVector()) {
1883 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1886 // fold (sub x, 0) -> x, vector edition
1887 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1891 // fold (sub x, x) -> 0
1892 // FIXME: Refactor this and xor and other similar operations together.
1894 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1895 // fold (sub c1, c2) -> c1-c2
1896 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1897 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1899 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1900 // fold (sub x, c) -> (add x, -c)
1903 return DAG.getNode(ISD::ADD, DL, VT, N0,
1904 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1906 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1907 if (isAllOnesConstant(N0))
1908 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1909 // fold A-(A-B) -> B
1910 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1911 return N1.getOperand(1);
1912 // fold (A+B)-A -> B
1913 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1914 return N0.getOperand(1);
1915 // fold (A+B)-B -> A
1916 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1917 return N0.getOperand(0);
1918 // fold C2-(A+C1) -> (C2-C1)-A
1919 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1920 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1921 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1923 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1925 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1928 // fold ((A+(B+or-C))-B) -> A+or-C
1929 if (N0.getOpcode() == ISD::ADD &&
1930 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1931 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1932 N0.getOperand(1).getOperand(0) == N1)
1933 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1934 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1935 // fold ((A+(C+B))-B) -> A+C
1936 if (N0.getOpcode() == ISD::ADD &&
1937 N0.getOperand(1).getOpcode() == ISD::ADD &&
1938 N0.getOperand(1).getOperand(1) == N1)
1939 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1940 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1941 // fold ((A-(B-C))-C) -> A-B
1942 if (N0.getOpcode() == ISD::SUB &&
1943 N0.getOperand(1).getOpcode() == ISD::SUB &&
1944 N0.getOperand(1).getOperand(1) == N1)
1945 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1946 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1948 // If either operand of a sub is undef, the result is undef
1949 if (N0.getOpcode() == ISD::UNDEF)
1951 if (N1.getOpcode() == ISD::UNDEF)
1954 // If the relocation model supports it, consider symbol offsets.
1955 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1956 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1957 // fold (sub Sym, c) -> Sym-c
1958 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1959 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1961 (uint64_t)N1C->getSExtValue());
1962 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1963 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1964 if (GA->getGlobal() == GB->getGlobal())
1965 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1969 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1970 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1971 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1972 if (TN->getVT() == MVT::i1) {
1974 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1975 DAG.getConstant(1, DL, VT));
1976 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1983 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1984 SDValue N0 = N->getOperand(0);
1985 SDValue N1 = N->getOperand(1);
1986 EVT VT = N0.getValueType();
1988 // If the flag result is dead, turn this into an SUB.
1989 if (!N->hasAnyUseOfValue(1))
1990 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1991 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1994 // fold (subc x, x) -> 0 + no borrow
1997 return CombineTo(N, DAG.getConstant(0, DL, VT),
1998 DAG.getNode(ISD::CARRY_FALSE, DL,
2002 // fold (subc x, 0) -> x + no borrow
2003 if (isNullConstant(N1))
2004 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2007 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2008 if (isAllOnesConstant(N0))
2009 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2010 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2016 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2017 SDValue N0 = N->getOperand(0);
2018 SDValue N1 = N->getOperand(1);
2019 SDValue CarryIn = N->getOperand(2);
2021 // fold (sube x, y, false) -> (subc x, y)
2022 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2023 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2028 SDValue DAGCombiner::visitMUL(SDNode *N) {
2029 SDValue N0 = N->getOperand(0);
2030 SDValue N1 = N->getOperand(1);
2031 EVT VT = N0.getValueType();
2033 // fold (mul x, undef) -> 0
2034 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2035 return DAG.getConstant(0, SDLoc(N), VT);
2037 bool N0IsConst = false;
2038 bool N1IsConst = false;
2039 bool N1IsOpaqueConst = false;
2040 bool N0IsOpaqueConst = false;
2041 APInt ConstValue0, ConstValue1;
2043 if (VT.isVector()) {
2044 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2047 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2048 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2050 N0IsConst = isa<ConstantSDNode>(N0);
2052 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2053 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2055 N1IsConst = isa<ConstantSDNode>(N1);
2057 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2058 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2062 // fold (mul c1, c2) -> c1*c2
2063 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2064 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2065 N0.getNode(), N1.getNode());
2067 // canonicalize constant to RHS (vector doesn't have to splat)
2068 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2069 !isConstantIntBuildVectorOrConstantInt(N1))
2070 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2071 // fold (mul x, 0) -> 0
2072 if (N1IsConst && ConstValue1 == 0)
2074 // We require a splat of the entire scalar bit width for non-contiguous
2077 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2078 // fold (mul x, 1) -> x
2079 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2081 // fold (mul x, -1) -> 0-x
2082 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2084 return DAG.getNode(ISD::SUB, DL, VT,
2085 DAG.getConstant(0, DL, VT), N0);
2087 // fold (mul x, (1 << c)) -> x << c
2088 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2091 return DAG.getNode(ISD::SHL, DL, VT, N0,
2092 DAG.getConstant(ConstValue1.logBase2(), DL,
2093 getShiftAmountTy(N0.getValueType())));
2095 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2096 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2098 unsigned Log2Val = (-ConstValue1).logBase2();
2100 // FIXME: If the input is something that is easily negated (e.g. a
2101 // single-use add), we should put the negate there.
2102 return DAG.getNode(ISD::SUB, DL, VT,
2103 DAG.getConstant(0, DL, VT),
2104 DAG.getNode(ISD::SHL, DL, VT, N0,
2105 DAG.getConstant(Log2Val, DL,
2106 getShiftAmountTy(N0.getValueType()))));
2110 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2111 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2112 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2113 isa<ConstantSDNode>(N0.getOperand(1)))) {
2114 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2115 N1, N0.getOperand(1));
2116 AddToWorklist(C3.getNode());
2117 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2118 N0.getOperand(0), C3);
2121 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2124 SDValue Sh(nullptr,0), Y(nullptr,0);
2125 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2126 if (N0.getOpcode() == ISD::SHL &&
2127 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2128 isa<ConstantSDNode>(N0.getOperand(1))) &&
2129 N0.getNode()->hasOneUse()) {
2131 } else if (N1.getOpcode() == ISD::SHL &&
2132 isa<ConstantSDNode>(N1.getOperand(1)) &&
2133 N1.getNode()->hasOneUse()) {
2138 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2139 Sh.getOperand(0), Y);
2140 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2141 Mul, Sh.getOperand(1));
2145 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2146 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2147 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2148 isa<ConstantSDNode>(N0.getOperand(1))))
2149 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2150 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2151 N0.getOperand(0), N1),
2152 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2153 N0.getOperand(1), N1));
2156 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2162 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2163 SDValue N0 = N->getOperand(0);
2164 SDValue N1 = N->getOperand(1);
2165 EVT VT = N->getValueType(0);
2169 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2172 // fold (sdiv c1, c2) -> c1/c2
2173 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2174 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2175 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2176 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2177 // fold (sdiv X, 1) -> X
2178 if (N1C && N1C->isOne())
2180 // fold (sdiv X, -1) -> 0-X
2181 if (N1C && N1C->isAllOnesValue()) {
2183 return DAG.getNode(ISD::SUB, DL, VT,
2184 DAG.getConstant(0, DL, VT), N0);
2186 // If we know the sign bits of both operands are zero, strength reduce to a
2187 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2188 if (!VT.isVector()) {
2189 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2190 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2194 // fold (sdiv X, pow2) -> simple ops after legalize
2195 // FIXME: We check for the exact bit here because the generic lowering gives
2196 // better results in that case. The target-specific lowering should learn how
2197 // to handle exact sdivs efficiently.
2198 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2199 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2200 (N1C->getAPIntValue().isPowerOf2() ||
2201 (-N1C->getAPIntValue()).isPowerOf2())) {
2202 // Target-specific implementation of sdiv x, pow2.
2203 if (SDValue Res = BuildSDIVPow2(N))
2206 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2209 // Splat the sign bit into the register
2211 DAG.getNode(ISD::SRA, DL, VT, N0,
2212 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2213 getShiftAmountTy(N0.getValueType())));
2214 AddToWorklist(SGN.getNode());
2216 // Add (N0 < 0) ? abs2 - 1 : 0;
2218 DAG.getNode(ISD::SRL, DL, VT, SGN,
2219 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2220 getShiftAmountTy(SGN.getValueType())));
2221 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2222 AddToWorklist(SRL.getNode());
2223 AddToWorklist(ADD.getNode()); // Divide by pow2
2224 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2225 DAG.getConstant(lg2, DL,
2226 getShiftAmountTy(ADD.getValueType())));
2228 // If we're dividing by a positive value, we're done. Otherwise, we must
2229 // negate the result.
2230 if (N1C->getAPIntValue().isNonNegative())
2233 AddToWorklist(SRA.getNode());
2234 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2237 // If integer divide is expensive and we satisfy the requirements, emit an
2238 // alternate sequence. Targets may check function attributes for size/speed
2240 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2241 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2242 if (SDValue Op = BuildSDIV(N))
2246 if (N0.getOpcode() == ISD::UNDEF)
2247 return DAG.getConstant(0, SDLoc(N), VT);
2248 // X / undef -> undef
2249 if (N1.getOpcode() == ISD::UNDEF)
2255 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2256 SDValue N0 = N->getOperand(0);
2257 SDValue N1 = N->getOperand(1);
2258 EVT VT = N->getValueType(0);
2262 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2265 // fold (udiv c1, c2) -> c1/c2
2266 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2267 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2269 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2272 // fold (udiv x, (1 << c)) -> x >>u c
2273 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2275 return DAG.getNode(ISD::SRL, DL, VT, N0,
2276 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2277 getShiftAmountTy(N0.getValueType())));
2279 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2280 if (N1.getOpcode() == ISD::SHL) {
2281 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2282 if (SHC->getAPIntValue().isPowerOf2()) {
2283 EVT ADDVT = N1.getOperand(1).getValueType();
2285 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2287 DAG.getConstant(SHC->getAPIntValue()
2290 AddToWorklist(Add.getNode());
2291 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2296 // fold (udiv x, c) -> alternate
2297 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2298 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2299 if (SDValue Op = BuildUDIV(N))
2303 if (N0.getOpcode() == ISD::UNDEF)
2304 return DAG.getConstant(0, SDLoc(N), VT);
2305 // X / undef -> undef
2306 if (N1.getOpcode() == ISD::UNDEF)
2312 SDValue DAGCombiner::visitSREM(SDNode *N) {
2313 SDValue N0 = N->getOperand(0);
2314 SDValue N1 = N->getOperand(1);
2315 EVT VT = N->getValueType(0);
2317 // fold (srem c1, c2) -> c1%c2
2318 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2319 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2321 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2324 // If we know the sign bits of both operands are zero, strength reduce to a
2325 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2326 if (!VT.isVector()) {
2327 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2328 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2331 // If X/C can be simplified by the division-by-constant logic, lower
2332 // X%C to the equivalent of X-X/C*C.
2333 if (N1C && !N1C->isNullValue()) {
2334 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2335 AddToWorklist(Div.getNode());
2336 SDValue OptimizedDiv = combine(Div.getNode());
2337 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2338 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2340 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2341 AddToWorklist(Mul.getNode());
2347 if (N0.getOpcode() == ISD::UNDEF)
2348 return DAG.getConstant(0, SDLoc(N), VT);
2349 // X % undef -> undef
2350 if (N1.getOpcode() == ISD::UNDEF)
2356 SDValue DAGCombiner::visitUREM(SDNode *N) {
2357 SDValue N0 = N->getOperand(0);
2358 SDValue N1 = N->getOperand(1);
2359 EVT VT = N->getValueType(0);
2361 // fold (urem c1, c2) -> c1%c2
2362 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2363 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2365 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2368 // fold (urem x, pow2) -> (and x, pow2-1)
2369 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2370 N1C->getAPIntValue().isPowerOf2()) {
2372 return DAG.getNode(ISD::AND, DL, VT, N0,
2373 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2375 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2376 if (N1.getOpcode() == ISD::SHL) {
2377 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2378 if (SHC->getAPIntValue().isPowerOf2()) {
2381 DAG.getNode(ISD::ADD, DL, VT, N1,
2382 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2384 AddToWorklist(Add.getNode());
2385 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2390 // If X/C can be simplified by the division-by-constant logic, lower
2391 // X%C to the equivalent of X-X/C*C.
2392 if (N1C && !N1C->isNullValue()) {
2393 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2394 AddToWorklist(Div.getNode());
2395 SDValue OptimizedDiv = combine(Div.getNode());
2396 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2397 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2399 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2400 AddToWorklist(Mul.getNode());
2406 if (N0.getOpcode() == ISD::UNDEF)
2407 return DAG.getConstant(0, SDLoc(N), VT);
2408 // X % undef -> undef
2409 if (N1.getOpcode() == ISD::UNDEF)
2415 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2416 SDValue N0 = N->getOperand(0);
2417 SDValue N1 = N->getOperand(1);
2418 EVT VT = N->getValueType(0);
2421 // fold (mulhs x, 0) -> 0
2422 if (isNullConstant(N1))
2424 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2425 if (isOneConstant(N1)) {
2427 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2428 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2430 getShiftAmountTy(N0.getValueType())));
2432 // fold (mulhs x, undef) -> 0
2433 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2434 return DAG.getConstant(0, SDLoc(N), VT);
2436 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2438 if (VT.isSimple() && !VT.isVector()) {
2439 MVT Simple = VT.getSimpleVT();
2440 unsigned SimpleSize = Simple.getSizeInBits();
2441 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2442 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2443 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2444 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2445 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2446 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2447 DAG.getConstant(SimpleSize, DL,
2448 getShiftAmountTy(N1.getValueType())));
2449 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2456 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2457 SDValue N0 = N->getOperand(0);
2458 SDValue N1 = N->getOperand(1);
2459 EVT VT = N->getValueType(0);
2462 // fold (mulhu x, 0) -> 0
2463 if (isNullConstant(N1))
2465 // fold (mulhu x, 1) -> 0
2466 if (isOneConstant(N1))
2467 return DAG.getConstant(0, DL, N0.getValueType());
2468 // fold (mulhu x, undef) -> 0
2469 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2470 return DAG.getConstant(0, DL, VT);
2472 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2474 if (VT.isSimple() && !VT.isVector()) {
2475 MVT Simple = VT.getSimpleVT();
2476 unsigned SimpleSize = Simple.getSizeInBits();
2477 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2478 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2479 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2480 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2481 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2482 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2483 DAG.getConstant(SimpleSize, DL,
2484 getShiftAmountTy(N1.getValueType())));
2485 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2492 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2493 /// give the opcodes for the two computations that are being performed. Return
2494 /// true if a simplification was made.
2495 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2497 // If the high half is not needed, just compute the low half.
2498 bool HiExists = N->hasAnyUseOfValue(1);
2500 (!LegalOperations ||
2501 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2502 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2503 return CombineTo(N, Res, Res);
2506 // If the low half is not needed, just compute the high half.
2507 bool LoExists = N->hasAnyUseOfValue(0);
2509 (!LegalOperations ||
2510 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2511 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2512 return CombineTo(N, Res, Res);
2515 // If both halves are used, return as it is.
2516 if (LoExists && HiExists)
2519 // If the two computed results can be simplified separately, separate them.
2521 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2522 AddToWorklist(Lo.getNode());
2523 SDValue LoOpt = combine(Lo.getNode());
2524 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2525 (!LegalOperations ||
2526 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2527 return CombineTo(N, LoOpt, LoOpt);
2531 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2532 AddToWorklist(Hi.getNode());
2533 SDValue HiOpt = combine(Hi.getNode());
2534 if (HiOpt.getNode() && HiOpt != Hi &&
2535 (!LegalOperations ||
2536 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2537 return CombineTo(N, HiOpt, HiOpt);
2543 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2544 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2547 EVT VT = N->getValueType(0);
2550 // If the type is twice as wide is legal, transform the mulhu to a wider
2551 // multiply plus a shift.
2552 if (VT.isSimple() && !VT.isVector()) {
2553 MVT Simple = VT.getSimpleVT();
2554 unsigned SimpleSize = Simple.getSizeInBits();
2555 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2556 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2557 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2558 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2559 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2560 // Compute the high part as N1.
2561 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2562 DAG.getConstant(SimpleSize, DL,
2563 getShiftAmountTy(Lo.getValueType())));
2564 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2565 // Compute the low part as N0.
2566 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2567 return CombineTo(N, Lo, Hi);
2574 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2575 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2578 EVT VT = N->getValueType(0);
2581 // If the type is twice as wide is legal, transform the mulhu to a wider
2582 // multiply plus a shift.
2583 if (VT.isSimple() && !VT.isVector()) {
2584 MVT Simple = VT.getSimpleVT();
2585 unsigned SimpleSize = Simple.getSizeInBits();
2586 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2587 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2588 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2589 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2590 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2591 // Compute the high part as N1.
2592 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2593 DAG.getConstant(SimpleSize, DL,
2594 getShiftAmountTy(Lo.getValueType())));
2595 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2596 // Compute the low part as N0.
2597 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2598 return CombineTo(N, Lo, Hi);
2605 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2606 // (smulo x, 2) -> (saddo x, x)
2607 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2608 if (C2->getAPIntValue() == 2)
2609 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2610 N->getOperand(0), N->getOperand(0));
2615 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2616 // (umulo x, 2) -> (uaddo x, x)
2617 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2618 if (C2->getAPIntValue() == 2)
2619 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2620 N->getOperand(0), N->getOperand(0));
2625 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2626 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2632 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2633 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2639 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2640 SDValue N0 = N->getOperand(0);
2641 SDValue N1 = N->getOperand(1);
2642 EVT VT = N0.getValueType();
2646 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2649 // fold (add c1, c2) -> c1+c2
2650 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2651 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2653 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2655 // canonicalize constant to RHS
2656 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2657 !isConstantIntBuildVectorOrConstantInt(N1))
2658 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2663 /// If this is a binary operator with two operands of the same opcode, try to
2665 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2666 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2667 EVT VT = N0.getValueType();
2668 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2670 // Bail early if none of these transforms apply.
2671 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2673 // For each of OP in AND/OR/XOR:
2674 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2675 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2676 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2677 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2678 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2680 // do not sink logical op inside of a vector extend, since it may combine
2682 EVT Op0VT = N0.getOperand(0).getValueType();
2683 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2684 N0.getOpcode() == ISD::SIGN_EXTEND ||
2685 N0.getOpcode() == ISD::BSWAP ||
2686 // Avoid infinite looping with PromoteIntBinOp.
2687 (N0.getOpcode() == ISD::ANY_EXTEND &&
2688 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2689 (N0.getOpcode() == ISD::TRUNCATE &&
2690 (!TLI.isZExtFree(VT, Op0VT) ||
2691 !TLI.isTruncateFree(Op0VT, VT)) &&
2692 TLI.isTypeLegal(Op0VT))) &&
2694 Op0VT == N1.getOperand(0).getValueType() &&
2695 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2696 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2697 N0.getOperand(0).getValueType(),
2698 N0.getOperand(0), N1.getOperand(0));
2699 AddToWorklist(ORNode.getNode());
2700 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2703 // For each of OP in SHL/SRL/SRA/AND...
2704 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2705 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2706 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2707 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2708 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2709 N0.getOperand(1) == N1.getOperand(1)) {
2710 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2711 N0.getOperand(0).getValueType(),
2712 N0.getOperand(0), N1.getOperand(0));
2713 AddToWorklist(ORNode.getNode());
2714 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2715 ORNode, N0.getOperand(1));
2718 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2719 // Only perform this optimization after type legalization and before
2720 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2721 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2722 // we don't want to undo this promotion.
2723 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2725 if ((N0.getOpcode() == ISD::BITCAST ||
2726 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2727 Level == AfterLegalizeTypes) {
2728 SDValue In0 = N0.getOperand(0);
2729 SDValue In1 = N1.getOperand(0);
2730 EVT In0Ty = In0.getValueType();
2731 EVT In1Ty = In1.getValueType();
2733 // If both incoming values are integers, and the original types are the
2735 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2736 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2737 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2738 AddToWorklist(Op.getNode());
2743 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2744 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2745 // If both shuffles use the same mask, and both shuffle within a single
2746 // vector, then it is worthwhile to move the swizzle after the operation.
2747 // The type-legalizer generates this pattern when loading illegal
2748 // vector types from memory. In many cases this allows additional shuffle
2750 // There are other cases where moving the shuffle after the xor/and/or
2751 // is profitable even if shuffles don't perform a swizzle.
2752 // If both shuffles use the same mask, and both shuffles have the same first
2753 // or second operand, then it might still be profitable to move the shuffle
2754 // after the xor/and/or operation.
2755 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2756 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2757 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2759 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2760 "Inputs to shuffles are not the same type");
2762 // Check that both shuffles use the same mask. The masks are known to be of
2763 // the same length because the result vector type is the same.
2764 // Check also that shuffles have only one use to avoid introducing extra
2766 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2767 SVN0->getMask().equals(SVN1->getMask())) {
2768 SDValue ShOp = N0->getOperand(1);
2770 // Don't try to fold this node if it requires introducing a
2771 // build vector of all zeros that might be illegal at this stage.
2772 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2774 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2779 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2780 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2781 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2782 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2783 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2784 N0->getOperand(0), N1->getOperand(0));
2785 AddToWorklist(NewNode.getNode());
2786 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2787 &SVN0->getMask()[0]);
2790 // Don't try to fold this node if it requires introducing a
2791 // build vector of all zeros that might be illegal at this stage.
2792 ShOp = N0->getOperand(0);
2793 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2795 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2800 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2801 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2802 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2803 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2804 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2805 N0->getOperand(1), N1->getOperand(1));
2806 AddToWorklist(NewNode.getNode());
2807 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2808 &SVN0->getMask()[0]);
2816 /// This contains all DAGCombine rules which reduce two values combined by
2817 /// an And operation to a single value. This makes them reusable in the context
2818 /// of visitSELECT(). Rules involving constants are not included as
2819 /// visitSELECT() already handles those cases.
2820 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2821 SDNode *LocReference) {
2822 EVT VT = N1.getValueType();
2824 // fold (and x, undef) -> 0
2825 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2826 return DAG.getConstant(0, SDLoc(LocReference), VT);
2827 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2828 SDValue LL, LR, RL, RR, CC0, CC1;
2829 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2830 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2831 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2833 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2834 LL.getValueType().isInteger()) {
2835 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2836 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2837 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2838 LR.getValueType(), LL, RL);
2839 AddToWorklist(ORNode.getNode());
2840 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2842 if (isAllOnesConstant(LR)) {
2843 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2844 if (Op1 == ISD::SETEQ) {
2845 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2846 LR.getValueType(), LL, RL);
2847 AddToWorklist(ANDNode.getNode());
2848 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2850 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2851 if (Op1 == ISD::SETGT) {
2852 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2853 LR.getValueType(), LL, RL);
2854 AddToWorklist(ORNode.getNode());
2855 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2859 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2860 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2861 Op0 == Op1 && LL.getValueType().isInteger() &&
2862 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2863 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2865 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2866 LL, DAG.getConstant(1, DL,
2867 LL.getValueType()));
2868 AddToWorklist(ADDNode.getNode());
2869 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2870 DAG.getConstant(2, DL, LL.getValueType()),
2873 // canonicalize equivalent to ll == rl
2874 if (LL == RR && LR == RL) {
2875 Op1 = ISD::getSetCCSwappedOperands(Op1);
2878 if (LL == RL && LR == RR) {
2879 bool isInteger = LL.getValueType().isInteger();
2880 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2881 if (Result != ISD::SETCC_INVALID &&
2882 (!LegalOperations ||
2883 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2884 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2885 EVT CCVT = getSetCCResultType(LL.getValueType());
2886 if (N0.getValueType() == CCVT ||
2887 (!LegalOperations && N0.getValueType() == MVT::i1))
2888 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2894 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2895 VT.getSizeInBits() <= 64) {
2896 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2897 APInt ADDC = ADDI->getAPIntValue();
2898 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2899 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2900 // immediate for an add, but it is legal if its top c2 bits are set,
2901 // transform the ADD so the immediate doesn't need to be materialized
2903 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2904 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2905 SRLI->getZExtValue());
2906 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2908 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2911 DAG.getNode(ISD::ADD, DL, VT,
2912 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2913 CombineTo(N0.getNode(), NewAdd);
2914 // Return N so it doesn't get rechecked!
2915 return SDValue(LocReference, 0);
2926 SDValue DAGCombiner::visitAND(SDNode *N) {
2927 SDValue N0 = N->getOperand(0);
2928 SDValue N1 = N->getOperand(1);
2929 EVT VT = N1.getValueType();
2932 if (VT.isVector()) {
2933 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2936 // fold (and x, 0) -> 0, vector edition
2937 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2938 // do not return N0, because undef node may exist in N0
2939 return DAG.getConstant(
2940 APInt::getNullValue(
2941 N0.getValueType().getScalarType().getSizeInBits()),
2942 SDLoc(N), N0.getValueType());
2943 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2944 // do not return N1, because undef node may exist in N1
2945 return DAG.getConstant(
2946 APInt::getNullValue(
2947 N1.getValueType().getScalarType().getSizeInBits()),
2948 SDLoc(N), N1.getValueType());
2950 // fold (and x, -1) -> x, vector edition
2951 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2953 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2957 // fold (and c1, c2) -> c1&c2
2958 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2959 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2960 if (N0C && N1C && !N1C->isOpaque())
2961 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2962 // canonicalize constant to RHS
2963 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2964 !isConstantIntBuildVectorOrConstantInt(N1))
2965 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2966 // fold (and x, -1) -> x
2967 if (isAllOnesConstant(N1))
2969 // if (and x, c) is known to be zero, return 0
2970 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2971 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2972 APInt::getAllOnesValue(BitWidth)))
2973 return DAG.getConstant(0, SDLoc(N), VT);
2975 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2977 // fold (and (or x, C), D) -> D if (C & D) == D
2978 if (N1C && N0.getOpcode() == ISD::OR)
2979 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2980 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2982 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2983 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2984 SDValue N0Op0 = N0.getOperand(0);
2985 APInt Mask = ~N1C->getAPIntValue();
2986 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2987 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2988 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2989 N0.getValueType(), N0Op0);
2991 // Replace uses of the AND with uses of the Zero extend node.
2994 // We actually want to replace all uses of the any_extend with the
2995 // zero_extend, to avoid duplicating things. This will later cause this
2996 // AND to be folded.
2997 CombineTo(N0.getNode(), Zext);
2998 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3001 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3002 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3003 // already be zero by virtue of the width of the base type of the load.
3005 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3007 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3008 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3009 N0.getOpcode() == ISD::LOAD) {
3010 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3011 N0 : N0.getOperand(0) );
3013 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3014 // This can be a pure constant or a vector splat, in which case we treat the
3015 // vector as a scalar and use the splat value.
3016 APInt Constant = APInt::getNullValue(1);
3017 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3018 Constant = C->getAPIntValue();
3019 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3020 APInt SplatValue, SplatUndef;
3021 unsigned SplatBitSize;
3023 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3024 SplatBitSize, HasAnyUndefs);
3026 // Undef bits can contribute to a possible optimisation if set, so
3028 SplatValue |= SplatUndef;
3030 // The splat value may be something like "0x00FFFFFF", which means 0 for
3031 // the first vector value and FF for the rest, repeating. We need a mask
3032 // that will apply equally to all members of the vector, so AND all the
3033 // lanes of the constant together.
3034 EVT VT = Vector->getValueType(0);
3035 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3037 // If the splat value has been compressed to a bitlength lower
3038 // than the size of the vector lane, we need to re-expand it to
3040 if (BitWidth > SplatBitSize)
3041 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3042 SplatBitSize < BitWidth;
3043 SplatBitSize = SplatBitSize * 2)
3044 SplatValue |= SplatValue.shl(SplatBitSize);
3046 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3047 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3048 if (SplatBitSize % BitWidth == 0) {
3049 Constant = APInt::getAllOnesValue(BitWidth);
3050 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3051 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3056 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3057 // actually legal and isn't going to get expanded, else this is a false
3059 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3060 Load->getValueType(0),
3061 Load->getMemoryVT());
3063 // Resize the constant to the same size as the original memory access before
3064 // extension. If it is still the AllOnesValue then this AND is completely
3067 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3070 switch (Load->getExtensionType()) {
3071 default: B = false; break;
3072 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3074 case ISD::NON_EXTLOAD: B = true; break;
3077 if (B && Constant.isAllOnesValue()) {
3078 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3079 // preserve semantics once we get rid of the AND.
3080 SDValue NewLoad(Load, 0);
3081 if (Load->getExtensionType() == ISD::EXTLOAD) {
3082 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3083 Load->getValueType(0), SDLoc(Load),
3084 Load->getChain(), Load->getBasePtr(),
3085 Load->getOffset(), Load->getMemoryVT(),
3086 Load->getMemOperand());
3087 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3088 if (Load->getNumValues() == 3) {
3089 // PRE/POST_INC loads have 3 values.
3090 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3091 NewLoad.getValue(2) };
3092 CombineTo(Load, To, 3, true);
3094 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3098 // Fold the AND away, taking care not to fold to the old load node if we
3100 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3102 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3106 // fold (and (load x), 255) -> (zextload x, i8)
3107 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3108 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3109 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3110 (N0.getOpcode() == ISD::ANY_EXTEND &&
3111 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3112 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3113 LoadSDNode *LN0 = HasAnyExt
3114 ? cast<LoadSDNode>(N0.getOperand(0))
3115 : cast<LoadSDNode>(N0);
3116 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3117 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3118 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3119 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3120 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3121 EVT LoadedVT = LN0->getMemoryVT();
3122 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3124 if (ExtVT == LoadedVT &&
3125 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3129 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3130 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3131 LN0->getMemOperand());
3133 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3134 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3137 // Do not change the width of a volatile load.
3138 // Do not generate loads of non-round integer types since these can
3139 // be expensive (and would be wrong if the type is not byte sized).
3140 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3141 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3143 EVT PtrType = LN0->getOperand(1).getValueType();
3145 unsigned Alignment = LN0->getAlignment();
3146 SDValue NewPtr = LN0->getBasePtr();
3148 // For big endian targets, we need to add an offset to the pointer
3149 // to load the correct bytes. For little endian systems, we merely
3150 // need to read fewer bytes from the same pointer.
3151 if (DAG.getDataLayout().isBigEndian()) {
3152 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3153 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3154 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3156 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3157 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3158 Alignment = MinAlign(Alignment, PtrOff);
3161 AddToWorklist(NewPtr.getNode());
3164 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3165 LN0->getChain(), NewPtr,
3166 LN0->getPointerInfo(),
3167 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3168 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3170 CombineTo(LN0, Load, Load.getValue(1));
3171 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3177 if (SDValue Combined = visitANDLike(N0, N1, N))
3180 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3181 if (N0.getOpcode() == N1.getOpcode())
3182 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3185 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3186 // fold (and (sra)) -> (and (srl)) when possible.
3187 if (!VT.isVector() &&
3188 SimplifyDemandedBits(SDValue(N, 0)))
3189 return SDValue(N, 0);
3191 // fold (zext_inreg (extload x)) -> (zextload x)
3192 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3193 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3194 EVT MemVT = LN0->getMemoryVT();
3195 // If we zero all the possible extended bits, then we can turn this into
3196 // a zextload if we are running before legalize or the operation is legal.
3197 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3198 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3199 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3200 ((!LegalOperations && !LN0->isVolatile()) ||
3201 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3202 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3203 LN0->getChain(), LN0->getBasePtr(),
3204 MemVT, LN0->getMemOperand());
3206 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3207 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3210 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3211 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3213 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3214 EVT MemVT = LN0->getMemoryVT();
3215 // If we zero all the possible extended bits, then we can turn this into
3216 // a zextload if we are running before legalize or the operation is legal.
3217 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3218 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3219 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3220 ((!LegalOperations && !LN0->isVolatile()) ||
3221 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3222 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3223 LN0->getChain(), LN0->getBasePtr(),
3224 MemVT, LN0->getMemOperand());
3226 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3227 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3230 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3231 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3232 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3233 N0.getOperand(1), false);
3234 if (BSwap.getNode())
3241 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3242 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3243 bool DemandHighBits) {
3244 if (!LegalOperations)
3247 EVT VT = N->getValueType(0);
3248 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3250 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3253 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3254 bool LookPassAnd0 = false;
3255 bool LookPassAnd1 = false;
3256 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3258 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3260 if (N0.getOpcode() == ISD::AND) {
3261 if (!N0.getNode()->hasOneUse())
3263 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3264 if (!N01C || N01C->getZExtValue() != 0xFF00)
3266 N0 = N0.getOperand(0);
3267 LookPassAnd0 = true;
3270 if (N1.getOpcode() == ISD::AND) {
3271 if (!N1.getNode()->hasOneUse())
3273 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3274 if (!N11C || N11C->getZExtValue() != 0xFF)
3276 N1 = N1.getOperand(0);
3277 LookPassAnd1 = true;
3280 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3282 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3284 if (!N0.getNode()->hasOneUse() ||
3285 !N1.getNode()->hasOneUse())
3288 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3289 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3292 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3295 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3296 SDValue N00 = N0->getOperand(0);
3297 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3298 if (!N00.getNode()->hasOneUse())
3300 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3301 if (!N001C || N001C->getZExtValue() != 0xFF)
3303 N00 = N00.getOperand(0);
3304 LookPassAnd0 = true;
3307 SDValue N10 = N1->getOperand(0);
3308 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3309 if (!N10.getNode()->hasOneUse())
3311 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3312 if (!N101C || N101C->getZExtValue() != 0xFF00)
3314 N10 = N10.getOperand(0);
3315 LookPassAnd1 = true;
3321 // Make sure everything beyond the low halfword gets set to zero since the SRL
3322 // 16 will clear the top bits.
3323 unsigned OpSizeInBits = VT.getSizeInBits();
3324 if (DemandHighBits && OpSizeInBits > 16) {
3325 // If the left-shift isn't masked out then the only way this is a bswap is
3326 // if all bits beyond the low 8 are 0. In that case the entire pattern
3327 // reduces to a left shift anyway: leave it for other parts of the combiner.
3331 // However, if the right shift isn't masked out then it might be because
3332 // it's not needed. See if we can spot that too.
3333 if (!LookPassAnd1 &&
3334 !DAG.MaskedValueIsZero(
3335 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3339 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3340 if (OpSizeInBits > 16) {
3342 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3343 DAG.getConstant(OpSizeInBits - 16, DL,
3344 getShiftAmountTy(VT)));
3349 /// Return true if the specified node is an element that makes up a 32-bit
3350 /// packed halfword byteswap.
3351 /// ((x & 0x000000ff) << 8) |
3352 /// ((x & 0x0000ff00) >> 8) |
3353 /// ((x & 0x00ff0000) << 8) |
3354 /// ((x & 0xff000000) >> 8)
3355 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3356 if (!N.getNode()->hasOneUse())
3359 unsigned Opc = N.getOpcode();
3360 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3363 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3368 switch (N1C->getZExtValue()) {
3371 case 0xFF: Num = 0; break;
3372 case 0xFF00: Num = 1; break;
3373 case 0xFF0000: Num = 2; break;
3374 case 0xFF000000: Num = 3; break;
3377 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3378 SDValue N0 = N.getOperand(0);
3379 if (Opc == ISD::AND) {
3380 if (Num == 0 || Num == 2) {
3382 // (x >> 8) & 0xff0000
3383 if (N0.getOpcode() != ISD::SRL)
3385 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3386 if (!C || C->getZExtValue() != 8)
3389 // (x << 8) & 0xff00
3390 // (x << 8) & 0xff000000
3391 if (N0.getOpcode() != ISD::SHL)
3393 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3394 if (!C || C->getZExtValue() != 8)
3397 } else if (Opc == ISD::SHL) {
3399 // (x & 0xff0000) << 8
3400 if (Num != 0 && Num != 2)
3402 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3403 if (!C || C->getZExtValue() != 8)
3405 } else { // Opc == ISD::SRL
3406 // (x & 0xff00) >> 8
3407 // (x & 0xff000000) >> 8
3408 if (Num != 1 && Num != 3)
3410 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3411 if (!C || C->getZExtValue() != 8)
3418 Parts[Num] = N0.getOperand(0).getNode();
3422 /// Match a 32-bit packed halfword bswap. That is
3423 /// ((x & 0x000000ff) << 8) |
3424 /// ((x & 0x0000ff00) >> 8) |
3425 /// ((x & 0x00ff0000) << 8) |
3426 /// ((x & 0xff000000) >> 8)
3427 /// => (rotl (bswap x), 16)
3428 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3429 if (!LegalOperations)
3432 EVT VT = N->getValueType(0);
3435 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3439 // (or (or (and), (and)), (or (and), (and)))
3440 // (or (or (or (and), (and)), (and)), (and))
3441 if (N0.getOpcode() != ISD::OR)
3443 SDValue N00 = N0.getOperand(0);
3444 SDValue N01 = N0.getOperand(1);
3445 SDNode *Parts[4] = {};
3447 if (N1.getOpcode() == ISD::OR &&
3448 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3449 // (or (or (and), (and)), (or (and), (and)))
3450 SDValue N000 = N00.getOperand(0);
3451 if (!isBSwapHWordElement(N000, Parts))
3454 SDValue N001 = N00.getOperand(1);
3455 if (!isBSwapHWordElement(N001, Parts))
3457 SDValue N010 = N01.getOperand(0);
3458 if (!isBSwapHWordElement(N010, Parts))
3460 SDValue N011 = N01.getOperand(1);
3461 if (!isBSwapHWordElement(N011, Parts))
3464 // (or (or (or (and), (and)), (and)), (and))
3465 if (!isBSwapHWordElement(N1, Parts))
3467 if (!isBSwapHWordElement(N01, Parts))
3469 if (N00.getOpcode() != ISD::OR)
3471 SDValue N000 = N00.getOperand(0);
3472 if (!isBSwapHWordElement(N000, Parts))
3474 SDValue N001 = N00.getOperand(1);
3475 if (!isBSwapHWordElement(N001, Parts))
3479 // Make sure the parts are all coming from the same node.
3480 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3484 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3485 SDValue(Parts[0], 0));
3487 // Result of the bswap should be rotated by 16. If it's not legal, then
3488 // do (x << 16) | (x >> 16).
3489 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3490 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3491 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3492 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3493 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3494 return DAG.getNode(ISD::OR, DL, VT,
3495 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3496 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3499 /// This contains all DAGCombine rules which reduce two values combined by
3500 /// an Or operation to a single value \see visitANDLike().
3501 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3502 EVT VT = N1.getValueType();
3503 // fold (or x, undef) -> -1
3504 if (!LegalOperations &&
3505 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3506 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3507 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3508 SDLoc(LocReference), VT);
3510 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3511 SDValue LL, LR, RL, RR, CC0, CC1;
3512 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3513 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3514 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3516 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3517 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3518 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3519 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3520 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3521 LR.getValueType(), LL, RL);
3522 AddToWorklist(ORNode.getNode());
3523 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3525 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3526 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3527 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3528 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3529 LR.getValueType(), LL, RL);
3530 AddToWorklist(ANDNode.getNode());
3531 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3534 // canonicalize equivalent to ll == rl
3535 if (LL == RR && LR == RL) {
3536 Op1 = ISD::getSetCCSwappedOperands(Op1);
3539 if (LL == RL && LR == RR) {
3540 bool isInteger = LL.getValueType().isInteger();
3541 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3542 if (Result != ISD::SETCC_INVALID &&
3543 (!LegalOperations ||
3544 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3545 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3546 EVT CCVT = getSetCCResultType(LL.getValueType());
3547 if (N0.getValueType() == CCVT ||
3548 (!LegalOperations && N0.getValueType() == MVT::i1))
3549 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3555 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3556 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3557 // Don't increase # computations.
3558 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3559 // We can only do this xform if we know that bits from X that are set in C2
3560 // but not in C1 are already zero. Likewise for Y.
3561 if (const ConstantSDNode *N0O1C =
3562 getAsNonOpaqueConstant(N0.getOperand(1))) {
3563 if (const ConstantSDNode *N1O1C =
3564 getAsNonOpaqueConstant(N1.getOperand(1))) {
3565 // We can only do this xform if we know that bits from X that are set in
3566 // C2 but not in C1 are already zero. Likewise for Y.
3567 const APInt &LHSMask = N0O1C->getAPIntValue();
3568 const APInt &RHSMask = N1O1C->getAPIntValue();
3570 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3571 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3572 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3573 N0.getOperand(0), N1.getOperand(0));
3574 SDLoc DL(LocReference);
3575 return DAG.getNode(ISD::AND, DL, VT, X,
3576 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3582 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3583 if (N0.getOpcode() == ISD::AND &&
3584 N1.getOpcode() == ISD::AND &&
3585 N0.getOperand(0) == N1.getOperand(0) &&
3586 // Don't increase # computations.
3587 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3588 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3589 N0.getOperand(1), N1.getOperand(1));
3590 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3596 SDValue DAGCombiner::visitOR(SDNode *N) {
3597 SDValue N0 = N->getOperand(0);
3598 SDValue N1 = N->getOperand(1);
3599 EVT VT = N1.getValueType();
3602 if (VT.isVector()) {
3603 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3606 // fold (or x, 0) -> x, vector edition
3607 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3609 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3612 // fold (or x, -1) -> -1, vector edition
3613 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3614 // do not return N0, because undef node may exist in N0
3615 return DAG.getConstant(
3616 APInt::getAllOnesValue(
3617 N0.getValueType().getScalarType().getSizeInBits()),
3618 SDLoc(N), N0.getValueType());
3619 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3620 // do not return N1, because undef node may exist in N1
3621 return DAG.getConstant(
3622 APInt::getAllOnesValue(
3623 N1.getValueType().getScalarType().getSizeInBits()),
3624 SDLoc(N), N1.getValueType());
3626 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3627 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3628 // Do this only if the resulting shuffle is legal.
3629 if (isa<ShuffleVectorSDNode>(N0) &&
3630 isa<ShuffleVectorSDNode>(N1) &&
3631 // Avoid folding a node with illegal type.
3632 TLI.isTypeLegal(VT) &&
3633 N0->getOperand(1) == N1->getOperand(1) &&
3634 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3635 bool CanFold = true;
3636 unsigned NumElts = VT.getVectorNumElements();
3637 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3638 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3639 // We construct two shuffle masks:
3640 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3641 // and N1 as the second operand.
3642 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3643 // and N0 as the second operand.
3644 // We do this because OR is commutable and therefore there might be
3645 // two ways to fold this node into a shuffle.
3646 SmallVector<int,4> Mask1;
3647 SmallVector<int,4> Mask2;
3649 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3650 int M0 = SV0->getMaskElt(i);
3651 int M1 = SV1->getMaskElt(i);
3653 // Both shuffle indexes are undef. Propagate Undef.
3654 if (M0 < 0 && M1 < 0) {
3655 Mask1.push_back(M0);
3656 Mask2.push_back(M0);
3660 if (M0 < 0 || M1 < 0 ||
3661 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3662 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3667 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3668 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3672 // Fold this sequence only if the resulting shuffle is 'legal'.
3673 if (TLI.isShuffleMaskLegal(Mask1, VT))
3674 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3675 N1->getOperand(0), &Mask1[0]);
3676 if (TLI.isShuffleMaskLegal(Mask2, VT))
3677 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3678 N0->getOperand(0), &Mask2[0]);
3683 // fold (or c1, c2) -> c1|c2
3684 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3685 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3686 if (N0C && N1C && !N1C->isOpaque())
3687 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3688 // canonicalize constant to RHS
3689 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3690 !isConstantIntBuildVectorOrConstantInt(N1))
3691 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3692 // fold (or x, 0) -> x
3693 if (isNullConstant(N1))
3695 // fold (or x, -1) -> -1
3696 if (isAllOnesConstant(N1))
3698 // fold (or x, c) -> c iff (x & ~c) == 0
3699 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3702 if (SDValue Combined = visitORLike(N0, N1, N))
3705 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3706 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3708 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3712 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3714 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3715 // iff (c1 & c2) == 0.
3716 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3717 isa<ConstantSDNode>(N0.getOperand(1))) {
3718 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3719 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3720 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3723 ISD::AND, SDLoc(N), VT,
3724 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3728 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3729 if (N0.getOpcode() == N1.getOpcode())
3730 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3733 // See if this is some rotate idiom.
3734 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3735 return SDValue(Rot, 0);
3737 // Simplify the operands using demanded-bits information.
3738 if (!VT.isVector() &&
3739 SimplifyDemandedBits(SDValue(N, 0)))
3740 return SDValue(N, 0);
3745 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3746 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3747 if (Op.getOpcode() == ISD::AND) {
3748 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3749 Mask = Op.getOperand(1);
3750 Op = Op.getOperand(0);
3756 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3764 // Return true if we can prove that, whenever Neg and Pos are both in the
3765 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3766 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3768 // (or (shift1 X, Neg), (shift2 X, Pos))
3770 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3771 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3772 // to consider shift amounts with defined behavior.
3773 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3774 // If OpSize is a power of 2 then:
3776 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3777 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3779 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3780 // for the stronger condition:
3782 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3784 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3785 // we can just replace Neg with Neg' for the rest of the function.
3787 // In other cases we check for the even stronger condition:
3789 // Neg == OpSize - Pos [B]
3791 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3792 // behavior if Pos == 0 (and consequently Neg == OpSize).
3794 // We could actually use [A] whenever OpSize is a power of 2, but the
3795 // only extra cases that it would match are those uninteresting ones
3796 // where Neg and Pos are never in range at the same time. E.g. for
3797 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3798 // as well as (sub 32, Pos), but:
3800 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3802 // always invokes undefined behavior for 32-bit X.
3804 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3805 unsigned MaskLoBits = 0;
3806 if (Neg.getOpcode() == ISD::AND &&
3807 isPowerOf2_64(OpSize) &&
3808 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3809 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3810 Neg = Neg.getOperand(0);
3811 MaskLoBits = Log2_64(OpSize);
3814 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3815 if (Neg.getOpcode() != ISD::SUB)
3817 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3820 SDValue NegOp1 = Neg.getOperand(1);
3822 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3823 // Pos'. The truncation is redundant for the purpose of the equality.
3825 Pos.getOpcode() == ISD::AND &&
3826 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3827 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3828 Pos = Pos.getOperand(0);
3830 // The condition we need is now:
3832 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3834 // If NegOp1 == Pos then we need:
3836 // OpSize & Mask == NegC & Mask
3838 // (because "x & Mask" is a truncation and distributes through subtraction).
3841 Width = NegC->getAPIntValue();
3842 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3843 // Then the condition we want to prove becomes:
3845 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3847 // which, again because "x & Mask" is a truncation, becomes:
3849 // NegC & Mask == (OpSize - PosC) & Mask
3850 // OpSize & Mask == (NegC + PosC) & Mask
3851 else if (Pos.getOpcode() == ISD::ADD &&
3852 Pos.getOperand(0) == NegOp1 &&
3853 Pos.getOperand(1).getOpcode() == ISD::Constant)
3854 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3855 NegC->getAPIntValue());
3859 // Now we just need to check that OpSize & Mask == Width & Mask.
3861 // Opsize & Mask is 0 since Mask is Opsize - 1.
3862 return Width.getLoBits(MaskLoBits) == 0;
3863 return Width == OpSize;
3866 // A subroutine of MatchRotate used once we have found an OR of two opposite
3867 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3868 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3869 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3870 // Neg with outer conversions stripped away.
3871 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3872 SDValue Neg, SDValue InnerPos,
3873 SDValue InnerNeg, unsigned PosOpcode,
3874 unsigned NegOpcode, SDLoc DL) {
3875 // fold (or (shl x, (*ext y)),
3876 // (srl x, (*ext (sub 32, y)))) ->
3877 // (rotl x, y) or (rotr x, (sub 32, y))
3879 // fold (or (shl x, (*ext (sub 32, y))),
3880 // (srl x, (*ext y))) ->
3881 // (rotr x, y) or (rotl x, (sub 32, y))
3882 EVT VT = Shifted.getValueType();
3883 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3884 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3885 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3886 HasPos ? Pos : Neg).getNode();
3892 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3893 // idioms for rotate, and if the target supports rotation instructions, generate
3895 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3896 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3897 EVT VT = LHS.getValueType();
3898 if (!TLI.isTypeLegal(VT)) return nullptr;
3900 // The target must have at least one rotate flavor.
3901 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3902 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3903 if (!HasROTL && !HasROTR) return nullptr;
3905 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3906 SDValue LHSShift; // The shift.
3907 SDValue LHSMask; // AND value if any.
3908 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3909 return nullptr; // Not part of a rotate.
3911 SDValue RHSShift; // The shift.
3912 SDValue RHSMask; // AND value if any.
3913 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3914 return nullptr; // Not part of a rotate.
3916 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3917 return nullptr; // Not shifting the same value.
3919 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3920 return nullptr; // Shifts must disagree.
3922 // Canonicalize shl to left side in a shl/srl pair.
3923 if (RHSShift.getOpcode() == ISD::SHL) {
3924 std::swap(LHS, RHS);
3925 std::swap(LHSShift, RHSShift);
3926 std::swap(LHSMask , RHSMask );
3929 unsigned OpSizeInBits = VT.getSizeInBits();
3930 SDValue LHSShiftArg = LHSShift.getOperand(0);
3931 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3932 SDValue RHSShiftArg = RHSShift.getOperand(0);
3933 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3935 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3936 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3937 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3938 RHSShiftAmt.getOpcode() == ISD::Constant) {
3939 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3940 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3941 if ((LShVal + RShVal) != OpSizeInBits)
3944 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3945 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3947 // If there is an AND of either shifted operand, apply it to the result.
3948 if (LHSMask.getNode() || RHSMask.getNode()) {
3949 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3951 if (LHSMask.getNode()) {
3952 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3953 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3955 if (RHSMask.getNode()) {
3956 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3957 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3960 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3963 return Rot.getNode();
3966 // If there is a mask here, and we have a variable shift, we can't be sure
3967 // that we're masking out the right stuff.
3968 if (LHSMask.getNode() || RHSMask.getNode())
3971 // If the shift amount is sign/zext/any-extended just peel it off.
3972 SDValue LExtOp0 = LHSShiftAmt;
3973 SDValue RExtOp0 = RHSShiftAmt;
3974 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3975 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3976 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3977 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3978 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3979 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3980 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3981 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3982 LExtOp0 = LHSShiftAmt.getOperand(0);
3983 RExtOp0 = RHSShiftAmt.getOperand(0);
3986 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3987 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3991 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3992 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3999 SDValue DAGCombiner::visitXOR(SDNode *N) {
4000 SDValue N0 = N->getOperand(0);
4001 SDValue N1 = N->getOperand(1);
4002 EVT VT = N0.getValueType();
4005 if (VT.isVector()) {
4006 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4009 // fold (xor x, 0) -> x, vector edition
4010 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4012 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4016 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4017 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4018 return DAG.getConstant(0, SDLoc(N), VT);
4019 // fold (xor x, undef) -> undef
4020 if (N0.getOpcode() == ISD::UNDEF)
4022 if (N1.getOpcode() == ISD::UNDEF)
4024 // fold (xor c1, c2) -> c1^c2
4025 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4026 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4028 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4029 // canonicalize constant to RHS
4030 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4031 !isConstantIntBuildVectorOrConstantInt(N1))
4032 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4033 // fold (xor x, 0) -> x
4034 if (isNullConstant(N1))
4037 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4040 // fold !(x cc y) -> (x !cc y)
4041 SDValue LHS, RHS, CC;
4042 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4043 bool isInt = LHS.getValueType().isInteger();
4044 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4047 if (!LegalOperations ||
4048 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4049 switch (N0.getOpcode()) {
4051 llvm_unreachable("Unhandled SetCC Equivalent!");
4053 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4054 case ISD::SELECT_CC:
4055 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4056 N0.getOperand(3), NotCC);
4061 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4062 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4063 N0.getNode()->hasOneUse() &&
4064 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4065 SDValue V = N0.getOperand(0);
4067 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4068 DAG.getConstant(1, DL, V.getValueType()));
4069 AddToWorklist(V.getNode());
4070 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4073 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4074 if (isOneConstant(N1) && VT == MVT::i1 &&
4075 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4076 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4077 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4078 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4079 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4080 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4081 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4082 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4085 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4086 if (isAllOnesConstant(N1) &&
4087 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4088 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4089 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4090 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4091 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4092 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4093 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4094 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4097 // fold (xor (and x, y), y) -> (and (not x), y)
4098 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4099 N0->getOperand(1) == N1) {
4100 SDValue X = N0->getOperand(0);
4101 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4102 AddToWorklist(NotX.getNode());
4103 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4105 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4106 if (N1C && N0.getOpcode() == ISD::XOR) {
4107 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4109 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4110 DAG.getConstant(N1C->getAPIntValue() ^
4111 N00C->getAPIntValue(), DL, VT));
4113 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4115 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4116 DAG.getConstant(N1C->getAPIntValue() ^
4117 N01C->getAPIntValue(), DL, VT));
4120 // fold (xor x, x) -> 0
4122 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4124 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4125 // Here is a concrete example of this equivalence:
4127 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4128 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4132 // i16 ~1 == 0b1111111111111110
4133 // i16 rol(~1, 14) == 0b1011111111111111
4135 // Some additional tips to help conceptualize this transform:
4136 // - Try to see the operation as placing a single zero in a value of all ones.
4137 // - There exists no value for x which would allow the result to contain zero.
4138 // - Values of x larger than the bitwidth are undefined and do not require a
4139 // consistent result.
4140 // - Pushing the zero left requires shifting one bits in from the right.
4141 // A rotate left of ~1 is a nice way of achieving the desired result.
4142 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4143 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4145 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4149 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4150 if (N0.getOpcode() == N1.getOpcode())
4151 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4154 // Simplify the expression using non-local knowledge.
4155 if (!VT.isVector() &&
4156 SimplifyDemandedBits(SDValue(N, 0)))
4157 return SDValue(N, 0);
4162 /// Handle transforms common to the three shifts, when the shift amount is a
4164 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4165 SDNode *LHS = N->getOperand(0).getNode();
4166 if (!LHS->hasOneUse()) return SDValue();
4168 // We want to pull some binops through shifts, so that we have (and (shift))
4169 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4170 // thing happens with address calculations, so it's important to canonicalize
4172 bool HighBitSet = false; // Can we transform this if the high bit is set?
4174 switch (LHS->getOpcode()) {
4175 default: return SDValue();
4178 HighBitSet = false; // We can only transform sra if the high bit is clear.
4181 HighBitSet = true; // We can only transform sra if the high bit is set.
4184 if (N->getOpcode() != ISD::SHL)
4185 return SDValue(); // only shl(add) not sr[al](add).
4186 HighBitSet = false; // We can only transform sra if the high bit is clear.
4190 // We require the RHS of the binop to be a constant and not opaque as well.
4191 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4192 if (!BinOpCst) return SDValue();
4194 // FIXME: disable this unless the input to the binop is a shift by a constant.
4195 // If it is not a shift, it pessimizes some common cases like:
4197 // void foo(int *X, int i) { X[i & 1235] = 1; }
4198 // int bar(int *X, int i) { return X[i & 255]; }
4199 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4200 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4201 BinOpLHSVal->getOpcode() != ISD::SRA &&
4202 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4203 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4206 EVT VT = N->getValueType(0);
4208 // If this is a signed shift right, and the high bit is modified by the
4209 // logical operation, do not perform the transformation. The highBitSet
4210 // boolean indicates the value of the high bit of the constant which would
4211 // cause it to be modified for this operation.
4212 if (N->getOpcode() == ISD::SRA) {
4213 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4214 if (BinOpRHSSignSet != HighBitSet)
4218 if (!TLI.isDesirableToCommuteWithShift(LHS))
4221 // Fold the constants, shifting the binop RHS by the shift amount.
4222 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4224 LHS->getOperand(1), N->getOperand(1));
4225 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4227 // Create the new shift.
4228 SDValue NewShift = DAG.getNode(N->getOpcode(),
4229 SDLoc(LHS->getOperand(0)),
4230 VT, LHS->getOperand(0), N->getOperand(1));
4232 // Create the new binop.
4233 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4236 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4237 assert(N->getOpcode() == ISD::TRUNCATE);
4238 assert(N->getOperand(0).getOpcode() == ISD::AND);
4240 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4241 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4242 SDValue N01 = N->getOperand(0).getOperand(1);
4244 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4245 if (!N01C->isOpaque()) {
4246 EVT TruncVT = N->getValueType(0);
4247 SDValue N00 = N->getOperand(0).getOperand(0);
4248 APInt TruncC = N01C->getAPIntValue();
4249 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4252 return DAG.getNode(ISD::AND, DL, TruncVT,
4253 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4254 DAG.getConstant(TruncC, DL, TruncVT));
4262 SDValue DAGCombiner::visitRotate(SDNode *N) {
4263 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4264 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4265 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4266 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4267 if (NewOp1.getNode())
4268 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4269 N->getOperand(0), NewOp1);
4274 SDValue DAGCombiner::visitSHL(SDNode *N) {
4275 SDValue N0 = N->getOperand(0);
4276 SDValue N1 = N->getOperand(1);
4277 EVT VT = N0.getValueType();
4278 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4281 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4282 if (VT.isVector()) {
4283 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4286 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4287 // If setcc produces all-one true value then:
4288 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4289 if (N1CV && N1CV->isConstant()) {
4290 if (N0.getOpcode() == ISD::AND) {
4291 SDValue N00 = N0->getOperand(0);
4292 SDValue N01 = N0->getOperand(1);
4293 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4295 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4296 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4297 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4298 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4300 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4303 N1C = isConstOrConstSplat(N1);
4308 // fold (shl c1, c2) -> c1<<c2
4309 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4310 if (N0C && N1C && !N1C->isOpaque())
4311 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4312 // fold (shl 0, x) -> 0
4313 if (isNullConstant(N0))
4315 // fold (shl x, c >= size(x)) -> undef
4316 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4317 return DAG.getUNDEF(VT);
4318 // fold (shl x, 0) -> x
4319 if (N1C && N1C->isNullValue())
4321 // fold (shl undef, x) -> 0
4322 if (N0.getOpcode() == ISD::UNDEF)
4323 return DAG.getConstant(0, SDLoc(N), VT);
4324 // if (shl x, c) is known to be zero, return 0
4325 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4326 APInt::getAllOnesValue(OpSizeInBits)))
4327 return DAG.getConstant(0, SDLoc(N), VT);
4328 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4329 if (N1.getOpcode() == ISD::TRUNCATE &&
4330 N1.getOperand(0).getOpcode() == ISD::AND) {
4331 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4332 if (NewOp1.getNode())
4333 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4336 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4337 return SDValue(N, 0);
4339 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4340 if (N1C && N0.getOpcode() == ISD::SHL) {
4341 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4342 uint64_t c1 = N0C1->getZExtValue();
4343 uint64_t c2 = N1C->getZExtValue();
4345 if (c1 + c2 >= OpSizeInBits)
4346 return DAG.getConstant(0, DL, VT);
4347 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4348 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4352 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4353 // For this to be valid, the second form must not preserve any of the bits
4354 // that are shifted out by the inner shift in the first form. This means
4355 // the outer shift size must be >= the number of bits added by the ext.
4356 // As a corollary, we don't care what kind of ext it is.
4357 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4358 N0.getOpcode() == ISD::ANY_EXTEND ||
4359 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4360 N0.getOperand(0).getOpcode() == ISD::SHL) {
4361 SDValue N0Op0 = N0.getOperand(0);
4362 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4363 uint64_t c1 = N0Op0C1->getZExtValue();
4364 uint64_t c2 = N1C->getZExtValue();
4365 EVT InnerShiftVT = N0Op0.getValueType();
4366 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4367 if (c2 >= OpSizeInBits - InnerShiftSize) {
4369 if (c1 + c2 >= OpSizeInBits)
4370 return DAG.getConstant(0, DL, VT);
4371 return DAG.getNode(ISD::SHL, DL, VT,
4372 DAG.getNode(N0.getOpcode(), DL, VT,
4373 N0Op0->getOperand(0)),
4374 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4379 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4380 // Only fold this if the inner zext has no other uses to avoid increasing
4381 // the total number of instructions.
4382 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4383 N0.getOperand(0).getOpcode() == ISD::SRL) {
4384 SDValue N0Op0 = N0.getOperand(0);
4385 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4386 uint64_t c1 = N0Op0C1->getZExtValue();
4387 if (c1 < VT.getScalarSizeInBits()) {
4388 uint64_t c2 = N1C->getZExtValue();
4390 SDValue NewOp0 = N0.getOperand(0);
4391 EVT CountVT = NewOp0.getOperand(1).getValueType();
4393 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4395 DAG.getConstant(c2, DL, CountVT));
4396 AddToWorklist(NewSHL.getNode());
4397 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4403 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4404 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4405 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4406 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4407 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4408 uint64_t C1 = N0C1->getZExtValue();
4409 uint64_t C2 = N1C->getZExtValue();
4412 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4413 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4414 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4415 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4419 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4420 // (and (srl x, (sub c1, c2), MASK)
4421 // Only fold this if the inner shift has no other uses -- if it does, folding
4422 // this will increase the total number of instructions.
4423 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4424 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4425 uint64_t c1 = N0C1->getZExtValue();
4426 if (c1 < OpSizeInBits) {
4427 uint64_t c2 = N1C->getZExtValue();
4428 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4431 Mask = Mask.shl(c2 - c1);
4433 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4434 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4436 Mask = Mask.lshr(c1 - c2);
4438 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4439 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4442 return DAG.getNode(ISD::AND, DL, VT, Shift,
4443 DAG.getConstant(Mask, DL, VT));
4447 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4448 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4449 unsigned BitSize = VT.getScalarSizeInBits();
4451 SDValue HiBitsMask =
4452 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4453 BitSize - N1C->getZExtValue()),
4455 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4459 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4460 // Variant of version done on multiply, except mul by a power of 2 is turned
4463 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4464 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4465 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4466 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4467 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4468 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4471 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4472 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4473 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4474 if (SDValue Folded =
4475 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4476 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4480 if (N1C && !N1C->isOpaque())
4481 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4487 SDValue DAGCombiner::visitSRA(SDNode *N) {
4488 SDValue N0 = N->getOperand(0);
4489 SDValue N1 = N->getOperand(1);
4490 EVT VT = N0.getValueType();
4491 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4494 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4495 if (VT.isVector()) {
4496 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4499 N1C = isConstOrConstSplat(N1);
4502 // fold (sra c1, c2) -> (sra c1, c2)
4503 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4504 if (N0C && N1C && !N1C->isOpaque())
4505 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4506 // fold (sra 0, x) -> 0
4507 if (isNullConstant(N0))
4509 // fold (sra -1, x) -> -1
4510 if (isAllOnesConstant(N0))
4512 // fold (sra x, (setge c, size(x))) -> undef
4513 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4514 return DAG.getUNDEF(VT);
4515 // fold (sra x, 0) -> x
4516 if (N1C && N1C->isNullValue())
4518 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4520 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4521 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4522 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4524 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4525 ExtVT, VT.getVectorNumElements());
4526 if ((!LegalOperations ||
4527 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4528 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4529 N0.getOperand(0), DAG.getValueType(ExtVT));
4532 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4533 if (N1C && N0.getOpcode() == ISD::SRA) {
4534 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4535 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4536 if (Sum >= OpSizeInBits)
4537 Sum = OpSizeInBits - 1;
4539 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4540 DAG.getConstant(Sum, DL, N1.getValueType()));
4544 // fold (sra (shl X, m), (sub result_size, n))
4545 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4546 // result_size - n != m.
4547 // If truncate is free for the target sext(shl) is likely to result in better
4549 if (N0.getOpcode() == ISD::SHL && N1C) {
4550 // Get the two constanst of the shifts, CN0 = m, CN = n.
4551 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4553 LLVMContext &Ctx = *DAG.getContext();
4554 // Determine what the truncate's result bitsize and type would be.
4555 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4558 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4560 // Determine the residual right-shift amount.
4561 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4563 // If the shift is not a no-op (in which case this should be just a sign
4564 // extend already), the truncated to type is legal, sign_extend is legal
4565 // on that type, and the truncate to that type is both legal and free,
4566 // perform the transform.
4567 if ((ShiftAmt > 0) &&
4568 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4569 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4570 TLI.isTruncateFree(VT, TruncVT)) {
4573 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4574 getShiftAmountTy(N0.getOperand(0).getValueType()));
4575 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4576 N0.getOperand(0), Amt);
4577 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4579 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4580 N->getValueType(0), Trunc);
4585 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4586 if (N1.getOpcode() == ISD::TRUNCATE &&
4587 N1.getOperand(0).getOpcode() == ISD::AND) {
4588 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4589 if (NewOp1.getNode())
4590 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4593 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4594 // if c1 is equal to the number of bits the trunc removes
4595 if (N0.getOpcode() == ISD::TRUNCATE &&
4596 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4597 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4598 N0.getOperand(0).hasOneUse() &&
4599 N0.getOperand(0).getOperand(1).hasOneUse() &&
4601 SDValue N0Op0 = N0.getOperand(0);
4602 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4603 unsigned LargeShiftVal = LargeShift->getZExtValue();
4604 EVT LargeVT = N0Op0.getValueType();
4606 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4609 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4610 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4611 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4612 N0Op0.getOperand(0), Amt);
4613 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4618 // Simplify, based on bits shifted out of the LHS.
4619 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4620 return SDValue(N, 0);
4623 // If the sign bit is known to be zero, switch this to a SRL.
4624 if (DAG.SignBitIsZero(N0))
4625 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4627 if (N1C && !N1C->isOpaque())
4628 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4634 SDValue DAGCombiner::visitSRL(SDNode *N) {
4635 SDValue N0 = N->getOperand(0);
4636 SDValue N1 = N->getOperand(1);
4637 EVT VT = N0.getValueType();
4638 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4641 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4642 if (VT.isVector()) {
4643 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4646 N1C = isConstOrConstSplat(N1);
4649 // fold (srl c1, c2) -> c1 >>u c2
4650 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4651 if (N0C && N1C && !N1C->isOpaque())
4652 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4653 // fold (srl 0, x) -> 0
4654 if (isNullConstant(N0))
4656 // fold (srl x, c >= size(x)) -> undef
4657 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4658 return DAG.getUNDEF(VT);
4659 // fold (srl x, 0) -> x
4660 if (N1C && N1C->isNullValue())
4662 // if (srl x, c) is known to be zero, return 0
4663 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4664 APInt::getAllOnesValue(OpSizeInBits)))
4665 return DAG.getConstant(0, SDLoc(N), VT);
4667 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4668 if (N1C && N0.getOpcode() == ISD::SRL) {
4669 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4670 uint64_t c1 = N01C->getZExtValue();
4671 uint64_t c2 = N1C->getZExtValue();
4673 if (c1 + c2 >= OpSizeInBits)
4674 return DAG.getConstant(0, DL, VT);
4675 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4676 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4680 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4681 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4682 N0.getOperand(0).getOpcode() == ISD::SRL &&
4683 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4685 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4686 uint64_t c2 = N1C->getZExtValue();
4687 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4688 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4689 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4690 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4691 if (c1 + OpSizeInBits == InnerShiftSize) {
4693 if (c1 + c2 >= InnerShiftSize)
4694 return DAG.getConstant(0, DL, VT);
4695 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4696 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4697 N0.getOperand(0)->getOperand(0),
4698 DAG.getConstant(c1 + c2, DL,
4703 // fold (srl (shl x, c), c) -> (and x, cst2)
4704 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4705 unsigned BitSize = N0.getScalarValueSizeInBits();
4706 if (BitSize <= 64) {
4707 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4709 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4710 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4714 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4715 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4716 // Shifting in all undef bits?
4717 EVT SmallVT = N0.getOperand(0).getValueType();
4718 unsigned BitSize = SmallVT.getScalarSizeInBits();
4719 if (N1C->getZExtValue() >= BitSize)
4720 return DAG.getUNDEF(VT);
4722 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4723 uint64_t ShiftAmt = N1C->getZExtValue();
4725 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4727 DAG.getConstant(ShiftAmt, DL0,
4728 getShiftAmountTy(SmallVT)));
4729 AddToWorklist(SmallShift.getNode());
4730 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4732 return DAG.getNode(ISD::AND, DL, VT,
4733 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4734 DAG.getConstant(Mask, DL, VT));
4738 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4739 // bit, which is unmodified by sra.
4740 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4741 if (N0.getOpcode() == ISD::SRA)
4742 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4745 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4746 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4747 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4748 APInt KnownZero, KnownOne;
4749 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4751 // If any of the input bits are KnownOne, then the input couldn't be all
4752 // zeros, thus the result of the srl will always be zero.
4753 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4755 // If all of the bits input the to ctlz node are known to be zero, then
4756 // the result of the ctlz is "32" and the result of the shift is one.
4757 APInt UnknownBits = ~KnownZero;
4758 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4760 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4761 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4762 // Okay, we know that only that the single bit specified by UnknownBits
4763 // could be set on input to the CTLZ node. If this bit is set, the SRL
4764 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4765 // to an SRL/XOR pair, which is likely to simplify more.
4766 unsigned ShAmt = UnknownBits.countTrailingZeros();
4767 SDValue Op = N0.getOperand(0);
4771 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4772 DAG.getConstant(ShAmt, DL,
4773 getShiftAmountTy(Op.getValueType())));
4774 AddToWorklist(Op.getNode());
4778 return DAG.getNode(ISD::XOR, DL, VT,
4779 Op, DAG.getConstant(1, DL, VT));
4783 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4784 if (N1.getOpcode() == ISD::TRUNCATE &&
4785 N1.getOperand(0).getOpcode() == ISD::AND) {
4786 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4787 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4790 // fold operands of srl based on knowledge that the low bits are not
4792 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4793 return SDValue(N, 0);
4795 if (N1C && !N1C->isOpaque())
4796 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4799 // Attempt to convert a srl of a load into a narrower zero-extending load.
4800 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4803 // Here is a common situation. We want to optimize:
4806 // %b = and i32 %a, 2
4807 // %c = srl i32 %b, 1
4808 // brcond i32 %c ...
4814 // %c = setcc eq %b, 0
4817 // However when after the source operand of SRL is optimized into AND, the SRL
4818 // itself may not be optimized further. Look for it and add the BRCOND into
4820 if (N->hasOneUse()) {
4821 SDNode *Use = *N->use_begin();
4822 if (Use->getOpcode() == ISD::BRCOND)
4824 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4825 // Also look pass the truncate.
4826 Use = *Use->use_begin();
4827 if (Use->getOpcode() == ISD::BRCOND)
4835 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4836 SDValue N0 = N->getOperand(0);
4837 EVT VT = N->getValueType(0);
4839 // fold (bswap c1) -> c2
4840 if (isConstantIntBuildVectorOrConstantInt(N0))
4841 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4842 // fold (bswap (bswap x)) -> x
4843 if (N0.getOpcode() == ISD::BSWAP)
4844 return N0->getOperand(0);
4848 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4849 SDValue N0 = N->getOperand(0);
4850 EVT VT = N->getValueType(0);
4852 // fold (ctlz c1) -> c2
4853 if (isConstantIntBuildVectorOrConstantInt(N0))
4854 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4858 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4859 SDValue N0 = N->getOperand(0);
4860 EVT VT = N->getValueType(0);
4862 // fold (ctlz_zero_undef c1) -> c2
4863 if (isConstantIntBuildVectorOrConstantInt(N0))
4864 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4868 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4869 SDValue N0 = N->getOperand(0);
4870 EVT VT = N->getValueType(0);
4872 // fold (cttz c1) -> c2
4873 if (isConstantIntBuildVectorOrConstantInt(N0))
4874 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4878 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4879 SDValue N0 = N->getOperand(0);
4880 EVT VT = N->getValueType(0);
4882 // fold (cttz_zero_undef c1) -> c2
4883 if (isConstantIntBuildVectorOrConstantInt(N0))
4884 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4888 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4889 SDValue N0 = N->getOperand(0);
4890 EVT VT = N->getValueType(0);
4892 // fold (ctpop c1) -> c2
4893 if (isConstantIntBuildVectorOrConstantInt(N0))
4894 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4899 /// \brief Generate Min/Max node
4900 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4901 SDValue True, SDValue False,
4902 ISD::CondCode CC, const TargetLowering &TLI,
4903 SelectionDAG &DAG) {
4904 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4914 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4915 if (TLI.isOperationLegal(Opcode, VT))
4916 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4925 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4926 if (TLI.isOperationLegal(Opcode, VT))
4927 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4935 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4936 SDValue N0 = N->getOperand(0);
4937 SDValue N1 = N->getOperand(1);
4938 SDValue N2 = N->getOperand(2);
4939 EVT VT = N->getValueType(0);
4940 EVT VT0 = N0.getValueType();
4942 // fold (select C, X, X) -> X
4945 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4946 // fold (select true, X, Y) -> X
4947 // fold (select false, X, Y) -> Y
4948 return !N0C->isNullValue() ? N1 : N2;
4950 // fold (select C, 1, X) -> (or C, X)
4951 if (VT == MVT::i1 && isOneConstant(N1))
4952 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4953 // fold (select C, 0, 1) -> (xor C, 1)
4954 // We can't do this reliably if integer based booleans have different contents
4955 // to floating point based booleans. This is because we can't tell whether we
4956 // have an integer-based boolean or a floating-point-based boolean unless we
4957 // can find the SETCC that produced it and inspect its operands. This is
4958 // fairly easy if C is the SETCC node, but it can potentially be
4959 // undiscoverable (or not reasonably discoverable). For example, it could be
4960 // in another basic block or it could require searching a complicated
4962 if (VT.isInteger() &&
4963 (VT0 == MVT::i1 || (VT0.isInteger() &&
4964 TLI.getBooleanContents(false, false) ==
4965 TLI.getBooleanContents(false, true) &&
4966 TLI.getBooleanContents(false, false) ==
4967 TargetLowering::ZeroOrOneBooleanContent)) &&
4968 isNullConstant(N1) && isOneConstant(N2)) {
4972 return DAG.getNode(ISD::XOR, DL, VT0,
4973 N0, DAG.getConstant(1, DL, VT0));
4976 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4977 N0, DAG.getConstant(1, DL0, VT0));
4978 AddToWorklist(XORNode.getNode());
4980 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4981 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4983 // fold (select C, 0, X) -> (and (not C), X)
4984 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4985 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4986 AddToWorklist(NOTNode.getNode());
4987 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4989 // fold (select C, X, 1) -> (or (not C), X)
4990 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4991 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4992 AddToWorklist(NOTNode.getNode());
4993 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4995 // fold (select C, X, 0) -> (and C, X)
4996 if (VT == MVT::i1 && isNullConstant(N2))
4997 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4998 // fold (select X, X, Y) -> (or X, Y)
4999 // fold (select X, 1, Y) -> (or X, Y)
5000 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5001 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5002 // fold (select X, Y, X) -> (and X, Y)
5003 // fold (select X, Y, 0) -> (and X, Y)
5004 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5005 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5007 // If we can fold this based on the true/false value, do so.
5008 if (SimplifySelectOps(N, N1, N2))
5009 return SDValue(N, 0); // Don't revisit N.
5011 if (VT0 == MVT::i1) {
5012 // The code in this block deals with the following 2 equivalences:
5013 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5014 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5015 // The target can specify its prefered form with the
5016 // shouldNormalizeToSelectSequence() callback. However we always transform
5017 // to the right anyway if we find the inner select exists in the DAG anyway
5018 // and we always transform to the left side if we know that we can further
5019 // optimize the combination of the conditions.
5020 bool normalizeToSequence
5021 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5022 // select (and Cond0, Cond1), X, Y
5023 // -> select Cond0, (select Cond1, X, Y), Y
5024 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5025 SDValue Cond0 = N0->getOperand(0);
5026 SDValue Cond1 = N0->getOperand(1);
5027 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5028 N1.getValueType(), Cond1, N1, N2);
5029 if (normalizeToSequence || !InnerSelect.use_empty())
5030 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5033 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5034 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5035 SDValue Cond0 = N0->getOperand(0);
5036 SDValue Cond1 = N0->getOperand(1);
5037 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5038 N1.getValueType(), Cond1, N1, N2);
5039 if (normalizeToSequence || !InnerSelect.use_empty())
5040 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5044 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5045 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5046 SDValue N1_0 = N1->getOperand(0);
5047 SDValue N1_1 = N1->getOperand(1);
5048 SDValue N1_2 = N1->getOperand(2);
5049 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5050 // Create the actual and node if we can generate good code for it.
5051 if (!normalizeToSequence) {
5052 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5054 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5057 // Otherwise see if we can optimize the "and" to a better pattern.
5058 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5059 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5063 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5064 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5065 SDValue N2_0 = N2->getOperand(0);
5066 SDValue N2_1 = N2->getOperand(1);
5067 SDValue N2_2 = N2->getOperand(2);
5068 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5069 // Create the actual or node if we can generate good code for it.
5070 if (!normalizeToSequence) {
5071 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5073 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5076 // Otherwise see if we can optimize to a better pattern.
5077 if (SDValue Combined = visitORLike(N0, N2_0, N))
5078 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5084 // fold selects based on a setcc into other things, such as min/max/abs
5085 if (N0.getOpcode() == ISD::SETCC) {
5086 // select x, y (fcmp lt x, y) -> fminnum x, y
5087 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5089 // This is OK if we don't care about what happens if either operand is a
5093 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5094 // no signed zeros as well as no nans.
5095 const TargetOptions &Options = DAG.getTarget().Options;
5096 if (Options.UnsafeFPMath &&
5097 VT.isFloatingPoint() && N0.hasOneUse() &&
5098 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5099 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5101 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5102 N0.getOperand(1), N1, N2, CC,
5107 if ((!LegalOperations &&
5108 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5109 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5110 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5111 N0.getOperand(0), N0.getOperand(1),
5112 N1, N2, N0.getOperand(2));
5113 return SimplifySelect(SDLoc(N), N0, N1, N2);
5120 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5123 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5125 // Split the inputs.
5126 SDValue Lo, Hi, LL, LH, RL, RH;
5127 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5128 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5130 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5131 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5133 return std::make_pair(Lo, Hi);
5136 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5137 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5138 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5140 SDValue Cond = N->getOperand(0);
5141 SDValue LHS = N->getOperand(1);
5142 SDValue RHS = N->getOperand(2);
5143 EVT VT = N->getValueType(0);
5144 int NumElems = VT.getVectorNumElements();
5145 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5146 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5147 Cond.getOpcode() == ISD::BUILD_VECTOR);
5149 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5150 // binary ones here.
5151 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5154 // We're sure we have an even number of elements due to the
5155 // concat_vectors we have as arguments to vselect.
5156 // Skip BV elements until we find one that's not an UNDEF
5157 // After we find an UNDEF element, keep looping until we get to half the
5158 // length of the BV and see if all the non-undef nodes are the same.
5159 ConstantSDNode *BottomHalf = nullptr;
5160 for (int i = 0; i < NumElems / 2; ++i) {
5161 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5164 if (BottomHalf == nullptr)
5165 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5166 else if (Cond->getOperand(i).getNode() != BottomHalf)
5170 // Do the same for the second half of the BuildVector
5171 ConstantSDNode *TopHalf = nullptr;
5172 for (int i = NumElems / 2; i < NumElems; ++i) {
5173 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5176 if (TopHalf == nullptr)
5177 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5178 else if (Cond->getOperand(i).getNode() != TopHalf)
5182 assert(TopHalf && BottomHalf &&
5183 "One half of the selector was all UNDEFs and the other was all the "
5184 "same value. This should have been addressed before this function.");
5186 ISD::CONCAT_VECTORS, dl, VT,
5187 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5188 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5191 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5193 if (Level >= AfterLegalizeTypes)
5196 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5197 SDValue Mask = MSC->getMask();
5198 SDValue Data = MSC->getValue();
5201 // If the MSCATTER data type requires splitting and the mask is provided by a
5202 // SETCC, then split both nodes and its operands before legalization. This
5203 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5204 // and enables future optimizations (e.g. min/max pattern matching on X86).
5205 if (Mask.getOpcode() != ISD::SETCC)
5208 // Check if any splitting is required.
5209 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5210 TargetLowering::TypeSplitVector)
5212 SDValue MaskLo, MaskHi, Lo, Hi;
5213 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5216 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5218 SDValue Chain = MSC->getChain();
5220 EVT MemoryVT = MSC->getMemoryVT();
5221 unsigned Alignment = MSC->getOriginalAlignment();
5223 EVT LoMemVT, HiMemVT;
5224 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5226 SDValue DataLo, DataHi;
5227 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5229 SDValue BasePtr = MSC->getBasePtr();
5230 SDValue IndexLo, IndexHi;
5231 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5233 MachineMemOperand *MMO = DAG.getMachineFunction().
5234 getMachineMemOperand(MSC->getPointerInfo(),
5235 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5236 Alignment, MSC->getAAInfo(), MSC->getRanges());
5238 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5239 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5242 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5243 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5246 AddToWorklist(Lo.getNode());
5247 AddToWorklist(Hi.getNode());
5249 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5252 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5254 if (Level >= AfterLegalizeTypes)
5257 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5258 SDValue Mask = MST->getMask();
5259 SDValue Data = MST->getValue();
5262 // If the MSTORE data type requires splitting and the mask is provided by a
5263 // SETCC, then split both nodes and its operands before legalization. This
5264 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5265 // and enables future optimizations (e.g. min/max pattern matching on X86).
5266 if (Mask.getOpcode() == ISD::SETCC) {
5268 // Check if any splitting is required.
5269 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5270 TargetLowering::TypeSplitVector)
5273 SDValue MaskLo, MaskHi, Lo, Hi;
5274 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5277 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5279 SDValue Chain = MST->getChain();
5280 SDValue Ptr = MST->getBasePtr();
5282 EVT MemoryVT = MST->getMemoryVT();
5283 unsigned Alignment = MST->getOriginalAlignment();
5285 // if Alignment is equal to the vector size,
5286 // take the half of it for the second part
5287 unsigned SecondHalfAlignment =
5288 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5289 Alignment/2 : Alignment;
5291 EVT LoMemVT, HiMemVT;
5292 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5294 SDValue DataLo, DataHi;
5295 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5297 MachineMemOperand *MMO = DAG.getMachineFunction().
5298 getMachineMemOperand(MST->getPointerInfo(),
5299 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5300 Alignment, MST->getAAInfo(), MST->getRanges());
5302 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5303 MST->isTruncatingStore());
5305 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5306 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5307 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5309 MMO = DAG.getMachineFunction().
5310 getMachineMemOperand(MST->getPointerInfo(),
5311 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5312 SecondHalfAlignment, MST->getAAInfo(),
5315 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5316 MST->isTruncatingStore());
5318 AddToWorklist(Lo.getNode());
5319 AddToWorklist(Hi.getNode());
5321 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5326 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5328 if (Level >= AfterLegalizeTypes)
5331 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5332 SDValue Mask = MGT->getMask();
5335 // If the MGATHER result requires splitting and the mask is provided by a
5336 // SETCC, then split both nodes and its operands before legalization. This
5337 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5338 // and enables future optimizations (e.g. min/max pattern matching on X86).
5340 if (Mask.getOpcode() != ISD::SETCC)
5343 EVT VT = N->getValueType(0);
5345 // Check if any splitting is required.
5346 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5347 TargetLowering::TypeSplitVector)
5350 SDValue MaskLo, MaskHi, Lo, Hi;
5351 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5353 SDValue Src0 = MGT->getValue();
5354 SDValue Src0Lo, Src0Hi;
5355 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5358 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5360 SDValue Chain = MGT->getChain();
5361 EVT MemoryVT = MGT->getMemoryVT();
5362 unsigned Alignment = MGT->getOriginalAlignment();
5364 EVT LoMemVT, HiMemVT;
5365 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5367 SDValue BasePtr = MGT->getBasePtr();
5368 SDValue Index = MGT->getIndex();
5369 SDValue IndexLo, IndexHi;
5370 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5372 MachineMemOperand *MMO = DAG.getMachineFunction().
5373 getMachineMemOperand(MGT->getPointerInfo(),
5374 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5375 Alignment, MGT->getAAInfo(), MGT->getRanges());
5377 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5378 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5381 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5382 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5385 AddToWorklist(Lo.getNode());
5386 AddToWorklist(Hi.getNode());
5388 // Build a factor node to remember that this load is independent of the
5390 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5393 // Legalized the chain result - switch anything that used the old chain to
5395 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5397 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5399 SDValue RetOps[] = { GatherRes, Chain };
5400 return DAG.getMergeValues(RetOps, DL);
5403 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5405 if (Level >= AfterLegalizeTypes)
5408 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5409 SDValue Mask = MLD->getMask();
5412 // If the MLOAD result requires splitting and the mask is provided by a
5413 // SETCC, then split both nodes and its operands before legalization. This
5414 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5415 // and enables future optimizations (e.g. min/max pattern matching on X86).
5417 if (Mask.getOpcode() == ISD::SETCC) {
5418 EVT VT = N->getValueType(0);
5420 // Check if any splitting is required.
5421 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5422 TargetLowering::TypeSplitVector)
5425 SDValue MaskLo, MaskHi, Lo, Hi;
5426 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5428 SDValue Src0 = MLD->getSrc0();
5429 SDValue Src0Lo, Src0Hi;
5430 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5433 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5435 SDValue Chain = MLD->getChain();
5436 SDValue Ptr = MLD->getBasePtr();
5437 EVT MemoryVT = MLD->getMemoryVT();
5438 unsigned Alignment = MLD->getOriginalAlignment();
5440 // if Alignment is equal to the vector size,
5441 // take the half of it for the second part
5442 unsigned SecondHalfAlignment =
5443 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5444 Alignment/2 : Alignment;
5446 EVT LoMemVT, HiMemVT;
5447 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5449 MachineMemOperand *MMO = DAG.getMachineFunction().
5450 getMachineMemOperand(MLD->getPointerInfo(),
5451 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5452 Alignment, MLD->getAAInfo(), MLD->getRanges());
5454 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5457 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5458 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5459 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5461 MMO = DAG.getMachineFunction().
5462 getMachineMemOperand(MLD->getPointerInfo(),
5463 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5464 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5466 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5469 AddToWorklist(Lo.getNode());
5470 AddToWorklist(Hi.getNode());
5472 // Build a factor node to remember that this load is independent of the
5474 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5477 // Legalized the chain result - switch anything that used the old chain to
5479 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5481 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5483 SDValue RetOps[] = { LoadRes, Chain };
5484 return DAG.getMergeValues(RetOps, DL);
5489 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5490 SDValue N0 = N->getOperand(0);
5491 SDValue N1 = N->getOperand(1);
5492 SDValue N2 = N->getOperand(2);
5495 // Canonicalize integer abs.
5496 // vselect (setg[te] X, 0), X, -X ->
5497 // vselect (setgt X, -1), X, -X ->
5498 // vselect (setl[te] X, 0), -X, X ->
5499 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5500 if (N0.getOpcode() == ISD::SETCC) {
5501 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5502 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5504 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5506 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5507 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5508 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5509 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5510 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5511 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5512 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5515 EVT VT = LHS.getValueType();
5516 SDValue Shift = DAG.getNode(
5517 ISD::SRA, DL, VT, LHS,
5518 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5519 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5520 AddToWorklist(Shift.getNode());
5521 AddToWorklist(Add.getNode());
5522 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5526 if (SimplifySelectOps(N, N1, N2))
5527 return SDValue(N, 0); // Don't revisit N.
5529 // If the VSELECT result requires splitting and the mask is provided by a
5530 // SETCC, then split both nodes and its operands before legalization. This
5531 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5532 // and enables future optimizations (e.g. min/max pattern matching on X86).
5533 if (N0.getOpcode() == ISD::SETCC) {
5534 EVT VT = N->getValueType(0);
5536 // Check if any splitting is required.
5537 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5538 TargetLowering::TypeSplitVector)
5541 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5542 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5543 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5544 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5546 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5547 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5549 // Add the new VSELECT nodes to the work list in case they need to be split
5551 AddToWorklist(Lo.getNode());
5552 AddToWorklist(Hi.getNode());
5554 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5557 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5558 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5560 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5561 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5564 // The ConvertSelectToConcatVector function is assuming both the above
5565 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5567 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5568 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5569 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5570 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5577 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5578 SDValue N0 = N->getOperand(0);
5579 SDValue N1 = N->getOperand(1);
5580 SDValue N2 = N->getOperand(2);
5581 SDValue N3 = N->getOperand(3);
5582 SDValue N4 = N->getOperand(4);
5583 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5585 // fold select_cc lhs, rhs, x, x, cc -> x
5589 // Determine if the condition we're dealing with is constant
5590 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5591 N0, N1, CC, SDLoc(N), false);
5592 if (SCC.getNode()) {
5593 AddToWorklist(SCC.getNode());
5595 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5596 if (!SCCC->isNullValue())
5597 return N2; // cond always true -> true val
5599 return N3; // cond always false -> false val
5600 } else if (SCC->getOpcode() == ISD::UNDEF) {
5601 // When the condition is UNDEF, just return the first operand. This is
5602 // coherent the DAG creation, no setcc node is created in this case
5604 } else if (SCC.getOpcode() == ISD::SETCC) {
5605 // Fold to a simpler select_cc
5606 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5607 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5612 // If we can fold this based on the true/false value, do so.
5613 if (SimplifySelectOps(N, N2, N3))
5614 return SDValue(N, 0); // Don't revisit N.
5616 // fold select_cc into other things, such as min/max/abs
5617 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5620 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5621 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5622 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5626 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5627 /// a build_vector of constants.
5628 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5629 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5630 /// Vector extends are not folded if operations are legal; this is to
5631 /// avoid introducing illegal build_vector dag nodes.
5632 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5633 SelectionDAG &DAG, bool LegalTypes,
5634 bool LegalOperations) {
5635 unsigned Opcode = N->getOpcode();
5636 SDValue N0 = N->getOperand(0);
5637 EVT VT = N->getValueType(0);
5639 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5640 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5641 && "Expected EXTEND dag node in input!");
5643 // fold (sext c1) -> c1
5644 // fold (zext c1) -> c1
5645 // fold (aext c1) -> c1
5646 if (isa<ConstantSDNode>(N0))
5647 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5649 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5650 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5651 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5652 EVT SVT = VT.getScalarType();
5653 if (!(VT.isVector() &&
5654 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5655 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5658 // We can fold this node into a build_vector.
5659 unsigned VTBits = SVT.getSizeInBits();
5660 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5661 SmallVector<SDValue, 8> Elts;
5662 unsigned NumElts = VT.getVectorNumElements();
5665 for (unsigned i=0; i != NumElts; ++i) {
5666 SDValue Op = N0->getOperand(i);
5667 if (Op->getOpcode() == ISD::UNDEF) {
5668 Elts.push_back(DAG.getUNDEF(SVT));
5673 // Get the constant value and if needed trunc it to the size of the type.
5674 // Nodes like build_vector might have constants wider than the scalar type.
5675 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5676 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5677 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5679 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5682 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5685 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5686 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5687 // transformation. Returns true if extension are possible and the above
5688 // mentioned transformation is profitable.
5689 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5691 SmallVectorImpl<SDNode *> &ExtendNodes,
5692 const TargetLowering &TLI) {
5693 bool HasCopyToRegUses = false;
5694 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5695 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5696 UE = N0.getNode()->use_end();
5701 if (UI.getUse().getResNo() != N0.getResNo())
5703 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5704 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5705 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5706 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5707 // Sign bits will be lost after a zext.
5710 for (unsigned i = 0; i != 2; ++i) {
5711 SDValue UseOp = User->getOperand(i);
5714 if (!isa<ConstantSDNode>(UseOp))
5719 ExtendNodes.push_back(User);
5722 // If truncates aren't free and there are users we can't
5723 // extend, it isn't worthwhile.
5726 // Remember if this value is live-out.
5727 if (User->getOpcode() == ISD::CopyToReg)
5728 HasCopyToRegUses = true;
5731 if (HasCopyToRegUses) {
5732 bool BothLiveOut = false;
5733 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5735 SDUse &Use = UI.getUse();
5736 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5742 // Both unextended and extended values are live out. There had better be
5743 // a good reason for the transformation.
5744 return ExtendNodes.size();
5749 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5750 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5751 ISD::NodeType ExtType) {
5752 // Extend SetCC uses if necessary.
5753 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5754 SDNode *SetCC = SetCCs[i];
5755 SmallVector<SDValue, 4> Ops;
5757 for (unsigned j = 0; j != 2; ++j) {
5758 SDValue SOp = SetCC->getOperand(j);
5760 Ops.push_back(ExtLoad);
5762 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5765 Ops.push_back(SetCC->getOperand(2));
5766 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5770 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5771 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5772 SDValue N0 = N->getOperand(0);
5773 EVT DstVT = N->getValueType(0);
5774 EVT SrcVT = N0.getValueType();
5776 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5777 N->getOpcode() == ISD::ZERO_EXTEND) &&
5778 "Unexpected node type (not an extend)!");
5780 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5781 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5782 // (v8i32 (sext (v8i16 (load x))))
5784 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5785 // (v4i32 (sextload (x + 16)))))
5786 // Where uses of the original load, i.e.:
5788 // are replaced with:
5790 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5791 // (v4i32 (sextload (x + 16)))))))
5793 // This combine is only applicable to illegal, but splittable, vectors.
5794 // All legal types, and illegal non-vector types, are handled elsewhere.
5795 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5797 if (N0->getOpcode() != ISD::LOAD)
5800 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5802 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5803 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5804 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5807 SmallVector<SDNode *, 4> SetCCs;
5808 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5811 ISD::LoadExtType ExtType =
5812 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5814 // Try to split the vector types to get down to legal types.
5815 EVT SplitSrcVT = SrcVT;
5816 EVT SplitDstVT = DstVT;
5817 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5818 SplitSrcVT.getVectorNumElements() > 1) {
5819 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5820 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5823 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5827 const unsigned NumSplits =
5828 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5829 const unsigned Stride = SplitSrcVT.getStoreSize();
5830 SmallVector<SDValue, 4> Loads;
5831 SmallVector<SDValue, 4> Chains;
5833 SDValue BasePtr = LN0->getBasePtr();
5834 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5835 const unsigned Offset = Idx * Stride;
5836 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5838 SDValue SplitLoad = DAG.getExtLoad(
5839 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5840 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5841 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5842 Align, LN0->getAAInfo());
5844 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5845 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5847 Loads.push_back(SplitLoad.getValue(0));
5848 Chains.push_back(SplitLoad.getValue(1));
5851 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5852 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5854 CombineTo(N, NewValue);
5856 // Replace uses of the original load (before extension)
5857 // with a truncate of the concatenated sextloaded vectors.
5859 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5860 CombineTo(N0.getNode(), Trunc, NewChain);
5861 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5862 (ISD::NodeType)N->getOpcode());
5863 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5866 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5867 SDValue N0 = N->getOperand(0);
5868 EVT VT = N->getValueType(0);
5870 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5872 return SDValue(Res, 0);
5874 // fold (sext (sext x)) -> (sext x)
5875 // fold (sext (aext x)) -> (sext x)
5876 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5877 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5880 if (N0.getOpcode() == ISD::TRUNCATE) {
5881 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5882 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5883 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5884 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5885 if (NarrowLoad.getNode() != N0.getNode()) {
5886 CombineTo(N0.getNode(), NarrowLoad);
5887 // CombineTo deleted the truncate, if needed, but not what's under it.
5890 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5893 // See if the value being truncated is already sign extended. If so, just
5894 // eliminate the trunc/sext pair.
5895 SDValue Op = N0.getOperand(0);
5896 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5897 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5898 unsigned DestBits = VT.getScalarType().getSizeInBits();
5899 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5901 if (OpBits == DestBits) {
5902 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5903 // bits, it is already ready.
5904 if (NumSignBits > DestBits-MidBits)
5906 } else if (OpBits < DestBits) {
5907 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5908 // bits, just sext from i32.
5909 if (NumSignBits > OpBits-MidBits)
5910 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5912 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5913 // bits, just truncate to i32.
5914 if (NumSignBits > OpBits-MidBits)
5915 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5918 // fold (sext (truncate x)) -> (sextinreg x).
5919 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5920 N0.getValueType())) {
5921 if (OpBits < DestBits)
5922 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5923 else if (OpBits > DestBits)
5924 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5925 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5926 DAG.getValueType(N0.getValueType()));
5930 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5931 // Only generate vector extloads when 1) they're legal, and 2) they are
5932 // deemed desirable by the target.
5933 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5934 ((!LegalOperations && !VT.isVector() &&
5935 !cast<LoadSDNode>(N0)->isVolatile()) ||
5936 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5937 bool DoXform = true;
5938 SmallVector<SDNode*, 4> SetCCs;
5939 if (!N0.hasOneUse())
5940 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5942 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5944 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5945 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5947 LN0->getBasePtr(), N0.getValueType(),
5948 LN0->getMemOperand());
5949 CombineTo(N, ExtLoad);
5950 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5951 N0.getValueType(), ExtLoad);
5952 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5953 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5959 // fold (sext (load x)) to multiple smaller sextloads.
5960 // Only on illegal but splittable vectors.
5961 if (SDValue ExtLoad = CombineExtLoad(N))
5964 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5965 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5966 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5967 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5968 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5969 EVT MemVT = LN0->getMemoryVT();
5970 if ((!LegalOperations && !LN0->isVolatile()) ||
5971 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5972 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5974 LN0->getBasePtr(), MemVT,
5975 LN0->getMemOperand());
5976 CombineTo(N, ExtLoad);
5977 CombineTo(N0.getNode(),
5978 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5979 N0.getValueType(), ExtLoad),
5980 ExtLoad.getValue(1));
5981 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5985 // fold (sext (and/or/xor (load x), cst)) ->
5986 // (and/or/xor (sextload x), (sext cst))
5987 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5988 N0.getOpcode() == ISD::XOR) &&
5989 isa<LoadSDNode>(N0.getOperand(0)) &&
5990 N0.getOperand(1).getOpcode() == ISD::Constant &&
5991 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5992 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5993 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5994 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5995 bool DoXform = true;
5996 SmallVector<SDNode*, 4> SetCCs;
5997 if (!N0.hasOneUse())
5998 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6001 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6002 LN0->getChain(), LN0->getBasePtr(),
6004 LN0->getMemOperand());
6005 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6006 Mask = Mask.sext(VT.getSizeInBits());
6008 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6009 ExtLoad, DAG.getConstant(Mask, DL, VT));
6010 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6011 SDLoc(N0.getOperand(0)),
6012 N0.getOperand(0).getValueType(), ExtLoad);
6014 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6015 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6017 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6022 if (N0.getOpcode() == ISD::SETCC) {
6023 EVT N0VT = N0.getOperand(0).getValueType();
6024 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6025 // Only do this before legalize for now.
6026 if (VT.isVector() && !LegalOperations &&
6027 TLI.getBooleanContents(N0VT) ==
6028 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6029 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6030 // of the same size as the compared operands. Only optimize sext(setcc())
6031 // if this is the case.
6032 EVT SVT = getSetCCResultType(N0VT);
6034 // We know that the # elements of the results is the same as the
6035 // # elements of the compare (and the # elements of the compare result
6036 // for that matter). Check to see that they are the same size. If so,
6037 // we know that the element size of the sext'd result matches the
6038 // element size of the compare operands.
6039 if (VT.getSizeInBits() == SVT.getSizeInBits())
6040 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6042 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6044 // If the desired elements are smaller or larger than the source
6045 // elements we can use a matching integer vector type and then
6046 // truncate/sign extend
6047 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6048 if (SVT == MatchingVectorType) {
6049 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6050 N0.getOperand(0), N0.getOperand(1),
6051 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6052 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6056 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6057 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6060 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6062 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6063 NegOne, DAG.getConstant(0, DL, VT),
6064 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6065 if (SCC.getNode()) return SCC;
6067 if (!VT.isVector()) {
6068 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6069 if (!LegalOperations ||
6070 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6072 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6073 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6074 N0.getOperand(0), N0.getOperand(1), CC);
6075 return DAG.getSelect(DL, VT, SetCC,
6076 NegOne, DAG.getConstant(0, DL, VT));
6081 // fold (sext x) -> (zext x) if the sign bit is known zero.
6082 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6083 DAG.SignBitIsZero(N0))
6084 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6089 // isTruncateOf - If N is a truncate of some other value, return true, record
6090 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6091 // This function computes KnownZero to avoid a duplicated call to
6092 // computeKnownBits in the caller.
6093 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6096 if (N->getOpcode() == ISD::TRUNCATE) {
6097 Op = N->getOperand(0);
6098 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6102 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6103 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6106 SDValue Op0 = N->getOperand(0);
6107 SDValue Op1 = N->getOperand(1);
6108 assert(Op0.getValueType() == Op1.getValueType());
6110 if (isNullConstant(Op0))
6112 else if (isNullConstant(Op1))
6117 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6119 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6125 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6126 SDValue N0 = N->getOperand(0);
6127 EVT VT = N->getValueType(0);
6129 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6131 return SDValue(Res, 0);
6133 // fold (zext (zext x)) -> (zext x)
6134 // fold (zext (aext x)) -> (zext x)
6135 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6136 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6139 // fold (zext (truncate x)) -> (zext x) or
6140 // (zext (truncate x)) -> (truncate x)
6141 // This is valid when the truncated bits of x are already zero.
6142 // FIXME: We should extend this to work for vectors too.
6145 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6146 APInt TruncatedBits =
6147 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6148 APInt(Op.getValueSizeInBits(), 0) :
6149 APInt::getBitsSet(Op.getValueSizeInBits(),
6150 N0.getValueSizeInBits(),
6151 std::min(Op.getValueSizeInBits(),
6152 VT.getSizeInBits()));
6153 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6154 if (VT.bitsGT(Op.getValueType()))
6155 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6156 if (VT.bitsLT(Op.getValueType()))
6157 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6163 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6164 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6165 if (N0.getOpcode() == ISD::TRUNCATE) {
6166 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6167 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6168 if (NarrowLoad.getNode() != N0.getNode()) {
6169 CombineTo(N0.getNode(), NarrowLoad);
6170 // CombineTo deleted the truncate, if needed, but not what's under it.
6173 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6177 // fold (zext (truncate x)) -> (and x, mask)
6178 if (N0.getOpcode() == ISD::TRUNCATE) {
6179 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6180 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6181 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6182 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6183 if (NarrowLoad.getNode() != N0.getNode()) {
6184 CombineTo(N0.getNode(), NarrowLoad);
6185 // CombineTo deleted the truncate, if needed, but not what's under it.
6188 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6191 EVT SrcVT = N0.getOperand(0).getValueType();
6192 EVT MinVT = N0.getValueType();
6194 // Try to mask before the extension to avoid having to generate a larger mask,
6195 // possibly over several sub-vectors.
6196 if (SrcVT.bitsLT(VT)) {
6197 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6198 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6199 SDValue Op = N0.getOperand(0);
6200 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6201 AddToWorklist(Op.getNode());
6202 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6206 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6207 SDValue Op = N0.getOperand(0);
6208 if (SrcVT.bitsLT(VT)) {
6209 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6210 AddToWorklist(Op.getNode());
6211 } else if (SrcVT.bitsGT(VT)) {
6212 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6213 AddToWorklist(Op.getNode());
6215 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6219 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6220 // if either of the casts is not free.
6221 if (N0.getOpcode() == ISD::AND &&
6222 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6223 N0.getOperand(1).getOpcode() == ISD::Constant &&
6224 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6225 N0.getValueType()) ||
6226 !TLI.isZExtFree(N0.getValueType(), VT))) {
6227 SDValue X = N0.getOperand(0).getOperand(0);
6228 if (X.getValueType().bitsLT(VT)) {
6229 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6230 } else if (X.getValueType().bitsGT(VT)) {
6231 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6233 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6234 Mask = Mask.zext(VT.getSizeInBits());
6236 return DAG.getNode(ISD::AND, DL, VT,
6237 X, DAG.getConstant(Mask, DL, VT));
6240 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6241 // Only generate vector extloads when 1) they're legal, and 2) they are
6242 // deemed desirable by the target.
6243 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6244 ((!LegalOperations && !VT.isVector() &&
6245 !cast<LoadSDNode>(N0)->isVolatile()) ||
6246 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6247 bool DoXform = true;
6248 SmallVector<SDNode*, 4> SetCCs;
6249 if (!N0.hasOneUse())
6250 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6252 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6254 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6255 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6257 LN0->getBasePtr(), N0.getValueType(),
6258 LN0->getMemOperand());
6259 CombineTo(N, ExtLoad);
6260 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6261 N0.getValueType(), ExtLoad);
6262 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6264 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6266 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6270 // fold (zext (load x)) to multiple smaller zextloads.
6271 // Only on illegal but splittable vectors.
6272 if (SDValue ExtLoad = CombineExtLoad(N))
6275 // fold (zext (and/or/xor (load x), cst)) ->
6276 // (and/or/xor (zextload x), (zext cst))
6277 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6278 N0.getOpcode() == ISD::XOR) &&
6279 isa<LoadSDNode>(N0.getOperand(0)) &&
6280 N0.getOperand(1).getOpcode() == ISD::Constant &&
6281 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6282 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6283 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6284 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6285 bool DoXform = true;
6286 SmallVector<SDNode*, 4> SetCCs;
6287 if (!N0.hasOneUse())
6288 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6291 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6292 LN0->getChain(), LN0->getBasePtr(),
6294 LN0->getMemOperand());
6295 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6296 Mask = Mask.zext(VT.getSizeInBits());
6298 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6299 ExtLoad, DAG.getConstant(Mask, DL, VT));
6300 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6301 SDLoc(N0.getOperand(0)),
6302 N0.getOperand(0).getValueType(), ExtLoad);
6304 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6305 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6307 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6312 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6313 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6314 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6315 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6316 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6317 EVT MemVT = LN0->getMemoryVT();
6318 if ((!LegalOperations && !LN0->isVolatile()) ||
6319 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6320 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6322 LN0->getBasePtr(), MemVT,
6323 LN0->getMemOperand());
6324 CombineTo(N, ExtLoad);
6325 CombineTo(N0.getNode(),
6326 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6328 ExtLoad.getValue(1));
6329 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6333 if (N0.getOpcode() == ISD::SETCC) {
6334 if (!LegalOperations && VT.isVector() &&
6335 N0.getValueType().getVectorElementType() == MVT::i1) {
6336 EVT N0VT = N0.getOperand(0).getValueType();
6337 if (getSetCCResultType(N0VT) == N0.getValueType())
6340 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6341 // Only do this before legalize for now.
6342 EVT EltVT = VT.getVectorElementType();
6344 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6345 DAG.getConstant(1, DL, EltVT));
6346 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6347 // We know that the # elements of the results is the same as the
6348 // # elements of the compare (and the # elements of the compare result
6349 // for that matter). Check to see that they are the same size. If so,
6350 // we know that the element size of the sext'd result matches the
6351 // element size of the compare operands.
6352 return DAG.getNode(ISD::AND, DL, VT,
6353 DAG.getSetCC(DL, VT, N0.getOperand(0),
6355 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6356 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6359 // If the desired elements are smaller or larger than the source
6360 // elements we can use a matching integer vector type and then
6361 // truncate/sign extend
6362 EVT MatchingElementType =
6363 EVT::getIntegerVT(*DAG.getContext(),
6364 N0VT.getScalarType().getSizeInBits());
6365 EVT MatchingVectorType =
6366 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6367 N0VT.getVectorNumElements());
6369 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6371 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6372 return DAG.getNode(ISD::AND, DL, VT,
6373 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6374 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6377 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6380 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6381 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6382 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6383 if (SCC.getNode()) return SCC;
6386 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6387 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6388 isa<ConstantSDNode>(N0.getOperand(1)) &&
6389 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6391 SDValue ShAmt = N0.getOperand(1);
6392 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6393 if (N0.getOpcode() == ISD::SHL) {
6394 SDValue InnerZExt = N0.getOperand(0);
6395 // If the original shl may be shifting out bits, do not perform this
6397 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6398 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6399 if (ShAmtVal > KnownZeroBits)
6405 // Ensure that the shift amount is wide enough for the shifted value.
6406 if (VT.getSizeInBits() >= 256)
6407 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6409 return DAG.getNode(N0.getOpcode(), DL, VT,
6410 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6417 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6418 SDValue N0 = N->getOperand(0);
6419 EVT VT = N->getValueType(0);
6421 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6423 return SDValue(Res, 0);
6425 // fold (aext (aext x)) -> (aext x)
6426 // fold (aext (zext x)) -> (zext x)
6427 // fold (aext (sext x)) -> (sext x)
6428 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6429 N0.getOpcode() == ISD::ZERO_EXTEND ||
6430 N0.getOpcode() == ISD::SIGN_EXTEND)
6431 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6433 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6434 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6435 if (N0.getOpcode() == ISD::TRUNCATE) {
6436 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6437 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6438 if (NarrowLoad.getNode() != N0.getNode()) {
6439 CombineTo(N0.getNode(), NarrowLoad);
6440 // CombineTo deleted the truncate, if needed, but not what's under it.
6443 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6447 // fold (aext (truncate x))
6448 if (N0.getOpcode() == ISD::TRUNCATE) {
6449 SDValue TruncOp = N0.getOperand(0);
6450 if (TruncOp.getValueType() == VT)
6451 return TruncOp; // x iff x size == zext size.
6452 if (TruncOp.getValueType().bitsGT(VT))
6453 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6454 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6457 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6458 // if the trunc is not free.
6459 if (N0.getOpcode() == ISD::AND &&
6460 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6461 N0.getOperand(1).getOpcode() == ISD::Constant &&
6462 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6463 N0.getValueType())) {
6464 SDValue X = N0.getOperand(0).getOperand(0);
6465 if (X.getValueType().bitsLT(VT)) {
6466 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6467 } else if (X.getValueType().bitsGT(VT)) {
6468 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6470 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6471 Mask = Mask.zext(VT.getSizeInBits());
6473 return DAG.getNode(ISD::AND, DL, VT,
6474 X, DAG.getConstant(Mask, DL, VT));
6477 // fold (aext (load x)) -> (aext (truncate (extload x)))
6478 // None of the supported targets knows how to perform load and any_ext
6479 // on vectors in one instruction. We only perform this transformation on
6481 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6482 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6483 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6484 bool DoXform = true;
6485 SmallVector<SDNode*, 4> SetCCs;
6486 if (!N0.hasOneUse())
6487 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6489 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6490 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6492 LN0->getBasePtr(), N0.getValueType(),
6493 LN0->getMemOperand());
6494 CombineTo(N, ExtLoad);
6495 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6496 N0.getValueType(), ExtLoad);
6497 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6498 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6500 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6504 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6505 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6506 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6507 if (N0.getOpcode() == ISD::LOAD &&
6508 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6510 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6511 ISD::LoadExtType ExtType = LN0->getExtensionType();
6512 EVT MemVT = LN0->getMemoryVT();
6513 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6514 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6515 VT, LN0->getChain(), LN0->getBasePtr(),
6516 MemVT, LN0->getMemOperand());
6517 CombineTo(N, ExtLoad);
6518 CombineTo(N0.getNode(),
6519 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6520 N0.getValueType(), ExtLoad),
6521 ExtLoad.getValue(1));
6522 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6526 if (N0.getOpcode() == ISD::SETCC) {
6528 // aext(setcc) -> vsetcc
6529 // aext(setcc) -> truncate(vsetcc)
6530 // aext(setcc) -> aext(vsetcc)
6531 // Only do this before legalize for now.
6532 if (VT.isVector() && !LegalOperations) {
6533 EVT N0VT = N0.getOperand(0).getValueType();
6534 // We know that the # elements of the results is the same as the
6535 // # elements of the compare (and the # elements of the compare result
6536 // for that matter). Check to see that they are the same size. If so,
6537 // we know that the element size of the sext'd result matches the
6538 // element size of the compare operands.
6539 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6540 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6542 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6543 // If the desired elements are smaller or larger than the source
6544 // elements we can use a matching integer vector type and then
6545 // truncate/any extend
6547 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6549 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6551 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6552 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6556 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6559 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6560 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6561 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6569 /// See if the specified operand can be simplified with the knowledge that only
6570 /// the bits specified by Mask are used. If so, return the simpler operand,
6571 /// otherwise return a null SDValue.
6572 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6573 switch (V.getOpcode()) {
6575 case ISD::Constant: {
6576 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6577 assert(CV && "Const value should be ConstSDNode.");
6578 const APInt &CVal = CV->getAPIntValue();
6579 APInt NewVal = CVal & Mask;
6581 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6586 // If the LHS or RHS don't contribute bits to the or, drop them.
6587 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6588 return V.getOperand(1);
6589 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6590 return V.getOperand(0);
6593 // Only look at single-use SRLs.
6594 if (!V.getNode()->hasOneUse())
6596 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6597 // See if we can recursively simplify the LHS.
6598 unsigned Amt = RHSC->getZExtValue();
6600 // Watch out for shift count overflow though.
6601 if (Amt >= Mask.getBitWidth()) break;
6602 APInt NewMask = Mask << Amt;
6603 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6604 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6605 SimplifyLHS, V.getOperand(1));
6611 /// If the result of a wider load is shifted to right of N bits and then
6612 /// truncated to a narrower type and where N is a multiple of number of bits of
6613 /// the narrower type, transform it to a narrower load from address + N / num of
6614 /// bits of new type. If the result is to be extended, also fold the extension
6615 /// to form a extending load.
6616 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6617 unsigned Opc = N->getOpcode();
6619 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6620 SDValue N0 = N->getOperand(0);
6621 EVT VT = N->getValueType(0);
6624 // This transformation isn't valid for vector loads.
6628 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6630 if (Opc == ISD::SIGN_EXTEND_INREG) {
6631 ExtType = ISD::SEXTLOAD;
6632 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6633 } else if (Opc == ISD::SRL) {
6634 // Another special-case: SRL is basically zero-extending a narrower value.
6635 ExtType = ISD::ZEXTLOAD;
6637 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6638 if (!N01) return SDValue();
6639 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6640 VT.getSizeInBits() - N01->getZExtValue());
6642 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6645 unsigned EVTBits = ExtVT.getSizeInBits();
6647 // Do not generate loads of non-round integer types since these can
6648 // be expensive (and would be wrong if the type is not byte sized).
6649 if (!ExtVT.isRound())
6653 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6654 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6655 ShAmt = N01->getZExtValue();
6656 // Is the shift amount a multiple of size of VT?
6657 if ((ShAmt & (EVTBits-1)) == 0) {
6658 N0 = N0.getOperand(0);
6659 // Is the load width a multiple of size of VT?
6660 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6664 // At this point, we must have a load or else we can't do the transform.
6665 if (!isa<LoadSDNode>(N0)) return SDValue();
6667 // Because a SRL must be assumed to *need* to zero-extend the high bits
6668 // (as opposed to anyext the high bits), we can't combine the zextload
6669 // lowering of SRL and an sextload.
6670 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6673 // If the shift amount is larger than the input type then we're not
6674 // accessing any of the loaded bytes. If the load was a zextload/extload
6675 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6676 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6681 // If the load is shifted left (and the result isn't shifted back right),
6682 // we can fold the truncate through the shift.
6683 unsigned ShLeftAmt = 0;
6684 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6685 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6686 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6687 ShLeftAmt = N01->getZExtValue();
6688 N0 = N0.getOperand(0);
6692 // If we haven't found a load, we can't narrow it. Don't transform one with
6693 // multiple uses, this would require adding a new load.
6694 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6697 // Don't change the width of a volatile load.
6698 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6699 if (LN0->isVolatile())
6702 // Verify that we are actually reducing a load width here.
6703 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6706 // For the transform to be legal, the load must produce only two values
6707 // (the value loaded and the chain). Don't transform a pre-increment
6708 // load, for example, which produces an extra value. Otherwise the
6709 // transformation is not equivalent, and the downstream logic to replace
6710 // uses gets things wrong.
6711 if (LN0->getNumValues() > 2)
6714 // If the load that we're shrinking is an extload and we're not just
6715 // discarding the extension we can't simply shrink the load. Bail.
6716 // TODO: It would be possible to merge the extensions in some cases.
6717 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6718 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6721 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6724 EVT PtrType = N0.getOperand(1).getValueType();
6726 if (PtrType == MVT::Untyped || PtrType.isExtended())
6727 // It's not possible to generate a constant of extended or untyped type.
6730 // For big endian targets, we need to adjust the offset to the pointer to
6731 // load the correct bytes.
6732 if (DAG.getDataLayout().isBigEndian()) {
6733 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6734 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6735 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6738 uint64_t PtrOff = ShAmt / 8;
6739 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6741 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6742 PtrType, LN0->getBasePtr(),
6743 DAG.getConstant(PtrOff, DL, PtrType));
6744 AddToWorklist(NewPtr.getNode());
6747 if (ExtType == ISD::NON_EXTLOAD)
6748 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6749 LN0->getPointerInfo().getWithOffset(PtrOff),
6750 LN0->isVolatile(), LN0->isNonTemporal(),
6751 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6753 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6754 LN0->getPointerInfo().getWithOffset(PtrOff),
6755 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6756 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6758 // Replace the old load's chain with the new load's chain.
6759 WorklistRemover DeadNodes(*this);
6760 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6762 // Shift the result left, if we've swallowed a left shift.
6763 SDValue Result = Load;
6764 if (ShLeftAmt != 0) {
6765 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6766 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6768 // If the shift amount is as large as the result size (but, presumably,
6769 // no larger than the source) then the useful bits of the result are
6770 // zero; we can't simply return the shortened shift, because the result
6771 // of that operation is undefined.
6773 if (ShLeftAmt >= VT.getSizeInBits())
6774 Result = DAG.getConstant(0, DL, VT);
6776 Result = DAG.getNode(ISD::SHL, DL, VT,
6777 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6780 // Return the new loaded value.
6784 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6785 SDValue N0 = N->getOperand(0);
6786 SDValue N1 = N->getOperand(1);
6787 EVT VT = N->getValueType(0);
6788 EVT EVT = cast<VTSDNode>(N1)->getVT();
6789 unsigned VTBits = VT.getScalarType().getSizeInBits();
6790 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6792 // fold (sext_in_reg c1) -> c1
6793 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6794 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6796 // If the input is already sign extended, just drop the extension.
6797 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6800 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6801 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6802 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6803 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6804 N0.getOperand(0), N1);
6806 // fold (sext_in_reg (sext x)) -> (sext x)
6807 // fold (sext_in_reg (aext x)) -> (sext x)
6808 // if x is small enough.
6809 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6810 SDValue N00 = N0.getOperand(0);
6811 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6812 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6813 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6816 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6817 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6818 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6820 // fold operands of sext_in_reg based on knowledge that the top bits are not
6822 if (SimplifyDemandedBits(SDValue(N, 0)))
6823 return SDValue(N, 0);
6825 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6826 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6827 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6830 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6831 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6832 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6833 if (N0.getOpcode() == ISD::SRL) {
6834 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6835 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6836 // We can turn this into an SRA iff the input to the SRL is already sign
6838 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6839 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6840 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6841 N0.getOperand(0), N0.getOperand(1));
6845 // fold (sext_inreg (extload x)) -> (sextload x)
6846 if (ISD::isEXTLoad(N0.getNode()) &&
6847 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6848 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6849 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6850 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6851 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6852 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6854 LN0->getBasePtr(), EVT,
6855 LN0->getMemOperand());
6856 CombineTo(N, ExtLoad);
6857 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6858 AddToWorklist(ExtLoad.getNode());
6859 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6861 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6862 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6864 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6865 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6866 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6867 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6868 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6870 LN0->getBasePtr(), EVT,
6871 LN0->getMemOperand());
6872 CombineTo(N, ExtLoad);
6873 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6874 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6877 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6878 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6879 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6880 N0.getOperand(1), false);
6881 if (BSwap.getNode())
6882 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6886 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6887 // into a build_vector.
6888 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6889 SmallVector<SDValue, 8> Elts;
6890 unsigned NumElts = N0->getNumOperands();
6891 unsigned ShAmt = VTBits - EVTBits;
6893 for (unsigned i = 0; i != NumElts; ++i) {
6894 SDValue Op = N0->getOperand(i);
6895 if (Op->getOpcode() == ISD::UNDEF) {
6900 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6901 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6902 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6903 SDLoc(Op), Op.getValueType()));
6906 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6912 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6913 SDValue N0 = N->getOperand(0);
6914 EVT VT = N->getValueType(0);
6916 if (N0.getOpcode() == ISD::UNDEF)
6917 return DAG.getUNDEF(VT);
6919 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6921 return SDValue(Res, 0);
6926 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6927 SDValue N0 = N->getOperand(0);
6928 EVT VT = N->getValueType(0);
6929 bool isLE = DAG.getDataLayout().isLittleEndian();
6932 if (N0.getValueType() == N->getValueType(0))
6934 // fold (truncate c1) -> c1
6935 if (isConstantIntBuildVectorOrConstantInt(N0))
6936 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6937 // fold (truncate (truncate x)) -> (truncate x)
6938 if (N0.getOpcode() == ISD::TRUNCATE)
6939 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6940 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6941 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6942 N0.getOpcode() == ISD::SIGN_EXTEND ||
6943 N0.getOpcode() == ISD::ANY_EXTEND) {
6944 if (N0.getOperand(0).getValueType().bitsLT(VT))
6945 // if the source is smaller than the dest, we still need an extend
6946 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6948 if (N0.getOperand(0).getValueType().bitsGT(VT))
6949 // if the source is larger than the dest, than we just need the truncate
6950 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6951 // if the source and dest are the same type, we can drop both the extend
6952 // and the truncate.
6953 return N0.getOperand(0);
6956 // Fold extract-and-trunc into a narrow extract. For example:
6957 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6958 // i32 y = TRUNCATE(i64 x)
6960 // v16i8 b = BITCAST (v2i64 val)
6961 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6963 // Note: We only run this optimization after type legalization (which often
6964 // creates this pattern) and before operation legalization after which
6965 // we need to be more careful about the vector instructions that we generate.
6966 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6967 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6969 EVT VecTy = N0.getOperand(0).getValueType();
6970 EVT ExTy = N0.getValueType();
6971 EVT TrTy = N->getValueType(0);
6973 unsigned NumElem = VecTy.getVectorNumElements();
6974 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6976 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6977 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6979 SDValue EltNo = N0->getOperand(1);
6980 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6981 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6982 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6983 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6985 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6986 NVT, N0.getOperand(0));
6989 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6991 DAG.getConstant(Index, DL, IndexTy));
6995 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6996 if (N0.getOpcode() == ISD::SELECT) {
6997 EVT SrcVT = N0.getValueType();
6998 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6999 TLI.isTruncateFree(SrcVT, VT)) {
7001 SDValue Cond = N0.getOperand(0);
7002 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7003 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7004 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7008 // Fold a series of buildvector, bitcast, and truncate if possible.
7010 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7011 // (2xi32 (buildvector x, y)).
7012 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7013 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7014 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7015 N0.getOperand(0).hasOneUse()) {
7017 SDValue BuildVect = N0.getOperand(0);
7018 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7019 EVT TruncVecEltTy = VT.getVectorElementType();
7021 // Check that the element types match.
7022 if (BuildVectEltTy == TruncVecEltTy) {
7023 // Now we only need to compute the offset of the truncated elements.
7024 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7025 unsigned TruncVecNumElts = VT.getVectorNumElements();
7026 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7028 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7029 "Invalid number of elements");
7031 SmallVector<SDValue, 8> Opnds;
7032 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7033 Opnds.push_back(BuildVect.getOperand(i));
7035 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7039 // See if we can simplify the input to this truncate through knowledge that
7040 // only the low bits are being used.
7041 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7042 // Currently we only perform this optimization on scalars because vectors
7043 // may have different active low bits.
7044 if (!VT.isVector()) {
7046 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7047 VT.getSizeInBits()));
7048 if (Shorter.getNode())
7049 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7051 // fold (truncate (load x)) -> (smaller load x)
7052 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7053 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7054 if (SDValue Reduced = ReduceLoadWidth(N))
7057 // Handle the case where the load remains an extending load even
7058 // after truncation.
7059 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7060 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7061 if (!LN0->isVolatile() &&
7062 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7063 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7064 VT, LN0->getChain(), LN0->getBasePtr(),
7066 LN0->getMemOperand());
7067 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7072 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7073 // where ... are all 'undef'.
7074 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7075 SmallVector<EVT, 8> VTs;
7078 unsigned NumDefs = 0;
7080 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7081 SDValue X = N0.getOperand(i);
7082 if (X.getOpcode() != ISD::UNDEF) {
7087 // Stop if more than one members are non-undef.
7090 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7091 VT.getVectorElementType(),
7092 X.getValueType().getVectorNumElements()));
7096 return DAG.getUNDEF(VT);
7099 assert(V.getNode() && "The single defined operand is empty!");
7100 SmallVector<SDValue, 8> Opnds;
7101 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7103 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7106 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7107 AddToWorklist(NV.getNode());
7108 Opnds.push_back(NV);
7110 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7114 // Simplify the operands using demanded-bits information.
7115 if (!VT.isVector() &&
7116 SimplifyDemandedBits(SDValue(N, 0)))
7117 return SDValue(N, 0);
7122 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7123 SDValue Elt = N->getOperand(i);
7124 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7125 return Elt.getNode();
7126 return Elt.getOperand(Elt.getResNo()).getNode();
7129 /// build_pair (load, load) -> load
7130 /// if load locations are consecutive.
7131 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7132 assert(N->getOpcode() == ISD::BUILD_PAIR);
7134 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7135 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7136 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7137 LD1->getAddressSpace() != LD2->getAddressSpace())
7139 EVT LD1VT = LD1->getValueType(0);
7141 if (ISD::isNON_EXTLoad(LD2) &&
7143 // If both are volatile this would reduce the number of volatile loads.
7144 // If one is volatile it might be ok, but play conservative and bail out.
7145 !LD1->isVolatile() &&
7146 !LD2->isVolatile() &&
7147 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7148 unsigned Align = LD1->getAlignment();
7149 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7150 VT.getTypeForEVT(*DAG.getContext()));
7152 if (NewAlign <= Align &&
7153 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7154 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7155 LD1->getBasePtr(), LD1->getPointerInfo(),
7156 false, false, false, Align);
7162 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7163 SDValue N0 = N->getOperand(0);
7164 EVT VT = N->getValueType(0);
7166 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7167 // Only do this before legalize, since afterward the target may be depending
7168 // on the bitconvert.
7169 // First check to see if this is all constant.
7171 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7173 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7175 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7176 assert(!DestEltVT.isVector() &&
7177 "Element type of vector ValueType must not be vector!");
7179 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7182 // If the input is a constant, let getNode fold it.
7183 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7184 // If we can't allow illegal operations, we need to check that this is just
7185 // a fp -> int or int -> conversion and that the resulting operation will
7187 if (!LegalOperations ||
7188 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7189 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7190 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7191 TLI.isOperationLegal(ISD::Constant, VT)))
7192 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7195 // (conv (conv x, t1), t2) -> (conv x, t2)
7196 if (N0.getOpcode() == ISD::BITCAST)
7197 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7200 // fold (conv (load x)) -> (load (conv*)x)
7201 // If the resultant load doesn't need a higher alignment than the original!
7202 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7203 // Do not change the width of a volatile load.
7204 !cast<LoadSDNode>(N0)->isVolatile() &&
7205 // Do not remove the cast if the types differ in endian layout.
7206 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7207 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7208 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7209 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7210 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7211 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7212 VT.getTypeForEVT(*DAG.getContext()));
7213 unsigned OrigAlign = LN0->getAlignment();
7215 if (Align <= OrigAlign) {
7216 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7217 LN0->getBasePtr(), LN0->getPointerInfo(),
7218 LN0->isVolatile(), LN0->isNonTemporal(),
7219 LN0->isInvariant(), OrigAlign,
7221 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7226 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7227 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7228 // This often reduces constant pool loads.
7229 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7230 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7231 N0.getNode()->hasOneUse() && VT.isInteger() &&
7232 !VT.isVector() && !N0.getValueType().isVector()) {
7233 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7235 AddToWorklist(NewConv.getNode());
7238 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7239 if (N0.getOpcode() == ISD::FNEG)
7240 return DAG.getNode(ISD::XOR, DL, VT,
7241 NewConv, DAG.getConstant(SignBit, DL, VT));
7242 assert(N0.getOpcode() == ISD::FABS);
7243 return DAG.getNode(ISD::AND, DL, VT,
7244 NewConv, DAG.getConstant(~SignBit, DL, VT));
7247 // fold (bitconvert (fcopysign cst, x)) ->
7248 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7249 // Note that we don't handle (copysign x, cst) because this can always be
7250 // folded to an fneg or fabs.
7251 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7252 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7253 VT.isInteger() && !VT.isVector()) {
7254 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7255 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7256 if (isTypeLegal(IntXVT)) {
7257 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7258 IntXVT, N0.getOperand(1));
7259 AddToWorklist(X.getNode());
7261 // If X has a different width than the result/lhs, sext it or truncate it.
7262 unsigned VTWidth = VT.getSizeInBits();
7263 if (OrigXWidth < VTWidth) {
7264 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7265 AddToWorklist(X.getNode());
7266 } else if (OrigXWidth > VTWidth) {
7267 // To get the sign bit in the right place, we have to shift it right
7268 // before truncating.
7270 X = DAG.getNode(ISD::SRL, DL,
7271 X.getValueType(), X,
7272 DAG.getConstant(OrigXWidth-VTWidth, DL,
7274 AddToWorklist(X.getNode());
7275 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7276 AddToWorklist(X.getNode());
7279 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7280 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7281 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7282 AddToWorklist(X.getNode());
7284 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7285 VT, N0.getOperand(0));
7286 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7287 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7288 AddToWorklist(Cst.getNode());
7290 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7294 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7295 if (N0.getOpcode() == ISD::BUILD_PAIR)
7296 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7299 // Remove double bitcasts from shuffles - this is often a legacy of
7300 // XformToShuffleWithZero being used to combine bitmaskings (of
7301 // float vectors bitcast to integer vectors) into shuffles.
7302 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7303 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7304 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7305 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7306 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7307 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7309 // If operands are a bitcast, peek through if it casts the original VT.
7310 // If operands are a constant, just bitcast back to original VT.
7311 auto PeekThroughBitcast = [&](SDValue Op) {
7312 if (Op.getOpcode() == ISD::BITCAST &&
7313 Op.getOperand(0).getValueType() == VT)
7314 return SDValue(Op.getOperand(0));
7315 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7316 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7317 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7321 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7322 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7327 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7328 SmallVector<int, 8> NewMask;
7329 for (int M : SVN->getMask())
7330 for (int i = 0; i != MaskScale; ++i)
7331 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7333 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7335 std::swap(SV0, SV1);
7336 ShuffleVectorSDNode::commuteMask(NewMask);
7337 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7341 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7347 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7348 EVT VT = N->getValueType(0);
7349 return CombineConsecutiveLoads(N, VT);
7352 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7353 /// operands. DstEltVT indicates the destination element value type.
7354 SDValue DAGCombiner::
7355 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7356 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7358 // If this is already the right type, we're done.
7359 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7361 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7362 unsigned DstBitSize = DstEltVT.getSizeInBits();
7364 // If this is a conversion of N elements of one type to N elements of another
7365 // type, convert each element. This handles FP<->INT cases.
7366 if (SrcBitSize == DstBitSize) {
7367 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7368 BV->getValueType(0).getVectorNumElements());
7370 // Due to the FP element handling below calling this routine recursively,
7371 // we can end up with a scalar-to-vector node here.
7372 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7373 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7374 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7375 DstEltVT, BV->getOperand(0)));
7377 SmallVector<SDValue, 8> Ops;
7378 for (SDValue Op : BV->op_values()) {
7379 // If the vector element type is not legal, the BUILD_VECTOR operands
7380 // are promoted and implicitly truncated. Make that explicit here.
7381 if (Op.getValueType() != SrcEltVT)
7382 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7383 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7385 AddToWorklist(Ops.back().getNode());
7387 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7390 // Otherwise, we're growing or shrinking the elements. To avoid having to
7391 // handle annoying details of growing/shrinking FP values, we convert them to
7393 if (SrcEltVT.isFloatingPoint()) {
7394 // Convert the input float vector to a int vector where the elements are the
7396 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7397 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7401 // Now we know the input is an integer vector. If the output is a FP type,
7402 // convert to integer first, then to FP of the right size.
7403 if (DstEltVT.isFloatingPoint()) {
7404 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7405 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7407 // Next, convert to FP elements of the same size.
7408 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7413 // Okay, we know the src/dst types are both integers of differing types.
7414 // Handling growing first.
7415 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7416 if (SrcBitSize < DstBitSize) {
7417 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7419 SmallVector<SDValue, 8> Ops;
7420 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7421 i += NumInputsPerOutput) {
7422 bool isLE = DAG.getDataLayout().isLittleEndian();
7423 APInt NewBits = APInt(DstBitSize, 0);
7424 bool EltIsUndef = true;
7425 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7426 // Shift the previously computed bits over.
7427 NewBits <<= SrcBitSize;
7428 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7429 if (Op.getOpcode() == ISD::UNDEF) continue;
7432 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7433 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7437 Ops.push_back(DAG.getUNDEF(DstEltVT));
7439 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7442 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7443 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7446 // Finally, this must be the case where we are shrinking elements: each input
7447 // turns into multiple outputs.
7448 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7449 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7450 NumOutputsPerInput*BV->getNumOperands());
7451 SmallVector<SDValue, 8> Ops;
7453 for (const SDValue &Op : BV->op_values()) {
7454 if (Op.getOpcode() == ISD::UNDEF) {
7455 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7459 APInt OpVal = cast<ConstantSDNode>(Op)->
7460 getAPIntValue().zextOrTrunc(SrcBitSize);
7462 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7463 APInt ThisVal = OpVal.trunc(DstBitSize);
7464 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7465 OpVal = OpVal.lshr(DstBitSize);
7468 // For big endian targets, swap the order of the pieces of each element.
7469 if (DAG.getDataLayout().isBigEndian())
7470 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7473 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7476 /// Try to perform FMA combining on a given FADD node.
7477 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7478 SDValue N0 = N->getOperand(0);
7479 SDValue N1 = N->getOperand(1);
7480 EVT VT = N->getValueType(0);
7483 const TargetOptions &Options = DAG.getTarget().Options;
7484 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7485 Options.UnsafeFPMath);
7487 // Floating-point multiply-add with intermediate rounding.
7488 bool HasFMAD = (LegalOperations &&
7489 TLI.isOperationLegal(ISD::FMAD, VT));
7491 // Floating-point multiply-add without intermediate rounding.
7492 bool HasFMA = ((!LegalOperations ||
7493 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7494 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7497 // No valid opcode, do not combine.
7498 if (!HasFMAD && !HasFMA)
7501 // Always prefer FMAD to FMA for precision.
7502 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7503 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7504 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7506 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7507 // prefer to fold the multiply with fewer uses.
7508 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7509 N1.getOpcode() == ISD::FMUL) {
7510 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7514 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7515 if (N0.getOpcode() == ISD::FMUL &&
7516 (Aggressive || N0->hasOneUse())) {
7517 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7518 N0.getOperand(0), N0.getOperand(1), N1);
7521 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7522 // Note: Commutes FADD operands.
7523 if (N1.getOpcode() == ISD::FMUL &&
7524 (Aggressive || N1->hasOneUse())) {
7525 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7526 N1.getOperand(0), N1.getOperand(1), N0);
7529 // Look through FP_EXTEND nodes to do more combining.
7530 if (UnsafeFPMath && LookThroughFPExt) {
7531 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7532 if (N0.getOpcode() == ISD::FP_EXTEND) {
7533 SDValue N00 = N0.getOperand(0);
7534 if (N00.getOpcode() == ISD::FMUL)
7535 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7536 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7538 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7539 N00.getOperand(1)), N1);
7542 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7543 // Note: Commutes FADD operands.
7544 if (N1.getOpcode() == ISD::FP_EXTEND) {
7545 SDValue N10 = N1.getOperand(0);
7546 if (N10.getOpcode() == ISD::FMUL)
7547 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7548 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7550 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7551 N10.getOperand(1)), N0);
7555 // More folding opportunities when target permits.
7556 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7557 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7558 if (N0.getOpcode() == PreferredFusedOpcode &&
7559 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7560 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7561 N0.getOperand(0), N0.getOperand(1),
7562 DAG.getNode(PreferredFusedOpcode, SL, VT,
7563 N0.getOperand(2).getOperand(0),
7564 N0.getOperand(2).getOperand(1),
7568 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7569 if (N1->getOpcode() == PreferredFusedOpcode &&
7570 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7571 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7572 N1.getOperand(0), N1.getOperand(1),
7573 DAG.getNode(PreferredFusedOpcode, SL, VT,
7574 N1.getOperand(2).getOperand(0),
7575 N1.getOperand(2).getOperand(1),
7579 if (UnsafeFPMath && LookThroughFPExt) {
7580 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7581 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7582 auto FoldFAddFMAFPExtFMul = [&] (
7583 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7584 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7585 DAG.getNode(PreferredFusedOpcode, SL, VT,
7586 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7587 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7590 if (N0.getOpcode() == PreferredFusedOpcode) {
7591 SDValue N02 = N0.getOperand(2);
7592 if (N02.getOpcode() == ISD::FP_EXTEND) {
7593 SDValue N020 = N02.getOperand(0);
7594 if (N020.getOpcode() == ISD::FMUL)
7595 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7596 N020.getOperand(0), N020.getOperand(1),
7601 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7602 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7603 // FIXME: This turns two single-precision and one double-precision
7604 // operation into two double-precision operations, which might not be
7605 // interesting for all targets, especially GPUs.
7606 auto FoldFAddFPExtFMAFMul = [&] (
7607 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7608 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7609 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7610 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7611 DAG.getNode(PreferredFusedOpcode, SL, VT,
7612 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7613 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7616 if (N0.getOpcode() == ISD::FP_EXTEND) {
7617 SDValue N00 = N0.getOperand(0);
7618 if (N00.getOpcode() == PreferredFusedOpcode) {
7619 SDValue N002 = N00.getOperand(2);
7620 if (N002.getOpcode() == ISD::FMUL)
7621 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7622 N002.getOperand(0), N002.getOperand(1),
7627 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7628 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7629 if (N1.getOpcode() == PreferredFusedOpcode) {
7630 SDValue N12 = N1.getOperand(2);
7631 if (N12.getOpcode() == ISD::FP_EXTEND) {
7632 SDValue N120 = N12.getOperand(0);
7633 if (N120.getOpcode() == ISD::FMUL)
7634 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7635 N120.getOperand(0), N120.getOperand(1),
7640 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7641 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7642 // FIXME: This turns two single-precision and one double-precision
7643 // operation into two double-precision operations, which might not be
7644 // interesting for all targets, especially GPUs.
7645 if (N1.getOpcode() == ISD::FP_EXTEND) {
7646 SDValue N10 = N1.getOperand(0);
7647 if (N10.getOpcode() == PreferredFusedOpcode) {
7648 SDValue N102 = N10.getOperand(2);
7649 if (N102.getOpcode() == ISD::FMUL)
7650 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7651 N102.getOperand(0), N102.getOperand(1),
7661 /// Try to perform FMA combining on a given FSUB node.
7662 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7663 SDValue N0 = N->getOperand(0);
7664 SDValue N1 = N->getOperand(1);
7665 EVT VT = N->getValueType(0);
7668 const TargetOptions &Options = DAG.getTarget().Options;
7669 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7670 Options.UnsafeFPMath);
7672 // Floating-point multiply-add with intermediate rounding.
7673 bool HasFMAD = (LegalOperations &&
7674 TLI.isOperationLegal(ISD::FMAD, VT));
7676 // Floating-point multiply-add without intermediate rounding.
7677 bool HasFMA = ((!LegalOperations ||
7678 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7679 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7682 // No valid opcode, do not combine.
7683 if (!HasFMAD && !HasFMA)
7686 // Always prefer FMAD to FMA for precision.
7687 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7688 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7689 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7691 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7692 if (N0.getOpcode() == ISD::FMUL &&
7693 (Aggressive || N0->hasOneUse())) {
7694 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7695 N0.getOperand(0), N0.getOperand(1),
7696 DAG.getNode(ISD::FNEG, SL, VT, N1));
7699 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7700 // Note: Commutes FSUB operands.
7701 if (N1.getOpcode() == ISD::FMUL &&
7702 (Aggressive || N1->hasOneUse()))
7703 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7704 DAG.getNode(ISD::FNEG, SL, VT,
7706 N1.getOperand(1), N0);
7708 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7709 if (N0.getOpcode() == ISD::FNEG &&
7710 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7711 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7712 SDValue N00 = N0.getOperand(0).getOperand(0);
7713 SDValue N01 = N0.getOperand(0).getOperand(1);
7714 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7715 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7716 DAG.getNode(ISD::FNEG, SL, VT, N1));
7719 // Look through FP_EXTEND nodes to do more combining.
7720 if (UnsafeFPMath && LookThroughFPExt) {
7721 // fold (fsub (fpext (fmul x, y)), z)
7722 // -> (fma (fpext x), (fpext y), (fneg z))
7723 if (N0.getOpcode() == ISD::FP_EXTEND) {
7724 SDValue N00 = N0.getOperand(0);
7725 if (N00.getOpcode() == ISD::FMUL)
7726 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7727 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7729 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7731 DAG.getNode(ISD::FNEG, SL, VT, N1));
7734 // fold (fsub x, (fpext (fmul y, z)))
7735 // -> (fma (fneg (fpext y)), (fpext z), x)
7736 // Note: Commutes FSUB operands.
7737 if (N1.getOpcode() == ISD::FP_EXTEND) {
7738 SDValue N10 = N1.getOperand(0);
7739 if (N10.getOpcode() == ISD::FMUL)
7740 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7741 DAG.getNode(ISD::FNEG, SL, VT,
7742 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7743 N10.getOperand(0))),
7744 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7749 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7750 // -> (fneg (fma (fpext x), (fpext y), z))
7751 // Note: This could be removed with appropriate canonicalization of the
7752 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7753 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7754 // from implementing the canonicalization in visitFSUB.
7755 if (N0.getOpcode() == ISD::FP_EXTEND) {
7756 SDValue N00 = N0.getOperand(0);
7757 if (N00.getOpcode() == ISD::FNEG) {
7758 SDValue N000 = N00.getOperand(0);
7759 if (N000.getOpcode() == ISD::FMUL) {
7760 return DAG.getNode(ISD::FNEG, SL, VT,
7761 DAG.getNode(PreferredFusedOpcode, SL, VT,
7762 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7763 N000.getOperand(0)),
7764 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7765 N000.getOperand(1)),
7771 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7772 // -> (fneg (fma (fpext x)), (fpext y), z)
7773 // Note: This could be removed with appropriate canonicalization of the
7774 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7775 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7776 // from implementing the canonicalization in visitFSUB.
7777 if (N0.getOpcode() == ISD::FNEG) {
7778 SDValue N00 = N0.getOperand(0);
7779 if (N00.getOpcode() == ISD::FP_EXTEND) {
7780 SDValue N000 = N00.getOperand(0);
7781 if (N000.getOpcode() == ISD::FMUL) {
7782 return DAG.getNode(ISD::FNEG, SL, VT,
7783 DAG.getNode(PreferredFusedOpcode, SL, VT,
7784 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7785 N000.getOperand(0)),
7786 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7787 N000.getOperand(1)),
7795 // More folding opportunities when target permits.
7796 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7797 // fold (fsub (fma x, y, (fmul u, v)), z)
7798 // -> (fma x, y (fma u, v, (fneg z)))
7799 if (N0.getOpcode() == PreferredFusedOpcode &&
7800 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7801 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7802 N0.getOperand(0), N0.getOperand(1),
7803 DAG.getNode(PreferredFusedOpcode, SL, VT,
7804 N0.getOperand(2).getOperand(0),
7805 N0.getOperand(2).getOperand(1),
7806 DAG.getNode(ISD::FNEG, SL, VT,
7810 // fold (fsub x, (fma y, z, (fmul u, v)))
7811 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7812 if (N1.getOpcode() == PreferredFusedOpcode &&
7813 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7814 SDValue N20 = N1.getOperand(2).getOperand(0);
7815 SDValue N21 = N1.getOperand(2).getOperand(1);
7816 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7817 DAG.getNode(ISD::FNEG, SL, VT,
7820 DAG.getNode(PreferredFusedOpcode, SL, VT,
7821 DAG.getNode(ISD::FNEG, SL, VT, N20),
7826 if (UnsafeFPMath && LookThroughFPExt) {
7827 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7828 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7829 if (N0.getOpcode() == PreferredFusedOpcode) {
7830 SDValue N02 = N0.getOperand(2);
7831 if (N02.getOpcode() == ISD::FP_EXTEND) {
7832 SDValue N020 = N02.getOperand(0);
7833 if (N020.getOpcode() == ISD::FMUL)
7834 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7835 N0.getOperand(0), N0.getOperand(1),
7836 DAG.getNode(PreferredFusedOpcode, SL, VT,
7837 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7838 N020.getOperand(0)),
7839 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7840 N020.getOperand(1)),
7841 DAG.getNode(ISD::FNEG, SL, VT,
7846 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7847 // -> (fma (fpext x), (fpext y),
7848 // (fma (fpext u), (fpext v), (fneg z)))
7849 // FIXME: This turns two single-precision and one double-precision
7850 // operation into two double-precision operations, which might not be
7851 // interesting for all targets, especially GPUs.
7852 if (N0.getOpcode() == ISD::FP_EXTEND) {
7853 SDValue N00 = N0.getOperand(0);
7854 if (N00.getOpcode() == PreferredFusedOpcode) {
7855 SDValue N002 = N00.getOperand(2);
7856 if (N002.getOpcode() == ISD::FMUL)
7857 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7858 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7860 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7862 DAG.getNode(PreferredFusedOpcode, SL, VT,
7863 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7864 N002.getOperand(0)),
7865 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7866 N002.getOperand(1)),
7867 DAG.getNode(ISD::FNEG, SL, VT,
7872 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7873 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7874 if (N1.getOpcode() == PreferredFusedOpcode &&
7875 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7876 SDValue N120 = N1.getOperand(2).getOperand(0);
7877 if (N120.getOpcode() == ISD::FMUL) {
7878 SDValue N1200 = N120.getOperand(0);
7879 SDValue N1201 = N120.getOperand(1);
7880 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7881 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7883 DAG.getNode(PreferredFusedOpcode, SL, VT,
7884 DAG.getNode(ISD::FNEG, SL, VT,
7885 DAG.getNode(ISD::FP_EXTEND, SL,
7887 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7893 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7894 // -> (fma (fneg (fpext y)), (fpext z),
7895 // (fma (fneg (fpext u)), (fpext v), x))
7896 // FIXME: This turns two single-precision and one double-precision
7897 // operation into two double-precision operations, which might not be
7898 // interesting for all targets, especially GPUs.
7899 if (N1.getOpcode() == ISD::FP_EXTEND &&
7900 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7901 SDValue N100 = N1.getOperand(0).getOperand(0);
7902 SDValue N101 = N1.getOperand(0).getOperand(1);
7903 SDValue N102 = N1.getOperand(0).getOperand(2);
7904 if (N102.getOpcode() == ISD::FMUL) {
7905 SDValue N1020 = N102.getOperand(0);
7906 SDValue N1021 = N102.getOperand(1);
7907 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7908 DAG.getNode(ISD::FNEG, SL, VT,
7909 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7911 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7912 DAG.getNode(PreferredFusedOpcode, SL, VT,
7913 DAG.getNode(ISD::FNEG, SL, VT,
7914 DAG.getNode(ISD::FP_EXTEND, SL,
7916 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7927 SDValue DAGCombiner::visitFADD(SDNode *N) {
7928 SDValue N0 = N->getOperand(0);
7929 SDValue N1 = N->getOperand(1);
7930 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7931 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7932 EVT VT = N->getValueType(0);
7934 const TargetOptions &Options = DAG.getTarget().Options;
7935 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
7939 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7942 // fold (fadd c1, c2) -> c1 + c2
7944 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
7946 // canonicalize constant to RHS
7947 if (N0CFP && !N1CFP)
7948 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
7950 // fold (fadd A, (fneg B)) -> (fsub A, B)
7951 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7952 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7953 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7954 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
7956 // fold (fadd (fneg A), B) -> (fsub B, A)
7957 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7958 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7959 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7960 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
7962 // If 'unsafe math' is enabled, fold lots of things.
7963 if (Options.UnsafeFPMath) {
7964 // No FP constant should be created after legalization as Instruction
7965 // Selection pass has a hard time dealing with FP constants.
7966 bool AllowNewConst = (Level < AfterLegalizeDAG);
7968 // fold (fadd A, 0) -> A
7969 if (N1CFP && N1CFP->isZero())
7972 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7973 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7974 isa<ConstantFPSDNode>(N0.getOperand(1)))
7975 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7976 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
7980 // If allowed, fold (fadd (fneg x), x) -> 0.0
7981 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7982 return DAG.getConstantFP(0.0, DL, VT);
7984 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7985 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7986 return DAG.getConstantFP(0.0, DL, VT);
7988 // We can fold chains of FADD's of the same value into multiplications.
7989 // This transform is not safe in general because we are reducing the number
7990 // of rounding steps.
7991 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7992 if (N0.getOpcode() == ISD::FMUL) {
7993 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7994 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7996 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7997 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7998 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7999 DAG.getConstantFP(1.0, DL, VT), Flags);
8000 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8003 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8004 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8005 N1.getOperand(0) == N1.getOperand(1) &&
8006 N0.getOperand(0) == N1.getOperand(0)) {
8007 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
8008 DAG.getConstantFP(2.0, DL, VT), Flags);
8009 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8013 if (N1.getOpcode() == ISD::FMUL) {
8014 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8015 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
8017 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8018 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8019 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8020 DAG.getConstantFP(1.0, DL, VT), Flags);
8021 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8024 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8025 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8026 N0.getOperand(0) == N0.getOperand(1) &&
8027 N1.getOperand(0) == N0.getOperand(0)) {
8028 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8029 DAG.getConstantFP(2.0, DL, VT), Flags);
8030 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8034 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8035 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8036 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8037 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
8038 (N0.getOperand(0) == N1)) {
8039 return DAG.getNode(ISD::FMUL, DL, VT,
8040 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8044 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8045 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8046 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8047 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8048 N1.getOperand(0) == N0) {
8049 return DAG.getNode(ISD::FMUL, DL, VT,
8050 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8054 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8055 if (AllowNewConst &&
8056 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8057 N0.getOperand(0) == N0.getOperand(1) &&
8058 N1.getOperand(0) == N1.getOperand(1) &&
8059 N0.getOperand(0) == N1.getOperand(0)) {
8060 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8061 DAG.getConstantFP(4.0, DL, VT), Flags);
8064 } // enable-unsafe-fp-math
8066 // FADD -> FMA combines:
8067 if (SDValue Fused = visitFADDForFMACombine(N)) {
8068 AddToWorklist(Fused.getNode());
8075 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8076 SDValue N0 = N->getOperand(0);
8077 SDValue N1 = N->getOperand(1);
8078 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8079 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8080 EVT VT = N->getValueType(0);
8082 const TargetOptions &Options = DAG.getTarget().Options;
8083 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8087 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8090 // fold (fsub c1, c2) -> c1-c2
8092 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8094 // fold (fsub A, (fneg B)) -> (fadd A, B)
8095 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8096 return DAG.getNode(ISD::FADD, dl, VT, N0,
8097 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8099 // If 'unsafe math' is enabled, fold lots of things.
8100 if (Options.UnsafeFPMath) {
8102 if (N1CFP && N1CFP->isZero())
8105 // (fsub 0, B) -> -B
8106 if (N0CFP && N0CFP->isZero()) {
8107 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8108 return GetNegatedExpression(N1, DAG, LegalOperations);
8109 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8110 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8113 // (fsub x, x) -> 0.0
8115 return DAG.getConstantFP(0.0f, dl, VT);
8117 // (fsub x, (fadd x, y)) -> (fneg y)
8118 // (fsub x, (fadd y, x)) -> (fneg y)
8119 if (N1.getOpcode() == ISD::FADD) {
8120 SDValue N10 = N1->getOperand(0);
8121 SDValue N11 = N1->getOperand(1);
8123 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8124 return GetNegatedExpression(N11, DAG, LegalOperations);
8126 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8127 return GetNegatedExpression(N10, DAG, LegalOperations);
8131 // FSUB -> FMA combines:
8132 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8133 AddToWorklist(Fused.getNode());
8140 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8141 SDValue N0 = N->getOperand(0);
8142 SDValue N1 = N->getOperand(1);
8143 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8144 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8145 EVT VT = N->getValueType(0);
8147 const TargetOptions &Options = DAG.getTarget().Options;
8148 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8151 if (VT.isVector()) {
8152 // This just handles C1 * C2 for vectors. Other vector folds are below.
8153 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8157 // fold (fmul c1, c2) -> c1*c2
8159 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8161 // canonicalize constant to RHS
8162 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8163 !isConstantFPBuildVectorOrConstantFP(N1))
8164 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8166 // fold (fmul A, 1.0) -> A
8167 if (N1CFP && N1CFP->isExactlyValue(1.0))
8170 if (Options.UnsafeFPMath) {
8171 // fold (fmul A, 0) -> 0
8172 if (N1CFP && N1CFP->isZero())
8175 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8176 if (N0.getOpcode() == ISD::FMUL) {
8177 // Fold scalars or any vector constants (not just splats).
8178 // This fold is done in general by InstCombine, but extra fmul insts
8179 // may have been generated during lowering.
8180 SDValue N00 = N0.getOperand(0);
8181 SDValue N01 = N0.getOperand(1);
8182 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8183 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8184 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8186 // Check 1: Make sure that the first operand of the inner multiply is NOT
8187 // a constant. Otherwise, we may induce infinite looping.
8188 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8189 // Check 2: Make sure that the second operand of the inner multiply and
8190 // the second operand of the outer multiply are constants.
8191 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8192 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8193 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8194 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8199 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8200 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8201 // during an early run of DAGCombiner can prevent folding with fmuls
8202 // inserted during lowering.
8203 if (N0.getOpcode() == ISD::FADD &&
8204 (N0.getOperand(0) == N0.getOperand(1)) &&
8206 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8207 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8208 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8212 // fold (fmul X, 2.0) -> (fadd X, X)
8213 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8214 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8216 // fold (fmul X, -1.0) -> (fneg X)
8217 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8218 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8219 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8221 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8222 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8223 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8224 // Both can be negated for free, check to see if at least one is cheaper
8226 if (LHSNeg == 2 || RHSNeg == 2)
8227 return DAG.getNode(ISD::FMUL, DL, VT,
8228 GetNegatedExpression(N0, DAG, LegalOperations),
8229 GetNegatedExpression(N1, DAG, LegalOperations),
8237 SDValue DAGCombiner::visitFMA(SDNode *N) {
8238 SDValue N0 = N->getOperand(0);
8239 SDValue N1 = N->getOperand(1);
8240 SDValue N2 = N->getOperand(2);
8241 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8242 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8243 EVT VT = N->getValueType(0);
8245 const TargetOptions &Options = DAG.getTarget().Options;
8247 // Constant fold FMA.
8248 if (isa<ConstantFPSDNode>(N0) &&
8249 isa<ConstantFPSDNode>(N1) &&
8250 isa<ConstantFPSDNode>(N2)) {
8251 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8254 if (Options.UnsafeFPMath) {
8255 if (N0CFP && N0CFP->isZero())
8257 if (N1CFP && N1CFP->isZero())
8260 // TODO: The FMA node should have flags that propagate to these nodes.
8261 if (N0CFP && N0CFP->isExactlyValue(1.0))
8262 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8263 if (N1CFP && N1CFP->isExactlyValue(1.0))
8264 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8266 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8267 if (N0CFP && !N1CFP)
8268 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8270 // TODO: FMA nodes should have flags that propagate to the created nodes.
8271 // For now, create a Flags object for use with all unsafe math transforms.
8273 Flags.setUnsafeAlgebra(true);
8275 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8276 if (Options.UnsafeFPMath && N1CFP &&
8277 N2.getOpcode() == ISD::FMUL &&
8278 N0 == N2.getOperand(0) &&
8279 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8280 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8281 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8286 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8287 if (Options.UnsafeFPMath &&
8288 N0.getOpcode() == ISD::FMUL && N1CFP &&
8289 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8290 return DAG.getNode(ISD::FMA, dl, VT,
8292 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8297 // (fma x, 1, y) -> (fadd x, y)
8298 // (fma x, -1, y) -> (fadd (fneg x), y)
8300 if (N1CFP->isExactlyValue(1.0))
8301 // TODO: The FMA node should have flags that propagate to this node.
8302 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8304 if (N1CFP->isExactlyValue(-1.0) &&
8305 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8306 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8307 AddToWorklist(RHSNeg.getNode());
8308 // TODO: The FMA node should have flags that propagate to this node.
8309 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8313 // (fma x, c, x) -> (fmul x, (c+1))
8314 if (Options.UnsafeFPMath && N1CFP && N0 == N2) {
8315 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8316 DAG.getNode(ISD::FADD, dl, VT,
8317 N1, DAG.getConstantFP(1.0, dl, VT),
8320 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8321 if (Options.UnsafeFPMath && N1CFP &&
8322 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8323 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8324 DAG.getNode(ISD::FADD, dl, VT,
8325 N1, DAG.getConstantFP(-1.0, dl, VT),
8332 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8334 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8335 // Notice that this is not always beneficial. One reason is different target
8336 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8337 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8338 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8339 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8340 if (!DAG.getTarget().Options.UnsafeFPMath)
8343 // Skip if current node is a reciprocal.
8344 SDValue N0 = N->getOperand(0);
8345 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8346 if (N0CFP && N0CFP->isExactlyValue(1.0))
8349 // Exit early if the target does not want this transform or if there can't
8350 // possibly be enough uses of the divisor to make the transform worthwhile.
8351 SDValue N1 = N->getOperand(1);
8352 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8353 if (!MinUses || N1->use_size() < MinUses)
8356 // Find all FDIV users of the same divisor.
8357 // Use a set because duplicates may be present in the user list.
8358 SetVector<SDNode *> Users;
8359 for (auto *U : N1->uses())
8360 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8363 // Now that we have the actual number of divisor uses, make sure it meets
8364 // the minimum threshold specified by the target.
8365 if (Users.size() < MinUses)
8368 EVT VT = N->getValueType(0);
8370 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8371 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8372 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8374 // Dividend / Divisor -> Dividend * Reciprocal
8375 for (auto *U : Users) {
8376 SDValue Dividend = U->getOperand(0);
8377 if (Dividend != FPOne) {
8378 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8380 CombineTo(U, NewNode);
8381 } else if (U != Reciprocal.getNode()) {
8382 // In the absence of fast-math-flags, this user node is always the
8383 // same node as Reciprocal, but with FMF they may be different nodes.
8384 CombineTo(U, Reciprocal);
8387 return SDValue(N, 0); // N was replaced.
8390 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8391 SDValue N0 = N->getOperand(0);
8392 SDValue N1 = N->getOperand(1);
8393 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8394 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8395 EVT VT = N->getValueType(0);
8397 const TargetOptions &Options = DAG.getTarget().Options;
8398 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8402 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8405 // fold (fdiv c1, c2) -> c1/c2
8407 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8409 if (Options.UnsafeFPMath) {
8410 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8412 // Compute the reciprocal 1.0 / c2.
8413 APFloat N1APF = N1CFP->getValueAPF();
8414 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8415 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8416 // Only do the transform if the reciprocal is a legal fp immediate that
8417 // isn't too nasty (eg NaN, denormal, ...).
8418 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8419 (!LegalOperations ||
8420 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8421 // backend)... we should handle this gracefully after Legalize.
8422 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8423 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8424 TLI.isFPImmLegal(Recip, VT)))
8425 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8426 DAG.getConstantFP(Recip, DL, VT), Flags);
8429 // If this FDIV is part of a reciprocal square root, it may be folded
8430 // into a target-specific square root estimate instruction.
8431 if (N1.getOpcode() == ISD::FSQRT) {
8432 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8433 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8435 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8436 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8437 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8439 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8440 AddToWorklist(RV.getNode());
8441 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8443 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8444 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8445 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8447 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8448 AddToWorklist(RV.getNode());
8449 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8451 } else if (N1.getOpcode() == ISD::FMUL) {
8452 // Look through an FMUL. Even though this won't remove the FDIV directly,
8453 // it's still worthwhile to get rid of the FSQRT if possible.
8456 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8457 SqrtOp = N1.getOperand(0);
8458 OtherOp = N1.getOperand(1);
8459 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8460 SqrtOp = N1.getOperand(1);
8461 OtherOp = N1.getOperand(0);
8463 if (SqrtOp.getNode()) {
8464 // We found a FSQRT, so try to make this fold:
8465 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8466 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8467 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8468 AddToWorklist(RV.getNode());
8469 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8474 // Fold into a reciprocal estimate and multiply instead of a real divide.
8475 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8476 AddToWorklist(RV.getNode());
8477 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8481 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8482 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8483 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8484 // Both can be negated for free, check to see if at least one is cheaper
8486 if (LHSNeg == 2 || RHSNeg == 2)
8487 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8488 GetNegatedExpression(N0, DAG, LegalOperations),
8489 GetNegatedExpression(N1, DAG, LegalOperations),
8494 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8495 return CombineRepeatedDivisors;
8500 SDValue DAGCombiner::visitFREM(SDNode *N) {
8501 SDValue N0 = N->getOperand(0);
8502 SDValue N1 = N->getOperand(1);
8503 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8504 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8505 EVT VT = N->getValueType(0);
8507 // fold (frem c1, c2) -> fmod(c1,c2)
8509 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8510 &cast<BinaryWithFlagsSDNode>(N)->Flags);
8515 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8516 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8519 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8520 // For now, create a Flags object for use with all unsafe math transforms.
8522 Flags.setUnsafeAlgebra(true);
8524 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8525 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8529 EVT VT = RV.getValueType();
8531 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8532 AddToWorklist(RV.getNode());
8534 // Unfortunately, RV is now NaN if the input was exactly 0.
8535 // Select out this case and force the answer to 0.
8536 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8537 EVT CCVT = getSetCCResultType(VT);
8538 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8539 AddToWorklist(ZeroCmp.getNode());
8540 AddToWorklist(RV.getNode());
8542 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8546 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8547 SDValue N0 = N->getOperand(0);
8548 SDValue N1 = N->getOperand(1);
8549 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8550 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8551 EVT VT = N->getValueType(0);
8553 if (N0CFP && N1CFP) // Constant fold
8554 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8557 const APFloat& V = N1CFP->getValueAPF();
8558 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8559 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8560 if (!V.isNegative()) {
8561 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8562 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8564 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8565 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8566 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8570 // copysign(fabs(x), y) -> copysign(x, y)
8571 // copysign(fneg(x), y) -> copysign(x, y)
8572 // copysign(copysign(x,z), y) -> copysign(x, y)
8573 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8574 N0.getOpcode() == ISD::FCOPYSIGN)
8575 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8576 N0.getOperand(0), N1);
8578 // copysign(x, abs(y)) -> abs(x)
8579 if (N1.getOpcode() == ISD::FABS)
8580 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8582 // copysign(x, copysign(y,z)) -> copysign(x, z)
8583 if (N1.getOpcode() == ISD::FCOPYSIGN)
8584 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8585 N0, N1.getOperand(1));
8587 // copysign(x, fp_extend(y)) -> copysign(x, y)
8588 // copysign(x, fp_round(y)) -> copysign(x, y)
8589 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8590 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8591 N0, N1.getOperand(0));
8596 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8597 SDValue N0 = N->getOperand(0);
8598 EVT VT = N->getValueType(0);
8599 EVT OpVT = N0.getValueType();
8601 // fold (sint_to_fp c1) -> c1fp
8602 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8603 // ...but only if the target supports immediate floating-point values
8604 (!LegalOperations ||
8605 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8606 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8608 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8609 // but UINT_TO_FP is legal on this target, try to convert.
8610 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8611 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8612 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8613 if (DAG.SignBitIsZero(N0))
8614 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8617 // The next optimizations are desirable only if SELECT_CC can be lowered.
8618 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8619 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8620 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8622 (!LegalOperations ||
8623 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8626 { N0.getOperand(0), N0.getOperand(1),
8627 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8629 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8632 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8633 // (select_cc x, y, 1.0, 0.0,, cc)
8634 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8635 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8636 (!LegalOperations ||
8637 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8640 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8641 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8642 N0.getOperand(0).getOperand(2) };
8643 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8650 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8651 SDValue N0 = N->getOperand(0);
8652 EVT VT = N->getValueType(0);
8653 EVT OpVT = N0.getValueType();
8655 // fold (uint_to_fp c1) -> c1fp
8656 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8657 // ...but only if the target supports immediate floating-point values
8658 (!LegalOperations ||
8659 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8660 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8662 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8663 // but SINT_TO_FP is legal on this target, try to convert.
8664 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8665 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8666 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8667 if (DAG.SignBitIsZero(N0))
8668 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8671 // The next optimizations are desirable only if SELECT_CC can be lowered.
8672 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8673 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8675 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8676 (!LegalOperations ||
8677 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8680 { N0.getOperand(0), N0.getOperand(1),
8681 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8683 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8690 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8691 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8692 SDValue N0 = N->getOperand(0);
8693 EVT VT = N->getValueType(0);
8695 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8698 SDValue Src = N0.getOperand(0);
8699 EVT SrcVT = Src.getValueType();
8700 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8701 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8703 // We can safely assume the conversion won't overflow the output range,
8704 // because (for example) (uint8_t)18293.f is undefined behavior.
8706 // Since we can assume the conversion won't overflow, our decision as to
8707 // whether the input will fit in the float should depend on the minimum
8708 // of the input range and output range.
8710 // This means this is also safe for a signed input and unsigned output, since
8711 // a negative input would lead to undefined behavior.
8712 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8713 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8714 unsigned ActualSize = std::min(InputSize, OutputSize);
8715 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8717 // We can only fold away the float conversion if the input range can be
8718 // represented exactly in the float range.
8719 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8720 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8721 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8723 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8725 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8726 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8729 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8734 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8735 SDValue N0 = N->getOperand(0);
8736 EVT VT = N->getValueType(0);
8738 // fold (fp_to_sint c1fp) -> c1
8739 if (isConstantFPBuildVectorOrConstantFP(N0))
8740 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8742 return FoldIntToFPToInt(N, DAG);
8745 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8746 SDValue N0 = N->getOperand(0);
8747 EVT VT = N->getValueType(0);
8749 // fold (fp_to_uint c1fp) -> c1
8750 if (isConstantFPBuildVectorOrConstantFP(N0))
8751 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8753 return FoldIntToFPToInt(N, DAG);
8756 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8757 SDValue N0 = N->getOperand(0);
8758 SDValue N1 = N->getOperand(1);
8759 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8760 EVT VT = N->getValueType(0);
8762 // fold (fp_round c1fp) -> c1fp
8764 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8766 // fold (fp_round (fp_extend x)) -> x
8767 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8768 return N0.getOperand(0);
8770 // fold (fp_round (fp_round x)) -> (fp_round x)
8771 if (N0.getOpcode() == ISD::FP_ROUND) {
8772 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8773 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8774 // If the first fp_round isn't a value preserving truncation, it might
8775 // introduce a tie in the second fp_round, that wouldn't occur in the
8776 // single-step fp_round we want to fold to.
8777 // In other words, double rounding isn't the same as rounding.
8778 // Also, this is a value preserving truncation iff both fp_round's are.
8779 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8781 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8782 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8786 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8787 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8788 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8789 N0.getOperand(0), N1);
8790 AddToWorklist(Tmp.getNode());
8791 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8792 Tmp, N0.getOperand(1));
8798 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8799 SDValue N0 = N->getOperand(0);
8800 EVT VT = N->getValueType(0);
8801 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8802 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8804 // fold (fp_round_inreg c1fp) -> c1fp
8805 if (N0CFP && isTypeLegal(EVT)) {
8807 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8808 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8814 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8815 SDValue N0 = N->getOperand(0);
8816 EVT VT = N->getValueType(0);
8818 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8819 if (N->hasOneUse() &&
8820 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8823 // fold (fp_extend c1fp) -> c1fp
8824 if (isConstantFPBuildVectorOrConstantFP(N0))
8825 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8827 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8828 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8829 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8830 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8832 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8834 if (N0.getOpcode() == ISD::FP_ROUND
8835 && N0.getNode()->getConstantOperandVal(1) == 1) {
8836 SDValue In = N0.getOperand(0);
8837 if (In.getValueType() == VT) return In;
8838 if (VT.bitsLT(In.getValueType()))
8839 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8840 In, N0.getOperand(1));
8841 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8844 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8845 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8846 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8847 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8848 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8850 LN0->getBasePtr(), N0.getValueType(),
8851 LN0->getMemOperand());
8852 CombineTo(N, ExtLoad);
8853 CombineTo(N0.getNode(),
8854 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8855 N0.getValueType(), ExtLoad,
8856 DAG.getIntPtrConstant(1, SDLoc(N0))),
8857 ExtLoad.getValue(1));
8858 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8864 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8865 SDValue N0 = N->getOperand(0);
8866 EVT VT = N->getValueType(0);
8868 // fold (fceil c1) -> fceil(c1)
8869 if (isConstantFPBuildVectorOrConstantFP(N0))
8870 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8875 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8876 SDValue N0 = N->getOperand(0);
8877 EVT VT = N->getValueType(0);
8879 // fold (ftrunc c1) -> ftrunc(c1)
8880 if (isConstantFPBuildVectorOrConstantFP(N0))
8881 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8886 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8887 SDValue N0 = N->getOperand(0);
8888 EVT VT = N->getValueType(0);
8890 // fold (ffloor c1) -> ffloor(c1)
8891 if (isConstantFPBuildVectorOrConstantFP(N0))
8892 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8897 // FIXME: FNEG and FABS have a lot in common; refactor.
8898 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8899 SDValue N0 = N->getOperand(0);
8900 EVT VT = N->getValueType(0);
8902 // Constant fold FNEG.
8903 if (isConstantFPBuildVectorOrConstantFP(N0))
8904 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8906 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8907 &DAG.getTarget().Options))
8908 return GetNegatedExpression(N0, DAG, LegalOperations);
8910 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8911 // constant pool values.
8912 if (!TLI.isFNegFree(VT) &&
8913 N0.getOpcode() == ISD::BITCAST &&
8914 N0.getNode()->hasOneUse()) {
8915 SDValue Int = N0.getOperand(0);
8916 EVT IntVT = Int.getValueType();
8917 if (IntVT.isInteger() && !IntVT.isVector()) {
8919 if (N0.getValueType().isVector()) {
8920 // For a vector, get a mask such as 0x80... per scalar element
8922 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8923 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8925 // For a scalar, just generate 0x80...
8926 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8929 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8930 DAG.getConstant(SignMask, DL0, IntVT));
8931 AddToWorklist(Int.getNode());
8932 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8936 // (fneg (fmul c, x)) -> (fmul -c, x)
8937 if (N0.getOpcode() == ISD::FMUL &&
8938 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8939 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8941 APFloat CVal = CFP1->getValueAPF();
8943 if (Level >= AfterLegalizeDAG &&
8944 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8945 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8946 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8947 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8949 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
8956 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8957 SDValue N0 = N->getOperand(0);
8958 SDValue N1 = N->getOperand(1);
8959 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8960 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8962 if (N0CFP && N1CFP) {
8963 const APFloat &C0 = N0CFP->getValueAPF();
8964 const APFloat &C1 = N1CFP->getValueAPF();
8965 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8969 EVT VT = N->getValueType(0);
8970 // Canonicalize to constant on RHS.
8971 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8977 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8978 SDValue N0 = N->getOperand(0);
8979 SDValue N1 = N->getOperand(1);
8980 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8981 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8983 if (N0CFP && N1CFP) {
8984 const APFloat &C0 = N0CFP->getValueAPF();
8985 const APFloat &C1 = N1CFP->getValueAPF();
8986 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8990 EVT VT = N->getValueType(0);
8991 // Canonicalize to constant on RHS.
8992 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8998 SDValue DAGCombiner::visitFABS(SDNode *N) {
8999 SDValue N0 = N->getOperand(0);
9000 EVT VT = N->getValueType(0);
9002 // fold (fabs c1) -> fabs(c1)
9003 if (isConstantFPBuildVectorOrConstantFP(N0))
9004 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9006 // fold (fabs (fabs x)) -> (fabs x)
9007 if (N0.getOpcode() == ISD::FABS)
9008 return N->getOperand(0);
9010 // fold (fabs (fneg x)) -> (fabs x)
9011 // fold (fabs (fcopysign x, y)) -> (fabs x)
9012 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9013 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9015 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9016 // constant pool values.
9017 if (!TLI.isFAbsFree(VT) &&
9018 N0.getOpcode() == ISD::BITCAST &&
9019 N0.getNode()->hasOneUse()) {
9020 SDValue Int = N0.getOperand(0);
9021 EVT IntVT = Int.getValueType();
9022 if (IntVT.isInteger() && !IntVT.isVector()) {
9024 if (N0.getValueType().isVector()) {
9025 // For a vector, get a mask such as 0x7f... per scalar element
9027 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9028 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9030 // For a scalar, just generate 0x7f...
9031 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9034 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9035 DAG.getConstant(SignMask, DL, IntVT));
9036 AddToWorklist(Int.getNode());
9037 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9044 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9045 SDValue Chain = N->getOperand(0);
9046 SDValue N1 = N->getOperand(1);
9047 SDValue N2 = N->getOperand(2);
9049 // If N is a constant we could fold this into a fallthrough or unconditional
9050 // branch. However that doesn't happen very often in normal code, because
9051 // Instcombine/SimplifyCFG should have handled the available opportunities.
9052 // If we did this folding here, it would be necessary to update the
9053 // MachineBasicBlock CFG, which is awkward.
9055 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9057 if (N1.getOpcode() == ISD::SETCC &&
9058 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9059 N1.getOperand(0).getValueType())) {
9060 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9061 Chain, N1.getOperand(2),
9062 N1.getOperand(0), N1.getOperand(1), N2);
9065 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9066 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9067 (N1.getOperand(0).hasOneUse() &&
9068 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9069 SDNode *Trunc = nullptr;
9070 if (N1.getOpcode() == ISD::TRUNCATE) {
9071 // Look pass the truncate.
9072 Trunc = N1.getNode();
9073 N1 = N1.getOperand(0);
9076 // Match this pattern so that we can generate simpler code:
9079 // %b = and i32 %a, 2
9080 // %c = srl i32 %b, 1
9081 // brcond i32 %c ...
9086 // %b = and i32 %a, 2
9087 // %c = setcc eq %b, 0
9090 // This applies only when the AND constant value has one bit set and the
9091 // SRL constant is equal to the log2 of the AND constant. The back-end is
9092 // smart enough to convert the result into a TEST/JMP sequence.
9093 SDValue Op0 = N1.getOperand(0);
9094 SDValue Op1 = N1.getOperand(1);
9096 if (Op0.getOpcode() == ISD::AND &&
9097 Op1.getOpcode() == ISD::Constant) {
9098 SDValue AndOp1 = Op0.getOperand(1);
9100 if (AndOp1.getOpcode() == ISD::Constant) {
9101 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9103 if (AndConst.isPowerOf2() &&
9104 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9108 getSetCCResultType(Op0.getValueType()),
9109 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9112 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9113 MVT::Other, Chain, SetCC, N2);
9114 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9115 // will convert it back to (X & C1) >> C2.
9116 CombineTo(N, NewBRCond, false);
9117 // Truncate is dead.
9119 deleteAndRecombine(Trunc);
9120 // Replace the uses of SRL with SETCC
9121 WorklistRemover DeadNodes(*this);
9122 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9123 deleteAndRecombine(N1.getNode());
9124 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9130 // Restore N1 if the above transformation doesn't match.
9131 N1 = N->getOperand(1);
9134 // Transform br(xor(x, y)) -> br(x != y)
9135 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9136 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9137 SDNode *TheXor = N1.getNode();
9138 SDValue Op0 = TheXor->getOperand(0);
9139 SDValue Op1 = TheXor->getOperand(1);
9140 if (Op0.getOpcode() == Op1.getOpcode()) {
9141 // Avoid missing important xor optimizations.
9142 if (SDValue Tmp = visitXOR(TheXor)) {
9143 if (Tmp.getNode() != TheXor) {
9144 DEBUG(dbgs() << "\nReplacing.8 ";
9146 dbgs() << "\nWith: ";
9147 Tmp.getNode()->dump(&DAG);
9149 WorklistRemover DeadNodes(*this);
9150 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9151 deleteAndRecombine(TheXor);
9152 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9153 MVT::Other, Chain, Tmp, N2);
9156 // visitXOR has changed XOR's operands or replaced the XOR completely,
9158 return SDValue(N, 0);
9162 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9164 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9165 Op0.getOpcode() == ISD::XOR) {
9166 TheXor = Op0.getNode();
9170 EVT SetCCVT = N1.getValueType();
9172 SetCCVT = getSetCCResultType(SetCCVT);
9173 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9176 Equal ? ISD::SETEQ : ISD::SETNE);
9177 // Replace the uses of XOR with SETCC
9178 WorklistRemover DeadNodes(*this);
9179 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9180 deleteAndRecombine(N1.getNode());
9181 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9182 MVT::Other, Chain, SetCC, N2);
9189 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9191 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9192 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9193 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9195 // If N is a constant we could fold this into a fallthrough or unconditional
9196 // branch. However that doesn't happen very often in normal code, because
9197 // Instcombine/SimplifyCFG should have handled the available opportunities.
9198 // If we did this folding here, it would be necessary to update the
9199 // MachineBasicBlock CFG, which is awkward.
9201 // Use SimplifySetCC to simplify SETCC's.
9202 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9203 CondLHS, CondRHS, CC->get(), SDLoc(N),
9205 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9207 // fold to a simpler setcc
9208 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9209 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9210 N->getOperand(0), Simp.getOperand(2),
9211 Simp.getOperand(0), Simp.getOperand(1),
9217 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9218 /// and that N may be folded in the load / store addressing mode.
9219 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9221 const TargetLowering &TLI) {
9225 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9226 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9228 VT = LD->getMemoryVT();
9229 AS = LD->getAddressSpace();
9230 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9231 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9233 VT = ST->getMemoryVT();
9234 AS = ST->getAddressSpace();
9238 TargetLowering::AddrMode AM;
9239 if (N->getOpcode() == ISD::ADD) {
9240 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9243 AM.BaseOffs = Offset->getSExtValue();
9247 } else if (N->getOpcode() == ISD::SUB) {
9248 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9251 AM.BaseOffs = -Offset->getSExtValue();
9258 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9259 VT.getTypeForEVT(*DAG.getContext()), AS);
9262 /// Try turning a load/store into a pre-indexed load/store when the base
9263 /// pointer is an add or subtract and it has other uses besides the load/store.
9264 /// After the transformation, the new indexed load/store has effectively folded
9265 /// the add/subtract in and all of its other uses are redirected to the
9267 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9268 if (Level < AfterLegalizeDAG)
9274 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9275 if (LD->isIndexed())
9277 VT = LD->getMemoryVT();
9278 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9279 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9281 Ptr = LD->getBasePtr();
9282 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9283 if (ST->isIndexed())
9285 VT = ST->getMemoryVT();
9286 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9287 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9289 Ptr = ST->getBasePtr();
9295 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9296 // out. There is no reason to make this a preinc/predec.
9297 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9298 Ptr.getNode()->hasOneUse())
9301 // Ask the target to do addressing mode selection.
9304 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9305 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9308 // Backends without true r+i pre-indexed forms may need to pass a
9309 // constant base with a variable offset so that constant coercion
9310 // will work with the patterns in canonical form.
9311 bool Swapped = false;
9312 if (isa<ConstantSDNode>(BasePtr)) {
9313 std::swap(BasePtr, Offset);
9317 // Don't create a indexed load / store with zero offset.
9318 if (isNullConstant(Offset))
9321 // Try turning it into a pre-indexed load / store except when:
9322 // 1) The new base ptr is a frame index.
9323 // 2) If N is a store and the new base ptr is either the same as or is a
9324 // predecessor of the value being stored.
9325 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9326 // that would create a cycle.
9327 // 4) All uses are load / store ops that use it as old base ptr.
9329 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9330 // (plus the implicit offset) to a register to preinc anyway.
9331 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9336 SDValue Val = cast<StoreSDNode>(N)->getValue();
9337 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9341 // If the offset is a constant, there may be other adds of constants that
9342 // can be folded with this one. We should do this to avoid having to keep
9343 // a copy of the original base pointer.
9344 SmallVector<SDNode *, 16> OtherUses;
9345 if (isa<ConstantSDNode>(Offset))
9346 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9347 UE = BasePtr.getNode()->use_end();
9349 SDUse &Use = UI.getUse();
9350 // Skip the use that is Ptr and uses of other results from BasePtr's
9351 // node (important for nodes that return multiple results).
9352 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9355 if (Use.getUser()->isPredecessorOf(N))
9358 if (Use.getUser()->getOpcode() != ISD::ADD &&
9359 Use.getUser()->getOpcode() != ISD::SUB) {
9364 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9365 if (!isa<ConstantSDNode>(Op1)) {
9370 // FIXME: In some cases, we can be smarter about this.
9371 if (Op1.getValueType() != Offset.getValueType()) {
9376 OtherUses.push_back(Use.getUser());
9380 std::swap(BasePtr, Offset);
9382 // Now check for #3 and #4.
9383 bool RealUse = false;
9385 // Caches for hasPredecessorHelper
9386 SmallPtrSet<const SDNode *, 32> Visited;
9387 SmallVector<const SDNode *, 16> Worklist;
9389 for (SDNode *Use : Ptr.getNode()->uses()) {
9392 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9395 // If Ptr may be folded in addressing mode of other use, then it's
9396 // not profitable to do this transformation.
9397 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9406 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9407 BasePtr, Offset, AM);
9409 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9410 BasePtr, Offset, AM);
9413 DEBUG(dbgs() << "\nReplacing.4 ";
9415 dbgs() << "\nWith: ";
9416 Result.getNode()->dump(&DAG);
9418 WorklistRemover DeadNodes(*this);
9420 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9421 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9423 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9426 // Finally, since the node is now dead, remove it from the graph.
9427 deleteAndRecombine(N);
9430 std::swap(BasePtr, Offset);
9432 // Replace other uses of BasePtr that can be updated to use Ptr
9433 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9434 unsigned OffsetIdx = 1;
9435 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9437 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9438 BasePtr.getNode() && "Expected BasePtr operand");
9440 // We need to replace ptr0 in the following expression:
9441 // x0 * offset0 + y0 * ptr0 = t0
9443 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9445 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9446 // indexed load/store and the expresion that needs to be re-written.
9448 // Therefore, we have:
9449 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9451 ConstantSDNode *CN =
9452 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9454 APInt Offset0 = CN->getAPIntValue();
9455 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9457 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9458 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9459 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9460 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9462 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9464 APInt CNV = Offset0;
9465 if (X0 < 0) CNV = -CNV;
9466 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9467 else CNV = CNV - Offset1;
9469 SDLoc DL(OtherUses[i]);
9471 // We can now generate the new expression.
9472 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9473 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9475 SDValue NewUse = DAG.getNode(Opcode,
9477 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9478 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9479 deleteAndRecombine(OtherUses[i]);
9482 // Replace the uses of Ptr with uses of the updated base value.
9483 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9484 deleteAndRecombine(Ptr.getNode());
9489 /// Try to combine a load/store with a add/sub of the base pointer node into a
9490 /// post-indexed load/store. The transformation folded the add/subtract into the
9491 /// new indexed load/store effectively and all of its uses are redirected to the
9493 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9494 if (Level < AfterLegalizeDAG)
9500 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9501 if (LD->isIndexed())
9503 VT = LD->getMemoryVT();
9504 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9505 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9507 Ptr = LD->getBasePtr();
9508 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9509 if (ST->isIndexed())
9511 VT = ST->getMemoryVT();
9512 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9513 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9515 Ptr = ST->getBasePtr();
9521 if (Ptr.getNode()->hasOneUse())
9524 for (SDNode *Op : Ptr.getNode()->uses()) {
9526 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9531 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9532 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9533 // Don't create a indexed load / store with zero offset.
9534 if (isNullConstant(Offset))
9537 // Try turning it into a post-indexed load / store except when
9538 // 1) All uses are load / store ops that use it as base ptr (and
9539 // it may be folded as addressing mmode).
9540 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9541 // nor a successor of N. Otherwise, if Op is folded that would
9544 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9548 bool TryNext = false;
9549 for (SDNode *Use : BasePtr.getNode()->uses()) {
9550 if (Use == Ptr.getNode())
9553 // If all the uses are load / store addresses, then don't do the
9555 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9556 bool RealUse = false;
9557 for (SDNode *UseUse : Use->uses()) {
9558 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9573 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9574 SDValue Result = isLoad
9575 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9576 BasePtr, Offset, AM)
9577 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9578 BasePtr, Offset, AM);
9581 DEBUG(dbgs() << "\nReplacing.5 ";
9583 dbgs() << "\nWith: ";
9584 Result.getNode()->dump(&DAG);
9586 WorklistRemover DeadNodes(*this);
9588 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9589 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9591 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9594 // Finally, since the node is now dead, remove it from the graph.
9595 deleteAndRecombine(N);
9597 // Replace the uses of Use with uses of the updated base value.
9598 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9599 Result.getValue(isLoad ? 1 : 0));
9600 deleteAndRecombine(Op);
9609 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9610 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9611 ISD::MemIndexedMode AM = LD->getAddressingMode();
9612 assert(AM != ISD::UNINDEXED);
9613 SDValue BP = LD->getOperand(1);
9614 SDValue Inc = LD->getOperand(2);
9616 // Some backends use TargetConstants for load offsets, but don't expect
9617 // TargetConstants in general ADD nodes. We can convert these constants into
9618 // regular Constants (if the constant is not opaque).
9619 assert((Inc.getOpcode() != ISD::TargetConstant ||
9620 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9621 "Cannot split out indexing using opaque target constants");
9622 if (Inc.getOpcode() == ISD::TargetConstant) {
9623 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9624 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9625 ConstInc->getValueType(0));
9629 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9630 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9633 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9634 LoadSDNode *LD = cast<LoadSDNode>(N);
9635 SDValue Chain = LD->getChain();
9636 SDValue Ptr = LD->getBasePtr();
9638 // If load is not volatile and there are no uses of the loaded value (and
9639 // the updated indexed value in case of indexed loads), change uses of the
9640 // chain value into uses of the chain input (i.e. delete the dead load).
9641 if (!LD->isVolatile()) {
9642 if (N->getValueType(1) == MVT::Other) {
9644 if (!N->hasAnyUseOfValue(0)) {
9645 // It's not safe to use the two value CombineTo variant here. e.g.
9646 // v1, chain2 = load chain1, loc
9647 // v2, chain3 = load chain2, loc
9649 // Now we replace use of chain2 with chain1. This makes the second load
9650 // isomorphic to the one we are deleting, and thus makes this load live.
9651 DEBUG(dbgs() << "\nReplacing.6 ";
9653 dbgs() << "\nWith chain: ";
9654 Chain.getNode()->dump(&DAG);
9656 WorklistRemover DeadNodes(*this);
9657 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9660 deleteAndRecombine(N);
9662 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9666 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9668 // If this load has an opaque TargetConstant offset, then we cannot split
9669 // the indexing into an add/sub directly (that TargetConstant may not be
9670 // valid for a different type of node, and we cannot convert an opaque
9671 // target constant into a regular constant).
9672 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9673 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9675 if (!N->hasAnyUseOfValue(0) &&
9676 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9677 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9679 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9680 Index = SplitIndexingFromLoad(LD);
9681 // Try to fold the base pointer arithmetic into subsequent loads and
9683 AddUsersToWorklist(N);
9685 Index = DAG.getUNDEF(N->getValueType(1));
9686 DEBUG(dbgs() << "\nReplacing.7 ";
9688 dbgs() << "\nWith: ";
9689 Undef.getNode()->dump(&DAG);
9690 dbgs() << " and 2 other values\n");
9691 WorklistRemover DeadNodes(*this);
9692 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9693 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9694 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9695 deleteAndRecombine(N);
9696 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9701 // If this load is directly stored, replace the load value with the stored
9703 // TODO: Handle store large -> read small portion.
9704 // TODO: Handle TRUNCSTORE/LOADEXT
9705 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9706 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9707 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9708 if (PrevST->getBasePtr() == Ptr &&
9709 PrevST->getValue().getValueType() == N->getValueType(0))
9710 return CombineTo(N, Chain.getOperand(1), Chain);
9714 // Try to infer better alignment information than the load already has.
9715 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9716 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9717 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9719 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9720 LD->getValueType(0),
9721 Chain, Ptr, LD->getPointerInfo(),
9723 LD->isVolatile(), LD->isNonTemporal(),
9724 LD->isInvariant(), Align, LD->getAAInfo());
9725 if (NewLoad.getNode() != N)
9726 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9731 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9732 : DAG.getSubtarget().useAA();
9734 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9735 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9738 if (UseAA && LD->isUnindexed()) {
9739 // Walk up chain skipping non-aliasing memory nodes.
9740 SDValue BetterChain = FindBetterChain(N, Chain);
9742 // If there is a better chain.
9743 if (Chain != BetterChain) {
9746 // Replace the chain to void dependency.
9747 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9748 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9749 BetterChain, Ptr, LD->getMemOperand());
9751 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9752 LD->getValueType(0),
9753 BetterChain, Ptr, LD->getMemoryVT(),
9754 LD->getMemOperand());
9757 // Create token factor to keep old chain connected.
9758 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9759 MVT::Other, Chain, ReplLoad.getValue(1));
9761 // Make sure the new and old chains are cleaned up.
9762 AddToWorklist(Token.getNode());
9764 // Replace uses with load result and token factor. Don't add users
9766 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9770 // Try transforming N to an indexed load.
9771 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9772 return SDValue(N, 0);
9774 // Try to slice up N to more direct loads if the slices are mapped to
9775 // different register banks or pairing can take place.
9777 return SDValue(N, 0);
9783 /// \brief Helper structure used to slice a load in smaller loads.
9784 /// Basically a slice is obtained from the following sequence:
9785 /// Origin = load Ty1, Base
9786 /// Shift = srl Ty1 Origin, CstTy Amount
9787 /// Inst = trunc Shift to Ty2
9789 /// Then, it will be rewriten into:
9790 /// Slice = load SliceTy, Base + SliceOffset
9791 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9793 /// SliceTy is deduced from the number of bits that are actually used to
9795 struct LoadedSlice {
9796 /// \brief Helper structure used to compute the cost of a slice.
9798 /// Are we optimizing for code size.
9803 unsigned CrossRegisterBanksCopies;
9807 Cost(bool ForCodeSize = false)
9808 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9809 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9811 /// \brief Get the cost of one isolated slice.
9812 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9813 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9814 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9815 EVT TruncType = LS.Inst->getValueType(0);
9816 EVT LoadedType = LS.getLoadedType();
9817 if (TruncType != LoadedType &&
9818 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9822 /// \brief Account for slicing gain in the current cost.
9823 /// Slicing provide a few gains like removing a shift or a
9824 /// truncate. This method allows to grow the cost of the original
9825 /// load with the gain from this slice.
9826 void addSliceGain(const LoadedSlice &LS) {
9827 // Each slice saves a truncate.
9828 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9829 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9830 LS.Inst->getValueType(0)))
9832 // If there is a shift amount, this slice gets rid of it.
9835 // If this slice can merge a cross register bank copy, account for it.
9836 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9837 ++CrossRegisterBanksCopies;
9840 Cost &operator+=(const Cost &RHS) {
9842 Truncates += RHS.Truncates;
9843 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9849 bool operator==(const Cost &RHS) const {
9850 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9851 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9852 ZExts == RHS.ZExts && Shift == RHS.Shift;
9855 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9857 bool operator<(const Cost &RHS) const {
9858 // Assume cross register banks copies are as expensive as loads.
9859 // FIXME: Do we want some more target hooks?
9860 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9861 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9862 // Unless we are optimizing for code size, consider the
9863 // expensive operation first.
9864 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9865 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9866 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9867 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9870 bool operator>(const Cost &RHS) const { return RHS < *this; }
9872 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9874 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9876 // The last instruction that represent the slice. This should be a
9877 // truncate instruction.
9879 // The original load instruction.
9881 // The right shift amount in bits from the original load.
9883 // The DAG from which Origin came from.
9884 // This is used to get some contextual information about legal types, etc.
9887 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9888 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9889 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9891 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9892 /// \return Result is \p BitWidth and has used bits set to 1 and
9893 /// not used bits set to 0.
9894 APInt getUsedBits() const {
9895 // Reproduce the trunc(lshr) sequence:
9896 // - Start from the truncated value.
9897 // - Zero extend to the desired bit width.
9899 assert(Origin && "No original load to compare against.");
9900 unsigned BitWidth = Origin->getValueSizeInBits(0);
9901 assert(Inst && "This slice is not bound to an instruction");
9902 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9903 "Extracted slice is bigger than the whole type!");
9904 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9905 UsedBits.setAllBits();
9906 UsedBits = UsedBits.zext(BitWidth);
9911 /// \brief Get the size of the slice to be loaded in bytes.
9912 unsigned getLoadedSize() const {
9913 unsigned SliceSize = getUsedBits().countPopulation();
9914 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9915 return SliceSize / 8;
9918 /// \brief Get the type that will be loaded for this slice.
9919 /// Note: This may not be the final type for the slice.
9920 EVT getLoadedType() const {
9921 assert(DAG && "Missing context");
9922 LLVMContext &Ctxt = *DAG->getContext();
9923 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9926 /// \brief Get the alignment of the load used for this slice.
9927 unsigned getAlignment() const {
9928 unsigned Alignment = Origin->getAlignment();
9929 unsigned Offset = getOffsetFromBase();
9931 Alignment = MinAlign(Alignment, Alignment + Offset);
9935 /// \brief Check if this slice can be rewritten with legal operations.
9936 bool isLegal() const {
9937 // An invalid slice is not legal.
9938 if (!Origin || !Inst || !DAG)
9941 // Offsets are for indexed load only, we do not handle that.
9942 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9945 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9947 // Check that the type is legal.
9948 EVT SliceType = getLoadedType();
9949 if (!TLI.isTypeLegal(SliceType))
9952 // Check that the load is legal for this type.
9953 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9956 // Check that the offset can be computed.
9957 // 1. Check its type.
9958 EVT PtrType = Origin->getBasePtr().getValueType();
9959 if (PtrType == MVT::Untyped || PtrType.isExtended())
9962 // 2. Check that it fits in the immediate.
9963 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9966 // 3. Check that the computation is legal.
9967 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9970 // Check that the zext is legal if it needs one.
9971 EVT TruncateType = Inst->getValueType(0);
9972 if (TruncateType != SliceType &&
9973 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9979 /// \brief Get the offset in bytes of this slice in the original chunk of
9981 /// \pre DAG != nullptr.
9982 uint64_t getOffsetFromBase() const {
9983 assert(DAG && "Missing context.");
9984 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9985 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9986 uint64_t Offset = Shift / 8;
9987 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9988 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9989 "The size of the original loaded type is not a multiple of a"
9991 // If Offset is bigger than TySizeInBytes, it means we are loading all
9992 // zeros. This should have been optimized before in the process.
9993 assert(TySizeInBytes > Offset &&
9994 "Invalid shift amount for given loaded size");
9996 Offset = TySizeInBytes - Offset - getLoadedSize();
10000 /// \brief Generate the sequence of instructions to load the slice
10001 /// represented by this object and redirect the uses of this slice to
10002 /// this new sequence of instructions.
10003 /// \pre this->Inst && this->Origin are valid Instructions and this
10004 /// object passed the legal check: LoadedSlice::isLegal returned true.
10005 /// \return The last instruction of the sequence used to load the slice.
10006 SDValue loadSlice() const {
10007 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10008 const SDValue &OldBaseAddr = Origin->getBasePtr();
10009 SDValue BaseAddr = OldBaseAddr;
10010 // Get the offset in that chunk of bytes w.r.t. the endianess.
10011 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10012 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10014 // BaseAddr = BaseAddr + Offset.
10015 EVT ArithType = BaseAddr.getValueType();
10017 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10018 DAG->getConstant(Offset, DL, ArithType));
10021 // Create the type of the loaded slice according to its size.
10022 EVT SliceType = getLoadedType();
10024 // Create the load for the slice.
10025 SDValue LastInst = DAG->getLoad(
10026 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10027 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10028 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10029 // If the final type is not the same as the loaded type, this means that
10030 // we have to pad with zero. Create a zero extend for that.
10031 EVT FinalType = Inst->getValueType(0);
10032 if (SliceType != FinalType)
10034 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10038 /// \brief Check if this slice can be merged with an expensive cross register
10039 /// bank copy. E.g.,
10041 /// f = bitcast i32 i to float
10042 bool canMergeExpensiveCrossRegisterBankCopy() const {
10043 if (!Inst || !Inst->hasOneUse())
10045 SDNode *Use = *Inst->use_begin();
10046 if (Use->getOpcode() != ISD::BITCAST)
10048 assert(DAG && "Missing context");
10049 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10050 EVT ResVT = Use->getValueType(0);
10051 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10052 const TargetRegisterClass *ArgRC =
10053 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10054 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10057 // At this point, we know that we perform a cross-register-bank copy.
10058 // Check if it is expensive.
10059 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10060 // Assume bitcasts are cheap, unless both register classes do not
10061 // explicitly share a common sub class.
10062 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10065 // Check if it will be merged with the load.
10066 // 1. Check the alignment constraint.
10067 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10068 ResVT.getTypeForEVT(*DAG->getContext()));
10070 if (RequiredAlignment > getAlignment())
10073 // 2. Check that the load is a legal operation for that type.
10074 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10077 // 3. Check that we do not have a zext in the way.
10078 if (Inst->getValueType(0) != getLoadedType())
10086 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10087 /// \p UsedBits looks like 0..0 1..1 0..0.
10088 static bool areUsedBitsDense(const APInt &UsedBits) {
10089 // If all the bits are one, this is dense!
10090 if (UsedBits.isAllOnesValue())
10093 // Get rid of the unused bits on the right.
10094 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10095 // Get rid of the unused bits on the left.
10096 if (NarrowedUsedBits.countLeadingZeros())
10097 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10098 // Check that the chunk of bits is completely used.
10099 return NarrowedUsedBits.isAllOnesValue();
10102 /// \brief Check whether or not \p First and \p Second are next to each other
10103 /// in memory. This means that there is no hole between the bits loaded
10104 /// by \p First and the bits loaded by \p Second.
10105 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10106 const LoadedSlice &Second) {
10107 assert(First.Origin == Second.Origin && First.Origin &&
10108 "Unable to match different memory origins.");
10109 APInt UsedBits = First.getUsedBits();
10110 assert((UsedBits & Second.getUsedBits()) == 0 &&
10111 "Slices are not supposed to overlap.");
10112 UsedBits |= Second.getUsedBits();
10113 return areUsedBitsDense(UsedBits);
10116 /// \brief Adjust the \p GlobalLSCost according to the target
10117 /// paring capabilities and the layout of the slices.
10118 /// \pre \p GlobalLSCost should account for at least as many loads as
10119 /// there is in the slices in \p LoadedSlices.
10120 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10121 LoadedSlice::Cost &GlobalLSCost) {
10122 unsigned NumberOfSlices = LoadedSlices.size();
10123 // If there is less than 2 elements, no pairing is possible.
10124 if (NumberOfSlices < 2)
10127 // Sort the slices so that elements that are likely to be next to each
10128 // other in memory are next to each other in the list.
10129 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10130 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10131 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10132 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10134 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10135 // First (resp. Second) is the first (resp. Second) potentially candidate
10136 // to be placed in a paired load.
10137 const LoadedSlice *First = nullptr;
10138 const LoadedSlice *Second = nullptr;
10139 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10140 // Set the beginning of the pair.
10143 Second = &LoadedSlices[CurrSlice];
10145 // If First is NULL, it means we start a new pair.
10146 // Get to the next slice.
10150 EVT LoadedType = First->getLoadedType();
10152 // If the types of the slices are different, we cannot pair them.
10153 if (LoadedType != Second->getLoadedType())
10156 // Check if the target supplies paired loads for this type.
10157 unsigned RequiredAlignment = 0;
10158 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10159 // move to the next pair, this type is hopeless.
10163 // Check if we meet the alignment requirement.
10164 if (RequiredAlignment > First->getAlignment())
10167 // Check that both loads are next to each other in memory.
10168 if (!areSlicesNextToEachOther(*First, *Second))
10171 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10172 --GlobalLSCost.Loads;
10173 // Move to the next pair.
10178 /// \brief Check the profitability of all involved LoadedSlice.
10179 /// Currently, it is considered profitable if there is exactly two
10180 /// involved slices (1) which are (2) next to each other in memory, and
10181 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10183 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10184 /// the elements themselves.
10186 /// FIXME: When the cost model will be mature enough, we can relax
10187 /// constraints (1) and (2).
10188 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10189 const APInt &UsedBits, bool ForCodeSize) {
10190 unsigned NumberOfSlices = LoadedSlices.size();
10191 if (StressLoadSlicing)
10192 return NumberOfSlices > 1;
10195 if (NumberOfSlices != 2)
10199 if (!areUsedBitsDense(UsedBits))
10203 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10204 // The original code has one big load.
10205 OrigCost.Loads = 1;
10206 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10207 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10208 // Accumulate the cost of all the slices.
10209 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10210 GlobalSlicingCost += SliceCost;
10212 // Account as cost in the original configuration the gain obtained
10213 // with the current slices.
10214 OrigCost.addSliceGain(LS);
10217 // If the target supports paired load, adjust the cost accordingly.
10218 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10219 return OrigCost > GlobalSlicingCost;
10222 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10223 /// operations, split it in the various pieces being extracted.
10225 /// This sort of thing is introduced by SROA.
10226 /// This slicing takes care not to insert overlapping loads.
10227 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10228 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10229 if (Level < AfterLegalizeDAG)
10232 LoadSDNode *LD = cast<LoadSDNode>(N);
10233 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10234 !LD->getValueType(0).isInteger())
10237 // Keep track of already used bits to detect overlapping values.
10238 // In that case, we will just abort the transformation.
10239 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10241 SmallVector<LoadedSlice, 4> LoadedSlices;
10243 // Check if this load is used as several smaller chunks of bits.
10244 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10245 // of computation for each trunc.
10246 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10247 UI != UIEnd; ++UI) {
10248 // Skip the uses of the chain.
10249 if (UI.getUse().getResNo() != 0)
10252 SDNode *User = *UI;
10253 unsigned Shift = 0;
10255 // Check if this is a trunc(lshr).
10256 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10257 isa<ConstantSDNode>(User->getOperand(1))) {
10258 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10259 User = *User->use_begin();
10262 // At this point, User is a Truncate, iff we encountered, trunc or
10264 if (User->getOpcode() != ISD::TRUNCATE)
10267 // The width of the type must be a power of 2 and greater than 8-bits.
10268 // Otherwise the load cannot be represented in LLVM IR.
10269 // Moreover, if we shifted with a non-8-bits multiple, the slice
10270 // will be across several bytes. We do not support that.
10271 unsigned Width = User->getValueSizeInBits(0);
10272 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10275 // Build the slice for this chain of computations.
10276 LoadedSlice LS(User, LD, Shift, &DAG);
10277 APInt CurrentUsedBits = LS.getUsedBits();
10279 // Check if this slice overlaps with another.
10280 if ((CurrentUsedBits & UsedBits) != 0)
10282 // Update the bits used globally.
10283 UsedBits |= CurrentUsedBits;
10285 // Check if the new slice would be legal.
10289 // Record the slice.
10290 LoadedSlices.push_back(LS);
10293 // Abort slicing if it does not seem to be profitable.
10294 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10299 // Rewrite each chain to use an independent load.
10300 // By construction, each chain can be represented by a unique load.
10302 // Prepare the argument for the new token factor for all the slices.
10303 SmallVector<SDValue, 8> ArgChains;
10304 for (SmallVectorImpl<LoadedSlice>::const_iterator
10305 LSIt = LoadedSlices.begin(),
10306 LSItEnd = LoadedSlices.end();
10307 LSIt != LSItEnd; ++LSIt) {
10308 SDValue SliceInst = LSIt->loadSlice();
10309 CombineTo(LSIt->Inst, SliceInst, true);
10310 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10311 SliceInst = SliceInst.getOperand(0);
10312 assert(SliceInst->getOpcode() == ISD::LOAD &&
10313 "It takes more than a zext to get to the loaded slice!!");
10314 ArgChains.push_back(SliceInst.getValue(1));
10317 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10319 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10323 /// Check to see if V is (and load (ptr), imm), where the load is having
10324 /// specific bytes cleared out. If so, return the byte size being masked out
10325 /// and the shift amount.
10326 static std::pair<unsigned, unsigned>
10327 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10328 std::pair<unsigned, unsigned> Result(0, 0);
10330 // Check for the structure we're looking for.
10331 if (V->getOpcode() != ISD::AND ||
10332 !isa<ConstantSDNode>(V->getOperand(1)) ||
10333 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10336 // Check the chain and pointer.
10337 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10338 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10340 // The store should be chained directly to the load or be an operand of a
10342 if (LD == Chain.getNode())
10344 else if (Chain->getOpcode() != ISD::TokenFactor)
10345 return Result; // Fail.
10348 for (const SDValue &ChainOp : Chain->op_values())
10349 if (ChainOp.getNode() == LD) {
10353 if (!isOk) return Result;
10356 // This only handles simple types.
10357 if (V.getValueType() != MVT::i16 &&
10358 V.getValueType() != MVT::i32 &&
10359 V.getValueType() != MVT::i64)
10362 // Check the constant mask. Invert it so that the bits being masked out are
10363 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10364 // follow the sign bit for uniformity.
10365 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10366 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10367 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10368 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10369 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10370 if (NotMaskLZ == 64) return Result; // All zero mask.
10372 // See if we have a continuous run of bits. If so, we have 0*1+0*
10373 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10376 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10377 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10378 NotMaskLZ -= 64-V.getValueSizeInBits();
10380 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10381 switch (MaskedBytes) {
10385 default: return Result; // All one mask, or 5-byte mask.
10388 // Verify that the first bit starts at a multiple of mask so that the access
10389 // is aligned the same as the access width.
10390 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10392 Result.first = MaskedBytes;
10393 Result.second = NotMaskTZ/8;
10398 /// Check to see if IVal is something that provides a value as specified by
10399 /// MaskInfo. If so, replace the specified store with a narrower store of
10400 /// truncated IVal.
10402 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10403 SDValue IVal, StoreSDNode *St,
10405 unsigned NumBytes = MaskInfo.first;
10406 unsigned ByteShift = MaskInfo.second;
10407 SelectionDAG &DAG = DC->getDAG();
10409 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10410 // that uses this. If not, this is not a replacement.
10411 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10412 ByteShift*8, (ByteShift+NumBytes)*8);
10413 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10415 // Check that it is legal on the target to do this. It is legal if the new
10416 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10418 MVT VT = MVT::getIntegerVT(NumBytes*8);
10419 if (!DC->isTypeLegal(VT))
10422 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10423 // shifted by ByteShift and truncated down to NumBytes.
10426 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10427 DAG.getConstant(ByteShift*8, DL,
10428 DC->getShiftAmountTy(IVal.getValueType())));
10431 // Figure out the offset for the store and the alignment of the access.
10433 unsigned NewAlign = St->getAlignment();
10435 if (DAG.getDataLayout().isLittleEndian())
10436 StOffset = ByteShift;
10438 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10440 SDValue Ptr = St->getBasePtr();
10443 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10444 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10445 NewAlign = MinAlign(NewAlign, StOffset);
10448 // Truncate down to the new size.
10449 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10452 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10453 St->getPointerInfo().getWithOffset(StOffset),
10454 false, false, NewAlign).getNode();
10458 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10459 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10460 /// narrowing the load and store if it would end up being a win for performance
10462 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10463 StoreSDNode *ST = cast<StoreSDNode>(N);
10464 if (ST->isVolatile())
10467 SDValue Chain = ST->getChain();
10468 SDValue Value = ST->getValue();
10469 SDValue Ptr = ST->getBasePtr();
10470 EVT VT = Value.getValueType();
10472 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10475 unsigned Opc = Value.getOpcode();
10477 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10478 // is a byte mask indicating a consecutive number of bytes, check to see if
10479 // Y is known to provide just those bytes. If so, we try to replace the
10480 // load + replace + store sequence with a single (narrower) store, which makes
10482 if (Opc == ISD::OR) {
10483 std::pair<unsigned, unsigned> MaskedLoad;
10484 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10485 if (MaskedLoad.first)
10486 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10487 Value.getOperand(1), ST,this))
10488 return SDValue(NewST, 0);
10490 // Or is commutative, so try swapping X and Y.
10491 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10492 if (MaskedLoad.first)
10493 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10494 Value.getOperand(0), ST,this))
10495 return SDValue(NewST, 0);
10498 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10499 Value.getOperand(1).getOpcode() != ISD::Constant)
10502 SDValue N0 = Value.getOperand(0);
10503 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10504 Chain == SDValue(N0.getNode(), 1)) {
10505 LoadSDNode *LD = cast<LoadSDNode>(N0);
10506 if (LD->getBasePtr() != Ptr ||
10507 LD->getPointerInfo().getAddrSpace() !=
10508 ST->getPointerInfo().getAddrSpace())
10511 // Find the type to narrow it the load / op / store to.
10512 SDValue N1 = Value.getOperand(1);
10513 unsigned BitWidth = N1.getValueSizeInBits();
10514 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10515 if (Opc == ISD::AND)
10516 Imm ^= APInt::getAllOnesValue(BitWidth);
10517 if (Imm == 0 || Imm.isAllOnesValue())
10519 unsigned ShAmt = Imm.countTrailingZeros();
10520 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10521 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10522 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10523 // The narrowing should be profitable, the load/store operation should be
10524 // legal (or custom) and the store size should be equal to the NewVT width.
10525 while (NewBW < BitWidth &&
10526 (NewVT.getStoreSizeInBits() != NewBW ||
10527 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10528 !TLI.isNarrowingProfitable(VT, NewVT))) {
10529 NewBW = NextPowerOf2(NewBW);
10530 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10532 if (NewBW >= BitWidth)
10535 // If the lsb changed does not start at the type bitwidth boundary,
10536 // start at the previous one.
10538 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10539 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10540 std::min(BitWidth, ShAmt + NewBW));
10541 if ((Imm & Mask) == Imm) {
10542 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10543 if (Opc == ISD::AND)
10544 NewImm ^= APInt::getAllOnesValue(NewBW);
10545 uint64_t PtrOff = ShAmt / 8;
10546 // For big endian targets, we need to adjust the offset to the pointer to
10547 // load the correct bytes.
10548 if (DAG.getDataLayout().isBigEndian())
10549 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10551 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10552 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10553 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10556 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10557 Ptr.getValueType(), Ptr,
10558 DAG.getConstant(PtrOff, SDLoc(LD),
10559 Ptr.getValueType()));
10560 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10561 LD->getChain(), NewPtr,
10562 LD->getPointerInfo().getWithOffset(PtrOff),
10563 LD->isVolatile(), LD->isNonTemporal(),
10564 LD->isInvariant(), NewAlign,
10566 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10567 DAG.getConstant(NewImm, SDLoc(Value),
10569 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10571 ST->getPointerInfo().getWithOffset(PtrOff),
10572 false, false, NewAlign);
10574 AddToWorklist(NewPtr.getNode());
10575 AddToWorklist(NewLD.getNode());
10576 AddToWorklist(NewVal.getNode());
10577 WorklistRemover DeadNodes(*this);
10578 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10587 /// For a given floating point load / store pair, if the load value isn't used
10588 /// by any other operations, then consider transforming the pair to integer
10589 /// load / store operations if the target deems the transformation profitable.
10590 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10591 StoreSDNode *ST = cast<StoreSDNode>(N);
10592 SDValue Chain = ST->getChain();
10593 SDValue Value = ST->getValue();
10594 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10595 Value.hasOneUse() &&
10596 Chain == SDValue(Value.getNode(), 1)) {
10597 LoadSDNode *LD = cast<LoadSDNode>(Value);
10598 EVT VT = LD->getMemoryVT();
10599 if (!VT.isFloatingPoint() ||
10600 VT != ST->getMemoryVT() ||
10601 LD->isNonTemporal() ||
10602 ST->isNonTemporal() ||
10603 LD->getPointerInfo().getAddrSpace() != 0 ||
10604 ST->getPointerInfo().getAddrSpace() != 0)
10607 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10608 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10609 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10610 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10611 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10614 unsigned LDAlign = LD->getAlignment();
10615 unsigned STAlign = ST->getAlignment();
10616 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10617 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10618 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10621 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10622 LD->getChain(), LD->getBasePtr(),
10623 LD->getPointerInfo(),
10624 false, false, false, LDAlign);
10626 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10627 NewLD, ST->getBasePtr(),
10628 ST->getPointerInfo(),
10629 false, false, STAlign);
10631 AddToWorklist(NewLD.getNode());
10632 AddToWorklist(NewST.getNode());
10633 WorklistRemover DeadNodes(*this);
10634 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10643 /// Helper struct to parse and store a memory address as base + index + offset.
10644 /// We ignore sign extensions when it is safe to do so.
10645 /// The following two expressions are not equivalent. To differentiate we need
10646 /// to store whether there was a sign extension involved in the index
10648 /// (load (i64 add (i64 copyfromreg %c)
10649 /// (i64 signextend (add (i8 load %index)
10653 /// (load (i64 add (i64 copyfromreg %c)
10654 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10656 struct BaseIndexOffset {
10660 bool IsIndexSignExt;
10662 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10664 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10665 bool IsIndexSignExt) :
10666 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10668 bool equalBaseIndex(const BaseIndexOffset &Other) {
10669 return Other.Base == Base && Other.Index == Index &&
10670 Other.IsIndexSignExt == IsIndexSignExt;
10673 /// Parses tree in Ptr for base, index, offset addresses.
10674 static BaseIndexOffset match(SDValue Ptr) {
10675 bool IsIndexSignExt = false;
10677 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10678 // instruction, then it could be just the BASE or everything else we don't
10679 // know how to handle. Just use Ptr as BASE and give up.
10680 if (Ptr->getOpcode() != ISD::ADD)
10681 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10683 // We know that we have at least an ADD instruction. Try to pattern match
10684 // the simple case of BASE + OFFSET.
10685 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10686 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10687 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10691 // Inside a loop the current BASE pointer is calculated using an ADD and a
10692 // MUL instruction. In this case Ptr is the actual BASE pointer.
10693 // (i64 add (i64 %array_ptr)
10694 // (i64 mul (i64 %induction_var)
10695 // (i64 %element_size)))
10696 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10697 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10699 // Look at Base + Index + Offset cases.
10700 SDValue Base = Ptr->getOperand(0);
10701 SDValue IndexOffset = Ptr->getOperand(1);
10703 // Skip signextends.
10704 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10705 IndexOffset = IndexOffset->getOperand(0);
10706 IsIndexSignExt = true;
10709 // Either the case of Base + Index (no offset) or something else.
10710 if (IndexOffset->getOpcode() != ISD::ADD)
10711 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10713 // Now we have the case of Base + Index + offset.
10714 SDValue Index = IndexOffset->getOperand(0);
10715 SDValue Offset = IndexOffset->getOperand(1);
10717 if (!isa<ConstantSDNode>(Offset))
10718 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10720 // Ignore signextends.
10721 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10722 Index = Index->getOperand(0);
10723 IsIndexSignExt = true;
10724 } else IsIndexSignExt = false;
10726 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10727 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10732 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10734 ArrayRef<MemOpLink> Stores,
10736 SmallVector<SDValue, 8> BuildVector;
10738 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10739 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10741 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10744 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10745 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10746 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10747 // Make sure we have something to merge.
10751 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10752 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10753 unsigned LatestNodeUsed = 0;
10755 for (unsigned i=0; i < NumStores; ++i) {
10756 // Find a chain for the new wide-store operand. Notice that some
10757 // of the store nodes that we found may not be selected for inclusion
10758 // in the wide store. The chain we use needs to be the chain of the
10759 // latest store node which is *used* and replaced by the wide store.
10760 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10761 LatestNodeUsed = i;
10764 // The latest Node in the DAG.
10765 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10766 SDLoc DL(StoreNodes[0].MemNode);
10770 bool IsVec = MemVT.isVector();
10771 unsigned Elts = NumStores;
10773 // When merging vector stores, get the total number of elements.
10774 Elts *= MemVT.getVectorNumElements();
10776 // Get the type for the merged vector store.
10777 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10778 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10780 if (IsConstantSrc) {
10781 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10783 SmallVector<SDValue, 8> Ops;
10784 for (unsigned i = 0; i < NumStores; ++i) {
10785 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10786 SDValue Val = St->getValue();
10787 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10788 if (Val.getValueType() != MemVT)
10790 Ops.push_back(Val);
10793 // Build the extracted vector elements back into a vector.
10794 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10797 // We should always use a vector store when merging extracted vector
10798 // elements, so this path implies a store of constants.
10799 assert(IsConstantSrc && "Merged vector elements should use vector store");
10801 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10802 APInt StoreInt(SizeInBits, 0);
10804 // Construct a single integer constant which is made of the smaller
10805 // constant inputs.
10806 bool IsLE = DAG.getDataLayout().isLittleEndian();
10807 for (unsigned i = 0; i < NumStores; ++i) {
10808 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10809 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10810 SDValue Val = St->getValue();
10811 StoreInt <<= ElementSizeBytes * 8;
10812 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10813 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10814 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10815 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10817 llvm_unreachable("Invalid constant element type");
10821 // Create the new Load and Store operations.
10822 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10823 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10826 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10827 FirstInChain->getBasePtr(),
10828 FirstInChain->getPointerInfo(),
10830 FirstInChain->getAlignment());
10832 // Replace the last store with the new store
10833 CombineTo(LatestOp, NewStore);
10834 // Erase all other stores.
10835 for (unsigned i = 0; i < NumStores; ++i) {
10836 if (StoreNodes[i].MemNode == LatestOp)
10838 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10839 // ReplaceAllUsesWith will replace all uses that existed when it was
10840 // called, but graph optimizations may cause new ones to appear. For
10841 // example, the case in pr14333 looks like
10843 // St's chain -> St -> another store -> X
10845 // And the only difference from St to the other store is the chain.
10846 // When we change it's chain to be St's chain they become identical,
10847 // get CSEed and the net result is that X is now a use of St.
10848 // Since we know that St is redundant, just iterate.
10849 while (!St->use_empty())
10850 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10851 deleteAndRecombine(St);
10857 void DAGCombiner::getStoreMergeAndAliasCandidates(
10858 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10859 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10860 // This holds the base pointer, index, and the offset in bytes from the base
10862 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10864 // We must have a base and an offset.
10865 if (!BasePtr.Base.getNode())
10868 // Do not handle stores to undef base pointers.
10869 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10872 // Walk up the chain and look for nodes with offsets from the same
10873 // base pointer. Stop when reaching an instruction with a different kind
10874 // or instruction which has a different base pointer.
10875 EVT MemVT = St->getMemoryVT();
10877 StoreSDNode *Index = St;
10880 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10881 : DAG.getSubtarget().useAA();
10884 // Look at other users of the same chain. Stores on the same chain do not
10885 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10886 // to be on the same chain, so don't bother looking at adjacent chains.
10888 SDValue Chain = St->getChain();
10889 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10890 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10892 if (OtherST->isVolatile() || OtherST->isIndexed())
10895 if (OtherST->getMemoryVT() != MemVT)
10898 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10900 if (Ptr.equalBaseIndex(BasePtr))
10901 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
10909 // If the chain has more than one use, then we can't reorder the mem ops.
10910 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10913 // Find the base pointer and offset for this memory node.
10914 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10916 // Check that the base pointer is the same as the original one.
10917 if (!Ptr.equalBaseIndex(BasePtr))
10920 // The memory operands must not be volatile.
10921 if (Index->isVolatile() || Index->isIndexed())
10925 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10926 if (St->isTruncatingStore())
10929 // The stored memory type must be the same.
10930 if (Index->getMemoryVT() != MemVT)
10933 // We found a potential memory operand to merge.
10934 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10936 // Find the next memory operand in the chain. If the next operand in the
10937 // chain is a store then move up and continue the scan with the next
10938 // memory operand. If the next operand is a load save it and use alias
10939 // information to check if it interferes with anything.
10940 SDNode *NextInChain = Index->getChain().getNode();
10942 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10943 // We found a store node. Use it for the next iteration.
10946 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10947 if (Ldn->isVolatile()) {
10952 // Save the load node for later. Continue the scan.
10953 AliasLoadNodes.push_back(Ldn);
10954 NextInChain = Ldn->getChain().getNode();
10964 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10965 if (OptLevel == CodeGenOpt::None)
10968 EVT MemVT = St->getMemoryVT();
10969 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10970 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10971 Attribute::NoImplicitFloat);
10973 // This function cannot currently deal with non-byte-sized memory sizes.
10974 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10977 // Don't merge vectors into wider inputs.
10978 if (MemVT.isVector() || !MemVT.isSimple())
10981 // Perform an early exit check. Do not bother looking at stored values that
10982 // are not constants, loads, or extracted vector elements.
10983 SDValue StoredVal = St->getValue();
10984 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10985 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10986 isa<ConstantFPSDNode>(StoredVal);
10987 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10989 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10992 // Only look at ends of store sequences.
10993 SDValue Chain = SDValue(St, 0);
10994 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10997 // Save the LoadSDNodes that we find in the chain.
10998 // We need to make sure that these nodes do not interfere with
10999 // any of the store nodes.
11000 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11002 // Save the StoreSDNodes that we find in the chain.
11003 SmallVector<MemOpLink, 8> StoreNodes;
11005 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11007 // Check if there is anything to merge.
11008 if (StoreNodes.size() < 2)
11011 // Sort the memory operands according to their distance from the base pointer.
11012 std::sort(StoreNodes.begin(), StoreNodes.end(),
11013 [](MemOpLink LHS, MemOpLink RHS) {
11014 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11015 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11016 LHS.SequenceNum > RHS.SequenceNum);
11019 // Scan the memory operations on the chain and find the first non-consecutive
11020 // store memory address.
11021 unsigned LastConsecutiveStore = 0;
11022 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11023 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11025 // Check that the addresses are consecutive starting from the second
11026 // element in the list of stores.
11028 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11029 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11033 bool Alias = false;
11034 // Check if this store interferes with any of the loads that we found.
11035 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11036 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11040 // We found a load that alias with this store. Stop the sequence.
11044 // Mark this node as useful.
11045 LastConsecutiveStore = i;
11048 // The node with the lowest store address.
11049 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11050 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11051 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11052 LLVMContext &Context = *DAG.getContext();
11053 const DataLayout &DL = DAG.getDataLayout();
11055 // Store the constants into memory as one consecutive store.
11056 if (IsConstantSrc) {
11057 unsigned LastLegalType = 0;
11058 unsigned LastLegalVectorType = 0;
11059 bool NonZero = false;
11060 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11061 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11062 SDValue StoredVal = St->getValue();
11064 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11065 NonZero |= !C->isNullValue();
11066 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11067 NonZero |= !C->getConstantFPValue()->isNullValue();
11073 // Find a legal type for the constant store.
11074 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11075 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11077 if (TLI.isTypeLegal(StoreTy) &&
11078 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11079 FirstStoreAlign, &IsFast) && IsFast) {
11080 LastLegalType = i+1;
11081 // Or check whether a truncstore is legal.
11082 } else if (TLI.getTypeAction(Context, StoreTy) ==
11083 TargetLowering::TypePromoteInteger) {
11084 EVT LegalizedStoredValueTy =
11085 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11086 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11087 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11088 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11090 LastLegalType = i + 1;
11094 // We only use vectors if the constant is known to be zero or the target
11095 // allows it and the function is not marked with the noimplicitfloat
11097 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11100 // Find a legal type for the vector store.
11101 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11102 if (TLI.isTypeLegal(Ty) &&
11103 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11104 FirstStoreAlign, &IsFast) && IsFast)
11105 LastLegalVectorType = i + 1;
11109 // Check if we found a legal integer type to store.
11110 if (LastLegalType == 0 && LastLegalVectorType == 0)
11113 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11114 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11116 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11120 // When extracting multiple vector elements, try to store them
11121 // in one vector store rather than a sequence of scalar stores.
11122 if (IsExtractVecEltSrc) {
11123 unsigned NumElem = 0;
11124 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11125 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11126 SDValue StoredVal = St->getValue();
11127 // This restriction could be loosened.
11128 // Bail out if any stored values are not elements extracted from a vector.
11129 // It should be possible to handle mixed sources, but load sources need
11130 // more careful handling (see the block of code below that handles
11131 // consecutive loads).
11132 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11135 // Find a legal type for the vector store.
11136 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11138 if (TLI.isTypeLegal(Ty) &&
11139 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11140 FirstStoreAlign, &IsFast) && IsFast)
11144 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11148 // Below we handle the case of multiple consecutive stores that
11149 // come from multiple consecutive loads. We merge them into a single
11150 // wide load and a single wide store.
11152 // Look for load nodes which are used by the stored values.
11153 SmallVector<MemOpLink, 8> LoadNodes;
11155 // Find acceptable loads. Loads need to have the same chain (token factor),
11156 // must not be zext, volatile, indexed, and they must be consecutive.
11157 BaseIndexOffset LdBasePtr;
11158 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11159 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11160 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11163 // Loads must only have one use.
11164 if (!Ld->hasNUsesOfValue(1, 0))
11167 // The memory operands must not be volatile.
11168 if (Ld->isVolatile() || Ld->isIndexed())
11171 // We do not accept ext loads.
11172 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11175 // The stored memory type must be the same.
11176 if (Ld->getMemoryVT() != MemVT)
11179 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11180 // If this is not the first ptr that we check.
11181 if (LdBasePtr.Base.getNode()) {
11182 // The base ptr must be the same.
11183 if (!LdPtr.equalBaseIndex(LdBasePtr))
11186 // Check that all other base pointers are the same as this one.
11190 // We found a potential memory operand to merge.
11191 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11194 if (LoadNodes.size() < 2)
11197 // If we have load/store pair instructions and we only have two values,
11199 unsigned RequiredAlignment;
11200 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11201 St->getAlignment() >= RequiredAlignment)
11204 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11205 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11206 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11208 // Scan the memory operations on the chain and find the first non-consecutive
11209 // load memory address. These variables hold the index in the store node
11211 unsigned LastConsecutiveLoad = 0;
11212 // This variable refers to the size and not index in the array.
11213 unsigned LastLegalVectorType = 0;
11214 unsigned LastLegalIntegerType = 0;
11215 StartAddress = LoadNodes[0].OffsetFromBase;
11216 SDValue FirstChain = FirstLoad->getChain();
11217 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11218 // All loads much share the same chain.
11219 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11222 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11223 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11225 LastConsecutiveLoad = i;
11226 // Find a legal type for the vector store.
11227 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11228 bool IsFastSt, IsFastLd;
11229 if (TLI.isTypeLegal(StoreTy) &&
11230 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11231 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11232 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11233 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11234 LastLegalVectorType = i + 1;
11237 // Find a legal type for the integer store.
11238 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11239 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11240 if (TLI.isTypeLegal(StoreTy) &&
11241 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11242 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11243 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11244 FirstLoadAlign, &IsFastLd) && IsFastLd)
11245 LastLegalIntegerType = i + 1;
11246 // Or check whether a truncstore and extload is legal.
11247 else if (TLI.getTypeAction(Context, StoreTy) ==
11248 TargetLowering::TypePromoteInteger) {
11249 EVT LegalizedStoredValueTy =
11250 TLI.getTypeToTransformTo(Context, StoreTy);
11251 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11252 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11253 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11254 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11255 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11256 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11258 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11259 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11261 LastLegalIntegerType = i+1;
11265 // Only use vector types if the vector type is larger than the integer type.
11266 // If they are the same, use integers.
11267 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11268 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11270 // We add +1 here because the LastXXX variables refer to location while
11271 // the NumElem refers to array/index size.
11272 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11273 NumElem = std::min(LastLegalType, NumElem);
11278 // The latest Node in the DAG.
11279 unsigned LatestNodeUsed = 0;
11280 for (unsigned i=1; i<NumElem; ++i) {
11281 // Find a chain for the new wide-store operand. Notice that some
11282 // of the store nodes that we found may not be selected for inclusion
11283 // in the wide store. The chain we use needs to be the chain of the
11284 // latest store node which is *used* and replaced by the wide store.
11285 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11286 LatestNodeUsed = i;
11289 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11291 // Find if it is better to use vectors or integers to load and store
11295 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11297 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11298 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11301 SDLoc LoadDL(LoadNodes[0].MemNode);
11302 SDLoc StoreDL(StoreNodes[0].MemNode);
11304 SDValue NewLoad = DAG.getLoad(
11305 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11306 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11308 SDValue NewStore = DAG.getStore(
11309 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11310 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11312 // Replace one of the loads with the new load.
11313 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11314 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11315 SDValue(NewLoad.getNode(), 1));
11317 // Remove the rest of the load chains.
11318 for (unsigned i = 1; i < NumElem ; ++i) {
11319 // Replace all chain users of the old load nodes with the chain of the new
11321 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11322 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11325 // Replace the last store with the new store.
11326 CombineTo(LatestOp, NewStore);
11327 // Erase all other stores.
11328 for (unsigned i = 0; i < NumElem ; ++i) {
11329 // Remove all Store nodes.
11330 if (StoreNodes[i].MemNode == LatestOp)
11332 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11333 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11334 deleteAndRecombine(St);
11340 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11344 // Replace the chain to avoid dependency.
11345 if (ST->isTruncatingStore()) {
11346 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11347 ST->getBasePtr(), ST->getMemoryVT(),
11348 ST->getMemOperand());
11350 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11351 ST->getMemOperand());
11354 // Create token to keep both nodes around.
11355 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11356 MVT::Other, ST->getChain(), ReplStore);
11358 // Make sure the new and old chains are cleaned up.
11359 AddToWorklist(Token.getNode());
11361 // Don't add users to work list.
11362 return CombineTo(ST, Token, false);
11365 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11366 SDValue Value = ST->getValue();
11367 if (Value.getOpcode() == ISD::TargetConstantFP)
11372 SDValue Chain = ST->getChain();
11373 SDValue Ptr = ST->getBasePtr();
11375 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11377 // NOTE: If the original store is volatile, this transform must not increase
11378 // the number of stores. For example, on x86-32 an f64 can be stored in one
11379 // processor operation but an i64 (which is not legal) requires two. So the
11380 // transform should not be done in this case.
11383 switch (CFP->getSimpleValueType(0).SimpleTy) {
11385 llvm_unreachable("Unknown FP type");
11386 case MVT::f16: // We don't do this for these yet.
11392 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11393 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11395 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11396 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11398 SDValue NewSt = DAG.getStore(Chain, DL, Tmp,
11399 Ptr, ST->getMemOperand());
11401 dbgs() << "Replacing FP constant: ";
11404 if (cast<StoreSDNode>(NewSt)->getMemoryVT() != MVT::i32) {
11405 dbgs() << "Different memoryvt\n";
11407 dbgs() << "same memoryvt\n";
11416 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11417 !ST->isVolatile()) ||
11418 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11420 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11421 getZExtValue(), SDLoc(CFP), MVT::i64);
11422 return DAG.getStore(Chain, DL, Tmp,
11423 Ptr, ST->getMemOperand());
11426 if (!ST->isVolatile() &&
11427 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11428 // Many FP stores are not made apparent until after legalize, e.g. for
11429 // argument passing. Since this is so common, custom legalize the
11430 // 64-bit integer store into two 32-bit stores.
11431 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11432 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11433 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11434 if (DAG.getDataLayout().isBigEndian())
11437 unsigned Alignment = ST->getAlignment();
11438 bool isVolatile = ST->isVolatile();
11439 bool isNonTemporal = ST->isNonTemporal();
11440 AAMDNodes AAInfo = ST->getAAInfo();
11442 SDValue St0 = DAG.getStore(Chain, DL, Lo,
11443 Ptr, ST->getPointerInfo(),
11444 isVolatile, isNonTemporal,
11445 ST->getAlignment(), AAInfo);
11446 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11447 DAG.getConstant(4, DL, Ptr.getValueType()));
11448 Alignment = MinAlign(Alignment, 4U);
11449 SDValue St1 = DAG.getStore(Chain, DL, Hi,
11450 Ptr, ST->getPointerInfo().getWithOffset(4),
11451 isVolatile, isNonTemporal,
11452 Alignment, AAInfo);
11453 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11461 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11462 StoreSDNode *ST = cast<StoreSDNode>(N);
11463 SDValue Chain = ST->getChain();
11464 SDValue Value = ST->getValue();
11465 SDValue Ptr = ST->getBasePtr();
11467 // If this is a store of a bit convert, store the input value if the
11468 // resultant store does not need a higher alignment than the original.
11469 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11470 ST->isUnindexed()) {
11471 unsigned OrigAlign = ST->getAlignment();
11472 EVT SVT = Value.getOperand(0).getValueType();
11473 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11474 SVT.getTypeForEVT(*DAG.getContext()));
11475 if (Align <= OrigAlign &&
11476 ((!LegalOperations && !ST->isVolatile()) ||
11477 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11478 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11479 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11480 ST->isNonTemporal(), OrigAlign,
11484 // Turn 'store undef, Ptr' -> nothing.
11485 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11488 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11490 // Make sure to do this only after attempting to merge stores in order to
11491 // avoid changing the types of some subset of stores due to visit order,
11492 // preventing their merging.
11493 if (isa<ConstantFPSDNode>(Value)) {
11494 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11498 // Try to infer better alignment information than the store already has.
11499 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11500 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11501 if (Align > ST->getAlignment()) {
11503 DAG.getTruncStore(Chain, SDLoc(N), Value,
11504 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11505 ST->isVolatile(), ST->isNonTemporal(), Align,
11507 if (NewStore.getNode() != N)
11508 return CombineTo(ST, NewStore, true);
11513 // Try transforming a pair floating point load / store ops to integer
11514 // load / store ops.
11515 if (SDValue NewST = TransformFPLoadStorePair(N))
11518 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11519 : DAG.getSubtarget().useAA();
11521 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11522 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11525 if (UseAA && ST->isUnindexed()) {
11526 // FIXME: We should do this even without AA enabled. AA will just allow
11527 // FindBetterChain to work in more situations. The problem with this is that
11528 // any combine that expects memory operations to be on consecutive chains
11529 // first needs to be updated to look for users of the same chain.
11531 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11532 // adjacent stores.
11533 if (findBetterNeighborChains(ST)) {
11534 // replaceStoreChain uses CombineTo, which handled all of the worklist
11535 // manipulation. Return the original node to not do anything else.
11536 return SDValue(ST, 0);
11540 // Try transforming N to an indexed store.
11541 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11542 return SDValue(N, 0);
11544 // FIXME: is there such a thing as a truncating indexed store?
11545 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11546 Value.getValueType().isInteger()) {
11547 // See if we can simplify the input to this truncstore with knowledge that
11548 // only the low bits are being used. For example:
11549 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11551 GetDemandedBits(Value,
11552 APInt::getLowBitsSet(
11553 Value.getValueType().getScalarType().getSizeInBits(),
11554 ST->getMemoryVT().getScalarType().getSizeInBits()));
11555 AddToWorklist(Value.getNode());
11556 if (Shorter.getNode())
11557 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11558 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11560 // Otherwise, see if we can simplify the operation with
11561 // SimplifyDemandedBits, which only works if the value has a single use.
11562 if (SimplifyDemandedBits(Value,
11563 APInt::getLowBitsSet(
11564 Value.getValueType().getScalarType().getSizeInBits(),
11565 ST->getMemoryVT().getScalarType().getSizeInBits())))
11566 return SDValue(N, 0);
11569 // If this is a load followed by a store to the same location, then the store
11571 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11572 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11573 ST->isUnindexed() && !ST->isVolatile() &&
11574 // There can't be any side effects between the load and store, such as
11575 // a call or store.
11576 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11577 // The store is dead, remove it.
11582 // If this is a store followed by a store with the same value to the same
11583 // location, then the store is dead/noop.
11584 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11585 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11586 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11587 ST1->isUnindexed() && !ST1->isVolatile()) {
11588 // The store is dead, remove it.
11593 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11594 // truncating store. We can do this even if this is already a truncstore.
11595 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11596 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11597 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11598 ST->getMemoryVT())) {
11599 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11600 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11603 // Only perform this optimization before the types are legal, because we
11604 // don't want to perform this optimization on every DAGCombine invocation.
11606 bool EverChanged = false;
11609 // There can be multiple store sequences on the same chain.
11610 // Keep trying to merge store sequences until we are unable to do so
11611 // or until we merge the last store on the chain.
11612 bool Changed = MergeConsecutiveStores(ST);
11613 EverChanged |= Changed;
11614 if (!Changed) break;
11615 } while (ST->getOpcode() != ISD::DELETED_NODE);
11618 return SDValue(N, 0);
11621 return ReduceLoadOpStoreWidth(N);
11624 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11625 SDValue InVec = N->getOperand(0);
11626 SDValue InVal = N->getOperand(1);
11627 SDValue EltNo = N->getOperand(2);
11630 // If the inserted element is an UNDEF, just use the input vector.
11631 if (InVal.getOpcode() == ISD::UNDEF)
11634 EVT VT = InVec.getValueType();
11636 // If we can't generate a legal BUILD_VECTOR, exit
11637 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11640 // Check that we know which element is being inserted
11641 if (!isa<ConstantSDNode>(EltNo))
11643 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11645 // Canonicalize insert_vector_elt dag nodes.
11647 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11648 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11650 // Do this only if the child insert_vector node has one use; also
11651 // do this only if indices are both constants and Idx1 < Idx0.
11652 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11653 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11654 unsigned OtherElt =
11655 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11656 if (Elt < OtherElt) {
11658 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11659 InVec.getOperand(0), InVal, EltNo);
11660 AddToWorklist(NewOp.getNode());
11661 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11662 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11666 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11667 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11668 // vector elements.
11669 SmallVector<SDValue, 8> Ops;
11670 // Do not combine these two vectors if the output vector will not replace
11671 // the input vector.
11672 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11673 Ops.append(InVec.getNode()->op_begin(),
11674 InVec.getNode()->op_end());
11675 } else if (InVec.getOpcode() == ISD::UNDEF) {
11676 unsigned NElts = VT.getVectorNumElements();
11677 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11682 // Insert the element
11683 if (Elt < Ops.size()) {
11684 // All the operands of BUILD_VECTOR must have the same type;
11685 // we enforce that here.
11686 EVT OpVT = Ops[0].getValueType();
11687 if (InVal.getValueType() != OpVT)
11688 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11689 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11690 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11694 // Return the new vector
11695 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11698 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11699 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11700 EVT ResultVT = EVE->getValueType(0);
11701 EVT VecEltVT = InVecVT.getVectorElementType();
11702 unsigned Align = OriginalLoad->getAlignment();
11703 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11704 VecEltVT.getTypeForEVT(*DAG.getContext()));
11706 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11711 SDValue NewPtr = OriginalLoad->getBasePtr();
11713 EVT PtrType = NewPtr.getValueType();
11714 MachinePointerInfo MPI;
11716 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11717 int Elt = ConstEltNo->getZExtValue();
11718 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11719 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11720 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11722 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11723 Offset = DAG.getNode(
11724 ISD::MUL, DL, PtrType, Offset,
11725 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11726 MPI = OriginalLoad->getPointerInfo();
11728 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11730 // The replacement we need to do here is a little tricky: we need to
11731 // replace an extractelement of a load with a load.
11732 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11733 // Note that this replacement assumes that the extractvalue is the only
11734 // use of the load; that's okay because we don't want to perform this
11735 // transformation in other cases anyway.
11738 if (ResultVT.bitsGT(VecEltVT)) {
11739 // If the result type of vextract is wider than the load, then issue an
11740 // extending load instead.
11741 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11745 Load = DAG.getExtLoad(
11746 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11747 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11748 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11749 Chain = Load.getValue(1);
11751 Load = DAG.getLoad(
11752 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11753 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11754 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11755 Chain = Load.getValue(1);
11756 if (ResultVT.bitsLT(VecEltVT))
11757 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11759 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11761 WorklistRemover DeadNodes(*this);
11762 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11763 SDValue To[] = { Load, Chain };
11764 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11765 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11766 // worklist explicitly as well.
11767 AddToWorklist(Load.getNode());
11768 AddUsersToWorklist(Load.getNode()); // Add users too
11769 // Make sure to revisit this node to clean it up; it will usually be dead.
11770 AddToWorklist(EVE);
11772 return SDValue(EVE, 0);
11775 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11776 // (vextract (scalar_to_vector val, 0) -> val
11777 SDValue InVec = N->getOperand(0);
11778 EVT VT = InVec.getValueType();
11779 EVT NVT = N->getValueType(0);
11781 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11782 // Check if the result type doesn't match the inserted element type. A
11783 // SCALAR_TO_VECTOR may truncate the inserted element and the
11784 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11785 SDValue InOp = InVec.getOperand(0);
11786 if (InOp.getValueType() != NVT) {
11787 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11788 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11793 SDValue EltNo = N->getOperand(1);
11794 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11796 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11797 // We only perform this optimization before the op legalization phase because
11798 // we may introduce new vector instructions which are not backed by TD
11799 // patterns. For example on AVX, extracting elements from a wide vector
11800 // without using extract_subvector. However, if we can find an underlying
11801 // scalar value, then we can always use that.
11802 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11804 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11805 int NumElem = VT.getVectorNumElements();
11806 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11807 // Find the new index to extract from.
11808 int OrigElt = SVOp->getMaskElt(Elt);
11810 // Extracting an undef index is undef.
11812 return DAG.getUNDEF(NVT);
11814 // Select the right vector half to extract from.
11816 if (OrigElt < NumElem) {
11817 SVInVec = InVec->getOperand(0);
11819 SVInVec = InVec->getOperand(1);
11820 OrigElt -= NumElem;
11823 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11824 SDValue InOp = SVInVec.getOperand(OrigElt);
11825 if (InOp.getValueType() != NVT) {
11826 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11827 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11833 // FIXME: We should handle recursing on other vector shuffles and
11834 // scalar_to_vector here as well.
11836 if (!LegalOperations) {
11837 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11838 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11839 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11843 bool BCNumEltsChanged = false;
11844 EVT ExtVT = VT.getVectorElementType();
11847 // If the result of load has to be truncated, then it's not necessarily
11849 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11852 if (InVec.getOpcode() == ISD::BITCAST) {
11853 // Don't duplicate a load with other uses.
11854 if (!InVec.hasOneUse())
11857 EVT BCVT = InVec.getOperand(0).getValueType();
11858 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11860 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11861 BCNumEltsChanged = true;
11862 InVec = InVec.getOperand(0);
11863 ExtVT = BCVT.getVectorElementType();
11866 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11867 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11868 ISD::isNormalLoad(InVec.getNode()) &&
11869 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11870 SDValue Index = N->getOperand(1);
11871 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11872 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11876 // Perform only after legalization to ensure build_vector / vector_shuffle
11877 // optimizations have already been done.
11878 if (!LegalOperations) return SDValue();
11880 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11881 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11882 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11885 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11887 LoadSDNode *LN0 = nullptr;
11888 const ShuffleVectorSDNode *SVN = nullptr;
11889 if (ISD::isNormalLoad(InVec.getNode())) {
11890 LN0 = cast<LoadSDNode>(InVec);
11891 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11892 InVec.getOperand(0).getValueType() == ExtVT &&
11893 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11894 // Don't duplicate a load with other uses.
11895 if (!InVec.hasOneUse())
11898 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11899 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11900 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11902 // (load $addr+1*size)
11904 // Don't duplicate a load with other uses.
11905 if (!InVec.hasOneUse())
11908 // If the bit convert changed the number of elements, it is unsafe
11909 // to examine the mask.
11910 if (BCNumEltsChanged)
11913 // Select the input vector, guarding against out of range extract vector.
11914 unsigned NumElems = VT.getVectorNumElements();
11915 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11916 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11918 if (InVec.getOpcode() == ISD::BITCAST) {
11919 // Don't duplicate a load with other uses.
11920 if (!InVec.hasOneUse())
11923 InVec = InVec.getOperand(0);
11925 if (ISD::isNormalLoad(InVec.getNode())) {
11926 LN0 = cast<LoadSDNode>(InVec);
11927 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11928 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11932 // Make sure we found a non-volatile load and the extractelement is
11934 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11937 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11939 return DAG.getUNDEF(LVT);
11941 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11947 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11948 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11949 // We perform this optimization post type-legalization because
11950 // the type-legalizer often scalarizes integer-promoted vectors.
11951 // Performing this optimization before may create bit-casts which
11952 // will be type-legalized to complex code sequences.
11953 // We perform this optimization only before the operation legalizer because we
11954 // may introduce illegal operations.
11955 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11958 unsigned NumInScalars = N->getNumOperands();
11960 EVT VT = N->getValueType(0);
11962 // Check to see if this is a BUILD_VECTOR of a bunch of values
11963 // which come from any_extend or zero_extend nodes. If so, we can create
11964 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11965 // optimizations. We do not handle sign-extend because we can't fill the sign
11967 EVT SourceType = MVT::Other;
11968 bool AllAnyExt = true;
11970 for (unsigned i = 0; i != NumInScalars; ++i) {
11971 SDValue In = N->getOperand(i);
11972 // Ignore undef inputs.
11973 if (In.getOpcode() == ISD::UNDEF) continue;
11975 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11976 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11978 // Abort if the element is not an extension.
11979 if (!ZeroExt && !AnyExt) {
11980 SourceType = MVT::Other;
11984 // The input is a ZeroExt or AnyExt. Check the original type.
11985 EVT InTy = In.getOperand(0).getValueType();
11987 // Check that all of the widened source types are the same.
11988 if (SourceType == MVT::Other)
11991 else if (InTy != SourceType) {
11992 // Multiple income types. Abort.
11993 SourceType = MVT::Other;
11997 // Check if all of the extends are ANY_EXTENDs.
11998 AllAnyExt &= AnyExt;
12001 // In order to have valid types, all of the inputs must be extended from the
12002 // same source type and all of the inputs must be any or zero extend.
12003 // Scalar sizes must be a power of two.
12004 EVT OutScalarTy = VT.getScalarType();
12005 bool ValidTypes = SourceType != MVT::Other &&
12006 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12007 isPowerOf2_32(SourceType.getSizeInBits());
12009 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12010 // turn into a single shuffle instruction.
12014 bool isLE = DAG.getDataLayout().isLittleEndian();
12015 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12016 assert(ElemRatio > 1 && "Invalid element size ratio");
12017 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12018 DAG.getConstant(0, SDLoc(N), SourceType);
12020 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12021 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12023 // Populate the new build_vector
12024 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12025 SDValue Cast = N->getOperand(i);
12026 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12027 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12028 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12030 if (Cast.getOpcode() == ISD::UNDEF)
12031 In = DAG.getUNDEF(SourceType);
12033 In = Cast->getOperand(0);
12034 unsigned Index = isLE ? (i * ElemRatio) :
12035 (i * ElemRatio + (ElemRatio - 1));
12037 assert(Index < Ops.size() && "Invalid index");
12041 // The type of the new BUILD_VECTOR node.
12042 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12043 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12044 "Invalid vector size");
12045 // Check if the new vector type is legal.
12046 if (!isTypeLegal(VecVT)) return SDValue();
12048 // Make the new BUILD_VECTOR.
12049 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12051 // The new BUILD_VECTOR node has the potential to be further optimized.
12052 AddToWorklist(BV.getNode());
12053 // Bitcast to the desired type.
12054 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12057 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12058 EVT VT = N->getValueType(0);
12060 unsigned NumInScalars = N->getNumOperands();
12063 EVT SrcVT = MVT::Other;
12064 unsigned Opcode = ISD::DELETED_NODE;
12065 unsigned NumDefs = 0;
12067 for (unsigned i = 0; i != NumInScalars; ++i) {
12068 SDValue In = N->getOperand(i);
12069 unsigned Opc = In.getOpcode();
12071 if (Opc == ISD::UNDEF)
12074 // If all scalar values are floats and converted from integers.
12075 if (Opcode == ISD::DELETED_NODE &&
12076 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12083 EVT InVT = In.getOperand(0).getValueType();
12085 // If all scalar values are typed differently, bail out. It's chosen to
12086 // simplify BUILD_VECTOR of integer types.
12087 if (SrcVT == MVT::Other)
12094 // If the vector has just one element defined, it's not worth to fold it into
12095 // a vectorized one.
12099 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12100 && "Should only handle conversion from integer to float.");
12101 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12103 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12105 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12108 // Just because the floating-point vector type is legal does not necessarily
12109 // mean that the corresponding integer vector type is.
12110 if (!isTypeLegal(NVT))
12113 SmallVector<SDValue, 8> Opnds;
12114 for (unsigned i = 0; i != NumInScalars; ++i) {
12115 SDValue In = N->getOperand(i);
12117 if (In.getOpcode() == ISD::UNDEF)
12118 Opnds.push_back(DAG.getUNDEF(SrcVT));
12120 Opnds.push_back(In.getOperand(0));
12122 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12123 AddToWorklist(BV.getNode());
12125 return DAG.getNode(Opcode, dl, VT, BV);
12128 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12129 unsigned NumInScalars = N->getNumOperands();
12131 EVT VT = N->getValueType(0);
12133 // A vector built entirely of undefs is undef.
12134 if (ISD::allOperandsUndef(N))
12135 return DAG.getUNDEF(VT);
12137 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12140 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12143 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12144 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12145 // at most two distinct vectors, turn this into a shuffle node.
12147 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12148 if (!isTypeLegal(VT))
12151 // May only combine to shuffle after legalize if shuffle is legal.
12152 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12155 SDValue VecIn1, VecIn2;
12156 bool UsesZeroVector = false;
12157 for (unsigned i = 0; i != NumInScalars; ++i) {
12158 SDValue Op = N->getOperand(i);
12159 // Ignore undef inputs.
12160 if (Op.getOpcode() == ISD::UNDEF) continue;
12162 // See if we can combine this build_vector into a blend with a zero vector.
12163 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12164 UsesZeroVector = true;
12168 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12169 // constant index, bail out.
12170 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12171 !isa<ConstantSDNode>(Op.getOperand(1))) {
12172 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12176 // We allow up to two distinct input vectors.
12177 SDValue ExtractedFromVec = Op.getOperand(0);
12178 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12181 if (!VecIn1.getNode()) {
12182 VecIn1 = ExtractedFromVec;
12183 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12184 VecIn2 = ExtractedFromVec;
12186 // Too many inputs.
12187 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12192 // If everything is good, we can make a shuffle operation.
12193 if (VecIn1.getNode()) {
12194 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12195 SmallVector<int, 8> Mask;
12196 for (unsigned i = 0; i != NumInScalars; ++i) {
12197 unsigned Opcode = N->getOperand(i).getOpcode();
12198 if (Opcode == ISD::UNDEF) {
12199 Mask.push_back(-1);
12203 // Operands can also be zero.
12204 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12205 assert(UsesZeroVector &&
12206 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12207 "Unexpected node found!");
12208 Mask.push_back(NumInScalars+i);
12212 // If extracting from the first vector, just use the index directly.
12213 SDValue Extract = N->getOperand(i);
12214 SDValue ExtVal = Extract.getOperand(1);
12215 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12216 if (Extract.getOperand(0) == VecIn1) {
12217 Mask.push_back(ExtIndex);
12221 // Otherwise, use InIdx + InputVecSize
12222 Mask.push_back(InNumElements + ExtIndex);
12225 // Avoid introducing illegal shuffles with zero.
12226 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12229 // We can't generate a shuffle node with mismatched input and output types.
12230 // Attempt to transform a single input vector to the correct type.
12231 if ((VT != VecIn1.getValueType())) {
12232 // If the input vector type has a different base type to the output
12233 // vector type, bail out.
12234 EVT VTElemType = VT.getVectorElementType();
12235 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12236 (VecIn2.getNode() &&
12237 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12240 // If the input vector is too small, widen it.
12241 // We only support widening of vectors which are half the size of the
12242 // output registers. For example XMM->YMM widening on X86 with AVX.
12243 EVT VecInT = VecIn1.getValueType();
12244 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12245 // If we only have one small input, widen it by adding undef values.
12246 if (!VecIn2.getNode())
12247 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12248 DAG.getUNDEF(VecIn1.getValueType()));
12249 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12250 // If we have two small inputs of the same type, try to concat them.
12251 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12252 VecIn2 = SDValue(nullptr, 0);
12255 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12256 // If the input vector is too large, try to split it.
12257 // We don't support having two input vectors that are too large.
12258 // If the zero vector was used, we can not split the vector,
12259 // since we'd need 3 inputs.
12260 if (UsesZeroVector || VecIn2.getNode())
12263 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12266 // Try to replace VecIn1 with two extract_subvectors
12267 // No need to update the masks, they should still be correct.
12268 VecIn2 = DAG.getNode(
12269 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12270 DAG.getConstant(VT.getVectorNumElements(), dl,
12271 TLI.getVectorIdxTy(DAG.getDataLayout())));
12272 VecIn1 = DAG.getNode(
12273 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12274 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12279 if (UsesZeroVector)
12280 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12281 DAG.getConstantFP(0.0, dl, VT);
12283 // If VecIn2 is unused then change it to undef.
12284 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12286 // Check that we were able to transform all incoming values to the same
12288 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12289 VecIn1.getValueType() != VT)
12292 // Return the new VECTOR_SHUFFLE node.
12296 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12302 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12303 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12304 EVT OpVT = N->getOperand(0).getValueType();
12306 // If the operands are legal vectors, leave them alone.
12307 if (TLI.isTypeLegal(OpVT))
12311 EVT VT = N->getValueType(0);
12312 SmallVector<SDValue, 8> Ops;
12314 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12315 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12317 // Keep track of what we encounter.
12318 bool AnyInteger = false;
12319 bool AnyFP = false;
12320 for (const SDValue &Op : N->ops()) {
12321 if (ISD::BITCAST == Op.getOpcode() &&
12322 !Op.getOperand(0).getValueType().isVector())
12323 Ops.push_back(Op.getOperand(0));
12324 else if (ISD::UNDEF == Op.getOpcode())
12325 Ops.push_back(ScalarUndef);
12329 // Note whether we encounter an integer or floating point scalar.
12330 // If it's neither, bail out, it could be something weird like x86mmx.
12331 EVT LastOpVT = Ops.back().getValueType();
12332 if (LastOpVT.isFloatingPoint())
12334 else if (LastOpVT.isInteger())
12340 // If any of the operands is a floating point scalar bitcast to a vector,
12341 // use floating point types throughout, and bitcast everything.
12342 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12344 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12345 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12347 for (SDValue &Op : Ops) {
12348 if (Op.getValueType() == SVT)
12350 if (Op.getOpcode() == ISD::UNDEF)
12353 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12358 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12359 VT.getSizeInBits() / SVT.getSizeInBits());
12360 return DAG.getNode(ISD::BITCAST, DL, VT,
12361 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12364 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12365 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12366 // most two distinct vectors the same size as the result, attempt to turn this
12367 // into a legal shuffle.
12368 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12369 EVT VT = N->getValueType(0);
12370 EVT OpVT = N->getOperand(0).getValueType();
12371 int NumElts = VT.getVectorNumElements();
12372 int NumOpElts = OpVT.getVectorNumElements();
12374 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12375 SmallVector<int, 8> Mask;
12377 for (SDValue Op : N->ops()) {
12378 // Peek through any bitcast.
12379 while (Op.getOpcode() == ISD::BITCAST)
12380 Op = Op.getOperand(0);
12382 // UNDEF nodes convert to UNDEF shuffle mask values.
12383 if (Op.getOpcode() == ISD::UNDEF) {
12384 Mask.append((unsigned)NumOpElts, -1);
12388 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12391 // What vector are we extracting the subvector from and at what index?
12392 SDValue ExtVec = Op.getOperand(0);
12394 // We want the EVT of the original extraction to correctly scale the
12395 // extraction index.
12396 EVT ExtVT = ExtVec.getValueType();
12398 // Peek through any bitcast.
12399 while (ExtVec.getOpcode() == ISD::BITCAST)
12400 ExtVec = ExtVec.getOperand(0);
12402 // UNDEF nodes convert to UNDEF shuffle mask values.
12403 if (ExtVec.getOpcode() == ISD::UNDEF) {
12404 Mask.append((unsigned)NumOpElts, -1);
12408 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12410 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12412 // Ensure that we are extracting a subvector from a vector the same
12413 // size as the result.
12414 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12417 // Scale the subvector index to account for any bitcast.
12418 int NumExtElts = ExtVT.getVectorNumElements();
12419 if (0 == (NumExtElts % NumElts))
12420 ExtIdx /= (NumExtElts / NumElts);
12421 else if (0 == (NumElts % NumExtElts))
12422 ExtIdx *= (NumElts / NumExtElts);
12426 // At most we can reference 2 inputs in the final shuffle.
12427 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12429 for (int i = 0; i != NumOpElts; ++i)
12430 Mask.push_back(i + ExtIdx);
12431 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12433 for (int i = 0; i != NumOpElts; ++i)
12434 Mask.push_back(i + ExtIdx + NumElts);
12440 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12443 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12444 DAG.getBitcast(VT, SV1), Mask);
12447 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12448 // If we only have one input vector, we don't need to do any concatenation.
12449 if (N->getNumOperands() == 1)
12450 return N->getOperand(0);
12452 // Check if all of the operands are undefs.
12453 EVT VT = N->getValueType(0);
12454 if (ISD::allOperandsUndef(N))
12455 return DAG.getUNDEF(VT);
12457 // Optimize concat_vectors where all but the first of the vectors are undef.
12458 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12459 return Op.getOpcode() == ISD::UNDEF;
12461 SDValue In = N->getOperand(0);
12462 assert(In.getValueType().isVector() && "Must concat vectors");
12464 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12465 if (In->getOpcode() == ISD::BITCAST &&
12466 !In->getOperand(0)->getValueType(0).isVector()) {
12467 SDValue Scalar = In->getOperand(0);
12469 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12470 // look through the trunc so we can still do the transform:
12471 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12472 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12473 !TLI.isTypeLegal(Scalar.getValueType()) &&
12474 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12475 Scalar = Scalar->getOperand(0);
12477 EVT SclTy = Scalar->getValueType(0);
12479 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12482 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12483 VT.getSizeInBits() / SclTy.getSizeInBits());
12484 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12487 SDLoc dl = SDLoc(N);
12488 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12489 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12493 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12494 // We have already tested above for an UNDEF only concatenation.
12495 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12496 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12497 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12498 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12500 bool AllBuildVectorsOrUndefs =
12501 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12502 if (AllBuildVectorsOrUndefs) {
12503 SmallVector<SDValue, 8> Opnds;
12504 EVT SVT = VT.getScalarType();
12507 if (!SVT.isFloatingPoint()) {
12508 // If BUILD_VECTOR are from built from integer, they may have different
12509 // operand types. Get the smallest type and truncate all operands to it.
12510 bool FoundMinVT = false;
12511 for (const SDValue &Op : N->ops())
12512 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12513 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12514 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12517 assert(FoundMinVT && "Concat vector type mismatch");
12520 for (const SDValue &Op : N->ops()) {
12521 EVT OpVT = Op.getValueType();
12522 unsigned NumElts = OpVT.getVectorNumElements();
12524 if (ISD::UNDEF == Op.getOpcode())
12525 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12527 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12528 if (SVT.isFloatingPoint()) {
12529 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12530 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12532 for (unsigned i = 0; i != NumElts; ++i)
12534 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12539 assert(VT.getVectorNumElements() == Opnds.size() &&
12540 "Concat vector type mismatch");
12541 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12544 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12545 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12548 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12549 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12550 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12553 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12554 // nodes often generate nop CONCAT_VECTOR nodes.
12555 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12556 // place the incoming vectors at the exact same location.
12557 SDValue SingleSource = SDValue();
12558 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12560 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12561 SDValue Op = N->getOperand(i);
12563 if (Op.getOpcode() == ISD::UNDEF)
12566 // Check if this is the identity extract:
12567 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12570 // Find the single incoming vector for the extract_subvector.
12571 if (SingleSource.getNode()) {
12572 if (Op.getOperand(0) != SingleSource)
12575 SingleSource = Op.getOperand(0);
12577 // Check the source type is the same as the type of the result.
12578 // If not, this concat may extend the vector, so we can not
12579 // optimize it away.
12580 if (SingleSource.getValueType() != N->getValueType(0))
12584 unsigned IdentityIndex = i * PartNumElem;
12585 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12586 // The extract index must be constant.
12590 // Check that we are reading from the identity index.
12591 if (CS->getZExtValue() != IdentityIndex)
12595 if (SingleSource.getNode())
12596 return SingleSource;
12601 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12602 EVT NVT = N->getValueType(0);
12603 SDValue V = N->getOperand(0);
12605 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12607 // (extract_subvec (concat V1, V2, ...), i)
12610 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12612 if (V->getOperand(0).getValueType() != NVT)
12614 unsigned Idx = N->getConstantOperandVal(1);
12615 unsigned NumElems = NVT.getVectorNumElements();
12616 assert((Idx % NumElems) == 0 &&
12617 "IDX in concat is not a multiple of the result vector length.");
12618 return V->getOperand(Idx / NumElems);
12622 if (V->getOpcode() == ISD::BITCAST)
12623 V = V.getOperand(0);
12625 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12627 // Handle only simple case where vector being inserted and vector
12628 // being extracted are of same type, and are half size of larger vectors.
12629 EVT BigVT = V->getOperand(0).getValueType();
12630 EVT SmallVT = V->getOperand(1).getValueType();
12631 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12634 // Only handle cases where both indexes are constants with the same type.
12635 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12636 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12638 if (InsIdx && ExtIdx &&
12639 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12640 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12642 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12644 // indices are equal or bit offsets are equal => V1
12645 // otherwise => (extract_subvec V1, ExtIdx)
12646 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12647 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12648 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12649 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12650 DAG.getNode(ISD::BITCAST, dl,
12651 N->getOperand(0).getValueType(),
12652 V->getOperand(0)), N->getOperand(1));
12659 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12660 SDValue V, SelectionDAG &DAG) {
12662 EVT VT = V.getValueType();
12664 switch (V.getOpcode()) {
12668 case ISD::CONCAT_VECTORS: {
12669 EVT OpVT = V->getOperand(0).getValueType();
12670 int OpSize = OpVT.getVectorNumElements();
12671 SmallBitVector OpUsedElements(OpSize, false);
12672 bool FoundSimplification = false;
12673 SmallVector<SDValue, 4> NewOps;
12674 NewOps.reserve(V->getNumOperands());
12675 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12676 SDValue Op = V->getOperand(i);
12677 bool OpUsed = false;
12678 for (int j = 0; j < OpSize; ++j)
12679 if (UsedElements[i * OpSize + j]) {
12680 OpUsedElements[j] = true;
12684 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12685 : DAG.getUNDEF(OpVT));
12686 FoundSimplification |= Op == NewOps.back();
12687 OpUsedElements.reset();
12689 if (FoundSimplification)
12690 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12694 case ISD::INSERT_SUBVECTOR: {
12695 SDValue BaseV = V->getOperand(0);
12696 SDValue SubV = V->getOperand(1);
12697 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12701 int SubSize = SubV.getValueType().getVectorNumElements();
12702 int Idx = IdxN->getZExtValue();
12703 bool SubVectorUsed = false;
12704 SmallBitVector SubUsedElements(SubSize, false);
12705 for (int i = 0; i < SubSize; ++i)
12706 if (UsedElements[i + Idx]) {
12707 SubVectorUsed = true;
12708 SubUsedElements[i] = true;
12709 UsedElements[i + Idx] = false;
12712 // Now recurse on both the base and sub vectors.
12713 SDValue SimplifiedSubV =
12715 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12716 : DAG.getUNDEF(SubV.getValueType());
12717 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12718 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12719 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12720 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12726 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12727 SDValue N1, SelectionDAG &DAG) {
12728 EVT VT = SVN->getValueType(0);
12729 int NumElts = VT.getVectorNumElements();
12730 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12731 for (int M : SVN->getMask())
12732 if (M >= 0 && M < NumElts)
12733 N0UsedElements[M] = true;
12734 else if (M >= NumElts)
12735 N1UsedElements[M - NumElts] = true;
12737 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12738 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12739 if (S0 == N0 && S1 == N1)
12742 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12745 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12746 // or turn a shuffle of a single concat into simpler shuffle then concat.
12747 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12748 EVT VT = N->getValueType(0);
12749 unsigned NumElts = VT.getVectorNumElements();
12751 SDValue N0 = N->getOperand(0);
12752 SDValue N1 = N->getOperand(1);
12753 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12755 SmallVector<SDValue, 4> Ops;
12756 EVT ConcatVT = N0.getOperand(0).getValueType();
12757 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12758 unsigned NumConcats = NumElts / NumElemsPerConcat;
12760 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12761 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12762 // half vector elements.
12763 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12764 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12765 SVN->getMask().end(), [](int i) { return i == -1; })) {
12766 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12767 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
12768 N1 = DAG.getUNDEF(ConcatVT);
12769 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12772 // Look at every vector that's inserted. We're looking for exact
12773 // subvector-sized copies from a concatenated vector
12774 for (unsigned I = 0; I != NumConcats; ++I) {
12775 // Make sure we're dealing with a copy.
12776 unsigned Begin = I * NumElemsPerConcat;
12777 bool AllUndef = true, NoUndef = true;
12778 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12779 if (SVN->getMaskElt(J) >= 0)
12786 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12789 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12790 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12793 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12794 if (FirstElt < N0.getNumOperands())
12795 Ops.push_back(N0.getOperand(FirstElt));
12797 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12799 } else if (AllUndef) {
12800 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12801 } else { // Mixed with general masks and undefs, can't do optimization.
12806 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12809 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12810 EVT VT = N->getValueType(0);
12811 unsigned NumElts = VT.getVectorNumElements();
12813 SDValue N0 = N->getOperand(0);
12814 SDValue N1 = N->getOperand(1);
12816 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12818 // Canonicalize shuffle undef, undef -> undef
12819 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12820 return DAG.getUNDEF(VT);
12822 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12824 // Canonicalize shuffle v, v -> v, undef
12826 SmallVector<int, 8> NewMask;
12827 for (unsigned i = 0; i != NumElts; ++i) {
12828 int Idx = SVN->getMaskElt(i);
12829 if (Idx >= (int)NumElts) Idx -= NumElts;
12830 NewMask.push_back(Idx);
12832 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12836 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12837 if (N0.getOpcode() == ISD::UNDEF) {
12838 SmallVector<int, 8> NewMask;
12839 for (unsigned i = 0; i != NumElts; ++i) {
12840 int Idx = SVN->getMaskElt(i);
12842 if (Idx >= (int)NumElts)
12845 Idx = -1; // remove reference to lhs
12847 NewMask.push_back(Idx);
12849 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12853 // Remove references to rhs if it is undef
12854 if (N1.getOpcode() == ISD::UNDEF) {
12855 bool Changed = false;
12856 SmallVector<int, 8> NewMask;
12857 for (unsigned i = 0; i != NumElts; ++i) {
12858 int Idx = SVN->getMaskElt(i);
12859 if (Idx >= (int)NumElts) {
12863 NewMask.push_back(Idx);
12866 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12869 // If it is a splat, check if the argument vector is another splat or a
12871 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12872 SDNode *V = N0.getNode();
12874 // If this is a bit convert that changes the element type of the vector but
12875 // not the number of vector elements, look through it. Be careful not to
12876 // look though conversions that change things like v4f32 to v2f64.
12877 if (V->getOpcode() == ISD::BITCAST) {
12878 SDValue ConvInput = V->getOperand(0);
12879 if (ConvInput.getValueType().isVector() &&
12880 ConvInput.getValueType().getVectorNumElements() == NumElts)
12881 V = ConvInput.getNode();
12884 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12885 assert(V->getNumOperands() == NumElts &&
12886 "BUILD_VECTOR has wrong number of operands");
12888 bool AllSame = true;
12889 for (unsigned i = 0; i != NumElts; ++i) {
12890 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12891 Base = V->getOperand(i);
12895 // Splat of <u, u, u, u>, return <u, u, u, u>
12896 if (!Base.getNode())
12898 for (unsigned i = 0; i != NumElts; ++i) {
12899 if (V->getOperand(i) != Base) {
12904 // Splat of <x, x, x, x>, return <x, x, x, x>
12908 // Canonicalize any other splat as a build_vector.
12909 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12910 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12911 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12912 V->getValueType(0), Ops);
12914 // We may have jumped through bitcasts, so the type of the
12915 // BUILD_VECTOR may not match the type of the shuffle.
12916 if (V->getValueType(0) != VT)
12917 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12922 // There are various patterns used to build up a vector from smaller vectors,
12923 // subvectors, or elements. Scan chains of these and replace unused insertions
12924 // or components with undef.
12925 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12928 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12929 Level < AfterLegalizeVectorOps &&
12930 (N1.getOpcode() == ISD::UNDEF ||
12931 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12932 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12933 SDValue V = partitionShuffleOfConcats(N, DAG);
12939 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12940 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12941 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12942 SmallVector<SDValue, 8> Ops;
12943 for (int M : SVN->getMask()) {
12944 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12946 int Idx = M % NumElts;
12947 SDValue &S = (M < (int)NumElts ? N0 : N1);
12948 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12949 Op = S.getOperand(Idx);
12950 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12952 Op = S.getOperand(0);
12954 // Operand can't be combined - bail out.
12960 if (Ops.size() == VT.getVectorNumElements()) {
12961 // BUILD_VECTOR requires all inputs to be of the same type, find the
12962 // maximum type and extend them all.
12963 EVT SVT = VT.getScalarType();
12964 if (SVT.isInteger())
12965 for (SDValue &Op : Ops)
12966 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12967 if (SVT != VT.getScalarType())
12968 for (SDValue &Op : Ops)
12969 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12970 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12971 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12972 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12976 // If this shuffle only has a single input that is a bitcasted shuffle,
12977 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12978 // back to their original types.
12979 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12980 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12981 TLI.isTypeLegal(VT)) {
12983 // Peek through the bitcast only if there is one user.
12985 while (BC0.getOpcode() == ISD::BITCAST) {
12986 if (!BC0.hasOneUse())
12988 BC0 = BC0.getOperand(0);
12991 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12993 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12995 SmallVector<int, 8> NewMask;
12997 for (int s = 0; s != Scale; ++s)
12998 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13002 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13003 EVT SVT = VT.getScalarType();
13004 EVT InnerVT = BC0->getValueType(0);
13005 EVT InnerSVT = InnerVT.getScalarType();
13007 // Determine which shuffle works with the smaller scalar type.
13008 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13009 EVT ScaleSVT = ScaleVT.getScalarType();
13011 if (TLI.isTypeLegal(ScaleVT) &&
13012 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13013 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13015 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13016 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13018 // Scale the shuffle masks to the smaller scalar type.
13019 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13020 SmallVector<int, 8> InnerMask =
13021 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13022 SmallVector<int, 8> OuterMask =
13023 ScaleShuffleMask(SVN->getMask(), OuterScale);
13025 // Merge the shuffle masks.
13026 SmallVector<int, 8> NewMask;
13027 for (int M : OuterMask)
13028 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13030 // Test for shuffle mask legality over both commutations.
13031 SDValue SV0 = BC0->getOperand(0);
13032 SDValue SV1 = BC0->getOperand(1);
13033 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13035 std::swap(SV0, SV1);
13036 ShuffleVectorSDNode::commuteMask(NewMask);
13037 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13041 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13042 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13043 return DAG.getNode(
13044 ISD::BITCAST, SDLoc(N), VT,
13045 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13051 // Canonicalize shuffles according to rules:
13052 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13053 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13054 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13055 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13056 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13057 TLI.isTypeLegal(VT)) {
13058 // The incoming shuffle must be of the same type as the result of the
13059 // current shuffle.
13060 assert(N1->getOperand(0).getValueType() == VT &&
13061 "Shuffle types don't match");
13063 SDValue SV0 = N1->getOperand(0);
13064 SDValue SV1 = N1->getOperand(1);
13065 bool HasSameOp0 = N0 == SV0;
13066 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13067 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13068 // Commute the operands of this shuffle so that next rule
13070 return DAG.getCommutedVectorShuffle(*SVN);
13073 // Try to fold according to rules:
13074 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13075 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13076 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13077 // Don't try to fold shuffles with illegal type.
13078 // Only fold if this shuffle is the only user of the other shuffle.
13079 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13080 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13081 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13083 // The incoming shuffle must be of the same type as the result of the
13084 // current shuffle.
13085 assert(OtherSV->getOperand(0).getValueType() == VT &&
13086 "Shuffle types don't match");
13089 SmallVector<int, 4> Mask;
13090 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13091 // operand, and SV1 as the second operand.
13092 for (unsigned i = 0; i != NumElts; ++i) {
13093 int Idx = SVN->getMaskElt(i);
13095 // Propagate Undef.
13096 Mask.push_back(Idx);
13100 SDValue CurrentVec;
13101 if (Idx < (int)NumElts) {
13102 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13103 // shuffle mask to identify which vector is actually referenced.
13104 Idx = OtherSV->getMaskElt(Idx);
13106 // Propagate Undef.
13107 Mask.push_back(Idx);
13111 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13112 : OtherSV->getOperand(1);
13114 // This shuffle index references an element within N1.
13118 // Simple case where 'CurrentVec' is UNDEF.
13119 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13120 Mask.push_back(-1);
13124 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13125 // will be the first or second operand of the combined shuffle.
13126 Idx = Idx % NumElts;
13127 if (!SV0.getNode() || SV0 == CurrentVec) {
13128 // Ok. CurrentVec is the left hand side.
13129 // Update the mask accordingly.
13131 Mask.push_back(Idx);
13135 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13136 if (SV1.getNode() && SV1 != CurrentVec)
13139 // Ok. CurrentVec is the right hand side.
13140 // Update the mask accordingly.
13142 Mask.push_back(Idx + NumElts);
13145 // Check if all indices in Mask are Undef. In case, propagate Undef.
13146 bool isUndefMask = true;
13147 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13148 isUndefMask &= Mask[i] < 0;
13151 return DAG.getUNDEF(VT);
13153 if (!SV0.getNode())
13154 SV0 = DAG.getUNDEF(VT);
13155 if (!SV1.getNode())
13156 SV1 = DAG.getUNDEF(VT);
13158 // Avoid introducing shuffles with illegal mask.
13159 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13160 ShuffleVectorSDNode::commuteMask(Mask);
13162 if (!TLI.isShuffleMaskLegal(Mask, VT))
13165 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13166 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13167 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13168 std::swap(SV0, SV1);
13171 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13172 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13173 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13174 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13180 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13181 SDValue InVal = N->getOperand(0);
13182 EVT VT = N->getValueType(0);
13184 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13185 // with a VECTOR_SHUFFLE.
13186 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13187 SDValue InVec = InVal->getOperand(0);
13188 SDValue EltNo = InVal->getOperand(1);
13190 // FIXME: We could support implicit truncation if the shuffle can be
13191 // scaled to a smaller vector scalar type.
13192 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13193 if (C0 && VT == InVec.getValueType() &&
13194 VT.getScalarType() == InVal.getValueType()) {
13195 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13196 int Elt = C0->getZExtValue();
13199 if (TLI.isShuffleMaskLegal(NewMask, VT))
13200 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13208 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13209 SDValue N0 = N->getOperand(0);
13210 SDValue N2 = N->getOperand(2);
13212 // If the input vector is a concatenation, and the insert replaces
13213 // one of the halves, we can optimize into a single concat_vectors.
13214 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13215 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13216 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13217 EVT VT = N->getValueType(0);
13219 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13220 // (concat_vectors Z, Y)
13222 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13223 N->getOperand(1), N0.getOperand(1));
13225 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13226 // (concat_vectors X, Z)
13227 if (InsIdx == VT.getVectorNumElements()/2)
13228 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13229 N0.getOperand(0), N->getOperand(1));
13235 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13236 SDValue N0 = N->getOperand(0);
13238 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13239 if (N0->getOpcode() == ISD::FP16_TO_FP)
13240 return N0->getOperand(0);
13245 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13246 SDValue N0 = N->getOperand(0);
13248 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13249 if (N0->getOpcode() == ISD::AND) {
13250 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13251 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13252 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13260 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13261 /// with the destination vector and a zero vector.
13262 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13263 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13264 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13265 EVT VT = N->getValueType(0);
13266 SDValue LHS = N->getOperand(0);
13267 SDValue RHS = N->getOperand(1);
13270 // Make sure we're not running after operation legalization where it
13271 // may have custom lowered the vector shuffles.
13272 if (LegalOperations)
13275 if (N->getOpcode() != ISD::AND)
13278 if (RHS.getOpcode() == ISD::BITCAST)
13279 RHS = RHS.getOperand(0);
13281 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13284 EVT RVT = RHS.getValueType();
13285 unsigned NumElts = RHS.getNumOperands();
13287 // Attempt to create a valid clear mask, splitting the mask into
13288 // sub elements and checking to see if each is
13289 // all zeros or all ones - suitable for shuffle masking.
13290 auto BuildClearMask = [&](int Split) {
13291 int NumSubElts = NumElts * Split;
13292 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13294 SmallVector<int, 8> Indices;
13295 for (int i = 0; i != NumSubElts; ++i) {
13296 int EltIdx = i / Split;
13297 int SubIdx = i % Split;
13298 SDValue Elt = RHS.getOperand(EltIdx);
13299 if (Elt.getOpcode() == ISD::UNDEF) {
13300 Indices.push_back(-1);
13305 if (isa<ConstantSDNode>(Elt))
13306 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13307 else if (isa<ConstantFPSDNode>(Elt))
13308 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13312 // Extract the sub element from the constant bit mask.
13313 if (DAG.getDataLayout().isBigEndian()) {
13314 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13316 Bits = Bits.lshr(SubIdx * NumSubBits);
13320 Bits = Bits.trunc(NumSubBits);
13322 if (Bits.isAllOnesValue())
13323 Indices.push_back(i);
13324 else if (Bits == 0)
13325 Indices.push_back(i + NumSubElts);
13330 // Let's see if the target supports this vector_shuffle.
13331 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13332 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13333 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13336 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13337 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13338 DAG.getBitcast(ClearVT, LHS),
13339 Zero, &Indices[0]));
13342 // Determine maximum split level (byte level masking).
13344 if (RVT.getScalarSizeInBits() % 8 == 0)
13345 MaxSplit = RVT.getScalarSizeInBits() / 8;
13347 for (int Split = 1; Split <= MaxSplit; ++Split)
13348 if (RVT.getScalarSizeInBits() % Split == 0)
13349 if (SDValue S = BuildClearMask(Split))
13355 /// Visit a binary vector operation, like ADD.
13356 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13357 assert(N->getValueType(0).isVector() &&
13358 "SimplifyVBinOp only works on vectors!");
13360 SDValue LHS = N->getOperand(0);
13361 SDValue RHS = N->getOperand(1);
13363 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13365 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13366 RHS.getOpcode() == ISD::BUILD_VECTOR) {
13367 // Check if both vectors are constants. If not bail out.
13368 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13369 cast<BuildVectorSDNode>(RHS)->isConstant()))
13372 SmallVector<SDValue, 8> Ops;
13373 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13374 SDValue LHSOp = LHS.getOperand(i);
13375 SDValue RHSOp = RHS.getOperand(i);
13377 // Can't fold divide by zero.
13378 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13379 N->getOpcode() == ISD::FDIV) {
13380 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13381 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13385 EVT VT = LHSOp.getValueType();
13386 EVT RVT = RHSOp.getValueType();
13389 if (RVT.getSizeInBits() < VT.getSizeInBits())
13392 // Integer BUILD_VECTOR operands may have types larger than the element
13393 // size (e.g., when the element type is not legal). Prior to type
13394 // legalization, the types may not match between the two BUILD_VECTORS.
13395 // Truncate the operands to make them match.
13396 if (VT.getSizeInBits() != LHS.getValueType().getScalarSizeInBits()) {
13397 EVT ScalarT = LHS.getValueType().getScalarType();
13398 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, LHSOp);
13399 VT = LHSOp.getValueType();
13401 if (RVT.getSizeInBits() != RHS.getValueType().getScalarSizeInBits()) {
13402 EVT ScalarT = RHS.getValueType().getScalarType();
13403 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, RHSOp);
13404 RVT = RHSOp.getValueType();
13407 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13408 LHSOp, RHSOp, N->getFlags());
13410 // We need the resulting constant to be legal if we are in a phase after
13411 // legalization, so zero extend to the smallest operand type if required.
13412 if (ST != VT && Level != BeforeLegalizeTypes)
13413 FoldOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LHS), ST, FoldOp);
13415 if (FoldOp.getOpcode() != ISD::UNDEF &&
13416 FoldOp.getOpcode() != ISD::Constant &&
13417 FoldOp.getOpcode() != ISD::ConstantFP)
13419 Ops.push_back(FoldOp);
13420 AddToWorklist(FoldOp.getNode());
13423 if (Ops.size() == LHS.getNumOperands())
13424 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13427 // Try to convert a constant mask AND into a shuffle clear mask.
13428 if (SDValue Shuffle = XformToShuffleWithZero(N))
13431 // Type legalization might introduce new shuffles in the DAG.
13432 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13433 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13434 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13435 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13436 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13437 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13438 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13439 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13441 if (SVN0->getMask().equals(SVN1->getMask())) {
13442 EVT VT = N->getValueType(0);
13443 SDValue UndefVector = LHS.getOperand(1);
13444 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13445 LHS.getOperand(0), RHS.getOperand(0),
13447 AddUsersToWorklist(N);
13448 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13449 &SVN0->getMask()[0]);
13456 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13457 SDValue N1, SDValue N2){
13458 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13460 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13461 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13463 // If we got a simplified select_cc node back from SimplifySelectCC, then
13464 // break it down into a new SETCC node, and a new SELECT node, and then return
13465 // the SELECT node, since we were called with a SELECT node.
13466 if (SCC.getNode()) {
13467 // Check to see if we got a select_cc back (to turn into setcc/select).
13468 // Otherwise, just return whatever node we got back, like fabs.
13469 if (SCC.getOpcode() == ISD::SELECT_CC) {
13470 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13472 SCC.getOperand(0), SCC.getOperand(1),
13473 SCC.getOperand(4));
13474 AddToWorklist(SETCC.getNode());
13475 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13476 SCC.getOperand(2), SCC.getOperand(3));
13484 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13485 /// being selected between, see if we can simplify the select. Callers of this
13486 /// should assume that TheSelect is deleted if this returns true. As such, they
13487 /// should return the appropriate thing (e.g. the node) back to the top-level of
13488 /// the DAG combiner loop to avoid it being looked at.
13489 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13492 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13493 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13494 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13495 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13496 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13497 SDValue Sqrt = RHS;
13500 const ConstantFPSDNode *NegZero = nullptr;
13502 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13503 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13504 CmpLHS = TheSelect->getOperand(0);
13505 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13507 // SELECT or VSELECT
13508 SDValue Cmp = TheSelect->getOperand(0);
13509 if (Cmp.getOpcode() == ISD::SETCC) {
13510 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13511 CmpLHS = Cmp.getOperand(0);
13512 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13515 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13516 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13517 CC == ISD::SETULT || CC == ISD::SETLT)) {
13518 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13519 CombineTo(TheSelect, Sqrt);
13524 // Cannot simplify select with vector condition
13525 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13527 // If this is a select from two identical things, try to pull the operation
13528 // through the select.
13529 if (LHS.getOpcode() != RHS.getOpcode() ||
13530 !LHS.hasOneUse() || !RHS.hasOneUse())
13533 // If this is a load and the token chain is identical, replace the select
13534 // of two loads with a load through a select of the address to load from.
13535 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13536 // constants have been dropped into the constant pool.
13537 if (LHS.getOpcode() == ISD::LOAD) {
13538 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13539 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13541 // Token chains must be identical.
13542 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13543 // Do not let this transformation reduce the number of volatile loads.
13544 LLD->isVolatile() || RLD->isVolatile() ||
13545 // FIXME: If either is a pre/post inc/dec load,
13546 // we'd need to split out the address adjustment.
13547 LLD->isIndexed() || RLD->isIndexed() ||
13548 // If this is an EXTLOAD, the VT's must match.
13549 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13550 // If this is an EXTLOAD, the kind of extension must match.
13551 (LLD->getExtensionType() != RLD->getExtensionType() &&
13552 // The only exception is if one of the extensions is anyext.
13553 LLD->getExtensionType() != ISD::EXTLOAD &&
13554 RLD->getExtensionType() != ISD::EXTLOAD) ||
13555 // FIXME: this discards src value information. This is
13556 // over-conservative. It would be beneficial to be able to remember
13557 // both potential memory locations. Since we are discarding
13558 // src value info, don't do the transformation if the memory
13559 // locations are not in the default address space.
13560 LLD->getPointerInfo().getAddrSpace() != 0 ||
13561 RLD->getPointerInfo().getAddrSpace() != 0 ||
13562 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13563 LLD->getBasePtr().getValueType()))
13566 // Check that the select condition doesn't reach either load. If so,
13567 // folding this will induce a cycle into the DAG. If not, this is safe to
13568 // xform, so create a select of the addresses.
13570 if (TheSelect->getOpcode() == ISD::SELECT) {
13571 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13572 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13573 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13575 // The loads must not depend on one another.
13576 if (LLD->isPredecessorOf(RLD) ||
13577 RLD->isPredecessorOf(LLD))
13579 Addr = DAG.getSelect(SDLoc(TheSelect),
13580 LLD->getBasePtr().getValueType(),
13581 TheSelect->getOperand(0), LLD->getBasePtr(),
13582 RLD->getBasePtr());
13583 } else { // Otherwise SELECT_CC
13584 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13585 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13587 if ((LLD->hasAnyUseOfValue(1) &&
13588 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13589 (RLD->hasAnyUseOfValue(1) &&
13590 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13593 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13594 LLD->getBasePtr().getValueType(),
13595 TheSelect->getOperand(0),
13596 TheSelect->getOperand(1),
13597 LLD->getBasePtr(), RLD->getBasePtr(),
13598 TheSelect->getOperand(4));
13602 // It is safe to replace the two loads if they have different alignments,
13603 // but the new load must be the minimum (most restrictive) alignment of the
13605 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13606 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13607 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13608 Load = DAG.getLoad(TheSelect->getValueType(0),
13610 // FIXME: Discards pointer and AA info.
13611 LLD->getChain(), Addr, MachinePointerInfo(),
13612 LLD->isVolatile(), LLD->isNonTemporal(),
13613 isInvariant, Alignment);
13615 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13616 RLD->getExtensionType() : LLD->getExtensionType(),
13618 TheSelect->getValueType(0),
13619 // FIXME: Discards pointer and AA info.
13620 LLD->getChain(), Addr, MachinePointerInfo(),
13621 LLD->getMemoryVT(), LLD->isVolatile(),
13622 LLD->isNonTemporal(), isInvariant, Alignment);
13625 // Users of the select now use the result of the load.
13626 CombineTo(TheSelect, Load);
13628 // Users of the old loads now use the new load's chain. We know the
13629 // old-load value is dead now.
13630 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13631 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13638 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13639 /// where 'cond' is the comparison specified by CC.
13640 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13641 SDValue N2, SDValue N3,
13642 ISD::CondCode CC, bool NotExtCompare) {
13643 // (x ? y : y) -> y.
13644 if (N2 == N3) return N2;
13646 EVT VT = N2.getValueType();
13647 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13648 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13650 // Determine if the condition we're dealing with is constant
13651 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13652 N0, N1, CC, DL, false);
13653 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13655 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13656 // fold select_cc true, x, y -> x
13657 // fold select_cc false, x, y -> y
13658 return !SCCC->isNullValue() ? N2 : N3;
13661 // Check to see if we can simplify the select into an fabs node
13662 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13663 // Allow either -0.0 or 0.0
13664 if (CFP->isZero()) {
13665 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13666 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13667 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13668 N2 == N3.getOperand(0))
13669 return DAG.getNode(ISD::FABS, DL, VT, N0);
13671 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13672 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13673 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13674 N2.getOperand(0) == N3)
13675 return DAG.getNode(ISD::FABS, DL, VT, N3);
13679 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13680 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13681 // in it. This is a win when the constant is not otherwise available because
13682 // it replaces two constant pool loads with one. We only do this if the FP
13683 // type is known to be legal, because if it isn't, then we are before legalize
13684 // types an we want the other legalization to happen first (e.g. to avoid
13685 // messing with soft float) and if the ConstantFP is not legal, because if
13686 // it is legal, we may not need to store the FP constant in a constant pool.
13687 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13688 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13689 if (TLI.isTypeLegal(N2.getValueType()) &&
13690 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13691 TargetLowering::Legal &&
13692 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13693 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13694 // If both constants have multiple uses, then we won't need to do an
13695 // extra load, they are likely around in registers for other users.
13696 (TV->hasOneUse() || FV->hasOneUse())) {
13697 Constant *Elts[] = {
13698 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13699 const_cast<ConstantFP*>(TV->getConstantFPValue())
13701 Type *FPTy = Elts[0]->getType();
13702 const DataLayout &TD = DAG.getDataLayout();
13704 // Create a ConstantArray of the two constants.
13705 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13707 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13708 TD.getPrefTypeAlignment(FPTy));
13709 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13711 // Get the offsets to the 0 and 1 element of the array so that we can
13712 // select between them.
13713 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13714 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13715 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13717 SDValue Cond = DAG.getSetCC(DL,
13718 getSetCCResultType(N0.getValueType()),
13720 AddToWorklist(Cond.getNode());
13721 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13723 AddToWorklist(CstOffset.getNode());
13724 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13726 AddToWorklist(CPIdx.getNode());
13727 return DAG.getLoad(
13728 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13729 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13730 false, false, false, Alignment);
13734 // Check to see if we can perform the "gzip trick", transforming
13735 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13736 if (isNullConstant(N3) && CC == ISD::SETLT &&
13737 (isNullConstant(N1) || // (a < 0) ? b : 0
13738 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13739 EVT XType = N0.getValueType();
13740 EVT AType = N2.getValueType();
13741 if (XType.bitsGE(AType)) {
13742 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13743 // single-bit constant.
13744 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13745 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13746 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13747 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13748 getShiftAmountTy(N0.getValueType()));
13749 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13751 AddToWorklist(Shift.getNode());
13753 if (XType.bitsGT(AType)) {
13754 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13755 AddToWorklist(Shift.getNode());
13758 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13761 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13763 DAG.getConstant(XType.getSizeInBits() - 1,
13765 getShiftAmountTy(N0.getValueType())));
13766 AddToWorklist(Shift.getNode());
13768 if (XType.bitsGT(AType)) {
13769 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13770 AddToWorklist(Shift.getNode());
13773 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13777 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13778 // where y is has a single bit set.
13779 // A plaintext description would be, we can turn the SELECT_CC into an AND
13780 // when the condition can be materialized as an all-ones register. Any
13781 // single bit-test can be materialized as an all-ones register with
13782 // shift-left and shift-right-arith.
13783 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13784 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13785 SDValue AndLHS = N0->getOperand(0);
13786 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13787 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13788 // Shift the tested bit over the sign bit.
13789 APInt AndMask = ConstAndRHS->getAPIntValue();
13791 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13792 getShiftAmountTy(AndLHS.getValueType()));
13793 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13795 // Now arithmetic right shift it all the way over, so the result is either
13796 // all-ones, or zero.
13798 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13799 getShiftAmountTy(Shl.getValueType()));
13800 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13802 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13806 // fold select C, 16, 0 -> shl C, 4
13807 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13808 TLI.getBooleanContents(N0.getValueType()) ==
13809 TargetLowering::ZeroOrOneBooleanContent) {
13811 // If the caller doesn't want us to simplify this into a zext of a compare,
13813 if (NotExtCompare && N2C->isOne())
13816 // Get a SetCC of the condition
13817 // NOTE: Don't create a SETCC if it's not legal on this target.
13818 if (!LegalOperations ||
13819 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13821 // cast from setcc result type to select result type
13823 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13825 if (N2.getValueType().bitsLT(SCC.getValueType()))
13826 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13827 N2.getValueType());
13829 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13830 N2.getValueType(), SCC);
13832 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13833 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13834 N2.getValueType(), SCC);
13837 AddToWorklist(SCC.getNode());
13838 AddToWorklist(Temp.getNode());
13843 // shl setcc result by log2 n2c
13844 return DAG.getNode(
13845 ISD::SHL, DL, N2.getValueType(), Temp,
13846 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13847 getShiftAmountTy(Temp.getValueType())));
13851 // Check to see if this is an integer abs.
13852 // select_cc setg[te] X, 0, X, -X ->
13853 // select_cc setgt X, -1, X, -X ->
13854 // select_cc setl[te] X, 0, -X, X ->
13855 // select_cc setlt X, 1, -X, X ->
13856 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13858 ConstantSDNode *SubC = nullptr;
13859 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13860 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13861 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13862 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13863 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13864 (N1C->isOne() && CC == ISD::SETLT)) &&
13865 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13866 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13868 EVT XType = N0.getValueType();
13869 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13871 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13873 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13874 getShiftAmountTy(N0.getValueType())));
13875 SDValue Add = DAG.getNode(ISD::ADD, DL,
13877 AddToWorklist(Shift.getNode());
13878 AddToWorklist(Add.getNode());
13879 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13886 /// This is a stub for TargetLowering::SimplifySetCC.
13887 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13888 SDValue N1, ISD::CondCode Cond,
13889 SDLoc DL, bool foldBooleans) {
13890 TargetLowering::DAGCombinerInfo
13891 DagCombineInfo(DAG, Level, false, this);
13892 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13895 /// Given an ISD::SDIV node expressing a divide by constant, return
13896 /// a DAG expression to select that will generate the same value by multiplying
13897 /// by a magic number.
13898 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13899 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13900 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13904 // Avoid division by zero.
13905 if (C->isNullValue())
13908 std::vector<SDNode*> Built;
13910 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13912 for (SDNode *N : Built)
13917 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13918 /// DAG expression that will generate the same value by right shifting.
13919 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13920 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13924 // Avoid division by zero.
13925 if (C->isNullValue())
13928 std::vector<SDNode *> Built;
13929 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13931 for (SDNode *N : Built)
13936 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13937 /// expression that will generate the same value by multiplying by a magic
13939 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13940 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13941 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13945 // Avoid division by zero.
13946 if (C->isNullValue())
13949 std::vector<SDNode*> Built;
13951 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13953 for (SDNode *N : Built)
13958 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
13959 if (Level >= AfterLegalizeDAG)
13962 // Expose the DAG combiner to the target combiner implementations.
13963 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13965 unsigned Iterations = 0;
13966 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13968 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13969 // For the reciprocal, we need to find the zero of the function:
13970 // F(X) = A X - 1 [which has a zero at X = 1/A]
13972 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13973 // does not require additional intermediate precision]
13974 EVT VT = Op.getValueType();
13976 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13978 AddToWorklist(Est.getNode());
13980 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13981 for (unsigned i = 0; i < Iterations; ++i) {
13982 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
13983 AddToWorklist(NewEst.getNode());
13985 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
13986 AddToWorklist(NewEst.getNode());
13988 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
13989 AddToWorklist(NewEst.getNode());
13991 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
13992 AddToWorklist(Est.getNode());
14001 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14002 /// For the reciprocal sqrt, we need to find the zero of the function:
14003 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14005 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14006 /// As a result, we precompute A/2 prior to the iteration loop.
14007 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14008 unsigned Iterations,
14009 SDNodeFlags *Flags) {
14010 EVT VT = Arg.getValueType();
14012 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14014 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14015 // this entire sequence requires only one FP constant.
14016 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14017 AddToWorklist(HalfArg.getNode());
14019 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14020 AddToWorklist(HalfArg.getNode());
14022 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14023 for (unsigned i = 0; i < Iterations; ++i) {
14024 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14025 AddToWorklist(NewEst.getNode());
14027 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14028 AddToWorklist(NewEst.getNode());
14030 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14031 AddToWorklist(NewEst.getNode());
14033 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14034 AddToWorklist(Est.getNode());
14039 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14040 /// For the reciprocal sqrt, we need to find the zero of the function:
14041 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14043 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14044 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14045 unsigned Iterations,
14046 SDNodeFlags *Flags) {
14047 EVT VT = Arg.getValueType();
14049 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14050 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14052 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14053 for (unsigned i = 0; i < Iterations; ++i) {
14054 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14055 AddToWorklist(HalfEst.getNode());
14057 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14058 AddToWorklist(Est.getNode());
14060 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14061 AddToWorklist(Est.getNode());
14063 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14064 AddToWorklist(Est.getNode());
14066 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14067 AddToWorklist(Est.getNode());
14072 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14073 if (Level >= AfterLegalizeDAG)
14076 // Expose the DAG combiner to the target combiner implementations.
14077 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14078 unsigned Iterations = 0;
14079 bool UseOneConstNR = false;
14080 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14081 AddToWorklist(Est.getNode());
14083 Est = UseOneConstNR ?
14084 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14085 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14093 /// Return true if base is a frame index, which is known not to alias with
14094 /// anything but itself. Provides base object and offset as results.
14095 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14096 const GlobalValue *&GV, const void *&CV) {
14097 // Assume it is a primitive operation.
14098 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14100 // If it's an adding a simple constant then integrate the offset.
14101 if (Base.getOpcode() == ISD::ADD) {
14102 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14103 Base = Base.getOperand(0);
14104 Offset += C->getZExtValue();
14108 // Return the underlying GlobalValue, and update the Offset. Return false
14109 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14110 // by multiple nodes with different offsets.
14111 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14112 GV = G->getGlobal();
14113 Offset += G->getOffset();
14117 // Return the underlying Constant value, and update the Offset. Return false
14118 // for ConstantSDNodes since the same constant pool entry may be represented
14119 // by multiple nodes with different offsets.
14120 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14121 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14122 : (const void *)C->getConstVal();
14123 Offset += C->getOffset();
14126 // If it's any of the following then it can't alias with anything but itself.
14127 return isa<FrameIndexSDNode>(Base);
14130 /// Return true if there is any possibility that the two addresses overlap.
14131 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14132 // If they are the same then they must be aliases.
14133 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14135 // If they are both volatile then they cannot be reordered.
14136 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14138 // If one operation reads from invariant memory, and the other may store, they
14139 // cannot alias. These should really be checking the equivalent of mayWrite,
14140 // but it only matters for memory nodes other than load /store.
14141 if (Op0->isInvariant() && Op1->writeMem())
14144 if (Op1->isInvariant() && Op0->writeMem())
14147 // Gather base node and offset information.
14148 SDValue Base1, Base2;
14149 int64_t Offset1, Offset2;
14150 const GlobalValue *GV1, *GV2;
14151 const void *CV1, *CV2;
14152 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14153 Base1, Offset1, GV1, CV1);
14154 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14155 Base2, Offset2, GV2, CV2);
14157 // If they have a same base address then check to see if they overlap.
14158 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14159 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14160 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14162 // It is possible for different frame indices to alias each other, mostly
14163 // when tail call optimization reuses return address slots for arguments.
14164 // To catch this case, look up the actual index of frame indices to compute
14165 // the real alias relationship.
14166 if (isFrameIndex1 && isFrameIndex2) {
14167 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14168 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14169 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14170 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14171 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14174 // Otherwise, if we know what the bases are, and they aren't identical, then
14175 // we know they cannot alias.
14176 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14179 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14180 // compared to the size and offset of the access, we may be able to prove they
14181 // do not alias. This check is conservative for now to catch cases created by
14182 // splitting vector types.
14183 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14184 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14185 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14186 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14187 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14188 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14189 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14191 // There is no overlap between these relatively aligned accesses of similar
14192 // size, return no alias.
14193 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14194 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14198 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14200 : DAG.getSubtarget().useAA();
14202 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14203 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14207 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14208 // Use alias analysis information.
14209 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14210 Op1->getSrcValueOffset());
14211 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14212 Op0->getSrcValueOffset() - MinOffset;
14213 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14214 Op1->getSrcValueOffset() - MinOffset;
14215 AliasResult AAResult =
14216 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14217 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14218 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14219 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14220 if (AAResult == NoAlias)
14224 // Otherwise we have to assume they alias.
14228 /// Walk up chain skipping non-aliasing memory nodes,
14229 /// looking for aliasing nodes and adding them to the Aliases vector.
14230 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14231 SmallVectorImpl<SDValue> &Aliases) {
14232 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14233 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14235 // Get alias information for node.
14236 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14239 Chains.push_back(OriginalChain);
14240 unsigned Depth = 0;
14242 // Look at each chain and determine if it is an alias. If so, add it to the
14243 // aliases list. If not, then continue up the chain looking for the next
14245 while (!Chains.empty()) {
14246 SDValue Chain = Chains.pop_back_val();
14248 // For TokenFactor nodes, look at each operand and only continue up the
14249 // chain until we find two aliases. If we've seen two aliases, assume we'll
14250 // find more and revert to original chain since the xform is unlikely to be
14253 // FIXME: The depth check could be made to return the last non-aliasing
14254 // chain we found before we hit a tokenfactor rather than the original
14256 if (Depth > 6 || Aliases.size() == 2) {
14258 Aliases.push_back(OriginalChain);
14262 // Don't bother if we've been before.
14263 if (!Visited.insert(Chain.getNode()).second)
14266 switch (Chain.getOpcode()) {
14267 case ISD::EntryToken:
14268 // Entry token is ideal chain operand, but handled in FindBetterChain.
14273 // Get alias information for Chain.
14274 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14275 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14277 // If chain is alias then stop here.
14278 if (!(IsLoad && IsOpLoad) &&
14279 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14280 Aliases.push_back(Chain);
14282 // Look further up the chain.
14283 Chains.push_back(Chain.getOperand(0));
14289 case ISD::TokenFactor:
14290 // We have to check each of the operands of the token factor for "small"
14291 // token factors, so we queue them up. Adding the operands to the queue
14292 // (stack) in reverse order maintains the original order and increases the
14293 // likelihood that getNode will find a matching token factor (CSE.)
14294 if (Chain.getNumOperands() > 16) {
14295 Aliases.push_back(Chain);
14298 for (unsigned n = Chain.getNumOperands(); n;)
14299 Chains.push_back(Chain.getOperand(--n));
14304 // For all other instructions we will just have to take what we can get.
14305 Aliases.push_back(Chain);
14310 // We need to be careful here to also search for aliases through the
14311 // value operand of a store, etc. Consider the following situation:
14313 // L1 = load Token1, %52
14314 // S1 = store Token1, L1, %51
14315 // L2 = load Token1, %52+8
14316 // S2 = store Token1, L2, %51+8
14317 // Token2 = Token(S1, S2)
14318 // L3 = load Token2, %53
14319 // S3 = store Token2, L3, %52
14320 // L4 = load Token2, %53+8
14321 // S4 = store Token2, L4, %52+8
14322 // If we search for aliases of S3 (which loads address %52), and we look
14323 // only through the chain, then we'll miss the trivial dependence on L1
14324 // (which also loads from %52). We then might change all loads and
14325 // stores to use Token1 as their chain operand, which could result in
14326 // copying %53 into %52 before copying %52 into %51 (which should
14329 // The problem is, however, that searching for such data dependencies
14330 // can become expensive, and the cost is not directly related to the
14331 // chain depth. Instead, we'll rule out such configurations here by
14332 // insisting that we've visited all chain users (except for users
14333 // of the original chain, which is not necessary). When doing this,
14334 // we need to look through nodes we don't care about (otherwise, things
14335 // like register copies will interfere with trivial cases).
14337 SmallVector<const SDNode *, 16> Worklist;
14338 for (const SDNode *N : Visited)
14339 if (N != OriginalChain.getNode())
14340 Worklist.push_back(N);
14342 while (!Worklist.empty()) {
14343 const SDNode *M = Worklist.pop_back_val();
14345 // We have already visited M, and want to make sure we've visited any uses
14346 // of M that we care about. For uses that we've not visisted, and don't
14347 // care about, queue them to the worklist.
14349 for (SDNode::use_iterator UI = M->use_begin(),
14350 UIE = M->use_end(); UI != UIE; ++UI)
14351 if (UI.getUse().getValueType() == MVT::Other &&
14352 Visited.insert(*UI).second) {
14353 if (isa<MemSDNode>(*UI)) {
14354 // We've not visited this use, and we care about it (it could have an
14355 // ordering dependency with the original node).
14357 Aliases.push_back(OriginalChain);
14361 // We've not visited this use, but we don't care about it. Mark it as
14362 // visited and enqueue it to the worklist.
14363 Worklist.push_back(*UI);
14368 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14369 /// (aliasing node.)
14370 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14371 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14373 // Accumulate all the aliases to this node.
14374 GatherAllAliases(N, OldChain, Aliases);
14376 // If no operands then chain to entry token.
14377 if (Aliases.size() == 0)
14378 return DAG.getEntryNode();
14380 // If a single operand then chain to it. We don't need to revisit it.
14381 if (Aliases.size() == 1)
14384 // Construct a custom tailored token factor.
14385 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14388 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14389 // This holds the base pointer, index, and the offset in bytes from the base
14391 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14393 // We must have a base and an offset.
14394 if (!BasePtr.Base.getNode())
14397 // Do not handle stores to undef base pointers.
14398 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14401 SmallVector<StoreSDNode *, 8> ChainedStores;
14402 ChainedStores.push_back(St);
14404 // Walk up the chain and look for nodes with offsets from the same
14405 // base pointer. Stop when reaching an instruction with a different kind
14406 // or instruction which has a different base pointer.
14407 StoreSDNode *Index = St;
14409 // If the chain has more than one use, then we can't reorder the mem ops.
14410 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14413 // Find the base pointer and offset for this memory node.
14414 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14416 // Check that the base pointer is the same as the original one.
14417 if (!Ptr.equalBaseIndex(BasePtr))
14420 if (Index->isVolatile() || Index->isIndexed())
14423 // Find the next memory operand in the chain. If the next operand in the
14424 // chain is a store then move up and continue the scan with the next
14425 // memory operand. If the next operand is a load save it and use alias
14426 // information to check if it interferes with anything.
14427 SDNode *NextInChain = Index->getChain().getNode();
14429 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14430 // We found a store node. Use it for the next iteration.
14431 ChainedStores.push_back(STn);
14434 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14435 NextInChain = Ldn->getChain().getNode();
14444 bool MadeChange = false;
14445 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14447 for (StoreSDNode *ChainedStore : ChainedStores) {
14448 SDValue Chain = ChainedStore->getChain();
14449 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14451 if (Chain != BetterChain) {
14453 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14457 // Do all replacements after finding the replacements to make to avoid making
14458 // the chains more complicated by introducing new TokenFactors.
14459 for (auto Replacement : BetterChains)
14460 replaceStoreChain(Replacement.first, Replacement.second);
14465 /// This is the entry point for the file.
14466 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14467 CodeGenOpt::Level OptLevel) {
14468 /// This is the main entry point to this class.
14469 DAGCombiner(*this, AA, OptLevel).Run(Level);