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 /// Replaces all uses of the results of one DAG node with new values.
160 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
163 /// Replaces all uses of the results of one DAG node with new values.
164 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
165 return CombineTo(N, &Res, 1, AddTo);
168 /// Replaces all uses of the results of one DAG node with new values.
169 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
171 SDValue To[] = { Res0, Res1 };
172 return CombineTo(N, To, 2, AddTo);
175 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
179 /// Check the specified integer node value to see if it can be simplified or
180 /// if things it uses can be simplified by bit propagation.
181 /// If so, return true.
182 bool SimplifyDemandedBits(SDValue Op) {
183 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
184 APInt Demanded = APInt::getAllOnesValue(BitWidth);
185 return SimplifyDemandedBits(Op, Demanded);
188 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
190 bool CombineToPreIndexedLoadStore(SDNode *N);
191 bool CombineToPostIndexedLoadStore(SDNode *N);
192 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
193 bool SliceUpLoad(SDNode *N);
195 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
198 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
199 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
200 /// \param EltNo index of the vector element to load.
201 /// \param OriginalLoad load that EVE came from to be replaced.
202 /// \returns EVE on success SDValue() on failure.
203 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
204 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
205 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
206 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
207 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
208 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
209 SDValue PromoteIntBinOp(SDValue Op);
210 SDValue PromoteIntShiftOp(SDValue Op);
211 SDValue PromoteExtend(SDValue Op);
212 bool PromoteLoad(SDValue Op);
214 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
215 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
216 ISD::NodeType ExtType);
218 /// Call the node-specific routine that knows how to fold each
219 /// particular type of node. If that doesn't do anything, try the
220 /// target-specific DAG combines.
221 SDValue combine(SDNode *N);
223 // Visitation implementation - Implement dag node combining for different
224 // node types. The semantics are as follows:
226 // SDValue.getNode() == 0 - No change was made
227 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
228 // otherwise - N should be replaced by the returned Operand.
230 SDValue visitTokenFactor(SDNode *N);
231 SDValue visitMERGE_VALUES(SDNode *N);
232 SDValue visitADD(SDNode *N);
233 SDValue visitSUB(SDNode *N);
234 SDValue visitADDC(SDNode *N);
235 SDValue visitSUBC(SDNode *N);
236 SDValue visitADDE(SDNode *N);
237 SDValue visitSUBE(SDNode *N);
238 SDValue visitMUL(SDNode *N);
239 SDValue useDivRem(SDNode *N);
240 SDValue visitSDIV(SDNode *N);
241 SDValue visitUDIV(SDNode *N);
242 SDValue visitREM(SDNode *N);
243 SDValue visitMULHU(SDNode *N);
244 SDValue visitMULHS(SDNode *N);
245 SDValue visitSMUL_LOHI(SDNode *N);
246 SDValue visitUMUL_LOHI(SDNode *N);
247 SDValue visitSMULO(SDNode *N);
248 SDValue visitUMULO(SDNode *N);
249 SDValue visitIMINMAX(SDNode *N);
250 SDValue visitAND(SDNode *N);
251 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitOR(SDNode *N);
253 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
254 SDValue visitXOR(SDNode *N);
255 SDValue SimplifyVBinOp(SDNode *N);
256 SDValue visitSHL(SDNode *N);
257 SDValue visitSRA(SDNode *N);
258 SDValue visitSRL(SDNode *N);
259 SDValue visitRotate(SDNode *N);
260 SDValue visitBSWAP(SDNode *N);
261 SDValue visitCTLZ(SDNode *N);
262 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
263 SDValue visitCTTZ(SDNode *N);
264 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
265 SDValue visitCTPOP(SDNode *N);
266 SDValue visitSELECT(SDNode *N);
267 SDValue visitVSELECT(SDNode *N);
268 SDValue visitSELECT_CC(SDNode *N);
269 SDValue visitSETCC(SDNode *N);
270 SDValue visitSIGN_EXTEND(SDNode *N);
271 SDValue visitZERO_EXTEND(SDNode *N);
272 SDValue visitANY_EXTEND(SDNode *N);
273 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
274 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
275 SDValue visitTRUNCATE(SDNode *N);
276 SDValue visitBITCAST(SDNode *N);
277 SDValue visitBUILD_PAIR(SDNode *N);
278 SDValue visitFADD(SDNode *N);
279 SDValue visitFSUB(SDNode *N);
280 SDValue visitFMUL(SDNode *N);
281 SDValue visitFMA(SDNode *N);
282 SDValue visitFDIV(SDNode *N);
283 SDValue visitFREM(SDNode *N);
284 SDValue visitFSQRT(SDNode *N);
285 SDValue visitFCOPYSIGN(SDNode *N);
286 SDValue visitSINT_TO_FP(SDNode *N);
287 SDValue visitUINT_TO_FP(SDNode *N);
288 SDValue visitFP_TO_SINT(SDNode *N);
289 SDValue visitFP_TO_UINT(SDNode *N);
290 SDValue visitFP_ROUND(SDNode *N);
291 SDValue visitFP_ROUND_INREG(SDNode *N);
292 SDValue visitFP_EXTEND(SDNode *N);
293 SDValue visitFNEG(SDNode *N);
294 SDValue visitFABS(SDNode *N);
295 SDValue visitFCEIL(SDNode *N);
296 SDValue visitFTRUNC(SDNode *N);
297 SDValue visitFFLOOR(SDNode *N);
298 SDValue visitFMINNUM(SDNode *N);
299 SDValue visitFMAXNUM(SDNode *N);
300 SDValue visitBRCOND(SDNode *N);
301 SDValue visitBR_CC(SDNode *N);
302 SDValue visitLOAD(SDNode *N);
304 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
305 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
307 SDValue visitSTORE(SDNode *N);
308 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
309 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
310 SDValue visitBUILD_VECTOR(SDNode *N);
311 SDValue visitCONCAT_VECTORS(SDNode *N);
312 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
313 SDValue visitVECTOR_SHUFFLE(SDNode *N);
314 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
315 SDValue visitINSERT_SUBVECTOR(SDNode *N);
316 SDValue visitMLOAD(SDNode *N);
317 SDValue visitMSTORE(SDNode *N);
318 SDValue visitMGATHER(SDNode *N);
319 SDValue visitMSCATTER(SDNode *N);
320 SDValue visitFP_TO_FP16(SDNode *N);
321 SDValue visitFP16_TO_FP(SDNode *N);
323 SDValue visitFADDForFMACombine(SDNode *N);
324 SDValue visitFSUBForFMACombine(SDNode *N);
325 SDValue visitFMULForFMACombine(SDNode *N);
327 SDValue XformToShuffleWithZero(SDNode *N);
328 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
330 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
332 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
333 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
334 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
335 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
336 SDValue N3, ISD::CondCode CC,
337 bool NotExtCompare = false);
338 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
339 SDLoc DL, bool foldBooleans = true);
341 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
343 bool isOneUseSetCC(SDValue N) const;
345 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
347 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
348 SDValue CombineExtLoad(SDNode *N);
349 SDValue combineRepeatedFPDivisors(SDNode *N);
350 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
351 SDValue BuildSDIV(SDNode *N);
352 SDValue BuildSDIVPow2(SDNode *N);
353 SDValue BuildUDIV(SDNode *N);
354 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
355 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
356 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
358 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
360 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
361 bool DemandHighBits = true);
362 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
363 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
364 SDValue InnerPos, SDValue InnerNeg,
365 unsigned PosOpcode, unsigned NegOpcode,
367 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
368 SDValue ReduceLoadWidth(SDNode *N);
369 SDValue ReduceLoadOpStoreWidth(SDNode *N);
370 SDValue TransformFPLoadStorePair(SDNode *N);
371 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
372 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
374 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
376 /// Walk up chain skipping non-aliasing memory nodes,
377 /// looking for aliasing nodes and adding them to the Aliases vector.
378 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
379 SmallVectorImpl<SDValue> &Aliases);
381 /// Return true if there is any possibility that the two addresses overlap.
382 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
384 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
385 /// chain (aliasing node.)
386 SDValue FindBetterChain(SDNode *N, SDValue Chain);
388 /// Do FindBetterChain for a store and any possibly adjacent stores on
389 /// consecutive chains.
390 bool findBetterNeighborChains(StoreSDNode *St);
392 /// Holds a pointer to an LSBaseSDNode as well as information on where it
393 /// is located in a sequence of memory operations connected by a chain.
395 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
396 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
397 // Ptr to the mem node.
398 LSBaseSDNode *MemNode;
399 // Offset from the base ptr.
400 int64_t OffsetFromBase;
401 // What is the sequence number of this mem node.
402 // Lowest mem operand in the DAG starts at zero.
403 unsigned SequenceNum;
406 /// This is a helper function for visitMUL to check the profitability
407 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
408 /// MulNode is the original multiply, AddNode is (add x, c1),
409 /// and ConstNode is c2.
410 bool isMulAddWithConstProfitable(SDNode *MulNode,
414 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
415 /// constant build_vector of the stored constant values in Stores.
416 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
418 ArrayRef<MemOpLink> Stores,
419 SmallVectorImpl<SDValue> &Chains,
422 /// This is a helper function for MergeConsecutiveStores. When the source
423 /// elements of the consecutive stores are all constants or all extracted
424 /// vector elements, try to merge them into one larger store.
425 /// \return True if a merged store was created.
426 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
427 EVT MemVT, unsigned NumStores,
428 bool IsConstantSrc, bool UseVector);
430 /// This is a helper function for MergeConsecutiveStores.
431 /// Stores that may be merged are placed in StoreNodes.
432 /// Loads that may alias with those stores are placed in AliasLoadNodes.
433 void getStoreMergeAndAliasCandidates(
434 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
435 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
437 /// Merge consecutive store operations into a wide store.
438 /// This optimization uses wide integers or vectors when possible.
439 /// \return True if some memory operations were changed.
440 bool MergeConsecutiveStores(StoreSDNode *N);
442 /// \brief Try to transform a truncation where C is a constant:
443 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
445 /// \p N needs to be a truncation and its first operand an AND. Other
446 /// requirements are checked by the function (e.g. that trunc is
447 /// single-use) and if missed an empty SDValue is returned.
448 SDValue distributeTruncateThroughAnd(SDNode *N);
451 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
452 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
453 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
454 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
457 /// Runs the dag combiner on all nodes in the work list
458 void Run(CombineLevel AtLevel);
460 SelectionDAG &getDAG() const { return DAG; }
462 /// Returns a type large enough to hold any valid shift amount - before type
463 /// legalization these can be huge.
464 EVT getShiftAmountTy(EVT LHSTy) {
465 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
466 if (LHSTy.isVector())
468 auto &DL = DAG.getDataLayout();
469 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
470 : TLI.getPointerTy(DL);
473 /// This method returns true if we are running before type legalization or
474 /// if the specified VT is legal.
475 bool isTypeLegal(const EVT &VT) {
476 if (!LegalTypes) return true;
477 return TLI.isTypeLegal(VT);
480 /// Convenience wrapper around TargetLowering::getSetCCResultType
481 EVT getSetCCResultType(EVT VT) const {
482 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
489 /// This class is a DAGUpdateListener that removes any deleted
490 /// nodes from the worklist.
491 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
494 explicit WorklistRemover(DAGCombiner &dc)
495 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
497 void NodeDeleted(SDNode *N, SDNode *E) override {
498 DC.removeFromWorklist(N);
503 //===----------------------------------------------------------------------===//
504 // TargetLowering::DAGCombinerInfo implementation
505 //===----------------------------------------------------------------------===//
507 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
508 ((DAGCombiner*)DC)->AddToWorklist(N);
511 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
512 ((DAGCombiner*)DC)->removeFromWorklist(N);
515 SDValue TargetLowering::DAGCombinerInfo::
516 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
517 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
520 SDValue TargetLowering::DAGCombinerInfo::
521 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
522 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
526 SDValue TargetLowering::DAGCombinerInfo::
527 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
528 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
531 void TargetLowering::DAGCombinerInfo::
532 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
533 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
536 //===----------------------------------------------------------------------===//
538 //===----------------------------------------------------------------------===//
540 void DAGCombiner::deleteAndRecombine(SDNode *N) {
541 removeFromWorklist(N);
543 // If the operands of this node are only used by the node, they will now be
544 // dead. Make sure to re-visit them and recursively delete dead nodes.
545 for (const SDValue &Op : N->ops())
546 // For an operand generating multiple values, one of the values may
547 // become dead allowing further simplification (e.g. split index
548 // arithmetic from an indexed load).
549 if (Op->hasOneUse() || Op->getNumValues() > 1)
550 AddToWorklist(Op.getNode());
555 /// Return 1 if we can compute the negated form of the specified expression for
556 /// the same cost as the expression itself, or 2 if we can compute the negated
557 /// form more cheaply than the expression itself.
558 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
559 const TargetLowering &TLI,
560 const TargetOptions *Options,
561 unsigned Depth = 0) {
562 // fneg is removable even if it has multiple uses.
563 if (Op.getOpcode() == ISD::FNEG) return 2;
565 // Don't allow anything with multiple uses.
566 if (!Op.hasOneUse()) return 0;
568 // Don't recurse exponentially.
569 if (Depth > 6) return 0;
571 switch (Op.getOpcode()) {
572 default: return false;
573 case ISD::ConstantFP:
574 // Don't invert constant FP values after legalize. The negated constant
575 // isn't necessarily legal.
576 return LegalOperations ? 0 : 1;
578 // FIXME: determine better conditions for this xform.
579 if (!Options->UnsafeFPMath) return 0;
581 // After operation legalization, it might not be legal to create new FSUBs.
582 if (LegalOperations &&
583 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
586 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
587 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
590 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
591 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
594 // We can't turn -(A-B) into B-A when we honor signed zeros.
595 if (!Options->UnsafeFPMath) return 0;
597 // fold (fneg (fsub A, B)) -> (fsub B, A)
602 if (Options->HonorSignDependentRoundingFPMath()) return 0;
604 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
605 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
609 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
615 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
620 /// If isNegatibleForFree returns true, return the newly negated expression.
621 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
622 bool LegalOperations, unsigned Depth = 0) {
623 const TargetOptions &Options = DAG.getTarget().Options;
624 // fneg is removable even if it has multiple uses.
625 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
627 // Don't allow anything with multiple uses.
628 assert(Op.hasOneUse() && "Unknown reuse!");
630 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
632 const SDNodeFlags *Flags = Op.getNode()->getFlags();
634 switch (Op.getOpcode()) {
635 default: llvm_unreachable("Unknown code");
636 case ISD::ConstantFP: {
637 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
639 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
642 // FIXME: determine better conditions for this xform.
643 assert(Options.UnsafeFPMath);
645 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
646 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
647 DAG.getTargetLoweringInfo(), &Options, Depth+1))
648 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
649 GetNegatedExpression(Op.getOperand(0), DAG,
650 LegalOperations, Depth+1),
651 Op.getOperand(1), Flags);
652 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
653 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
654 GetNegatedExpression(Op.getOperand(1), DAG,
655 LegalOperations, Depth+1),
656 Op.getOperand(0), Flags);
658 // We can't turn -(A-B) into B-A when we honor signed zeros.
659 assert(Options.UnsafeFPMath);
661 // fold (fneg (fsub 0, B)) -> B
662 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
664 return Op.getOperand(1);
666 // fold (fneg (fsub A, B)) -> (fsub B, A)
667 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
668 Op.getOperand(1), Op.getOperand(0), Flags);
672 assert(!Options.HonorSignDependentRoundingFPMath());
674 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
675 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
676 DAG.getTargetLoweringInfo(), &Options, Depth+1))
677 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
678 GetNegatedExpression(Op.getOperand(0), DAG,
679 LegalOperations, Depth+1),
680 Op.getOperand(1), Flags);
682 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
683 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
685 GetNegatedExpression(Op.getOperand(1), DAG,
686 LegalOperations, Depth+1), Flags);
690 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
691 GetNegatedExpression(Op.getOperand(0), DAG,
692 LegalOperations, Depth+1));
694 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
695 GetNegatedExpression(Op.getOperand(0), DAG,
696 LegalOperations, Depth+1),
701 // Return true if this node is a setcc, or is a select_cc
702 // that selects between the target values used for true and false, making it
703 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
704 // the appropriate nodes based on the type of node we are checking. This
705 // simplifies life a bit for the callers.
706 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
708 if (N.getOpcode() == ISD::SETCC) {
709 LHS = N.getOperand(0);
710 RHS = N.getOperand(1);
711 CC = N.getOperand(2);
715 if (N.getOpcode() != ISD::SELECT_CC ||
716 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
717 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
720 if (TLI.getBooleanContents(N.getValueType()) ==
721 TargetLowering::UndefinedBooleanContent)
724 LHS = N.getOperand(0);
725 RHS = N.getOperand(1);
726 CC = N.getOperand(4);
730 /// Return true if this is a SetCC-equivalent operation with only one use.
731 /// If this is true, it allows the users to invert the operation for free when
732 /// it is profitable to do so.
733 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
735 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
740 /// Returns true if N is a BUILD_VECTOR node whose
741 /// elements are all the same constant or undefined.
742 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
743 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
748 unsigned SplatBitSize;
750 EVT EltVT = N->getValueType(0).getVectorElementType();
751 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
753 EltVT.getSizeInBits() >= SplatBitSize);
756 // \brief Returns the SDNode if it is a constant integer BuildVector
757 // or constant integer.
758 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
759 if (isa<ConstantSDNode>(N))
761 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
766 // \brief Returns the SDNode if it is a constant float BuildVector
767 // or constant float.
768 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
769 if (isa<ConstantFPSDNode>(N))
771 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
776 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
778 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
779 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
782 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
783 BitVector UndefElements;
784 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
786 // BuildVectors can truncate their operands. Ignore that case here.
787 // FIXME: We blindly ignore splats which include undef which is overly
789 if (CN && UndefElements.none() &&
790 CN->getValueType(0) == N.getValueType().getScalarType())
797 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
799 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
800 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
803 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
804 BitVector UndefElements;
805 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
807 if (CN && UndefElements.none())
814 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
815 SDValue N0, SDValue N1) {
816 EVT VT = N0.getValueType();
817 if (N0.getOpcode() == Opc) {
818 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
819 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
820 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
821 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
822 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
825 if (N0.hasOneUse()) {
826 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
828 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
829 if (!OpNode.getNode())
831 AddToWorklist(OpNode.getNode());
832 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
837 if (N1.getOpcode() == Opc) {
838 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
839 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
840 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
841 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
842 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
845 if (N1.hasOneUse()) {
846 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
848 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
849 if (!OpNode.getNode())
851 AddToWorklist(OpNode.getNode());
852 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
860 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
862 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
864 DEBUG(dbgs() << "\nReplacing.1 ";
866 dbgs() << "\nWith: ";
867 To[0].getNode()->dump(&DAG);
868 dbgs() << " and " << NumTo-1 << " other values\n");
869 for (unsigned i = 0, e = NumTo; i != e; ++i)
870 assert((!To[i].getNode() ||
871 N->getValueType(i) == To[i].getValueType()) &&
872 "Cannot combine value to value of different type!");
874 WorklistRemover DeadNodes(*this);
875 DAG.ReplaceAllUsesWith(N, To);
877 // Push the new nodes and any users onto the worklist
878 for (unsigned i = 0, e = NumTo; i != e; ++i) {
879 if (To[i].getNode()) {
880 AddToWorklist(To[i].getNode());
881 AddUsersToWorklist(To[i].getNode());
886 // Finally, if the node is now dead, remove it from the graph. The node
887 // may not be dead if the replacement process recursively simplified to
888 // something else needing this node.
890 deleteAndRecombine(N);
891 return SDValue(N, 0);
895 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
896 // Replace all uses. If any nodes become isomorphic to other nodes and
897 // are deleted, make sure to remove them from our worklist.
898 WorklistRemover DeadNodes(*this);
899 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
901 // Push the new node and any (possibly new) users onto the worklist.
902 AddToWorklist(TLO.New.getNode());
903 AddUsersToWorklist(TLO.New.getNode());
905 // Finally, if the node is now dead, remove it from the graph. The node
906 // may not be dead if the replacement process recursively simplified to
907 // something else needing this node.
908 if (TLO.Old.getNode()->use_empty())
909 deleteAndRecombine(TLO.Old.getNode());
912 /// Check the specified integer node value to see if it can be simplified or if
913 /// things it uses can be simplified by bit propagation. If so, return true.
914 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
915 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
916 APInt KnownZero, KnownOne;
917 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
921 AddToWorklist(Op.getNode());
923 // Replace the old value with the new one.
925 DEBUG(dbgs() << "\nReplacing.2 ";
926 TLO.Old.getNode()->dump(&DAG);
927 dbgs() << "\nWith: ";
928 TLO.New.getNode()->dump(&DAG);
931 CommitTargetLoweringOpt(TLO);
935 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
937 EVT VT = Load->getValueType(0);
938 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
940 DEBUG(dbgs() << "\nReplacing.9 ";
942 dbgs() << "\nWith: ";
943 Trunc.getNode()->dump(&DAG);
945 WorklistRemover DeadNodes(*this);
946 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
947 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
948 deleteAndRecombine(Load);
949 AddToWorklist(Trunc.getNode());
952 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
955 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
956 EVT MemVT = LD->getMemoryVT();
957 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
958 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
960 : LD->getExtensionType();
962 return DAG.getExtLoad(ExtType, dl, PVT,
963 LD->getChain(), LD->getBasePtr(),
964 MemVT, LD->getMemOperand());
967 unsigned Opc = Op.getOpcode();
970 case ISD::AssertSext:
971 return DAG.getNode(ISD::AssertSext, dl, PVT,
972 SExtPromoteOperand(Op.getOperand(0), PVT),
974 case ISD::AssertZext:
975 return DAG.getNode(ISD::AssertZext, dl, PVT,
976 ZExtPromoteOperand(Op.getOperand(0), PVT),
978 case ISD::Constant: {
980 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
981 return DAG.getNode(ExtOpc, dl, PVT, Op);
985 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
987 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
990 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
991 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
993 EVT OldVT = Op.getValueType();
995 bool Replace = false;
996 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
997 if (!NewOp.getNode())
999 AddToWorklist(NewOp.getNode());
1002 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1003 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1004 DAG.getValueType(OldVT));
1007 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1008 EVT OldVT = Op.getValueType();
1010 bool Replace = false;
1011 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1012 if (!NewOp.getNode())
1014 AddToWorklist(NewOp.getNode());
1017 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1018 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1021 /// Promote the specified integer binary operation if the target indicates it is
1022 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1023 /// i32 since i16 instructions are longer.
1024 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1025 if (!LegalOperations)
1028 EVT VT = Op.getValueType();
1029 if (VT.isVector() || !VT.isInteger())
1032 // If operation type is 'undesirable', e.g. i16 on x86, consider
1034 unsigned Opc = Op.getOpcode();
1035 if (TLI.isTypeDesirableForOp(Opc, VT))
1039 // Consult target whether it is a good idea to promote this operation and
1040 // what's the right type to promote it to.
1041 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1042 assert(PVT != VT && "Don't know what type to promote to!");
1044 bool Replace0 = false;
1045 SDValue N0 = Op.getOperand(0);
1046 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1050 bool Replace1 = false;
1051 SDValue N1 = Op.getOperand(1);
1056 NN1 = PromoteOperand(N1, PVT, Replace1);
1061 AddToWorklist(NN0.getNode());
1063 AddToWorklist(NN1.getNode());
1066 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1068 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1070 DEBUG(dbgs() << "\nPromoting ";
1071 Op.getNode()->dump(&DAG));
1073 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1074 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1079 /// Promote the specified integer shift operation if the target indicates it is
1080 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1081 /// i32 since i16 instructions are longer.
1082 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1083 if (!LegalOperations)
1086 EVT VT = Op.getValueType();
1087 if (VT.isVector() || !VT.isInteger())
1090 // If operation type is 'undesirable', e.g. i16 on x86, consider
1092 unsigned Opc = Op.getOpcode();
1093 if (TLI.isTypeDesirableForOp(Opc, VT))
1097 // Consult target whether it is a good idea to promote this operation and
1098 // what's the right type to promote it to.
1099 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100 assert(PVT != VT && "Don't know what type to promote to!");
1102 bool Replace = false;
1103 SDValue N0 = Op.getOperand(0);
1104 if (Opc == ISD::SRA)
1105 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1106 else if (Opc == ISD::SRL)
1107 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1109 N0 = PromoteOperand(N0, PVT, Replace);
1113 AddToWorklist(N0.getNode());
1115 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1117 DEBUG(dbgs() << "\nPromoting ";
1118 Op.getNode()->dump(&DAG));
1120 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1121 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1126 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1127 if (!LegalOperations)
1130 EVT VT = Op.getValueType();
1131 if (VT.isVector() || !VT.isInteger())
1134 // If operation type is 'undesirable', e.g. i16 on x86, consider
1136 unsigned Opc = Op.getOpcode();
1137 if (TLI.isTypeDesirableForOp(Opc, VT))
1141 // Consult target whether it is a good idea to promote this operation and
1142 // what's the right type to promote it to.
1143 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1144 assert(PVT != VT && "Don't know what type to promote to!");
1145 // fold (aext (aext x)) -> (aext x)
1146 // fold (aext (zext x)) -> (zext x)
1147 // fold (aext (sext x)) -> (sext x)
1148 DEBUG(dbgs() << "\nPromoting ";
1149 Op.getNode()->dump(&DAG));
1150 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1155 bool DAGCombiner::PromoteLoad(SDValue Op) {
1156 if (!LegalOperations)
1159 EVT VT = Op.getValueType();
1160 if (VT.isVector() || !VT.isInteger())
1163 // If operation type is 'undesirable', e.g. i16 on x86, consider
1165 unsigned Opc = Op.getOpcode();
1166 if (TLI.isTypeDesirableForOp(Opc, VT))
1170 // Consult target whether it is a good idea to promote this operation and
1171 // what's the right type to promote it to.
1172 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1173 assert(PVT != VT && "Don't know what type to promote to!");
1176 SDNode *N = Op.getNode();
1177 LoadSDNode *LD = cast<LoadSDNode>(N);
1178 EVT MemVT = LD->getMemoryVT();
1179 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1180 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1182 : LD->getExtensionType();
1183 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1184 LD->getChain(), LD->getBasePtr(),
1185 MemVT, LD->getMemOperand());
1186 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1188 DEBUG(dbgs() << "\nPromoting ";
1191 Result.getNode()->dump(&DAG);
1193 WorklistRemover DeadNodes(*this);
1194 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1195 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1196 deleteAndRecombine(N);
1197 AddToWorklist(Result.getNode());
1203 /// \brief Recursively delete a node which has no uses and any operands for
1204 /// which it is the only use.
1206 /// Note that this both deletes the nodes and removes them from the worklist.
1207 /// It also adds any nodes who have had a user deleted to the worklist as they
1208 /// may now have only one use and subject to other combines.
1209 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1210 if (!N->use_empty())
1213 SmallSetVector<SDNode *, 16> Nodes;
1216 N = Nodes.pop_back_val();
1220 if (N->use_empty()) {
1221 for (const SDValue &ChildN : N->op_values())
1222 Nodes.insert(ChildN.getNode());
1224 removeFromWorklist(N);
1229 } while (!Nodes.empty());
1233 //===----------------------------------------------------------------------===//
1234 // Main DAG Combiner implementation
1235 //===----------------------------------------------------------------------===//
1237 void DAGCombiner::Run(CombineLevel AtLevel) {
1238 // set the instance variables, so that the various visit routines may use it.
1240 LegalOperations = Level >= AfterLegalizeVectorOps;
1241 LegalTypes = Level >= AfterLegalizeTypes;
1243 // Add all the dag nodes to the worklist.
1244 for (SDNode &Node : DAG.allnodes())
1245 AddToWorklist(&Node);
1247 // Create a dummy node (which is not added to allnodes), that adds a reference
1248 // to the root node, preventing it from being deleted, and tracking any
1249 // changes of the root.
1250 HandleSDNode Dummy(DAG.getRoot());
1252 // while the worklist isn't empty, find a node and
1253 // try and combine it.
1254 while (!WorklistMap.empty()) {
1256 // The Worklist holds the SDNodes in order, but it may contain null entries.
1258 N = Worklist.pop_back_val();
1261 bool GoodWorklistEntry = WorklistMap.erase(N);
1262 (void)GoodWorklistEntry;
1263 assert(GoodWorklistEntry &&
1264 "Found a worklist entry without a corresponding map entry!");
1266 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1267 // N is deleted from the DAG, since they too may now be dead or may have a
1268 // reduced number of uses, allowing other xforms.
1269 if (recursivelyDeleteUnusedNodes(N))
1272 WorklistRemover DeadNodes(*this);
1274 // If this combine is running after legalizing the DAG, re-legalize any
1275 // nodes pulled off the worklist.
1276 if (Level == AfterLegalizeDAG) {
1277 SmallSetVector<SDNode *, 16> UpdatedNodes;
1278 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1280 for (SDNode *LN : UpdatedNodes) {
1282 AddUsersToWorklist(LN);
1288 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1290 // Add any operands of the new node which have not yet been combined to the
1291 // worklist as well. Because the worklist uniques things already, this
1292 // won't repeatedly process the same operand.
1293 CombinedNodes.insert(N);
1294 for (const SDValue &ChildN : N->op_values())
1295 if (!CombinedNodes.count(ChildN.getNode()))
1296 AddToWorklist(ChildN.getNode());
1298 SDValue RV = combine(N);
1305 // If we get back the same node we passed in, rather than a new node or
1306 // zero, we know that the node must have defined multiple values and
1307 // CombineTo was used. Since CombineTo takes care of the worklist
1308 // mechanics for us, we have no work to do in this case.
1309 if (RV.getNode() == N)
1312 assert(N->getOpcode() != ISD::DELETED_NODE &&
1313 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1314 "Node was deleted but visit returned new node!");
1316 DEBUG(dbgs() << " ... into: ";
1317 RV.getNode()->dump(&DAG));
1319 // Transfer debug value.
1320 DAG.TransferDbgValues(SDValue(N, 0), RV);
1321 if (N->getNumValues() == RV.getNode()->getNumValues())
1322 DAG.ReplaceAllUsesWith(N, RV.getNode());
1324 assert(N->getValueType(0) == RV.getValueType() &&
1325 N->getNumValues() == 1 && "Type mismatch");
1327 DAG.ReplaceAllUsesWith(N, &OpV);
1330 // Push the new node and any users onto the worklist
1331 AddToWorklist(RV.getNode());
1332 AddUsersToWorklist(RV.getNode());
1334 // Finally, if the node is now dead, remove it from the graph. The node
1335 // may not be dead if the replacement process recursively simplified to
1336 // something else needing this node. This will also take care of adding any
1337 // operands which have lost a user to the worklist.
1338 recursivelyDeleteUnusedNodes(N);
1341 // If the root changed (e.g. it was a dead load, update the root).
1342 DAG.setRoot(Dummy.getValue());
1343 DAG.RemoveDeadNodes();
1346 SDValue DAGCombiner::visit(SDNode *N) {
1347 switch (N->getOpcode()) {
1349 case ISD::TokenFactor: return visitTokenFactor(N);
1350 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1351 case ISD::ADD: return visitADD(N);
1352 case ISD::SUB: return visitSUB(N);
1353 case ISD::ADDC: return visitADDC(N);
1354 case ISD::SUBC: return visitSUBC(N);
1355 case ISD::ADDE: return visitADDE(N);
1356 case ISD::SUBE: return visitSUBE(N);
1357 case ISD::MUL: return visitMUL(N);
1358 case ISD::SDIV: return visitSDIV(N);
1359 case ISD::UDIV: return visitUDIV(N);
1361 case ISD::UREM: return visitREM(N);
1362 case ISD::MULHU: return visitMULHU(N);
1363 case ISD::MULHS: return visitMULHS(N);
1364 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1365 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1366 case ISD::SMULO: return visitSMULO(N);
1367 case ISD::UMULO: return visitUMULO(N);
1371 case ISD::UMAX: return visitIMINMAX(N);
1372 case ISD::AND: return visitAND(N);
1373 case ISD::OR: return visitOR(N);
1374 case ISD::XOR: return visitXOR(N);
1375 case ISD::SHL: return visitSHL(N);
1376 case ISD::SRA: return visitSRA(N);
1377 case ISD::SRL: return visitSRL(N);
1379 case ISD::ROTL: return visitRotate(N);
1380 case ISD::BSWAP: return visitBSWAP(N);
1381 case ISD::CTLZ: return visitCTLZ(N);
1382 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1383 case ISD::CTTZ: return visitCTTZ(N);
1384 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1385 case ISD::CTPOP: return visitCTPOP(N);
1386 case ISD::SELECT: return visitSELECT(N);
1387 case ISD::VSELECT: return visitVSELECT(N);
1388 case ISD::SELECT_CC: return visitSELECT_CC(N);
1389 case ISD::SETCC: return visitSETCC(N);
1390 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1391 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1392 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1393 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1394 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1395 case ISD::TRUNCATE: return visitTRUNCATE(N);
1396 case ISD::BITCAST: return visitBITCAST(N);
1397 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1398 case ISD::FADD: return visitFADD(N);
1399 case ISD::FSUB: return visitFSUB(N);
1400 case ISD::FMUL: return visitFMUL(N);
1401 case ISD::FMA: return visitFMA(N);
1402 case ISD::FDIV: return visitFDIV(N);
1403 case ISD::FREM: return visitFREM(N);
1404 case ISD::FSQRT: return visitFSQRT(N);
1405 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1406 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1407 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1408 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1409 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1410 case ISD::FP_ROUND: return visitFP_ROUND(N);
1411 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1412 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1413 case ISD::FNEG: return visitFNEG(N);
1414 case ISD::FABS: return visitFABS(N);
1415 case ISD::FFLOOR: return visitFFLOOR(N);
1416 case ISD::FMINNUM: return visitFMINNUM(N);
1417 case ISD::FMAXNUM: return visitFMAXNUM(N);
1418 case ISD::FCEIL: return visitFCEIL(N);
1419 case ISD::FTRUNC: return visitFTRUNC(N);
1420 case ISD::BRCOND: return visitBRCOND(N);
1421 case ISD::BR_CC: return visitBR_CC(N);
1422 case ISD::LOAD: return visitLOAD(N);
1423 case ISD::STORE: return visitSTORE(N);
1424 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1425 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1426 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1427 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1428 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1429 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1430 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1431 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1432 case ISD::MGATHER: return visitMGATHER(N);
1433 case ISD::MLOAD: return visitMLOAD(N);
1434 case ISD::MSCATTER: return visitMSCATTER(N);
1435 case ISD::MSTORE: return visitMSTORE(N);
1436 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1437 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1442 SDValue DAGCombiner::combine(SDNode *N) {
1443 SDValue RV = visit(N);
1445 // If nothing happened, try a target-specific DAG combine.
1446 if (!RV.getNode()) {
1447 assert(N->getOpcode() != ISD::DELETED_NODE &&
1448 "Node was deleted but visit returned NULL!");
1450 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1451 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1453 // Expose the DAG combiner to the target combiner impls.
1454 TargetLowering::DAGCombinerInfo
1455 DagCombineInfo(DAG, Level, false, this);
1457 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1461 // If nothing happened still, try promoting the operation.
1462 if (!RV.getNode()) {
1463 switch (N->getOpcode()) {
1471 RV = PromoteIntBinOp(SDValue(N, 0));
1476 RV = PromoteIntShiftOp(SDValue(N, 0));
1478 case ISD::SIGN_EXTEND:
1479 case ISD::ZERO_EXTEND:
1480 case ISD::ANY_EXTEND:
1481 RV = PromoteExtend(SDValue(N, 0));
1484 if (PromoteLoad(SDValue(N, 0)))
1490 // If N is a commutative binary node, try commuting it to enable more
1492 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1493 N->getNumValues() == 1) {
1494 SDValue N0 = N->getOperand(0);
1495 SDValue N1 = N->getOperand(1);
1497 // Constant operands are canonicalized to RHS.
1498 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1499 SDValue Ops[] = {N1, N0};
1500 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1503 return SDValue(CSENode, 0);
1510 /// Given a node, return its input chain if it has one, otherwise return a null
1512 static SDValue getInputChainForNode(SDNode *N) {
1513 if (unsigned NumOps = N->getNumOperands()) {
1514 if (N->getOperand(0).getValueType() == MVT::Other)
1515 return N->getOperand(0);
1516 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1517 return N->getOperand(NumOps-1);
1518 for (unsigned i = 1; i < NumOps-1; ++i)
1519 if (N->getOperand(i).getValueType() == MVT::Other)
1520 return N->getOperand(i);
1525 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1526 // If N has two operands, where one has an input chain equal to the other,
1527 // the 'other' chain is redundant.
1528 if (N->getNumOperands() == 2) {
1529 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1530 return N->getOperand(0);
1531 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1532 return N->getOperand(1);
1535 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1536 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1537 SmallPtrSet<SDNode*, 16> SeenOps;
1538 bool Changed = false; // If we should replace this token factor.
1540 // Start out with this token factor.
1543 // Iterate through token factors. The TFs grows when new token factors are
1545 for (unsigned i = 0; i < TFs.size(); ++i) {
1546 SDNode *TF = TFs[i];
1548 // Check each of the operands.
1549 for (const SDValue &Op : TF->op_values()) {
1551 switch (Op.getOpcode()) {
1552 case ISD::EntryToken:
1553 // Entry tokens don't need to be added to the list. They are
1558 case ISD::TokenFactor:
1559 if (Op.hasOneUse() &&
1560 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1561 // Queue up for processing.
1562 TFs.push_back(Op.getNode());
1563 // Clean up in case the token factor is removed.
1564 AddToWorklist(Op.getNode());
1571 // Only add if it isn't already in the list.
1572 if (SeenOps.insert(Op.getNode()).second)
1583 // If we've changed things around then replace token factor.
1586 // The entry token is the only possible outcome.
1587 Result = DAG.getEntryNode();
1589 // New and improved token factor.
1590 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1593 // Add users to worklist if AA is enabled, since it may introduce
1594 // a lot of new chained token factors while removing memory deps.
1595 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1596 : DAG.getSubtarget().useAA();
1597 return CombineTo(N, Result, UseAA /*add to worklist*/);
1603 /// MERGE_VALUES can always be eliminated.
1604 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1605 WorklistRemover DeadNodes(*this);
1606 // Replacing results may cause a different MERGE_VALUES to suddenly
1607 // be CSE'd with N, and carry its uses with it. Iterate until no
1608 // uses remain, to ensure that the node can be safely deleted.
1609 // First add the users of this node to the work list so that they
1610 // can be tried again once they have new operands.
1611 AddUsersToWorklist(N);
1613 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1614 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1615 } while (!N->use_empty());
1616 deleteAndRecombine(N);
1617 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1620 static bool isNullConstant(SDValue V) {
1621 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1622 return Const != nullptr && Const->isNullValue();
1625 static bool isNullFPConstant(SDValue V) {
1626 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1627 return Const != nullptr && Const->isZero() && !Const->isNegative();
1630 static bool isAllOnesConstant(SDValue V) {
1631 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1632 return Const != nullptr && Const->isAllOnesValue();
1635 static bool isOneConstant(SDValue V) {
1636 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1637 return Const != nullptr && Const->isOne();
1640 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1641 /// ContantSDNode pointer else nullptr.
1642 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1643 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1644 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1647 SDValue DAGCombiner::visitADD(SDNode *N) {
1648 SDValue N0 = N->getOperand(0);
1649 SDValue N1 = N->getOperand(1);
1650 EVT VT = N0.getValueType();
1653 if (VT.isVector()) {
1654 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1657 // fold (add x, 0) -> x, vector edition
1658 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1660 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1664 // fold (add x, undef) -> undef
1665 if (N0.getOpcode() == ISD::UNDEF)
1667 if (N1.getOpcode() == ISD::UNDEF)
1669 // fold (add c1, c2) -> c1+c2
1670 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1671 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1673 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1674 // canonicalize constant to RHS
1675 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1676 !isConstantIntBuildVectorOrConstantInt(N1))
1677 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1678 // fold (add x, 0) -> x
1679 if (isNullConstant(N1))
1681 // fold (add Sym, c) -> Sym+c
1682 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1683 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1684 GA->getOpcode() == ISD::GlobalAddress)
1685 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1687 (uint64_t)N1C->getSExtValue());
1688 // fold ((c1-A)+c2) -> (c1+c2)-A
1689 if (N1C && N0.getOpcode() == ISD::SUB)
1690 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1692 return DAG.getNode(ISD::SUB, DL, VT,
1693 DAG.getConstant(N1C->getAPIntValue()+
1694 N0C->getAPIntValue(), DL, VT),
1698 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1700 // fold ((0-A) + B) -> B-A
1701 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1702 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1703 // fold (A + (0-B)) -> A-B
1704 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1705 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1706 // fold (A+(B-A)) -> B
1707 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1708 return N1.getOperand(0);
1709 // fold ((B-A)+A) -> B
1710 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1711 return N0.getOperand(0);
1712 // fold (A+(B-(A+C))) to (B-C)
1713 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1714 N0 == N1.getOperand(1).getOperand(0))
1715 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1716 N1.getOperand(1).getOperand(1));
1717 // fold (A+(B-(C+A))) to (B-C)
1718 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1719 N0 == N1.getOperand(1).getOperand(1))
1720 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1721 N1.getOperand(1).getOperand(0));
1722 // fold (A+((B-A)+or-C)) to (B+or-C)
1723 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1724 N1.getOperand(0).getOpcode() == ISD::SUB &&
1725 N0 == N1.getOperand(0).getOperand(1))
1726 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1727 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1729 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1730 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1731 SDValue N00 = N0.getOperand(0);
1732 SDValue N01 = N0.getOperand(1);
1733 SDValue N10 = N1.getOperand(0);
1734 SDValue N11 = N1.getOperand(1);
1736 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1737 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1738 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1739 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1742 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1743 return SDValue(N, 0);
1745 // fold (a+b) -> (a|b) iff a and b share no bits.
1746 if (VT.isInteger() && !VT.isVector()) {
1747 APInt LHSZero, LHSOne;
1748 APInt RHSZero, RHSOne;
1749 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1751 if (LHSZero.getBoolValue()) {
1752 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1754 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1755 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1756 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1757 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1758 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1763 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1764 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1765 isNullConstant(N1.getOperand(0).getOperand(0)))
1766 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1767 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1768 N1.getOperand(0).getOperand(1),
1770 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1771 isNullConstant(N0.getOperand(0).getOperand(0)))
1772 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1773 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1774 N0.getOperand(0).getOperand(1),
1777 if (N1.getOpcode() == ISD::AND) {
1778 SDValue AndOp0 = N1.getOperand(0);
1779 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1780 unsigned DestBits = VT.getScalarType().getSizeInBits();
1782 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1783 // and similar xforms where the inner op is either ~0 or 0.
1784 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1786 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1790 // add (sext i1), X -> sub X, (zext i1)
1791 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1792 N0.getOperand(0).getValueType() == MVT::i1 &&
1793 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1795 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1796 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1799 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1800 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1801 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1802 if (TN->getVT() == MVT::i1) {
1804 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1805 DAG.getConstant(1, DL, VT));
1806 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1813 SDValue DAGCombiner::visitADDC(SDNode *N) {
1814 SDValue N0 = N->getOperand(0);
1815 SDValue N1 = N->getOperand(1);
1816 EVT VT = N0.getValueType();
1818 // If the flag result is dead, turn this into an ADD.
1819 if (!N->hasAnyUseOfValue(1))
1820 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1821 DAG.getNode(ISD::CARRY_FALSE,
1822 SDLoc(N), MVT::Glue));
1824 // canonicalize constant to RHS.
1825 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1826 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1828 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1830 // fold (addc x, 0) -> x + no carry out
1831 if (isNullConstant(N1))
1832 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1833 SDLoc(N), MVT::Glue));
1835 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1836 APInt LHSZero, LHSOne;
1837 APInt RHSZero, RHSOne;
1838 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1840 if (LHSZero.getBoolValue()) {
1841 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1843 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1844 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1845 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1846 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1847 DAG.getNode(ISD::CARRY_FALSE,
1848 SDLoc(N), MVT::Glue));
1854 SDValue DAGCombiner::visitADDE(SDNode *N) {
1855 SDValue N0 = N->getOperand(0);
1856 SDValue N1 = N->getOperand(1);
1857 SDValue CarryIn = N->getOperand(2);
1859 // canonicalize constant to RHS
1860 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1861 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1863 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1866 // fold (adde x, y, false) -> (addc x, y)
1867 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1868 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1873 // Since it may not be valid to emit a fold to zero for vector initializers
1874 // check if we can before folding.
1875 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1877 bool LegalOperations, bool LegalTypes) {
1879 return DAG.getConstant(0, DL, VT);
1880 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1881 return DAG.getConstant(0, DL, VT);
1885 SDValue DAGCombiner::visitSUB(SDNode *N) {
1886 SDValue N0 = N->getOperand(0);
1887 SDValue N1 = N->getOperand(1);
1888 EVT VT = N0.getValueType();
1891 if (VT.isVector()) {
1892 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1895 // fold (sub x, 0) -> x, vector edition
1896 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1900 // fold (sub x, x) -> 0
1901 // FIXME: Refactor this and xor and other similar operations together.
1903 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1904 // fold (sub c1, c2) -> c1-c2
1905 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1906 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1908 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1909 // fold (sub x, c) -> (add x, -c)
1912 return DAG.getNode(ISD::ADD, DL, VT, N0,
1913 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1915 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1916 if (isAllOnesConstant(N0))
1917 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1918 // fold A-(A-B) -> B
1919 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1920 return N1.getOperand(1);
1921 // fold (A+B)-A -> B
1922 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1923 return N0.getOperand(1);
1924 // fold (A+B)-B -> A
1925 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1926 return N0.getOperand(0);
1927 // fold C2-(A+C1) -> (C2-C1)-A
1928 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1929 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1930 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1932 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1934 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1937 // fold ((A+(B+or-C))-B) -> A+or-C
1938 if (N0.getOpcode() == ISD::ADD &&
1939 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1940 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1941 N0.getOperand(1).getOperand(0) == N1)
1942 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1943 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1944 // fold ((A+(C+B))-B) -> A+C
1945 if (N0.getOpcode() == ISD::ADD &&
1946 N0.getOperand(1).getOpcode() == ISD::ADD &&
1947 N0.getOperand(1).getOperand(1) == N1)
1948 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1949 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1950 // fold ((A-(B-C))-C) -> A-B
1951 if (N0.getOpcode() == ISD::SUB &&
1952 N0.getOperand(1).getOpcode() == ISD::SUB &&
1953 N0.getOperand(1).getOperand(1) == N1)
1954 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1955 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1957 // If either operand of a sub is undef, the result is undef
1958 if (N0.getOpcode() == ISD::UNDEF)
1960 if (N1.getOpcode() == ISD::UNDEF)
1963 // If the relocation model supports it, consider symbol offsets.
1964 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1965 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1966 // fold (sub Sym, c) -> Sym-c
1967 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1968 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1970 (uint64_t)N1C->getSExtValue());
1971 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1972 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1973 if (GA->getGlobal() == GB->getGlobal())
1974 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1978 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1979 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1980 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1981 if (TN->getVT() == MVT::i1) {
1983 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1984 DAG.getConstant(1, DL, VT));
1985 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1992 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1993 SDValue N0 = N->getOperand(0);
1994 SDValue N1 = N->getOperand(1);
1995 EVT VT = N0.getValueType();
1998 // If the flag result is dead, turn this into an SUB.
1999 if (!N->hasAnyUseOfValue(1))
2000 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2001 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2003 // fold (subc x, x) -> 0 + no borrow
2005 return CombineTo(N, DAG.getConstant(0, DL, VT),
2006 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2008 // fold (subc x, 0) -> x + no borrow
2009 if (isNullConstant(N1))
2010 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2012 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2013 if (isAllOnesConstant(N0))
2014 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2015 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2020 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2021 SDValue N0 = N->getOperand(0);
2022 SDValue N1 = N->getOperand(1);
2023 SDValue CarryIn = N->getOperand(2);
2025 // fold (sube x, y, false) -> (subc x, y)
2026 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2027 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2032 SDValue DAGCombiner::visitMUL(SDNode *N) {
2033 SDValue N0 = N->getOperand(0);
2034 SDValue N1 = N->getOperand(1);
2035 EVT VT = N0.getValueType();
2037 // fold (mul x, undef) -> 0
2038 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2039 return DAG.getConstant(0, SDLoc(N), VT);
2041 bool N0IsConst = false;
2042 bool N1IsConst = false;
2043 bool N1IsOpaqueConst = false;
2044 bool N0IsOpaqueConst = false;
2045 APInt ConstValue0, ConstValue1;
2047 if (VT.isVector()) {
2048 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2051 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2052 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2054 N0IsConst = isa<ConstantSDNode>(N0);
2056 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2057 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2059 N1IsConst = isa<ConstantSDNode>(N1);
2061 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2062 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2066 // fold (mul c1, c2) -> c1*c2
2067 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2068 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2069 N0.getNode(), N1.getNode());
2071 // canonicalize constant to RHS (vector doesn't have to splat)
2072 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2073 !isConstantIntBuildVectorOrConstantInt(N1))
2074 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2075 // fold (mul x, 0) -> 0
2076 if (N1IsConst && ConstValue1 == 0)
2078 // We require a splat of the entire scalar bit width for non-contiguous
2081 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2082 // fold (mul x, 1) -> x
2083 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2085 // fold (mul x, -1) -> 0-x
2086 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2088 return DAG.getNode(ISD::SUB, DL, VT,
2089 DAG.getConstant(0, DL, VT), N0);
2091 // fold (mul x, (1 << c)) -> x << c
2092 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2095 return DAG.getNode(ISD::SHL, DL, VT, N0,
2096 DAG.getConstant(ConstValue1.logBase2(), DL,
2097 getShiftAmountTy(N0.getValueType())));
2099 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2100 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2102 unsigned Log2Val = (-ConstValue1).logBase2();
2104 // FIXME: If the input is something that is easily negated (e.g. a
2105 // single-use add), we should put the negate there.
2106 return DAG.getNode(ISD::SUB, DL, VT,
2107 DAG.getConstant(0, DL, VT),
2108 DAG.getNode(ISD::SHL, DL, VT, N0,
2109 DAG.getConstant(Log2Val, DL,
2110 getShiftAmountTy(N0.getValueType()))));
2114 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2115 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2116 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2117 isa<ConstantSDNode>(N0.getOperand(1)))) {
2118 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2119 N1, N0.getOperand(1));
2120 AddToWorklist(C3.getNode());
2121 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2122 N0.getOperand(0), C3);
2125 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2128 SDValue Sh(nullptr,0), Y(nullptr,0);
2129 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2130 if (N0.getOpcode() == ISD::SHL &&
2131 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2132 isa<ConstantSDNode>(N0.getOperand(1))) &&
2133 N0.getNode()->hasOneUse()) {
2135 } else if (N1.getOpcode() == ISD::SHL &&
2136 isa<ConstantSDNode>(N1.getOperand(1)) &&
2137 N1.getNode()->hasOneUse()) {
2142 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2143 Sh.getOperand(0), Y);
2144 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2145 Mul, Sh.getOperand(1));
2149 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2150 if (isConstantIntBuildVectorOrConstantInt(N1) &&
2151 N0.getOpcode() == ISD::ADD &&
2152 isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2153 isMulAddWithConstProfitable(N, N0, N1))
2154 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2155 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2156 N0.getOperand(0), N1),
2157 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2158 N0.getOperand(1), N1));
2161 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2167 /// Return true if divmod libcall is available.
2168 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2169 const TargetLowering &TLI) {
2171 switch (Node->getSimpleValueType(0).SimpleTy) {
2172 default: return false; // No libcall for vector types.
2173 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2174 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2175 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2176 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2177 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2180 return TLI.getLibcallName(LC) != nullptr;
2183 /// Issue divrem if both quotient and remainder are needed.
2184 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2185 if (Node->use_empty())
2186 return SDValue(); // This is a dead node, leave it alone.
2188 EVT VT = Node->getValueType(0);
2189 if (!TLI.isTypeLegal(VT))
2192 unsigned Opcode = Node->getOpcode();
2193 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2195 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2196 // If DIVREM is going to get expanded into a libcall,
2197 // but there is no libcall available, then don't combine.
2198 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2199 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2202 // If div is legal, it's better to do the normal expansion
2203 unsigned OtherOpcode = 0;
2204 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2205 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2206 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2209 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2210 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2214 SDValue Op0 = Node->getOperand(0);
2215 SDValue Op1 = Node->getOperand(1);
2217 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2218 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2220 if (User == Node || User->use_empty())
2222 // Convert the other matching node(s), too;
2223 // otherwise, the DIVREM may get target-legalized into something
2224 // target-specific that we won't be able to recognize.
2225 unsigned UserOpc = User->getOpcode();
2226 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2227 User->getOperand(0) == Op0 &&
2228 User->getOperand(1) == Op1) {
2230 if (UserOpc == OtherOpcode) {
2231 SDVTList VTs = DAG.getVTList(VT, VT);
2232 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2233 } else if (UserOpc == DivRemOpc) {
2234 combined = SDValue(User, 0);
2236 assert(UserOpc == Opcode);
2240 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2241 CombineTo(User, combined);
2242 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2243 CombineTo(User, combined.getValue(1));
2249 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2250 SDValue N0 = N->getOperand(0);
2251 SDValue N1 = N->getOperand(1);
2252 EVT VT = N->getValueType(0);
2256 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2261 // fold (sdiv c1, c2) -> c1/c2
2262 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2263 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2264 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2265 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2266 // fold (sdiv X, 1) -> X
2267 if (N1C && N1C->isOne())
2269 // fold (sdiv X, -1) -> 0-X
2270 if (N1C && N1C->isAllOnesValue())
2271 return DAG.getNode(ISD::SUB, DL, VT,
2272 DAG.getConstant(0, DL, VT), N0);
2274 // If we know the sign bits of both operands are zero, strength reduce to a
2275 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2276 if (!VT.isVector()) {
2277 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2278 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2281 // fold (sdiv X, pow2) -> simple ops after legalize
2282 // FIXME: We check for the exact bit here because the generic lowering gives
2283 // better results in that case. The target-specific lowering should learn how
2284 // to handle exact sdivs efficiently.
2285 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2286 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2287 (N1C->getAPIntValue().isPowerOf2() ||
2288 (-N1C->getAPIntValue()).isPowerOf2())) {
2289 // Target-specific implementation of sdiv x, pow2.
2290 if (SDValue Res = BuildSDIVPow2(N))
2293 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2295 // Splat the sign bit into the register
2297 DAG.getNode(ISD::SRA, DL, VT, N0,
2298 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2299 getShiftAmountTy(N0.getValueType())));
2300 AddToWorklist(SGN.getNode());
2302 // Add (N0 < 0) ? abs2 - 1 : 0;
2304 DAG.getNode(ISD::SRL, DL, VT, SGN,
2305 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2306 getShiftAmountTy(SGN.getValueType())));
2307 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2308 AddToWorklist(SRL.getNode());
2309 AddToWorklist(ADD.getNode()); // Divide by pow2
2310 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2311 DAG.getConstant(lg2, DL,
2312 getShiftAmountTy(ADD.getValueType())));
2314 // If we're dividing by a positive value, we're done. Otherwise, we must
2315 // negate the result.
2316 if (N1C->getAPIntValue().isNonNegative())
2319 AddToWorklist(SRA.getNode());
2320 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2323 // If integer divide is expensive and we satisfy the requirements, emit an
2324 // alternate sequence. Targets may check function attributes for size/speed
2326 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2327 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2328 if (SDValue Op = BuildSDIV(N))
2331 // sdiv, srem -> sdivrem
2332 if (SDValue DivRem = useDivRem(N))
2336 if (N0.getOpcode() == ISD::UNDEF)
2337 return DAG.getConstant(0, DL, VT);
2338 // X / undef -> undef
2339 if (N1.getOpcode() == ISD::UNDEF)
2345 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2346 SDValue N0 = N->getOperand(0);
2347 SDValue N1 = N->getOperand(1);
2348 EVT VT = N->getValueType(0);
2352 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2357 // fold (udiv c1, c2) -> c1/c2
2358 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2359 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2361 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2364 // fold (udiv x, (1 << c)) -> x >>u c
2365 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2366 return DAG.getNode(ISD::SRL, DL, VT, N0,
2367 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2368 getShiftAmountTy(N0.getValueType())));
2370 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2371 if (N1.getOpcode() == ISD::SHL) {
2372 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2373 if (SHC->getAPIntValue().isPowerOf2()) {
2374 EVT ADDVT = N1.getOperand(1).getValueType();
2375 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2377 DAG.getConstant(SHC->getAPIntValue()
2380 AddToWorklist(Add.getNode());
2381 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2386 // fold (udiv x, c) -> alternate
2387 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2388 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2389 if (SDValue Op = BuildUDIV(N))
2392 // sdiv, srem -> sdivrem
2393 if (SDValue DivRem = useDivRem(N))
2397 if (N0.getOpcode() == ISD::UNDEF)
2398 return DAG.getConstant(0, DL, VT);
2399 // X / undef -> undef
2400 if (N1.getOpcode() == ISD::UNDEF)
2406 // handles ISD::SREM and ISD::UREM
2407 SDValue DAGCombiner::visitREM(SDNode *N) {
2408 unsigned Opcode = N->getOpcode();
2409 SDValue N0 = N->getOperand(0);
2410 SDValue N1 = N->getOperand(1);
2411 EVT VT = N->getValueType(0);
2412 bool isSigned = (Opcode == ISD::SREM);
2415 // fold (rem c1, c2) -> c1%c2
2416 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2417 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2419 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2423 // If we know the sign bits of both operands are zero, strength reduce to a
2424 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2425 if (!VT.isVector()) {
2426 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2427 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2430 // fold (urem x, pow2) -> (and x, pow2-1)
2431 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2432 N1C->getAPIntValue().isPowerOf2()) {
2433 return DAG.getNode(ISD::AND, DL, VT, N0,
2434 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2436 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2437 if (N1.getOpcode() == ISD::SHL) {
2438 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2439 if (SHC->getAPIntValue().isPowerOf2()) {
2441 DAG.getNode(ISD::ADD, DL, VT, N1,
2442 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2444 AddToWorklist(Add.getNode());
2445 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2451 // If X/C can be simplified by the division-by-constant logic, lower
2452 // X%C to the equivalent of X-X/C*C.
2453 if (N1C && !N1C->isNullValue()) {
2454 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2455 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2456 AddToWorklist(Div.getNode());
2457 SDValue OptimizedDiv = combine(Div.getNode());
2458 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2459 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2460 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2461 AddToWorklist(Mul.getNode());
2466 // sdiv, srem -> sdivrem
2467 if (SDValue DivRem = useDivRem(N))
2468 return DivRem.getValue(1);
2471 if (N0.getOpcode() == ISD::UNDEF)
2472 return DAG.getConstant(0, DL, VT);
2473 // X % undef -> undef
2474 if (N1.getOpcode() == ISD::UNDEF)
2480 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2481 SDValue N0 = N->getOperand(0);
2482 SDValue N1 = N->getOperand(1);
2483 EVT VT = N->getValueType(0);
2486 // fold (mulhs x, 0) -> 0
2487 if (isNullConstant(N1))
2489 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2490 if (isOneConstant(N1)) {
2492 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2493 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2495 getShiftAmountTy(N0.getValueType())));
2497 // fold (mulhs x, undef) -> 0
2498 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2499 return DAG.getConstant(0, SDLoc(N), VT);
2501 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2503 if (VT.isSimple() && !VT.isVector()) {
2504 MVT Simple = VT.getSimpleVT();
2505 unsigned SimpleSize = Simple.getSizeInBits();
2506 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2507 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2508 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2509 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2510 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2511 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2512 DAG.getConstant(SimpleSize, DL,
2513 getShiftAmountTy(N1.getValueType())));
2514 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2521 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2522 SDValue N0 = N->getOperand(0);
2523 SDValue N1 = N->getOperand(1);
2524 EVT VT = N->getValueType(0);
2527 // fold (mulhu x, 0) -> 0
2528 if (isNullConstant(N1))
2530 // fold (mulhu x, 1) -> 0
2531 if (isOneConstant(N1))
2532 return DAG.getConstant(0, DL, N0.getValueType());
2533 // fold (mulhu x, undef) -> 0
2534 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2535 return DAG.getConstant(0, DL, VT);
2537 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2539 if (VT.isSimple() && !VT.isVector()) {
2540 MVT Simple = VT.getSimpleVT();
2541 unsigned SimpleSize = Simple.getSizeInBits();
2542 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2543 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2544 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2545 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2546 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2547 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2548 DAG.getConstant(SimpleSize, DL,
2549 getShiftAmountTy(N1.getValueType())));
2550 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2557 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2558 /// give the opcodes for the two computations that are being performed. Return
2559 /// true if a simplification was made.
2560 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2562 // If the high half is not needed, just compute the low half.
2563 bool HiExists = N->hasAnyUseOfValue(1);
2565 (!LegalOperations ||
2566 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2567 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2568 return CombineTo(N, Res, Res);
2571 // If the low half is not needed, just compute the high half.
2572 bool LoExists = N->hasAnyUseOfValue(0);
2574 (!LegalOperations ||
2575 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2576 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2577 return CombineTo(N, Res, Res);
2580 // If both halves are used, return as it is.
2581 if (LoExists && HiExists)
2584 // If the two computed results can be simplified separately, separate them.
2586 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2587 AddToWorklist(Lo.getNode());
2588 SDValue LoOpt = combine(Lo.getNode());
2589 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2590 (!LegalOperations ||
2591 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2592 return CombineTo(N, LoOpt, LoOpt);
2596 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2597 AddToWorklist(Hi.getNode());
2598 SDValue HiOpt = combine(Hi.getNode());
2599 if (HiOpt.getNode() && HiOpt != Hi &&
2600 (!LegalOperations ||
2601 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2602 return CombineTo(N, HiOpt, HiOpt);
2608 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2609 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2612 EVT VT = N->getValueType(0);
2615 // If the type is twice as wide is legal, transform the mulhu to a wider
2616 // multiply plus a shift.
2617 if (VT.isSimple() && !VT.isVector()) {
2618 MVT Simple = VT.getSimpleVT();
2619 unsigned SimpleSize = Simple.getSizeInBits();
2620 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2621 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2622 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2623 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2624 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2625 // Compute the high part as N1.
2626 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2627 DAG.getConstant(SimpleSize, DL,
2628 getShiftAmountTy(Lo.getValueType())));
2629 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2630 // Compute the low part as N0.
2631 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2632 return CombineTo(N, Lo, Hi);
2639 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2640 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2643 EVT VT = N->getValueType(0);
2646 // If the type is twice as wide is legal, transform the mulhu to a wider
2647 // multiply plus a shift.
2648 if (VT.isSimple() && !VT.isVector()) {
2649 MVT Simple = VT.getSimpleVT();
2650 unsigned SimpleSize = Simple.getSizeInBits();
2651 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2652 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2653 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2654 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2655 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2656 // Compute the high part as N1.
2657 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2658 DAG.getConstant(SimpleSize, DL,
2659 getShiftAmountTy(Lo.getValueType())));
2660 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2661 // Compute the low part as N0.
2662 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2663 return CombineTo(N, Lo, Hi);
2670 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2671 // (smulo x, 2) -> (saddo x, x)
2672 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2673 if (C2->getAPIntValue() == 2)
2674 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2675 N->getOperand(0), N->getOperand(0));
2680 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2681 // (umulo x, 2) -> (uaddo x, x)
2682 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2683 if (C2->getAPIntValue() == 2)
2684 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2685 N->getOperand(0), N->getOperand(0));
2690 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2691 SDValue N0 = N->getOperand(0);
2692 SDValue N1 = N->getOperand(1);
2693 EVT VT = N0.getValueType();
2697 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2700 // fold (add c1, c2) -> c1+c2
2701 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2702 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2704 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2706 // canonicalize constant to RHS
2707 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2708 !isConstantIntBuildVectorOrConstantInt(N1))
2709 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2714 /// If this is a binary operator with two operands of the same opcode, try to
2716 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2717 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2718 EVT VT = N0.getValueType();
2719 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2721 // Bail early if none of these transforms apply.
2722 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2724 // For each of OP in AND/OR/XOR:
2725 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2726 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2727 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2728 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2729 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2731 // do not sink logical op inside of a vector extend, since it may combine
2733 EVT Op0VT = N0.getOperand(0).getValueType();
2734 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2735 N0.getOpcode() == ISD::SIGN_EXTEND ||
2736 N0.getOpcode() == ISD::BSWAP ||
2737 // Avoid infinite looping with PromoteIntBinOp.
2738 (N0.getOpcode() == ISD::ANY_EXTEND &&
2739 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2740 (N0.getOpcode() == ISD::TRUNCATE &&
2741 (!TLI.isZExtFree(VT, Op0VT) ||
2742 !TLI.isTruncateFree(Op0VT, VT)) &&
2743 TLI.isTypeLegal(Op0VT))) &&
2745 Op0VT == N1.getOperand(0).getValueType() &&
2746 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2747 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2748 N0.getOperand(0).getValueType(),
2749 N0.getOperand(0), N1.getOperand(0));
2750 AddToWorklist(ORNode.getNode());
2751 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2754 // For each of OP in SHL/SRL/SRA/AND...
2755 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2756 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2757 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2758 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2759 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2760 N0.getOperand(1) == N1.getOperand(1)) {
2761 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2762 N0.getOperand(0).getValueType(),
2763 N0.getOperand(0), N1.getOperand(0));
2764 AddToWorklist(ORNode.getNode());
2765 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2766 ORNode, N0.getOperand(1));
2769 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2770 // Only perform this optimization after type legalization and before
2771 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2772 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2773 // we don't want to undo this promotion.
2774 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2776 if ((N0.getOpcode() == ISD::BITCAST ||
2777 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2778 Level == AfterLegalizeTypes) {
2779 SDValue In0 = N0.getOperand(0);
2780 SDValue In1 = N1.getOperand(0);
2781 EVT In0Ty = In0.getValueType();
2782 EVT In1Ty = In1.getValueType();
2784 // If both incoming values are integers, and the original types are the
2786 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2787 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2788 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2789 AddToWorklist(Op.getNode());
2794 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2795 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2796 // If both shuffles use the same mask, and both shuffle within a single
2797 // vector, then it is worthwhile to move the swizzle after the operation.
2798 // The type-legalizer generates this pattern when loading illegal
2799 // vector types from memory. In many cases this allows additional shuffle
2801 // There are other cases where moving the shuffle after the xor/and/or
2802 // is profitable even if shuffles don't perform a swizzle.
2803 // If both shuffles use the same mask, and both shuffles have the same first
2804 // or second operand, then it might still be profitable to move the shuffle
2805 // after the xor/and/or operation.
2806 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2807 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2808 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2810 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2811 "Inputs to shuffles are not the same type");
2813 // Check that both shuffles use the same mask. The masks are known to be of
2814 // the same length because the result vector type is the same.
2815 // Check also that shuffles have only one use to avoid introducing extra
2817 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2818 SVN0->getMask().equals(SVN1->getMask())) {
2819 SDValue ShOp = N0->getOperand(1);
2821 // Don't try to fold this node if it requires introducing a
2822 // build vector of all zeros that might be illegal at this stage.
2823 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2825 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2830 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2831 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2832 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2833 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2834 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2835 N0->getOperand(0), N1->getOperand(0));
2836 AddToWorklist(NewNode.getNode());
2837 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2838 &SVN0->getMask()[0]);
2841 // Don't try to fold this node if it requires introducing a
2842 // build vector of all zeros that might be illegal at this stage.
2843 ShOp = N0->getOperand(0);
2844 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2846 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2851 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2852 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2853 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2854 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2855 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2856 N0->getOperand(1), N1->getOperand(1));
2857 AddToWorklist(NewNode.getNode());
2858 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2859 &SVN0->getMask()[0]);
2867 /// This contains all DAGCombine rules which reduce two values combined by
2868 /// an And operation to a single value. This makes them reusable in the context
2869 /// of visitSELECT(). Rules involving constants are not included as
2870 /// visitSELECT() already handles those cases.
2871 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2872 SDNode *LocReference) {
2873 EVT VT = N1.getValueType();
2875 // fold (and x, undef) -> 0
2876 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2877 return DAG.getConstant(0, SDLoc(LocReference), VT);
2878 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2879 SDValue LL, LR, RL, RR, CC0, CC1;
2880 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2881 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2882 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2884 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2885 LL.getValueType().isInteger()) {
2886 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2887 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2888 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2889 LR.getValueType(), LL, RL);
2890 AddToWorklist(ORNode.getNode());
2891 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2893 if (isAllOnesConstant(LR)) {
2894 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2895 if (Op1 == ISD::SETEQ) {
2896 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2897 LR.getValueType(), LL, RL);
2898 AddToWorklist(ANDNode.getNode());
2899 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2901 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2902 if (Op1 == ISD::SETGT) {
2903 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2904 LR.getValueType(), LL, RL);
2905 AddToWorklist(ORNode.getNode());
2906 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2910 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2911 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2912 Op0 == Op1 && LL.getValueType().isInteger() &&
2913 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2914 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2916 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2917 LL, DAG.getConstant(1, DL,
2918 LL.getValueType()));
2919 AddToWorklist(ADDNode.getNode());
2920 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2921 DAG.getConstant(2, DL, LL.getValueType()),
2924 // canonicalize equivalent to ll == rl
2925 if (LL == RR && LR == RL) {
2926 Op1 = ISD::getSetCCSwappedOperands(Op1);
2929 if (LL == RL && LR == RR) {
2930 bool isInteger = LL.getValueType().isInteger();
2931 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2932 if (Result != ISD::SETCC_INVALID &&
2933 (!LegalOperations ||
2934 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2935 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2936 EVT CCVT = getSetCCResultType(LL.getValueType());
2937 if (N0.getValueType() == CCVT ||
2938 (!LegalOperations && N0.getValueType() == MVT::i1))
2939 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2945 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2946 VT.getSizeInBits() <= 64) {
2947 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2948 APInt ADDC = ADDI->getAPIntValue();
2949 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2950 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2951 // immediate for an add, but it is legal if its top c2 bits are set,
2952 // transform the ADD so the immediate doesn't need to be materialized
2954 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2955 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2956 SRLI->getZExtValue());
2957 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2959 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2962 DAG.getNode(ISD::ADD, DL, VT,
2963 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2964 CombineTo(N0.getNode(), NewAdd);
2965 // Return N so it doesn't get rechecked!
2966 return SDValue(LocReference, 0);
2977 SDValue DAGCombiner::visitAND(SDNode *N) {
2978 SDValue N0 = N->getOperand(0);
2979 SDValue N1 = N->getOperand(1);
2980 EVT VT = N1.getValueType();
2983 if (VT.isVector()) {
2984 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2987 // fold (and x, 0) -> 0, vector edition
2988 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2989 // do not return N0, because undef node may exist in N0
2990 return DAG.getConstant(
2991 APInt::getNullValue(
2992 N0.getValueType().getScalarType().getSizeInBits()),
2993 SDLoc(N), N0.getValueType());
2994 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2995 // do not return N1, because undef node may exist in N1
2996 return DAG.getConstant(
2997 APInt::getNullValue(
2998 N1.getValueType().getScalarType().getSizeInBits()),
2999 SDLoc(N), N1.getValueType());
3001 // fold (and x, -1) -> x, vector edition
3002 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3004 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3008 // fold (and c1, c2) -> c1&c2
3009 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3010 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3011 if (N0C && N1C && !N1C->isOpaque())
3012 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3013 // canonicalize constant to RHS
3014 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3015 !isConstantIntBuildVectorOrConstantInt(N1))
3016 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3017 // fold (and x, -1) -> x
3018 if (isAllOnesConstant(N1))
3020 // if (and x, c) is known to be zero, return 0
3021 unsigned BitWidth = VT.getScalarType().getSizeInBits();
3022 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3023 APInt::getAllOnesValue(BitWidth)))
3024 return DAG.getConstant(0, SDLoc(N), VT);
3026 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3028 // fold (and (or x, C), D) -> D if (C & D) == D
3029 if (N1C && N0.getOpcode() == ISD::OR)
3030 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3031 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3033 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3034 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3035 SDValue N0Op0 = N0.getOperand(0);
3036 APInt Mask = ~N1C->getAPIntValue();
3037 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3038 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3039 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3040 N0.getValueType(), N0Op0);
3042 // Replace uses of the AND with uses of the Zero extend node.
3045 // We actually want to replace all uses of the any_extend with the
3046 // zero_extend, to avoid duplicating things. This will later cause this
3047 // AND to be folded.
3048 CombineTo(N0.getNode(), Zext);
3049 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3052 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3053 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3054 // already be zero by virtue of the width of the base type of the load.
3056 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3058 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3059 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3060 N0.getOpcode() == ISD::LOAD) {
3061 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3062 N0 : N0.getOperand(0) );
3064 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3065 // This can be a pure constant or a vector splat, in which case we treat the
3066 // vector as a scalar and use the splat value.
3067 APInt Constant = APInt::getNullValue(1);
3068 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3069 Constant = C->getAPIntValue();
3070 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3071 APInt SplatValue, SplatUndef;
3072 unsigned SplatBitSize;
3074 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3075 SplatBitSize, HasAnyUndefs);
3077 // Undef bits can contribute to a possible optimisation if set, so
3079 SplatValue |= SplatUndef;
3081 // The splat value may be something like "0x00FFFFFF", which means 0 for
3082 // the first vector value and FF for the rest, repeating. We need a mask
3083 // that will apply equally to all members of the vector, so AND all the
3084 // lanes of the constant together.
3085 EVT VT = Vector->getValueType(0);
3086 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3088 // If the splat value has been compressed to a bitlength lower
3089 // than the size of the vector lane, we need to re-expand it to
3091 if (BitWidth > SplatBitSize)
3092 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3093 SplatBitSize < BitWidth;
3094 SplatBitSize = SplatBitSize * 2)
3095 SplatValue |= SplatValue.shl(SplatBitSize);
3097 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3098 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3099 if (SplatBitSize % BitWidth == 0) {
3100 Constant = APInt::getAllOnesValue(BitWidth);
3101 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3102 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3107 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3108 // actually legal and isn't going to get expanded, else this is a false
3110 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3111 Load->getValueType(0),
3112 Load->getMemoryVT());
3114 // Resize the constant to the same size as the original memory access before
3115 // extension. If it is still the AllOnesValue then this AND is completely
3118 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3121 switch (Load->getExtensionType()) {
3122 default: B = false; break;
3123 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3125 case ISD::NON_EXTLOAD: B = true; break;
3128 if (B && Constant.isAllOnesValue()) {
3129 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3130 // preserve semantics once we get rid of the AND.
3131 SDValue NewLoad(Load, 0);
3132 if (Load->getExtensionType() == ISD::EXTLOAD) {
3133 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3134 Load->getValueType(0), SDLoc(Load),
3135 Load->getChain(), Load->getBasePtr(),
3136 Load->getOffset(), Load->getMemoryVT(),
3137 Load->getMemOperand());
3138 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3139 if (Load->getNumValues() == 3) {
3140 // PRE/POST_INC loads have 3 values.
3141 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3142 NewLoad.getValue(2) };
3143 CombineTo(Load, To, 3, true);
3145 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3149 // Fold the AND away, taking care not to fold to the old load node if we
3151 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3153 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3157 // fold (and (load x), 255) -> (zextload x, i8)
3158 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3159 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3160 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3161 (N0.getOpcode() == ISD::ANY_EXTEND &&
3162 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3163 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3164 LoadSDNode *LN0 = HasAnyExt
3165 ? cast<LoadSDNode>(N0.getOperand(0))
3166 : cast<LoadSDNode>(N0);
3167 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3168 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3169 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3170 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3171 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3172 EVT LoadedVT = LN0->getMemoryVT();
3173 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3175 if (ExtVT == LoadedVT &&
3176 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3180 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3181 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3182 LN0->getMemOperand());
3184 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3185 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3188 // Do not change the width of a volatile load.
3189 // Do not generate loads of non-round integer types since these can
3190 // be expensive (and would be wrong if the type is not byte sized).
3191 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3192 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3194 EVT PtrType = LN0->getOperand(1).getValueType();
3196 unsigned Alignment = LN0->getAlignment();
3197 SDValue NewPtr = LN0->getBasePtr();
3199 // For big endian targets, we need to add an offset to the pointer
3200 // to load the correct bytes. For little endian systems, we merely
3201 // need to read fewer bytes from the same pointer.
3202 if (DAG.getDataLayout().isBigEndian()) {
3203 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3204 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3205 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3207 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3208 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3209 Alignment = MinAlign(Alignment, PtrOff);
3212 AddToWorklist(NewPtr.getNode());
3215 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3216 LN0->getChain(), NewPtr,
3217 LN0->getPointerInfo(),
3218 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3219 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3221 CombineTo(LN0, Load, Load.getValue(1));
3222 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3228 if (SDValue Combined = visitANDLike(N0, N1, N))
3231 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3232 if (N0.getOpcode() == N1.getOpcode())
3233 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3236 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3237 // fold (and (sra)) -> (and (srl)) when possible.
3238 if (!VT.isVector() &&
3239 SimplifyDemandedBits(SDValue(N, 0)))
3240 return SDValue(N, 0);
3242 // fold (zext_inreg (extload x)) -> (zextload x)
3243 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3244 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3245 EVT MemVT = LN0->getMemoryVT();
3246 // If we zero all the possible extended bits, then we can turn this into
3247 // a zextload if we are running before legalize or the operation is legal.
3248 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3249 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3250 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3251 ((!LegalOperations && !LN0->isVolatile()) ||
3252 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3253 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3254 LN0->getChain(), LN0->getBasePtr(),
3255 MemVT, LN0->getMemOperand());
3257 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3258 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3261 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3262 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3264 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3265 EVT MemVT = LN0->getMemoryVT();
3266 // If we zero all the possible extended bits, then we can turn this into
3267 // a zextload if we are running before legalize or the operation is legal.
3268 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3269 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3270 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3271 ((!LegalOperations && !LN0->isVolatile()) ||
3272 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3273 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3274 LN0->getChain(), LN0->getBasePtr(),
3275 MemVT, LN0->getMemOperand());
3277 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3278 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3281 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3282 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3283 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3284 N0.getOperand(1), false);
3285 if (BSwap.getNode())
3292 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3293 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3294 bool DemandHighBits) {
3295 if (!LegalOperations)
3298 EVT VT = N->getValueType(0);
3299 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3301 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3304 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3305 bool LookPassAnd0 = false;
3306 bool LookPassAnd1 = false;
3307 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3309 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3311 if (N0.getOpcode() == ISD::AND) {
3312 if (!N0.getNode()->hasOneUse())
3314 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3315 if (!N01C || N01C->getZExtValue() != 0xFF00)
3317 N0 = N0.getOperand(0);
3318 LookPassAnd0 = true;
3321 if (N1.getOpcode() == ISD::AND) {
3322 if (!N1.getNode()->hasOneUse())
3324 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3325 if (!N11C || N11C->getZExtValue() != 0xFF)
3327 N1 = N1.getOperand(0);
3328 LookPassAnd1 = true;
3331 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3333 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3335 if (!N0.getNode()->hasOneUse() ||
3336 !N1.getNode()->hasOneUse())
3339 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3340 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3343 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3346 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3347 SDValue N00 = N0->getOperand(0);
3348 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3349 if (!N00.getNode()->hasOneUse())
3351 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3352 if (!N001C || N001C->getZExtValue() != 0xFF)
3354 N00 = N00.getOperand(0);
3355 LookPassAnd0 = true;
3358 SDValue N10 = N1->getOperand(0);
3359 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3360 if (!N10.getNode()->hasOneUse())
3362 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3363 if (!N101C || N101C->getZExtValue() != 0xFF00)
3365 N10 = N10.getOperand(0);
3366 LookPassAnd1 = true;
3372 // Make sure everything beyond the low halfword gets set to zero since the SRL
3373 // 16 will clear the top bits.
3374 unsigned OpSizeInBits = VT.getSizeInBits();
3375 if (DemandHighBits && OpSizeInBits > 16) {
3376 // If the left-shift isn't masked out then the only way this is a bswap is
3377 // if all bits beyond the low 8 are 0. In that case the entire pattern
3378 // reduces to a left shift anyway: leave it for other parts of the combiner.
3382 // However, if the right shift isn't masked out then it might be because
3383 // it's not needed. See if we can spot that too.
3384 if (!LookPassAnd1 &&
3385 !DAG.MaskedValueIsZero(
3386 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3390 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3391 if (OpSizeInBits > 16) {
3393 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3394 DAG.getConstant(OpSizeInBits - 16, DL,
3395 getShiftAmountTy(VT)));
3400 /// Return true if the specified node is an element that makes up a 32-bit
3401 /// packed halfword byteswap.
3402 /// ((x & 0x000000ff) << 8) |
3403 /// ((x & 0x0000ff00) >> 8) |
3404 /// ((x & 0x00ff0000) << 8) |
3405 /// ((x & 0xff000000) >> 8)
3406 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3407 if (!N.getNode()->hasOneUse())
3410 unsigned Opc = N.getOpcode();
3411 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3414 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3419 switch (N1C->getZExtValue()) {
3422 case 0xFF: Num = 0; break;
3423 case 0xFF00: Num = 1; break;
3424 case 0xFF0000: Num = 2; break;
3425 case 0xFF000000: Num = 3; break;
3428 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3429 SDValue N0 = N.getOperand(0);
3430 if (Opc == ISD::AND) {
3431 if (Num == 0 || Num == 2) {
3433 // (x >> 8) & 0xff0000
3434 if (N0.getOpcode() != ISD::SRL)
3436 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3437 if (!C || C->getZExtValue() != 8)
3440 // (x << 8) & 0xff00
3441 // (x << 8) & 0xff000000
3442 if (N0.getOpcode() != ISD::SHL)
3444 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3445 if (!C || C->getZExtValue() != 8)
3448 } else if (Opc == ISD::SHL) {
3450 // (x & 0xff0000) << 8
3451 if (Num != 0 && Num != 2)
3453 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3454 if (!C || C->getZExtValue() != 8)
3456 } else { // Opc == ISD::SRL
3457 // (x & 0xff00) >> 8
3458 // (x & 0xff000000) >> 8
3459 if (Num != 1 && Num != 3)
3461 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3462 if (!C || C->getZExtValue() != 8)
3469 Parts[Num] = N0.getOperand(0).getNode();
3473 /// Match a 32-bit packed halfword bswap. That is
3474 /// ((x & 0x000000ff) << 8) |
3475 /// ((x & 0x0000ff00) >> 8) |
3476 /// ((x & 0x00ff0000) << 8) |
3477 /// ((x & 0xff000000) >> 8)
3478 /// => (rotl (bswap x), 16)
3479 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3480 if (!LegalOperations)
3483 EVT VT = N->getValueType(0);
3486 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3490 // (or (or (and), (and)), (or (and), (and)))
3491 // (or (or (or (and), (and)), (and)), (and))
3492 if (N0.getOpcode() != ISD::OR)
3494 SDValue N00 = N0.getOperand(0);
3495 SDValue N01 = N0.getOperand(1);
3496 SDNode *Parts[4] = {};
3498 if (N1.getOpcode() == ISD::OR &&
3499 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3500 // (or (or (and), (and)), (or (and), (and)))
3501 SDValue N000 = N00.getOperand(0);
3502 if (!isBSwapHWordElement(N000, Parts))
3505 SDValue N001 = N00.getOperand(1);
3506 if (!isBSwapHWordElement(N001, Parts))
3508 SDValue N010 = N01.getOperand(0);
3509 if (!isBSwapHWordElement(N010, Parts))
3511 SDValue N011 = N01.getOperand(1);
3512 if (!isBSwapHWordElement(N011, Parts))
3515 // (or (or (or (and), (and)), (and)), (and))
3516 if (!isBSwapHWordElement(N1, Parts))
3518 if (!isBSwapHWordElement(N01, Parts))
3520 if (N00.getOpcode() != ISD::OR)
3522 SDValue N000 = N00.getOperand(0);
3523 if (!isBSwapHWordElement(N000, Parts))
3525 SDValue N001 = N00.getOperand(1);
3526 if (!isBSwapHWordElement(N001, Parts))
3530 // Make sure the parts are all coming from the same node.
3531 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3535 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3536 SDValue(Parts[0], 0));
3538 // Result of the bswap should be rotated by 16. If it's not legal, then
3539 // do (x << 16) | (x >> 16).
3540 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3541 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3542 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3543 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3544 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3545 return DAG.getNode(ISD::OR, DL, VT,
3546 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3547 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3550 /// This contains all DAGCombine rules which reduce two values combined by
3551 /// an Or operation to a single value \see visitANDLike().
3552 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3553 EVT VT = N1.getValueType();
3554 // fold (or x, undef) -> -1
3555 if (!LegalOperations &&
3556 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3557 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3558 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3559 SDLoc(LocReference), VT);
3561 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3562 SDValue LL, LR, RL, RR, CC0, CC1;
3563 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3564 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3565 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3567 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3568 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3569 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3570 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3571 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3572 LR.getValueType(), LL, RL);
3573 AddToWorklist(ORNode.getNode());
3574 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3576 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3577 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3578 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3579 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3580 LR.getValueType(), LL, RL);
3581 AddToWorklist(ANDNode.getNode());
3582 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3585 // canonicalize equivalent to ll == rl
3586 if (LL == RR && LR == RL) {
3587 Op1 = ISD::getSetCCSwappedOperands(Op1);
3590 if (LL == RL && LR == RR) {
3591 bool isInteger = LL.getValueType().isInteger();
3592 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3593 if (Result != ISD::SETCC_INVALID &&
3594 (!LegalOperations ||
3595 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3596 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3597 EVT CCVT = getSetCCResultType(LL.getValueType());
3598 if (N0.getValueType() == CCVT ||
3599 (!LegalOperations && N0.getValueType() == MVT::i1))
3600 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3606 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3607 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3608 // Don't increase # computations.
3609 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3610 // We can only do this xform if we know that bits from X that are set in C2
3611 // but not in C1 are already zero. Likewise for Y.
3612 if (const ConstantSDNode *N0O1C =
3613 getAsNonOpaqueConstant(N0.getOperand(1))) {
3614 if (const ConstantSDNode *N1O1C =
3615 getAsNonOpaqueConstant(N1.getOperand(1))) {
3616 // We can only do this xform if we know that bits from X that are set in
3617 // C2 but not in C1 are already zero. Likewise for Y.
3618 const APInt &LHSMask = N0O1C->getAPIntValue();
3619 const APInt &RHSMask = N1O1C->getAPIntValue();
3621 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3622 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3623 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3624 N0.getOperand(0), N1.getOperand(0));
3625 SDLoc DL(LocReference);
3626 return DAG.getNode(ISD::AND, DL, VT, X,
3627 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3633 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3634 if (N0.getOpcode() == ISD::AND &&
3635 N1.getOpcode() == ISD::AND &&
3636 N0.getOperand(0) == N1.getOperand(0) &&
3637 // Don't increase # computations.
3638 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3639 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3640 N0.getOperand(1), N1.getOperand(1));
3641 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3647 SDValue DAGCombiner::visitOR(SDNode *N) {
3648 SDValue N0 = N->getOperand(0);
3649 SDValue N1 = N->getOperand(1);
3650 EVT VT = N1.getValueType();
3653 if (VT.isVector()) {
3654 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3657 // fold (or x, 0) -> x, vector edition
3658 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3660 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3663 // fold (or x, -1) -> -1, vector edition
3664 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3665 // do not return N0, because undef node may exist in N0
3666 return DAG.getConstant(
3667 APInt::getAllOnesValue(
3668 N0.getValueType().getScalarType().getSizeInBits()),
3669 SDLoc(N), N0.getValueType());
3670 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3671 // do not return N1, because undef node may exist in N1
3672 return DAG.getConstant(
3673 APInt::getAllOnesValue(
3674 N1.getValueType().getScalarType().getSizeInBits()),
3675 SDLoc(N), N1.getValueType());
3677 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3678 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3679 // Do this only if the resulting shuffle is legal.
3680 if (isa<ShuffleVectorSDNode>(N0) &&
3681 isa<ShuffleVectorSDNode>(N1) &&
3682 // Avoid folding a node with illegal type.
3683 TLI.isTypeLegal(VT) &&
3684 N0->getOperand(1) == N1->getOperand(1) &&
3685 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3686 bool CanFold = true;
3687 unsigned NumElts = VT.getVectorNumElements();
3688 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3689 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3690 // We construct two shuffle masks:
3691 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3692 // and N1 as the second operand.
3693 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3694 // and N0 as the second operand.
3695 // We do this because OR is commutable and therefore there might be
3696 // two ways to fold this node into a shuffle.
3697 SmallVector<int,4> Mask1;
3698 SmallVector<int,4> Mask2;
3700 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3701 int M0 = SV0->getMaskElt(i);
3702 int M1 = SV1->getMaskElt(i);
3704 // Both shuffle indexes are undef. Propagate Undef.
3705 if (M0 < 0 && M1 < 0) {
3706 Mask1.push_back(M0);
3707 Mask2.push_back(M0);
3711 if (M0 < 0 || M1 < 0 ||
3712 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3713 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3718 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3719 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3723 // Fold this sequence only if the resulting shuffle is 'legal'.
3724 if (TLI.isShuffleMaskLegal(Mask1, VT))
3725 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3726 N1->getOperand(0), &Mask1[0]);
3727 if (TLI.isShuffleMaskLegal(Mask2, VT))
3728 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3729 N0->getOperand(0), &Mask2[0]);
3734 // fold (or c1, c2) -> c1|c2
3735 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3736 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3737 if (N0C && N1C && !N1C->isOpaque())
3738 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3739 // canonicalize constant to RHS
3740 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3741 !isConstantIntBuildVectorOrConstantInt(N1))
3742 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3743 // fold (or x, 0) -> x
3744 if (isNullConstant(N1))
3746 // fold (or x, -1) -> -1
3747 if (isAllOnesConstant(N1))
3749 // fold (or x, c) -> c iff (x & ~c) == 0
3750 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3753 if (SDValue Combined = visitORLike(N0, N1, N))
3756 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3757 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3759 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3763 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3765 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3766 // iff (c1 & c2) == 0.
3767 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3768 isa<ConstantSDNode>(N0.getOperand(1))) {
3769 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3770 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3771 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3774 ISD::AND, SDLoc(N), VT,
3775 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3779 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3780 if (N0.getOpcode() == N1.getOpcode())
3781 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3784 // See if this is some rotate idiom.
3785 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3786 return SDValue(Rot, 0);
3788 // Simplify the operands using demanded-bits information.
3789 if (!VT.isVector() &&
3790 SimplifyDemandedBits(SDValue(N, 0)))
3791 return SDValue(N, 0);
3796 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3797 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3798 if (Op.getOpcode() == ISD::AND) {
3799 if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3800 Mask = Op.getOperand(1);
3801 Op = Op.getOperand(0);
3807 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3815 // Return true if we can prove that, whenever Neg and Pos are both in the
3816 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
3817 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3819 // (or (shift1 X, Neg), (shift2 X, Pos))
3821 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3822 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
3823 // to consider shift amounts with defined behavior.
3824 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3825 // If EltSize is a power of 2 then:
3827 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3828 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3830 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3831 // for the stronger condition:
3833 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
3835 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3836 // we can just replace Neg with Neg' for the rest of the function.
3838 // In other cases we check for the even stronger condition:
3840 // Neg == EltSize - Pos [B]
3842 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3843 // behavior if Pos == 0 (and consequently Neg == EltSize).
3845 // We could actually use [A] whenever EltSize is a power of 2, but the
3846 // only extra cases that it would match are those uninteresting ones
3847 // where Neg and Pos are never in range at the same time. E.g. for
3848 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3849 // as well as (sub 32, Pos), but:
3851 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3853 // always invokes undefined behavior for 32-bit X.
3855 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3856 unsigned MaskLoBits = 0;
3857 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3858 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3859 if (NegC->getAPIntValue() == EltSize - 1) {
3860 Neg = Neg.getOperand(0);
3861 MaskLoBits = Log2_64(EltSize);
3866 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3867 if (Neg.getOpcode() != ISD::SUB)
3869 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3872 SDValue NegOp1 = Neg.getOperand(1);
3874 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3875 // Pos'. The truncation is redundant for the purpose of the equality.
3876 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3877 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3878 if (PosC->getAPIntValue() == EltSize - 1)
3879 Pos = Pos.getOperand(0);
3881 // The condition we need is now:
3883 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3885 // If NegOp1 == Pos then we need:
3887 // EltSize & Mask == NegC & Mask
3889 // (because "x & Mask" is a truncation and distributes through subtraction).
3892 Width = NegC->getAPIntValue();
3894 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3895 // Then the condition we want to prove becomes:
3897 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3899 // which, again because "x & Mask" is a truncation, becomes:
3901 // NegC & Mask == (EltSize - PosC) & Mask
3902 // EltSize & Mask == (NegC + PosC) & Mask
3903 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3904 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3905 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3911 // Now we just need to check that EltSize & Mask == Width & Mask.
3913 // EltSize & Mask is 0 since Mask is EltSize - 1.
3914 return Width.getLoBits(MaskLoBits) == 0;
3915 return Width == EltSize;
3918 // A subroutine of MatchRotate used once we have found an OR of two opposite
3919 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3920 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3921 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3922 // Neg with outer conversions stripped away.
3923 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3924 SDValue Neg, SDValue InnerPos,
3925 SDValue InnerNeg, unsigned PosOpcode,
3926 unsigned NegOpcode, SDLoc DL) {
3927 // fold (or (shl x, (*ext y)),
3928 // (srl x, (*ext (sub 32, y)))) ->
3929 // (rotl x, y) or (rotr x, (sub 32, y))
3931 // fold (or (shl x, (*ext (sub 32, y))),
3932 // (srl x, (*ext y))) ->
3933 // (rotr x, y) or (rotl x, (sub 32, y))
3934 EVT VT = Shifted.getValueType();
3935 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
3936 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3937 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3938 HasPos ? Pos : Neg).getNode();
3944 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3945 // idioms for rotate, and if the target supports rotation instructions, generate
3947 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3948 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3949 EVT VT = LHS.getValueType();
3950 if (!TLI.isTypeLegal(VT)) return nullptr;
3952 // The target must have at least one rotate flavor.
3953 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3954 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3955 if (!HasROTL && !HasROTR) return nullptr;
3957 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3958 SDValue LHSShift; // The shift.
3959 SDValue LHSMask; // AND value if any.
3960 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3961 return nullptr; // Not part of a rotate.
3963 SDValue RHSShift; // The shift.
3964 SDValue RHSMask; // AND value if any.
3965 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3966 return nullptr; // Not part of a rotate.
3968 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3969 return nullptr; // Not shifting the same value.
3971 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3972 return nullptr; // Shifts must disagree.
3974 // Canonicalize shl to left side in a shl/srl pair.
3975 if (RHSShift.getOpcode() == ISD::SHL) {
3976 std::swap(LHS, RHS);
3977 std::swap(LHSShift, RHSShift);
3978 std::swap(LHSMask, RHSMask);
3981 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3982 SDValue LHSShiftArg = LHSShift.getOperand(0);
3983 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3984 SDValue RHSShiftArg = RHSShift.getOperand(0);
3985 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3987 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3988 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3989 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
3990 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
3991 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
3992 if ((LShVal + RShVal) != EltSizeInBits)
3995 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3996 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3998 // If there is an AND of either shifted operand, apply it to the result.
3999 if (LHSMask.getNode() || RHSMask.getNode()) {
4000 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4001 SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4003 if (LHSMask.getNode()) {
4004 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4005 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4006 DAG.getNode(ISD::OR, DL, VT, LHSMask,
4007 DAG.getConstant(RHSBits, DL, VT)));
4009 if (RHSMask.getNode()) {
4010 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4011 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4012 DAG.getNode(ISD::OR, DL, VT, RHSMask,
4013 DAG.getConstant(LHSBits, DL, VT)));
4016 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4019 return Rot.getNode();
4022 // If there is a mask here, and we have a variable shift, we can't be sure
4023 // that we're masking out the right stuff.
4024 if (LHSMask.getNode() || RHSMask.getNode())
4027 // If the shift amount is sign/zext/any-extended just peel it off.
4028 SDValue LExtOp0 = LHSShiftAmt;
4029 SDValue RExtOp0 = RHSShiftAmt;
4030 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4031 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4032 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4033 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4034 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4035 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4036 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4037 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4038 LExtOp0 = LHSShiftAmt.getOperand(0);
4039 RExtOp0 = RHSShiftAmt.getOperand(0);
4042 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4043 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4047 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4048 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4055 SDValue DAGCombiner::visitXOR(SDNode *N) {
4056 SDValue N0 = N->getOperand(0);
4057 SDValue N1 = N->getOperand(1);
4058 EVT VT = N0.getValueType();
4061 if (VT.isVector()) {
4062 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4065 // fold (xor x, 0) -> x, vector edition
4066 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4068 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4072 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4073 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4074 return DAG.getConstant(0, SDLoc(N), VT);
4075 // fold (xor x, undef) -> undef
4076 if (N0.getOpcode() == ISD::UNDEF)
4078 if (N1.getOpcode() == ISD::UNDEF)
4080 // fold (xor c1, c2) -> c1^c2
4081 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4082 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4084 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4085 // canonicalize constant to RHS
4086 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4087 !isConstantIntBuildVectorOrConstantInt(N1))
4088 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4089 // fold (xor x, 0) -> x
4090 if (isNullConstant(N1))
4093 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4096 // fold !(x cc y) -> (x !cc y)
4097 SDValue LHS, RHS, CC;
4098 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4099 bool isInt = LHS.getValueType().isInteger();
4100 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4103 if (!LegalOperations ||
4104 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4105 switch (N0.getOpcode()) {
4107 llvm_unreachable("Unhandled SetCC Equivalent!");
4109 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4110 case ISD::SELECT_CC:
4111 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4112 N0.getOperand(3), NotCC);
4117 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4118 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4119 N0.getNode()->hasOneUse() &&
4120 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4121 SDValue V = N0.getOperand(0);
4123 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4124 DAG.getConstant(1, DL, V.getValueType()));
4125 AddToWorklist(V.getNode());
4126 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4129 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4130 if (isOneConstant(N1) && VT == MVT::i1 &&
4131 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4132 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4133 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4134 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4135 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4136 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4137 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4138 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4141 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4142 if (isAllOnesConstant(N1) &&
4143 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4144 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4145 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4146 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4147 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4148 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4149 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4150 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4153 // fold (xor (and x, y), y) -> (and (not x), y)
4154 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4155 N0->getOperand(1) == N1) {
4156 SDValue X = N0->getOperand(0);
4157 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4158 AddToWorklist(NotX.getNode());
4159 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4161 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4162 if (N1C && N0.getOpcode() == ISD::XOR) {
4163 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4165 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4166 DAG.getConstant(N1C->getAPIntValue() ^
4167 N00C->getAPIntValue(), DL, VT));
4169 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4171 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4172 DAG.getConstant(N1C->getAPIntValue() ^
4173 N01C->getAPIntValue(), DL, VT));
4176 // fold (xor x, x) -> 0
4178 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4180 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4181 // Here is a concrete example of this equivalence:
4183 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4184 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4188 // i16 ~1 == 0b1111111111111110
4189 // i16 rol(~1, 14) == 0b1011111111111111
4191 // Some additional tips to help conceptualize this transform:
4192 // - Try to see the operation as placing a single zero in a value of all ones.
4193 // - There exists no value for x which would allow the result to contain zero.
4194 // - Values of x larger than the bitwidth are undefined and do not require a
4195 // consistent result.
4196 // - Pushing the zero left requires shifting one bits in from the right.
4197 // A rotate left of ~1 is a nice way of achieving the desired result.
4198 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4199 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4201 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4205 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4206 if (N0.getOpcode() == N1.getOpcode())
4207 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4210 // Simplify the expression using non-local knowledge.
4211 if (!VT.isVector() &&
4212 SimplifyDemandedBits(SDValue(N, 0)))
4213 return SDValue(N, 0);
4218 /// Handle transforms common to the three shifts, when the shift amount is a
4220 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4221 SDNode *LHS = N->getOperand(0).getNode();
4222 if (!LHS->hasOneUse()) return SDValue();
4224 // We want to pull some binops through shifts, so that we have (and (shift))
4225 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4226 // thing happens with address calculations, so it's important to canonicalize
4228 bool HighBitSet = false; // Can we transform this if the high bit is set?
4230 switch (LHS->getOpcode()) {
4231 default: return SDValue();
4234 HighBitSet = false; // We can only transform sra if the high bit is clear.
4237 HighBitSet = true; // We can only transform sra if the high bit is set.
4240 if (N->getOpcode() != ISD::SHL)
4241 return SDValue(); // only shl(add) not sr[al](add).
4242 HighBitSet = false; // We can only transform sra if the high bit is clear.
4246 // We require the RHS of the binop to be a constant and not opaque as well.
4247 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4248 if (!BinOpCst) return SDValue();
4250 // FIXME: disable this unless the input to the binop is a shift by a constant.
4251 // If it is not a shift, it pessimizes some common cases like:
4253 // void foo(int *X, int i) { X[i & 1235] = 1; }
4254 // int bar(int *X, int i) { return X[i & 255]; }
4255 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4256 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4257 BinOpLHSVal->getOpcode() != ISD::SRA &&
4258 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4259 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4262 EVT VT = N->getValueType(0);
4264 // If this is a signed shift right, and the high bit is modified by the
4265 // logical operation, do not perform the transformation. The highBitSet
4266 // boolean indicates the value of the high bit of the constant which would
4267 // cause it to be modified for this operation.
4268 if (N->getOpcode() == ISD::SRA) {
4269 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4270 if (BinOpRHSSignSet != HighBitSet)
4274 if (!TLI.isDesirableToCommuteWithShift(LHS))
4277 // Fold the constants, shifting the binop RHS by the shift amount.
4278 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4280 LHS->getOperand(1), N->getOperand(1));
4281 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4283 // Create the new shift.
4284 SDValue NewShift = DAG.getNode(N->getOpcode(),
4285 SDLoc(LHS->getOperand(0)),
4286 VT, LHS->getOperand(0), N->getOperand(1));
4288 // Create the new binop.
4289 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4292 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4293 assert(N->getOpcode() == ISD::TRUNCATE);
4294 assert(N->getOperand(0).getOpcode() == ISD::AND);
4296 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4297 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4298 SDValue N01 = N->getOperand(0).getOperand(1);
4300 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4301 if (!N01C->isOpaque()) {
4302 EVT TruncVT = N->getValueType(0);
4303 SDValue N00 = N->getOperand(0).getOperand(0);
4304 APInt TruncC = N01C->getAPIntValue();
4305 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4308 return DAG.getNode(ISD::AND, DL, TruncVT,
4309 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4310 DAG.getConstant(TruncC, DL, TruncVT));
4318 SDValue DAGCombiner::visitRotate(SDNode *N) {
4319 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4320 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4321 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4322 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4323 if (NewOp1.getNode())
4324 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4325 N->getOperand(0), NewOp1);
4330 SDValue DAGCombiner::visitSHL(SDNode *N) {
4331 SDValue N0 = N->getOperand(0);
4332 SDValue N1 = N->getOperand(1);
4333 EVT VT = N0.getValueType();
4334 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4337 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4338 if (VT.isVector()) {
4339 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4342 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4343 // If setcc produces all-one true value then:
4344 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4345 if (N1CV && N1CV->isConstant()) {
4346 if (N0.getOpcode() == ISD::AND) {
4347 SDValue N00 = N0->getOperand(0);
4348 SDValue N01 = N0->getOperand(1);
4349 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4351 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4352 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4353 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4354 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4356 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4359 N1C = isConstOrConstSplat(N1);
4364 // fold (shl c1, c2) -> c1<<c2
4365 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4366 if (N0C && N1C && !N1C->isOpaque())
4367 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4368 // fold (shl 0, x) -> 0
4369 if (isNullConstant(N0))
4371 // fold (shl x, c >= size(x)) -> undef
4372 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4373 return DAG.getUNDEF(VT);
4374 // fold (shl x, 0) -> x
4375 if (N1C && N1C->isNullValue())
4377 // fold (shl undef, x) -> 0
4378 if (N0.getOpcode() == ISD::UNDEF)
4379 return DAG.getConstant(0, SDLoc(N), VT);
4380 // if (shl x, c) is known to be zero, return 0
4381 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4382 APInt::getAllOnesValue(OpSizeInBits)))
4383 return DAG.getConstant(0, SDLoc(N), VT);
4384 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4385 if (N1.getOpcode() == ISD::TRUNCATE &&
4386 N1.getOperand(0).getOpcode() == ISD::AND) {
4387 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4388 if (NewOp1.getNode())
4389 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4392 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4393 return SDValue(N, 0);
4395 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4396 if (N1C && N0.getOpcode() == ISD::SHL) {
4397 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4398 uint64_t c1 = N0C1->getZExtValue();
4399 uint64_t c2 = N1C->getZExtValue();
4401 if (c1 + c2 >= OpSizeInBits)
4402 return DAG.getConstant(0, DL, VT);
4403 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4404 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4408 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4409 // For this to be valid, the second form must not preserve any of the bits
4410 // that are shifted out by the inner shift in the first form. This means
4411 // the outer shift size must be >= the number of bits added by the ext.
4412 // As a corollary, we don't care what kind of ext it is.
4413 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4414 N0.getOpcode() == ISD::ANY_EXTEND ||
4415 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4416 N0.getOperand(0).getOpcode() == ISD::SHL) {
4417 SDValue N0Op0 = N0.getOperand(0);
4418 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4419 uint64_t c1 = N0Op0C1->getZExtValue();
4420 uint64_t c2 = N1C->getZExtValue();
4421 EVT InnerShiftVT = N0Op0.getValueType();
4422 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4423 if (c2 >= OpSizeInBits - InnerShiftSize) {
4425 if (c1 + c2 >= OpSizeInBits)
4426 return DAG.getConstant(0, DL, VT);
4427 return DAG.getNode(ISD::SHL, DL, VT,
4428 DAG.getNode(N0.getOpcode(), DL, VT,
4429 N0Op0->getOperand(0)),
4430 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4435 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4436 // Only fold this if the inner zext has no other uses to avoid increasing
4437 // the total number of instructions.
4438 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4439 N0.getOperand(0).getOpcode() == ISD::SRL) {
4440 SDValue N0Op0 = N0.getOperand(0);
4441 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4442 uint64_t c1 = N0Op0C1->getZExtValue();
4443 if (c1 < VT.getScalarSizeInBits()) {
4444 uint64_t c2 = N1C->getZExtValue();
4446 SDValue NewOp0 = N0.getOperand(0);
4447 EVT CountVT = NewOp0.getOperand(1).getValueType();
4449 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4451 DAG.getConstant(c2, DL, CountVT));
4452 AddToWorklist(NewSHL.getNode());
4453 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4459 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4460 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4461 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4462 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4463 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4464 uint64_t C1 = N0C1->getZExtValue();
4465 uint64_t C2 = N1C->getZExtValue();
4468 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4469 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4470 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4471 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4475 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4476 // (and (srl x, (sub c1, c2), MASK)
4477 // Only fold this if the inner shift has no other uses -- if it does, folding
4478 // this will increase the total number of instructions.
4479 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4480 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4481 uint64_t c1 = N0C1->getZExtValue();
4482 if (c1 < OpSizeInBits) {
4483 uint64_t c2 = N1C->getZExtValue();
4484 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4487 Mask = Mask.shl(c2 - c1);
4489 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4490 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4492 Mask = Mask.lshr(c1 - c2);
4494 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4495 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4498 return DAG.getNode(ISD::AND, DL, VT, Shift,
4499 DAG.getConstant(Mask, DL, VT));
4503 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4504 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4505 unsigned BitSize = VT.getScalarSizeInBits();
4507 SDValue HiBitsMask =
4508 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4509 BitSize - N1C->getZExtValue()),
4511 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4515 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4516 // Variant of version done on multiply, except mul by a power of 2 is turned
4519 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4520 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4521 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4522 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4523 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4524 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4527 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4528 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4529 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4530 if (SDValue Folded =
4531 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4532 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4536 if (N1C && !N1C->isOpaque())
4537 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4543 SDValue DAGCombiner::visitSRA(SDNode *N) {
4544 SDValue N0 = N->getOperand(0);
4545 SDValue N1 = N->getOperand(1);
4546 EVT VT = N0.getValueType();
4547 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4550 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4551 if (VT.isVector()) {
4552 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4555 N1C = isConstOrConstSplat(N1);
4558 // fold (sra c1, c2) -> (sra c1, c2)
4559 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4560 if (N0C && N1C && !N1C->isOpaque())
4561 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4562 // fold (sra 0, x) -> 0
4563 if (isNullConstant(N0))
4565 // fold (sra -1, x) -> -1
4566 if (isAllOnesConstant(N0))
4568 // fold (sra x, (setge c, size(x))) -> undef
4569 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4570 return DAG.getUNDEF(VT);
4571 // fold (sra x, 0) -> x
4572 if (N1C && N1C->isNullValue())
4574 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4576 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4577 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4578 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4580 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4581 ExtVT, VT.getVectorNumElements());
4582 if ((!LegalOperations ||
4583 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4584 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4585 N0.getOperand(0), DAG.getValueType(ExtVT));
4588 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4589 if (N1C && N0.getOpcode() == ISD::SRA) {
4590 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4591 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4592 if (Sum >= OpSizeInBits)
4593 Sum = OpSizeInBits - 1;
4595 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4596 DAG.getConstant(Sum, DL, N1.getValueType()));
4600 // fold (sra (shl X, m), (sub result_size, n))
4601 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4602 // result_size - n != m.
4603 // If truncate is free for the target sext(shl) is likely to result in better
4605 if (N0.getOpcode() == ISD::SHL && N1C) {
4606 // Get the two constanst of the shifts, CN0 = m, CN = n.
4607 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4609 LLVMContext &Ctx = *DAG.getContext();
4610 // Determine what the truncate's result bitsize and type would be.
4611 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4614 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4616 // Determine the residual right-shift amount.
4617 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4619 // If the shift is not a no-op (in which case this should be just a sign
4620 // extend already), the truncated to type is legal, sign_extend is legal
4621 // on that type, and the truncate to that type is both legal and free,
4622 // perform the transform.
4623 if ((ShiftAmt > 0) &&
4624 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4625 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4626 TLI.isTruncateFree(VT, TruncVT)) {
4629 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4630 getShiftAmountTy(N0.getOperand(0).getValueType()));
4631 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4632 N0.getOperand(0), Amt);
4633 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4635 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4636 N->getValueType(0), Trunc);
4641 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4642 if (N1.getOpcode() == ISD::TRUNCATE &&
4643 N1.getOperand(0).getOpcode() == ISD::AND) {
4644 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4645 if (NewOp1.getNode())
4646 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4649 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4650 // if c1 is equal to the number of bits the trunc removes
4651 if (N0.getOpcode() == ISD::TRUNCATE &&
4652 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4653 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4654 N0.getOperand(0).hasOneUse() &&
4655 N0.getOperand(0).getOperand(1).hasOneUse() &&
4657 SDValue N0Op0 = N0.getOperand(0);
4658 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4659 unsigned LargeShiftVal = LargeShift->getZExtValue();
4660 EVT LargeVT = N0Op0.getValueType();
4662 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4665 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4666 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4667 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4668 N0Op0.getOperand(0), Amt);
4669 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4674 // Simplify, based on bits shifted out of the LHS.
4675 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4676 return SDValue(N, 0);
4679 // If the sign bit is known to be zero, switch this to a SRL.
4680 if (DAG.SignBitIsZero(N0))
4681 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4683 if (N1C && !N1C->isOpaque())
4684 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4690 SDValue DAGCombiner::visitSRL(SDNode *N) {
4691 SDValue N0 = N->getOperand(0);
4692 SDValue N1 = N->getOperand(1);
4693 EVT VT = N0.getValueType();
4694 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4697 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4698 if (VT.isVector()) {
4699 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4702 N1C = isConstOrConstSplat(N1);
4705 // fold (srl c1, c2) -> c1 >>u c2
4706 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4707 if (N0C && N1C && !N1C->isOpaque())
4708 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4709 // fold (srl 0, x) -> 0
4710 if (isNullConstant(N0))
4712 // fold (srl x, c >= size(x)) -> undef
4713 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4714 return DAG.getUNDEF(VT);
4715 // fold (srl x, 0) -> x
4716 if (N1C && N1C->isNullValue())
4718 // if (srl x, c) is known to be zero, return 0
4719 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4720 APInt::getAllOnesValue(OpSizeInBits)))
4721 return DAG.getConstant(0, SDLoc(N), VT);
4723 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4724 if (N1C && N0.getOpcode() == ISD::SRL) {
4725 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4726 uint64_t c1 = N01C->getZExtValue();
4727 uint64_t c2 = N1C->getZExtValue();
4729 if (c1 + c2 >= OpSizeInBits)
4730 return DAG.getConstant(0, DL, VT);
4731 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4732 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4736 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4737 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4738 N0.getOperand(0).getOpcode() == ISD::SRL &&
4739 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4741 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4742 uint64_t c2 = N1C->getZExtValue();
4743 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4744 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4745 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4746 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4747 if (c1 + OpSizeInBits == InnerShiftSize) {
4749 if (c1 + c2 >= InnerShiftSize)
4750 return DAG.getConstant(0, DL, VT);
4751 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4752 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4753 N0.getOperand(0)->getOperand(0),
4754 DAG.getConstant(c1 + c2, DL,
4759 // fold (srl (shl x, c), c) -> (and x, cst2)
4760 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4761 unsigned BitSize = N0.getScalarValueSizeInBits();
4762 if (BitSize <= 64) {
4763 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4765 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4766 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4770 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4771 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4772 // Shifting in all undef bits?
4773 EVT SmallVT = N0.getOperand(0).getValueType();
4774 unsigned BitSize = SmallVT.getScalarSizeInBits();
4775 if (N1C->getZExtValue() >= BitSize)
4776 return DAG.getUNDEF(VT);
4778 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4779 uint64_t ShiftAmt = N1C->getZExtValue();
4781 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4783 DAG.getConstant(ShiftAmt, DL0,
4784 getShiftAmountTy(SmallVT)));
4785 AddToWorklist(SmallShift.getNode());
4786 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4788 return DAG.getNode(ISD::AND, DL, VT,
4789 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4790 DAG.getConstant(Mask, DL, VT));
4794 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4795 // bit, which is unmodified by sra.
4796 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4797 if (N0.getOpcode() == ISD::SRA)
4798 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4801 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4802 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4803 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4804 APInt KnownZero, KnownOne;
4805 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4807 // If any of the input bits are KnownOne, then the input couldn't be all
4808 // zeros, thus the result of the srl will always be zero.
4809 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4811 // If all of the bits input the to ctlz node are known to be zero, then
4812 // the result of the ctlz is "32" and the result of the shift is one.
4813 APInt UnknownBits = ~KnownZero;
4814 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4816 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4817 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4818 // Okay, we know that only that the single bit specified by UnknownBits
4819 // could be set on input to the CTLZ node. If this bit is set, the SRL
4820 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4821 // to an SRL/XOR pair, which is likely to simplify more.
4822 unsigned ShAmt = UnknownBits.countTrailingZeros();
4823 SDValue Op = N0.getOperand(0);
4827 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4828 DAG.getConstant(ShAmt, DL,
4829 getShiftAmountTy(Op.getValueType())));
4830 AddToWorklist(Op.getNode());
4834 return DAG.getNode(ISD::XOR, DL, VT,
4835 Op, DAG.getConstant(1, DL, VT));
4839 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4840 if (N1.getOpcode() == ISD::TRUNCATE &&
4841 N1.getOperand(0).getOpcode() == ISD::AND) {
4842 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4843 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4846 // fold operands of srl based on knowledge that the low bits are not
4848 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4849 return SDValue(N, 0);
4851 if (N1C && !N1C->isOpaque())
4852 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4855 // Attempt to convert a srl of a load into a narrower zero-extending load.
4856 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4859 // Here is a common situation. We want to optimize:
4862 // %b = and i32 %a, 2
4863 // %c = srl i32 %b, 1
4864 // brcond i32 %c ...
4870 // %c = setcc eq %b, 0
4873 // However when after the source operand of SRL is optimized into AND, the SRL
4874 // itself may not be optimized further. Look for it and add the BRCOND into
4876 if (N->hasOneUse()) {
4877 SDNode *Use = *N->use_begin();
4878 if (Use->getOpcode() == ISD::BRCOND)
4880 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4881 // Also look pass the truncate.
4882 Use = *Use->use_begin();
4883 if (Use->getOpcode() == ISD::BRCOND)
4891 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4892 SDValue N0 = N->getOperand(0);
4893 EVT VT = N->getValueType(0);
4895 // fold (bswap c1) -> c2
4896 if (isConstantIntBuildVectorOrConstantInt(N0))
4897 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4898 // fold (bswap (bswap x)) -> x
4899 if (N0.getOpcode() == ISD::BSWAP)
4900 return N0->getOperand(0);
4904 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4905 SDValue N0 = N->getOperand(0);
4906 EVT VT = N->getValueType(0);
4908 // fold (ctlz c1) -> c2
4909 if (isConstantIntBuildVectorOrConstantInt(N0))
4910 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4914 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4915 SDValue N0 = N->getOperand(0);
4916 EVT VT = N->getValueType(0);
4918 // fold (ctlz_zero_undef c1) -> c2
4919 if (isConstantIntBuildVectorOrConstantInt(N0))
4920 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4924 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4925 SDValue N0 = N->getOperand(0);
4926 EVT VT = N->getValueType(0);
4928 // fold (cttz c1) -> c2
4929 if (isConstantIntBuildVectorOrConstantInt(N0))
4930 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4934 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4935 SDValue N0 = N->getOperand(0);
4936 EVT VT = N->getValueType(0);
4938 // fold (cttz_zero_undef c1) -> c2
4939 if (isConstantIntBuildVectorOrConstantInt(N0))
4940 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4944 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4945 SDValue N0 = N->getOperand(0);
4946 EVT VT = N->getValueType(0);
4948 // fold (ctpop c1) -> c2
4949 if (isConstantIntBuildVectorOrConstantInt(N0))
4950 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4955 /// \brief Generate Min/Max node
4956 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4957 SDValue True, SDValue False,
4958 ISD::CondCode CC, const TargetLowering &TLI,
4959 SelectionDAG &DAG) {
4960 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4970 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4971 if (TLI.isOperationLegal(Opcode, VT))
4972 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4981 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4982 if (TLI.isOperationLegal(Opcode, VT))
4983 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4991 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4992 SDValue N0 = N->getOperand(0);
4993 SDValue N1 = N->getOperand(1);
4994 SDValue N2 = N->getOperand(2);
4995 EVT VT = N->getValueType(0);
4996 EVT VT0 = N0.getValueType();
4998 // fold (select C, X, X) -> X
5001 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5002 // fold (select true, X, Y) -> X
5003 // fold (select false, X, Y) -> Y
5004 return !N0C->isNullValue() ? N1 : N2;
5006 // fold (select C, 1, X) -> (or C, X)
5007 if (VT == MVT::i1 && isOneConstant(N1))
5008 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5009 // fold (select C, 0, 1) -> (xor C, 1)
5010 // We can't do this reliably if integer based booleans have different contents
5011 // to floating point based booleans. This is because we can't tell whether we
5012 // have an integer-based boolean or a floating-point-based boolean unless we
5013 // can find the SETCC that produced it and inspect its operands. This is
5014 // fairly easy if C is the SETCC node, but it can potentially be
5015 // undiscoverable (or not reasonably discoverable). For example, it could be
5016 // in another basic block or it could require searching a complicated
5018 if (VT.isInteger() &&
5019 (VT0 == MVT::i1 || (VT0.isInteger() &&
5020 TLI.getBooleanContents(false, false) ==
5021 TLI.getBooleanContents(false, true) &&
5022 TLI.getBooleanContents(false, false) ==
5023 TargetLowering::ZeroOrOneBooleanContent)) &&
5024 isNullConstant(N1) && isOneConstant(N2)) {
5028 return DAG.getNode(ISD::XOR, DL, VT0,
5029 N0, DAG.getConstant(1, DL, VT0));
5032 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5033 N0, DAG.getConstant(1, DL0, VT0));
5034 AddToWorklist(XORNode.getNode());
5036 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5037 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5039 // fold (select C, 0, X) -> (and (not C), X)
5040 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5041 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5042 AddToWorklist(NOTNode.getNode());
5043 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5045 // fold (select C, X, 1) -> (or (not C), X)
5046 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5047 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5048 AddToWorklist(NOTNode.getNode());
5049 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5051 // fold (select C, X, 0) -> (and C, X)
5052 if (VT == MVT::i1 && isNullConstant(N2))
5053 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5054 // fold (select X, X, Y) -> (or X, Y)
5055 // fold (select X, 1, Y) -> (or X, Y)
5056 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5057 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5058 // fold (select X, Y, X) -> (and X, Y)
5059 // fold (select X, Y, 0) -> (and X, Y)
5060 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5061 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5063 // If we can fold this based on the true/false value, do so.
5064 if (SimplifySelectOps(N, N1, N2))
5065 return SDValue(N, 0); // Don't revisit N.
5067 if (VT0 == MVT::i1) {
5068 // The code in this block deals with the following 2 equivalences:
5069 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5070 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5071 // The target can specify its prefered form with the
5072 // shouldNormalizeToSelectSequence() callback. However we always transform
5073 // to the right anyway if we find the inner select exists in the DAG anyway
5074 // and we always transform to the left side if we know that we can further
5075 // optimize the combination of the conditions.
5076 bool normalizeToSequence
5077 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5078 // select (and Cond0, Cond1), X, Y
5079 // -> select Cond0, (select Cond1, X, Y), Y
5080 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5081 SDValue Cond0 = N0->getOperand(0);
5082 SDValue Cond1 = N0->getOperand(1);
5083 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5084 N1.getValueType(), Cond1, N1, N2);
5085 if (normalizeToSequence || !InnerSelect.use_empty())
5086 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5089 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5090 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5091 SDValue Cond0 = N0->getOperand(0);
5092 SDValue Cond1 = N0->getOperand(1);
5093 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5094 N1.getValueType(), Cond1, N1, N2);
5095 if (normalizeToSequence || !InnerSelect.use_empty())
5096 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5100 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5101 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5102 SDValue N1_0 = N1->getOperand(0);
5103 SDValue N1_1 = N1->getOperand(1);
5104 SDValue N1_2 = N1->getOperand(2);
5105 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5106 // Create the actual and node if we can generate good code for it.
5107 if (!normalizeToSequence) {
5108 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5110 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5113 // Otherwise see if we can optimize the "and" to a better pattern.
5114 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5115 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5119 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5120 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5121 SDValue N2_0 = N2->getOperand(0);
5122 SDValue N2_1 = N2->getOperand(1);
5123 SDValue N2_2 = N2->getOperand(2);
5124 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5125 // Create the actual or node if we can generate good code for it.
5126 if (!normalizeToSequence) {
5127 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5129 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5132 // Otherwise see if we can optimize to a better pattern.
5133 if (SDValue Combined = visitORLike(N0, N2_0, N))
5134 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5140 // fold selects based on a setcc into other things, such as min/max/abs
5141 if (N0.getOpcode() == ISD::SETCC) {
5142 // select x, y (fcmp lt x, y) -> fminnum x, y
5143 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5145 // This is OK if we don't care about what happens if either operand is a
5149 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5150 // no signed zeros as well as no nans.
5151 const TargetOptions &Options = DAG.getTarget().Options;
5152 if (Options.UnsafeFPMath &&
5153 VT.isFloatingPoint() && N0.hasOneUse() &&
5154 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5155 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5157 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5158 N0.getOperand(1), N1, N2, CC,
5163 if ((!LegalOperations &&
5164 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5165 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5166 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5167 N0.getOperand(0), N0.getOperand(1),
5168 N1, N2, N0.getOperand(2));
5169 return SimplifySelect(SDLoc(N), N0, N1, N2);
5176 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5179 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5181 // Split the inputs.
5182 SDValue Lo, Hi, LL, LH, RL, RH;
5183 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5184 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5186 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5187 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5189 return std::make_pair(Lo, Hi);
5192 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5193 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5194 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5196 SDValue Cond = N->getOperand(0);
5197 SDValue LHS = N->getOperand(1);
5198 SDValue RHS = N->getOperand(2);
5199 EVT VT = N->getValueType(0);
5200 int NumElems = VT.getVectorNumElements();
5201 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5202 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5203 Cond.getOpcode() == ISD::BUILD_VECTOR);
5205 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5206 // binary ones here.
5207 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5210 // We're sure we have an even number of elements due to the
5211 // concat_vectors we have as arguments to vselect.
5212 // Skip BV elements until we find one that's not an UNDEF
5213 // After we find an UNDEF element, keep looping until we get to half the
5214 // length of the BV and see if all the non-undef nodes are the same.
5215 ConstantSDNode *BottomHalf = nullptr;
5216 for (int i = 0; i < NumElems / 2; ++i) {
5217 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5220 if (BottomHalf == nullptr)
5221 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5222 else if (Cond->getOperand(i).getNode() != BottomHalf)
5226 // Do the same for the second half of the BuildVector
5227 ConstantSDNode *TopHalf = nullptr;
5228 for (int i = NumElems / 2; i < NumElems; ++i) {
5229 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5232 if (TopHalf == nullptr)
5233 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5234 else if (Cond->getOperand(i).getNode() != TopHalf)
5238 assert(TopHalf && BottomHalf &&
5239 "One half of the selector was all UNDEFs and the other was all the "
5240 "same value. This should have been addressed before this function.");
5242 ISD::CONCAT_VECTORS, dl, VT,
5243 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5244 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5247 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5249 if (Level >= AfterLegalizeTypes)
5252 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5253 SDValue Mask = MSC->getMask();
5254 SDValue Data = MSC->getValue();
5257 // If the MSCATTER data type requires splitting and the mask is provided by a
5258 // SETCC, then split both nodes and its operands before legalization. This
5259 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5260 // and enables future optimizations (e.g. min/max pattern matching on X86).
5261 if (Mask.getOpcode() != ISD::SETCC)
5264 // Check if any splitting is required.
5265 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5266 TargetLowering::TypeSplitVector)
5268 SDValue MaskLo, MaskHi, Lo, Hi;
5269 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5272 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5274 SDValue Chain = MSC->getChain();
5276 EVT MemoryVT = MSC->getMemoryVT();
5277 unsigned Alignment = MSC->getOriginalAlignment();
5279 EVT LoMemVT, HiMemVT;
5280 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5282 SDValue DataLo, DataHi;
5283 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5285 SDValue BasePtr = MSC->getBasePtr();
5286 SDValue IndexLo, IndexHi;
5287 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5289 MachineMemOperand *MMO = DAG.getMachineFunction().
5290 getMachineMemOperand(MSC->getPointerInfo(),
5291 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5292 Alignment, MSC->getAAInfo(), MSC->getRanges());
5294 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5295 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5298 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5299 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5302 AddToWorklist(Lo.getNode());
5303 AddToWorklist(Hi.getNode());
5305 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5308 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5310 if (Level >= AfterLegalizeTypes)
5313 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5314 SDValue Mask = MST->getMask();
5315 SDValue Data = MST->getValue();
5318 // If the MSTORE data type requires splitting and the mask is provided by a
5319 // SETCC, then split both nodes and its operands before legalization. This
5320 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5321 // and enables future optimizations (e.g. min/max pattern matching on X86).
5322 if (Mask.getOpcode() == ISD::SETCC) {
5324 // Check if any splitting is required.
5325 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5326 TargetLowering::TypeSplitVector)
5329 SDValue MaskLo, MaskHi, Lo, Hi;
5330 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5333 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5335 SDValue Chain = MST->getChain();
5336 SDValue Ptr = MST->getBasePtr();
5338 EVT MemoryVT = MST->getMemoryVT();
5339 unsigned Alignment = MST->getOriginalAlignment();
5341 // if Alignment is equal to the vector size,
5342 // take the half of it for the second part
5343 unsigned SecondHalfAlignment =
5344 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5345 Alignment/2 : Alignment;
5347 EVT LoMemVT, HiMemVT;
5348 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5350 SDValue DataLo, DataHi;
5351 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5353 MachineMemOperand *MMO = DAG.getMachineFunction().
5354 getMachineMemOperand(MST->getPointerInfo(),
5355 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5356 Alignment, MST->getAAInfo(), MST->getRanges());
5358 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5359 MST->isTruncatingStore());
5361 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5362 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5363 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5365 MMO = DAG.getMachineFunction().
5366 getMachineMemOperand(MST->getPointerInfo(),
5367 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5368 SecondHalfAlignment, MST->getAAInfo(),
5371 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5372 MST->isTruncatingStore());
5374 AddToWorklist(Lo.getNode());
5375 AddToWorklist(Hi.getNode());
5377 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5382 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5384 if (Level >= AfterLegalizeTypes)
5387 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5388 SDValue Mask = MGT->getMask();
5391 // If the MGATHER result requires splitting and the mask is provided by a
5392 // SETCC, then split both nodes and its operands before legalization. This
5393 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5394 // and enables future optimizations (e.g. min/max pattern matching on X86).
5396 if (Mask.getOpcode() != ISD::SETCC)
5399 EVT VT = N->getValueType(0);
5401 // Check if any splitting is required.
5402 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5403 TargetLowering::TypeSplitVector)
5406 SDValue MaskLo, MaskHi, Lo, Hi;
5407 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5409 SDValue Src0 = MGT->getValue();
5410 SDValue Src0Lo, Src0Hi;
5411 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5414 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5416 SDValue Chain = MGT->getChain();
5417 EVT MemoryVT = MGT->getMemoryVT();
5418 unsigned Alignment = MGT->getOriginalAlignment();
5420 EVT LoMemVT, HiMemVT;
5421 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5423 SDValue BasePtr = MGT->getBasePtr();
5424 SDValue Index = MGT->getIndex();
5425 SDValue IndexLo, IndexHi;
5426 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5428 MachineMemOperand *MMO = DAG.getMachineFunction().
5429 getMachineMemOperand(MGT->getPointerInfo(),
5430 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5431 Alignment, MGT->getAAInfo(), MGT->getRanges());
5433 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5434 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5437 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5438 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5441 AddToWorklist(Lo.getNode());
5442 AddToWorklist(Hi.getNode());
5444 // Build a factor node to remember that this load is independent of the
5446 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5449 // Legalized the chain result - switch anything that used the old chain to
5451 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5453 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5455 SDValue RetOps[] = { GatherRes, Chain };
5456 return DAG.getMergeValues(RetOps, DL);
5459 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5461 if (Level >= AfterLegalizeTypes)
5464 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5465 SDValue Mask = MLD->getMask();
5468 // If the MLOAD result requires splitting and the mask is provided by a
5469 // SETCC, then split both nodes and its operands before legalization. This
5470 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5471 // and enables future optimizations (e.g. min/max pattern matching on X86).
5473 if (Mask.getOpcode() == ISD::SETCC) {
5474 EVT VT = N->getValueType(0);
5476 // Check if any splitting is required.
5477 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5478 TargetLowering::TypeSplitVector)
5481 SDValue MaskLo, MaskHi, Lo, Hi;
5482 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5484 SDValue Src0 = MLD->getSrc0();
5485 SDValue Src0Lo, Src0Hi;
5486 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5489 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5491 SDValue Chain = MLD->getChain();
5492 SDValue Ptr = MLD->getBasePtr();
5493 EVT MemoryVT = MLD->getMemoryVT();
5494 unsigned Alignment = MLD->getOriginalAlignment();
5496 // if Alignment is equal to the vector size,
5497 // take the half of it for the second part
5498 unsigned SecondHalfAlignment =
5499 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5500 Alignment/2 : Alignment;
5502 EVT LoMemVT, HiMemVT;
5503 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5505 MachineMemOperand *MMO = DAG.getMachineFunction().
5506 getMachineMemOperand(MLD->getPointerInfo(),
5507 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5508 Alignment, MLD->getAAInfo(), MLD->getRanges());
5510 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5513 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5514 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5515 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5517 MMO = DAG.getMachineFunction().
5518 getMachineMemOperand(MLD->getPointerInfo(),
5519 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5520 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5522 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5525 AddToWorklist(Lo.getNode());
5526 AddToWorklist(Hi.getNode());
5528 // Build a factor node to remember that this load is independent of the
5530 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5533 // Legalized the chain result - switch anything that used the old chain to
5535 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5537 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5539 SDValue RetOps[] = { LoadRes, Chain };
5540 return DAG.getMergeValues(RetOps, DL);
5545 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5546 SDValue N0 = N->getOperand(0);
5547 SDValue N1 = N->getOperand(1);
5548 SDValue N2 = N->getOperand(2);
5551 // Canonicalize integer abs.
5552 // vselect (setg[te] X, 0), X, -X ->
5553 // vselect (setgt X, -1), X, -X ->
5554 // vselect (setl[te] X, 0), -X, X ->
5555 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5556 if (N0.getOpcode() == ISD::SETCC) {
5557 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5558 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5560 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5562 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5563 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5564 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5565 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5566 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5567 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5568 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5571 EVT VT = LHS.getValueType();
5572 SDValue Shift = DAG.getNode(
5573 ISD::SRA, DL, VT, LHS,
5574 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5575 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5576 AddToWorklist(Shift.getNode());
5577 AddToWorklist(Add.getNode());
5578 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5582 if (SimplifySelectOps(N, N1, N2))
5583 return SDValue(N, 0); // Don't revisit N.
5585 // If the VSELECT result requires splitting and the mask is provided by a
5586 // SETCC, then split both nodes and its operands before legalization. This
5587 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5588 // and enables future optimizations (e.g. min/max pattern matching on X86).
5589 if (N0.getOpcode() == ISD::SETCC) {
5590 EVT VT = N->getValueType(0);
5592 // Check if any splitting is required.
5593 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5594 TargetLowering::TypeSplitVector)
5597 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5598 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5599 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5600 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5602 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5603 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5605 // Add the new VSELECT nodes to the work list in case they need to be split
5607 AddToWorklist(Lo.getNode());
5608 AddToWorklist(Hi.getNode());
5610 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5613 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5614 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5616 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5617 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5620 // The ConvertSelectToConcatVector function is assuming both the above
5621 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5623 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5624 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5625 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5626 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5633 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5634 SDValue N0 = N->getOperand(0);
5635 SDValue N1 = N->getOperand(1);
5636 SDValue N2 = N->getOperand(2);
5637 SDValue N3 = N->getOperand(3);
5638 SDValue N4 = N->getOperand(4);
5639 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5641 // fold select_cc lhs, rhs, x, x, cc -> x
5645 // Determine if the condition we're dealing with is constant
5646 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5647 N0, N1, CC, SDLoc(N), false);
5648 if (SCC.getNode()) {
5649 AddToWorklist(SCC.getNode());
5651 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5652 if (!SCCC->isNullValue())
5653 return N2; // cond always true -> true val
5655 return N3; // cond always false -> false val
5656 } else if (SCC->getOpcode() == ISD::UNDEF) {
5657 // When the condition is UNDEF, just return the first operand. This is
5658 // coherent the DAG creation, no setcc node is created in this case
5660 } else if (SCC.getOpcode() == ISD::SETCC) {
5661 // Fold to a simpler select_cc
5662 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5663 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5668 // If we can fold this based on the true/false value, do so.
5669 if (SimplifySelectOps(N, N2, N3))
5670 return SDValue(N, 0); // Don't revisit N.
5672 // fold select_cc into other things, such as min/max/abs
5673 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5676 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5677 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5678 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5682 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5683 /// a build_vector of constants.
5684 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5685 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5686 /// Vector extends are not folded if operations are legal; this is to
5687 /// avoid introducing illegal build_vector dag nodes.
5688 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5689 SelectionDAG &DAG, bool LegalTypes,
5690 bool LegalOperations) {
5691 unsigned Opcode = N->getOpcode();
5692 SDValue N0 = N->getOperand(0);
5693 EVT VT = N->getValueType(0);
5695 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5696 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5697 && "Expected EXTEND dag node in input!");
5699 // fold (sext c1) -> c1
5700 // fold (zext c1) -> c1
5701 // fold (aext c1) -> c1
5702 if (isa<ConstantSDNode>(N0))
5703 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5705 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5706 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5707 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5708 EVT SVT = VT.getScalarType();
5709 if (!(VT.isVector() &&
5710 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5711 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5714 // We can fold this node into a build_vector.
5715 unsigned VTBits = SVT.getSizeInBits();
5716 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5717 SmallVector<SDValue, 8> Elts;
5718 unsigned NumElts = VT.getVectorNumElements();
5721 for (unsigned i=0; i != NumElts; ++i) {
5722 SDValue Op = N0->getOperand(i);
5723 if (Op->getOpcode() == ISD::UNDEF) {
5724 Elts.push_back(DAG.getUNDEF(SVT));
5729 // Get the constant value and if needed trunc it to the size of the type.
5730 // Nodes like build_vector might have constants wider than the scalar type.
5731 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5732 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5733 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5735 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5738 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5741 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5742 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5743 // transformation. Returns true if extension are possible and the above
5744 // mentioned transformation is profitable.
5745 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5747 SmallVectorImpl<SDNode *> &ExtendNodes,
5748 const TargetLowering &TLI) {
5749 bool HasCopyToRegUses = false;
5750 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5751 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5752 UE = N0.getNode()->use_end();
5757 if (UI.getUse().getResNo() != N0.getResNo())
5759 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5760 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5761 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5762 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5763 // Sign bits will be lost after a zext.
5766 for (unsigned i = 0; i != 2; ++i) {
5767 SDValue UseOp = User->getOperand(i);
5770 if (!isa<ConstantSDNode>(UseOp))
5775 ExtendNodes.push_back(User);
5778 // If truncates aren't free and there are users we can't
5779 // extend, it isn't worthwhile.
5782 // Remember if this value is live-out.
5783 if (User->getOpcode() == ISD::CopyToReg)
5784 HasCopyToRegUses = true;
5787 if (HasCopyToRegUses) {
5788 bool BothLiveOut = false;
5789 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5791 SDUse &Use = UI.getUse();
5792 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5798 // Both unextended and extended values are live out. There had better be
5799 // a good reason for the transformation.
5800 return ExtendNodes.size();
5805 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5806 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5807 ISD::NodeType ExtType) {
5808 // Extend SetCC uses if necessary.
5809 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5810 SDNode *SetCC = SetCCs[i];
5811 SmallVector<SDValue, 4> Ops;
5813 for (unsigned j = 0; j != 2; ++j) {
5814 SDValue SOp = SetCC->getOperand(j);
5816 Ops.push_back(ExtLoad);
5818 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5821 Ops.push_back(SetCC->getOperand(2));
5822 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5826 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5827 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5828 SDValue N0 = N->getOperand(0);
5829 EVT DstVT = N->getValueType(0);
5830 EVT SrcVT = N0.getValueType();
5832 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5833 N->getOpcode() == ISD::ZERO_EXTEND) &&
5834 "Unexpected node type (not an extend)!");
5836 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5837 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5838 // (v8i32 (sext (v8i16 (load x))))
5840 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5841 // (v4i32 (sextload (x + 16)))))
5842 // Where uses of the original load, i.e.:
5844 // are replaced with:
5846 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5847 // (v4i32 (sextload (x + 16)))))))
5849 // This combine is only applicable to illegal, but splittable, vectors.
5850 // All legal types, and illegal non-vector types, are handled elsewhere.
5851 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5853 if (N0->getOpcode() != ISD::LOAD)
5856 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5858 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5859 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5860 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5863 SmallVector<SDNode *, 4> SetCCs;
5864 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5867 ISD::LoadExtType ExtType =
5868 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5870 // Try to split the vector types to get down to legal types.
5871 EVT SplitSrcVT = SrcVT;
5872 EVT SplitDstVT = DstVT;
5873 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5874 SplitSrcVT.getVectorNumElements() > 1) {
5875 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5876 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5879 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5883 const unsigned NumSplits =
5884 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5885 const unsigned Stride = SplitSrcVT.getStoreSize();
5886 SmallVector<SDValue, 4> Loads;
5887 SmallVector<SDValue, 4> Chains;
5889 SDValue BasePtr = LN0->getBasePtr();
5890 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5891 const unsigned Offset = Idx * Stride;
5892 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5894 SDValue SplitLoad = DAG.getExtLoad(
5895 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5896 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5897 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5898 Align, LN0->getAAInfo());
5900 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5901 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5903 Loads.push_back(SplitLoad.getValue(0));
5904 Chains.push_back(SplitLoad.getValue(1));
5907 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5908 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5910 CombineTo(N, NewValue);
5912 // Replace uses of the original load (before extension)
5913 // with a truncate of the concatenated sextloaded vectors.
5915 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5916 CombineTo(N0.getNode(), Trunc, NewChain);
5917 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5918 (ISD::NodeType)N->getOpcode());
5919 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5922 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5923 SDValue N0 = N->getOperand(0);
5924 EVT VT = N->getValueType(0);
5926 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5928 return SDValue(Res, 0);
5930 // fold (sext (sext x)) -> (sext x)
5931 // fold (sext (aext x)) -> (sext x)
5932 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5933 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5936 if (N0.getOpcode() == ISD::TRUNCATE) {
5937 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5938 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5939 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5940 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5941 if (NarrowLoad.getNode() != N0.getNode()) {
5942 CombineTo(N0.getNode(), NarrowLoad);
5943 // CombineTo deleted the truncate, if needed, but not what's under it.
5946 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5949 // See if the value being truncated is already sign extended. If so, just
5950 // eliminate the trunc/sext pair.
5951 SDValue Op = N0.getOperand(0);
5952 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5953 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5954 unsigned DestBits = VT.getScalarType().getSizeInBits();
5955 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5957 if (OpBits == DestBits) {
5958 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5959 // bits, it is already ready.
5960 if (NumSignBits > DestBits-MidBits)
5962 } else if (OpBits < DestBits) {
5963 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5964 // bits, just sext from i32.
5965 if (NumSignBits > OpBits-MidBits)
5966 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5968 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5969 // bits, just truncate to i32.
5970 if (NumSignBits > OpBits-MidBits)
5971 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5974 // fold (sext (truncate x)) -> (sextinreg x).
5975 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5976 N0.getValueType())) {
5977 if (OpBits < DestBits)
5978 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5979 else if (OpBits > DestBits)
5980 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5981 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5982 DAG.getValueType(N0.getValueType()));
5986 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5987 // Only generate vector extloads when 1) they're legal, and 2) they are
5988 // deemed desirable by the target.
5989 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5990 ((!LegalOperations && !VT.isVector() &&
5991 !cast<LoadSDNode>(N0)->isVolatile()) ||
5992 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5993 bool DoXform = true;
5994 SmallVector<SDNode*, 4> SetCCs;
5995 if (!N0.hasOneUse())
5996 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5998 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6000 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6001 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6003 LN0->getBasePtr(), N0.getValueType(),
6004 LN0->getMemOperand());
6005 CombineTo(N, ExtLoad);
6006 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6007 N0.getValueType(), ExtLoad);
6008 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6009 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6011 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6015 // fold (sext (load x)) to multiple smaller sextloads.
6016 // Only on illegal but splittable vectors.
6017 if (SDValue ExtLoad = CombineExtLoad(N))
6020 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6021 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6022 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6023 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6024 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6025 EVT MemVT = LN0->getMemoryVT();
6026 if ((!LegalOperations && !LN0->isVolatile()) ||
6027 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6028 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6030 LN0->getBasePtr(), MemVT,
6031 LN0->getMemOperand());
6032 CombineTo(N, ExtLoad);
6033 CombineTo(N0.getNode(),
6034 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6035 N0.getValueType(), ExtLoad),
6036 ExtLoad.getValue(1));
6037 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6041 // fold (sext (and/or/xor (load x), cst)) ->
6042 // (and/or/xor (sextload x), (sext cst))
6043 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6044 N0.getOpcode() == ISD::XOR) &&
6045 isa<LoadSDNode>(N0.getOperand(0)) &&
6046 N0.getOperand(1).getOpcode() == ISD::Constant &&
6047 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6048 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6049 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6050 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6051 bool DoXform = true;
6052 SmallVector<SDNode*, 4> SetCCs;
6053 if (!N0.hasOneUse())
6054 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6057 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6058 LN0->getChain(), LN0->getBasePtr(),
6060 LN0->getMemOperand());
6061 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6062 Mask = Mask.sext(VT.getSizeInBits());
6064 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6065 ExtLoad, DAG.getConstant(Mask, DL, VT));
6066 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6067 SDLoc(N0.getOperand(0)),
6068 N0.getOperand(0).getValueType(), ExtLoad);
6070 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6071 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6073 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6078 if (N0.getOpcode() == ISD::SETCC) {
6079 EVT N0VT = N0.getOperand(0).getValueType();
6080 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6081 // Only do this before legalize for now.
6082 if (VT.isVector() && !LegalOperations &&
6083 TLI.getBooleanContents(N0VT) ==
6084 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6085 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6086 // of the same size as the compared operands. Only optimize sext(setcc())
6087 // if this is the case.
6088 EVT SVT = getSetCCResultType(N0VT);
6090 // We know that the # elements of the results is the same as the
6091 // # elements of the compare (and the # elements of the compare result
6092 // for that matter). Check to see that they are the same size. If so,
6093 // we know that the element size of the sext'd result matches the
6094 // element size of the compare operands.
6095 if (VT.getSizeInBits() == SVT.getSizeInBits())
6096 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6098 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6100 // If the desired elements are smaller or larger than the source
6101 // elements we can use a matching integer vector type and then
6102 // truncate/sign extend
6103 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6104 if (SVT == MatchingVectorType) {
6105 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6106 N0.getOperand(0), N0.getOperand(1),
6107 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6108 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6112 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6113 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6116 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6118 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6119 NegOne, DAG.getConstant(0, DL, VT),
6120 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6121 if (SCC.getNode()) return SCC;
6123 if (!VT.isVector()) {
6124 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6125 if (!LegalOperations ||
6126 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6128 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6129 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6130 N0.getOperand(0), N0.getOperand(1), CC);
6131 return DAG.getSelect(DL, VT, SetCC,
6132 NegOne, DAG.getConstant(0, DL, VT));
6137 // fold (sext x) -> (zext x) if the sign bit is known zero.
6138 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6139 DAG.SignBitIsZero(N0))
6140 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6145 // isTruncateOf - If N is a truncate of some other value, return true, record
6146 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6147 // This function computes KnownZero to avoid a duplicated call to
6148 // computeKnownBits in the caller.
6149 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6152 if (N->getOpcode() == ISD::TRUNCATE) {
6153 Op = N->getOperand(0);
6154 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6158 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6159 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6162 SDValue Op0 = N->getOperand(0);
6163 SDValue Op1 = N->getOperand(1);
6164 assert(Op0.getValueType() == Op1.getValueType());
6166 if (isNullConstant(Op0))
6168 else if (isNullConstant(Op1))
6173 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6175 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6181 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6182 SDValue N0 = N->getOperand(0);
6183 EVT VT = N->getValueType(0);
6185 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6187 return SDValue(Res, 0);
6189 // fold (zext (zext x)) -> (zext x)
6190 // fold (zext (aext x)) -> (zext x)
6191 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6192 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6195 // fold (zext (truncate x)) -> (zext x) or
6196 // (zext (truncate x)) -> (truncate x)
6197 // This is valid when the truncated bits of x are already zero.
6198 // FIXME: We should extend this to work for vectors too.
6201 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6202 APInt TruncatedBits =
6203 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6204 APInt(Op.getValueSizeInBits(), 0) :
6205 APInt::getBitsSet(Op.getValueSizeInBits(),
6206 N0.getValueSizeInBits(),
6207 std::min(Op.getValueSizeInBits(),
6208 VT.getSizeInBits()));
6209 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6210 if (VT.bitsGT(Op.getValueType()))
6211 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6212 if (VT.bitsLT(Op.getValueType()))
6213 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6219 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6220 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6221 if (N0.getOpcode() == ISD::TRUNCATE) {
6222 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6223 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6224 if (NarrowLoad.getNode() != N0.getNode()) {
6225 CombineTo(N0.getNode(), NarrowLoad);
6226 // CombineTo deleted the truncate, if needed, but not what's under it.
6229 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6233 // fold (zext (truncate x)) -> (and x, mask)
6234 if (N0.getOpcode() == ISD::TRUNCATE) {
6235 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6236 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6237 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6238 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6239 if (NarrowLoad.getNode() != N0.getNode()) {
6240 CombineTo(N0.getNode(), NarrowLoad);
6241 // CombineTo deleted the truncate, if needed, but not what's under it.
6244 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6247 EVT SrcVT = N0.getOperand(0).getValueType();
6248 EVT MinVT = N0.getValueType();
6250 // Try to mask before the extension to avoid having to generate a larger mask,
6251 // possibly over several sub-vectors.
6252 if (SrcVT.bitsLT(VT)) {
6253 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6254 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6255 SDValue Op = N0.getOperand(0);
6256 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6257 AddToWorklist(Op.getNode());
6258 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6262 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6263 SDValue Op = N0.getOperand(0);
6264 if (SrcVT.bitsLT(VT)) {
6265 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6266 AddToWorklist(Op.getNode());
6267 } else if (SrcVT.bitsGT(VT)) {
6268 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6269 AddToWorklist(Op.getNode());
6271 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6275 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6276 // if either of the casts is not free.
6277 if (N0.getOpcode() == ISD::AND &&
6278 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6279 N0.getOperand(1).getOpcode() == ISD::Constant &&
6280 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6281 N0.getValueType()) ||
6282 !TLI.isZExtFree(N0.getValueType(), VT))) {
6283 SDValue X = N0.getOperand(0).getOperand(0);
6284 if (X.getValueType().bitsLT(VT)) {
6285 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6286 } else if (X.getValueType().bitsGT(VT)) {
6287 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6289 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6290 Mask = Mask.zext(VT.getSizeInBits());
6292 return DAG.getNode(ISD::AND, DL, VT,
6293 X, DAG.getConstant(Mask, DL, VT));
6296 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6297 // Only generate vector extloads when 1) they're legal, and 2) they are
6298 // deemed desirable by the target.
6299 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6300 ((!LegalOperations && !VT.isVector() &&
6301 !cast<LoadSDNode>(N0)->isVolatile()) ||
6302 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6303 bool DoXform = true;
6304 SmallVector<SDNode*, 4> SetCCs;
6305 if (!N0.hasOneUse())
6306 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6308 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6310 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6311 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6313 LN0->getBasePtr(), N0.getValueType(),
6314 LN0->getMemOperand());
6315 CombineTo(N, ExtLoad);
6316 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6317 N0.getValueType(), ExtLoad);
6318 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6320 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6322 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6326 // fold (zext (load x)) to multiple smaller zextloads.
6327 // Only on illegal but splittable vectors.
6328 if (SDValue ExtLoad = CombineExtLoad(N))
6331 // fold (zext (and/or/xor (load x), cst)) ->
6332 // (and/or/xor (zextload x), (zext cst))
6333 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6334 N0.getOpcode() == ISD::XOR) &&
6335 isa<LoadSDNode>(N0.getOperand(0)) &&
6336 N0.getOperand(1).getOpcode() == ISD::Constant &&
6337 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6338 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6339 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6340 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6341 bool DoXform = true;
6342 SmallVector<SDNode*, 4> SetCCs;
6343 if (!N0.hasOneUse())
6344 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6347 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6348 LN0->getChain(), LN0->getBasePtr(),
6350 LN0->getMemOperand());
6351 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6352 Mask = Mask.zext(VT.getSizeInBits());
6354 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6355 ExtLoad, DAG.getConstant(Mask, DL, VT));
6356 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6357 SDLoc(N0.getOperand(0)),
6358 N0.getOperand(0).getValueType(), ExtLoad);
6360 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6361 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6363 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6368 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6369 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6370 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6371 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6372 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6373 EVT MemVT = LN0->getMemoryVT();
6374 if ((!LegalOperations && !LN0->isVolatile()) ||
6375 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6376 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6378 LN0->getBasePtr(), MemVT,
6379 LN0->getMemOperand());
6380 CombineTo(N, ExtLoad);
6381 CombineTo(N0.getNode(),
6382 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6384 ExtLoad.getValue(1));
6385 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6389 if (N0.getOpcode() == ISD::SETCC) {
6390 if (!LegalOperations && VT.isVector() &&
6391 N0.getValueType().getVectorElementType() == MVT::i1) {
6392 EVT N0VT = N0.getOperand(0).getValueType();
6393 if (getSetCCResultType(N0VT) == N0.getValueType())
6396 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6397 // Only do this before legalize for now.
6398 EVT EltVT = VT.getVectorElementType();
6400 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6401 DAG.getConstant(1, DL, EltVT));
6402 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6403 // We know that the # elements of the results is the same as the
6404 // # elements of the compare (and the # elements of the compare result
6405 // for that matter). Check to see that they are the same size. If so,
6406 // we know that the element size of the sext'd result matches the
6407 // element size of the compare operands.
6408 return DAG.getNode(ISD::AND, DL, VT,
6409 DAG.getSetCC(DL, VT, N0.getOperand(0),
6411 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6412 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6415 // If the desired elements are smaller or larger than the source
6416 // elements we can use a matching integer vector type and then
6417 // truncate/sign extend
6418 EVT MatchingElementType =
6419 EVT::getIntegerVT(*DAG.getContext(),
6420 N0VT.getScalarType().getSizeInBits());
6421 EVT MatchingVectorType =
6422 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6423 N0VT.getVectorNumElements());
6425 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6427 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6428 return DAG.getNode(ISD::AND, DL, VT,
6429 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6430 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6433 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6436 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6437 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6438 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6439 if (SCC.getNode()) return SCC;
6442 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6443 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6444 isa<ConstantSDNode>(N0.getOperand(1)) &&
6445 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6447 SDValue ShAmt = N0.getOperand(1);
6448 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6449 if (N0.getOpcode() == ISD::SHL) {
6450 SDValue InnerZExt = N0.getOperand(0);
6451 // If the original shl may be shifting out bits, do not perform this
6453 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6454 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6455 if (ShAmtVal > KnownZeroBits)
6461 // Ensure that the shift amount is wide enough for the shifted value.
6462 if (VT.getSizeInBits() >= 256)
6463 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6465 return DAG.getNode(N0.getOpcode(), DL, VT,
6466 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6473 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6474 SDValue N0 = N->getOperand(0);
6475 EVT VT = N->getValueType(0);
6477 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6479 return SDValue(Res, 0);
6481 // fold (aext (aext x)) -> (aext x)
6482 // fold (aext (zext x)) -> (zext x)
6483 // fold (aext (sext x)) -> (sext x)
6484 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6485 N0.getOpcode() == ISD::ZERO_EXTEND ||
6486 N0.getOpcode() == ISD::SIGN_EXTEND)
6487 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6489 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6490 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6491 if (N0.getOpcode() == ISD::TRUNCATE) {
6492 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6493 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6494 if (NarrowLoad.getNode() != N0.getNode()) {
6495 CombineTo(N0.getNode(), NarrowLoad);
6496 // CombineTo deleted the truncate, if needed, but not what's under it.
6499 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6503 // fold (aext (truncate x))
6504 if (N0.getOpcode() == ISD::TRUNCATE) {
6505 SDValue TruncOp = N0.getOperand(0);
6506 if (TruncOp.getValueType() == VT)
6507 return TruncOp; // x iff x size == zext size.
6508 if (TruncOp.getValueType().bitsGT(VT))
6509 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6510 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6513 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6514 // if the trunc is not free.
6515 if (N0.getOpcode() == ISD::AND &&
6516 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6517 N0.getOperand(1).getOpcode() == ISD::Constant &&
6518 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6519 N0.getValueType())) {
6520 SDValue X = N0.getOperand(0).getOperand(0);
6521 if (X.getValueType().bitsLT(VT)) {
6522 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6523 } else if (X.getValueType().bitsGT(VT)) {
6524 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6526 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6527 Mask = Mask.zext(VT.getSizeInBits());
6529 return DAG.getNode(ISD::AND, DL, VT,
6530 X, DAG.getConstant(Mask, DL, VT));
6533 // fold (aext (load x)) -> (aext (truncate (extload x)))
6534 // None of the supported targets knows how to perform load and any_ext
6535 // on vectors in one instruction. We only perform this transformation on
6537 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6538 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6539 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6540 bool DoXform = true;
6541 SmallVector<SDNode*, 4> SetCCs;
6542 if (!N0.hasOneUse())
6543 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6545 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6546 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6548 LN0->getBasePtr(), N0.getValueType(),
6549 LN0->getMemOperand());
6550 CombineTo(N, ExtLoad);
6551 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6552 N0.getValueType(), ExtLoad);
6553 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6554 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6556 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6560 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6561 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6562 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6563 if (N0.getOpcode() == ISD::LOAD &&
6564 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6566 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6567 ISD::LoadExtType ExtType = LN0->getExtensionType();
6568 EVT MemVT = LN0->getMemoryVT();
6569 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6570 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6571 VT, LN0->getChain(), LN0->getBasePtr(),
6572 MemVT, LN0->getMemOperand());
6573 CombineTo(N, ExtLoad);
6574 CombineTo(N0.getNode(),
6575 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6576 N0.getValueType(), ExtLoad),
6577 ExtLoad.getValue(1));
6578 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6582 if (N0.getOpcode() == ISD::SETCC) {
6584 // aext(setcc) -> vsetcc
6585 // aext(setcc) -> truncate(vsetcc)
6586 // aext(setcc) -> aext(vsetcc)
6587 // Only do this before legalize for now.
6588 if (VT.isVector() && !LegalOperations) {
6589 EVT N0VT = N0.getOperand(0).getValueType();
6590 // We know that the # elements of the results is the same as the
6591 // # elements of the compare (and the # elements of the compare result
6592 // for that matter). Check to see that they are the same size. If so,
6593 // we know that the element size of the sext'd result matches the
6594 // element size of the compare operands.
6595 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6596 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6598 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6599 // If the desired elements are smaller or larger than the source
6600 // elements we can use a matching integer vector type and then
6601 // truncate/any extend
6603 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6605 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6607 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6608 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6612 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6615 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6616 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6617 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6625 /// See if the specified operand can be simplified with the knowledge that only
6626 /// the bits specified by Mask are used. If so, return the simpler operand,
6627 /// otherwise return a null SDValue.
6628 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6629 switch (V.getOpcode()) {
6631 case ISD::Constant: {
6632 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6633 assert(CV && "Const value should be ConstSDNode.");
6634 const APInt &CVal = CV->getAPIntValue();
6635 APInt NewVal = CVal & Mask;
6637 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6642 // If the LHS or RHS don't contribute bits to the or, drop them.
6643 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6644 return V.getOperand(1);
6645 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6646 return V.getOperand(0);
6649 // Only look at single-use SRLs.
6650 if (!V.getNode()->hasOneUse())
6652 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6653 // See if we can recursively simplify the LHS.
6654 unsigned Amt = RHSC->getZExtValue();
6656 // Watch out for shift count overflow though.
6657 if (Amt >= Mask.getBitWidth()) break;
6658 APInt NewMask = Mask << Amt;
6659 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6660 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6661 SimplifyLHS, V.getOperand(1));
6667 /// If the result of a wider load is shifted to right of N bits and then
6668 /// truncated to a narrower type and where N is a multiple of number of bits of
6669 /// the narrower type, transform it to a narrower load from address + N / num of
6670 /// bits of new type. If the result is to be extended, also fold the extension
6671 /// to form a extending load.
6672 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6673 unsigned Opc = N->getOpcode();
6675 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6676 SDValue N0 = N->getOperand(0);
6677 EVT VT = N->getValueType(0);
6680 // This transformation isn't valid for vector loads.
6684 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6686 if (Opc == ISD::SIGN_EXTEND_INREG) {
6687 ExtType = ISD::SEXTLOAD;
6688 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6689 } else if (Opc == ISD::SRL) {
6690 // Another special-case: SRL is basically zero-extending a narrower value.
6691 ExtType = ISD::ZEXTLOAD;
6693 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6694 if (!N01) return SDValue();
6695 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6696 VT.getSizeInBits() - N01->getZExtValue());
6698 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6701 unsigned EVTBits = ExtVT.getSizeInBits();
6703 // Do not generate loads of non-round integer types since these can
6704 // be expensive (and would be wrong if the type is not byte sized).
6705 if (!ExtVT.isRound())
6709 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6710 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6711 ShAmt = N01->getZExtValue();
6712 // Is the shift amount a multiple of size of VT?
6713 if ((ShAmt & (EVTBits-1)) == 0) {
6714 N0 = N0.getOperand(0);
6715 // Is the load width a multiple of size of VT?
6716 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6720 // At this point, we must have a load or else we can't do the transform.
6721 if (!isa<LoadSDNode>(N0)) return SDValue();
6723 // Because a SRL must be assumed to *need* to zero-extend the high bits
6724 // (as opposed to anyext the high bits), we can't combine the zextload
6725 // lowering of SRL and an sextload.
6726 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6729 // If the shift amount is larger than the input type then we're not
6730 // accessing any of the loaded bytes. If the load was a zextload/extload
6731 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6732 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6737 // If the load is shifted left (and the result isn't shifted back right),
6738 // we can fold the truncate through the shift.
6739 unsigned ShLeftAmt = 0;
6740 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6741 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6742 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6743 ShLeftAmt = N01->getZExtValue();
6744 N0 = N0.getOperand(0);
6748 // If we haven't found a load, we can't narrow it. Don't transform one with
6749 // multiple uses, this would require adding a new load.
6750 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6753 // Don't change the width of a volatile load.
6754 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6755 if (LN0->isVolatile())
6758 // Verify that we are actually reducing a load width here.
6759 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6762 // For the transform to be legal, the load must produce only two values
6763 // (the value loaded and the chain). Don't transform a pre-increment
6764 // load, for example, which produces an extra value. Otherwise the
6765 // transformation is not equivalent, and the downstream logic to replace
6766 // uses gets things wrong.
6767 if (LN0->getNumValues() > 2)
6770 // If the load that we're shrinking is an extload and we're not just
6771 // discarding the extension we can't simply shrink the load. Bail.
6772 // TODO: It would be possible to merge the extensions in some cases.
6773 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6774 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6777 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6780 EVT PtrType = N0.getOperand(1).getValueType();
6782 if (PtrType == MVT::Untyped || PtrType.isExtended())
6783 // It's not possible to generate a constant of extended or untyped type.
6786 // For big endian targets, we need to adjust the offset to the pointer to
6787 // load the correct bytes.
6788 if (DAG.getDataLayout().isBigEndian()) {
6789 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6790 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6791 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6794 uint64_t PtrOff = ShAmt / 8;
6795 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6797 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6798 PtrType, LN0->getBasePtr(),
6799 DAG.getConstant(PtrOff, DL, PtrType));
6800 AddToWorklist(NewPtr.getNode());
6803 if (ExtType == ISD::NON_EXTLOAD)
6804 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6805 LN0->getPointerInfo().getWithOffset(PtrOff),
6806 LN0->isVolatile(), LN0->isNonTemporal(),
6807 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6809 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6810 LN0->getPointerInfo().getWithOffset(PtrOff),
6811 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6812 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6814 // Replace the old load's chain with the new load's chain.
6815 WorklistRemover DeadNodes(*this);
6816 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6818 // Shift the result left, if we've swallowed a left shift.
6819 SDValue Result = Load;
6820 if (ShLeftAmt != 0) {
6821 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6822 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6824 // If the shift amount is as large as the result size (but, presumably,
6825 // no larger than the source) then the useful bits of the result are
6826 // zero; we can't simply return the shortened shift, because the result
6827 // of that operation is undefined.
6829 if (ShLeftAmt >= VT.getSizeInBits())
6830 Result = DAG.getConstant(0, DL, VT);
6832 Result = DAG.getNode(ISD::SHL, DL, VT,
6833 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6836 // Return the new loaded value.
6840 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6841 SDValue N0 = N->getOperand(0);
6842 SDValue N1 = N->getOperand(1);
6843 EVT VT = N->getValueType(0);
6844 EVT EVT = cast<VTSDNode>(N1)->getVT();
6845 unsigned VTBits = VT.getScalarType().getSizeInBits();
6846 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6849 return DAG.getUNDEF(VT);
6851 // fold (sext_in_reg c1) -> c1
6852 if (isConstantIntBuildVectorOrConstantInt(N0))
6853 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6855 // If the input is already sign extended, just drop the extension.
6856 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6859 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6860 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6861 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6862 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6863 N0.getOperand(0), N1);
6865 // fold (sext_in_reg (sext x)) -> (sext x)
6866 // fold (sext_in_reg (aext x)) -> (sext x)
6867 // if x is small enough.
6868 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6869 SDValue N00 = N0.getOperand(0);
6870 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6871 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6872 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6875 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6876 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6877 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6879 // fold operands of sext_in_reg based on knowledge that the top bits are not
6881 if (SimplifyDemandedBits(SDValue(N, 0)))
6882 return SDValue(N, 0);
6884 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6885 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6886 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6889 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6890 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6891 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6892 if (N0.getOpcode() == ISD::SRL) {
6893 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6894 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6895 // We can turn this into an SRA iff the input to the SRL is already sign
6897 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6898 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6899 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6900 N0.getOperand(0), N0.getOperand(1));
6904 // fold (sext_inreg (extload x)) -> (sextload x)
6905 if (ISD::isEXTLoad(N0.getNode()) &&
6906 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6907 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6908 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6909 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6910 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6911 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6913 LN0->getBasePtr(), EVT,
6914 LN0->getMemOperand());
6915 CombineTo(N, ExtLoad);
6916 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6917 AddToWorklist(ExtLoad.getNode());
6918 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6920 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6921 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6923 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6924 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6925 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6926 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6927 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6929 LN0->getBasePtr(), EVT,
6930 LN0->getMemOperand());
6931 CombineTo(N, ExtLoad);
6932 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6933 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6936 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6937 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6938 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6939 N0.getOperand(1), false);
6940 if (BSwap.getNode())
6941 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6948 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6949 SDValue N0 = N->getOperand(0);
6950 EVT VT = N->getValueType(0);
6952 if (N0.getOpcode() == ISD::UNDEF)
6953 return DAG.getUNDEF(VT);
6955 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6957 return SDValue(Res, 0);
6962 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6963 SDValue N0 = N->getOperand(0);
6964 EVT VT = N->getValueType(0);
6965 bool isLE = DAG.getDataLayout().isLittleEndian();
6968 if (N0.getValueType() == N->getValueType(0))
6970 // fold (truncate c1) -> c1
6971 if (isConstantIntBuildVectorOrConstantInt(N0))
6972 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6973 // fold (truncate (truncate x)) -> (truncate x)
6974 if (N0.getOpcode() == ISD::TRUNCATE)
6975 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6976 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6977 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6978 N0.getOpcode() == ISD::SIGN_EXTEND ||
6979 N0.getOpcode() == ISD::ANY_EXTEND) {
6980 if (N0.getOperand(0).getValueType().bitsLT(VT))
6981 // if the source is smaller than the dest, we still need an extend
6982 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6984 if (N0.getOperand(0).getValueType().bitsGT(VT))
6985 // if the source is larger than the dest, than we just need the truncate
6986 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6987 // if the source and dest are the same type, we can drop both the extend
6988 // and the truncate.
6989 return N0.getOperand(0);
6992 // Fold extract-and-trunc into a narrow extract. For example:
6993 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6994 // i32 y = TRUNCATE(i64 x)
6996 // v16i8 b = BITCAST (v2i64 val)
6997 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6999 // Note: We only run this optimization after type legalization (which often
7000 // creates this pattern) and before operation legalization after which
7001 // we need to be more careful about the vector instructions that we generate.
7002 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7003 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7005 EVT VecTy = N0.getOperand(0).getValueType();
7006 EVT ExTy = N0.getValueType();
7007 EVT TrTy = N->getValueType(0);
7009 unsigned NumElem = VecTy.getVectorNumElements();
7010 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7012 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7013 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7015 SDValue EltNo = N0->getOperand(1);
7016 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7017 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7018 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7019 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7021 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7022 NVT, N0.getOperand(0));
7025 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7027 DAG.getConstant(Index, DL, IndexTy));
7031 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7032 if (N0.getOpcode() == ISD::SELECT) {
7033 EVT SrcVT = N0.getValueType();
7034 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7035 TLI.isTruncateFree(SrcVT, VT)) {
7037 SDValue Cond = N0.getOperand(0);
7038 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7039 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7040 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7044 // Fold a series of buildvector, bitcast, and truncate if possible.
7046 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7047 // (2xi32 (buildvector x, y)).
7048 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7049 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7050 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7051 N0.getOperand(0).hasOneUse()) {
7053 SDValue BuildVect = N0.getOperand(0);
7054 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7055 EVT TruncVecEltTy = VT.getVectorElementType();
7057 // Check that the element types match.
7058 if (BuildVectEltTy == TruncVecEltTy) {
7059 // Now we only need to compute the offset of the truncated elements.
7060 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7061 unsigned TruncVecNumElts = VT.getVectorNumElements();
7062 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7064 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7065 "Invalid number of elements");
7067 SmallVector<SDValue, 8> Opnds;
7068 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7069 Opnds.push_back(BuildVect.getOperand(i));
7071 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7075 // See if we can simplify the input to this truncate through knowledge that
7076 // only the low bits are being used.
7077 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7078 // Currently we only perform this optimization on scalars because vectors
7079 // may have different active low bits.
7080 if (!VT.isVector()) {
7082 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7083 VT.getSizeInBits()));
7084 if (Shorter.getNode())
7085 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7087 // fold (truncate (load x)) -> (smaller load x)
7088 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7089 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7090 if (SDValue Reduced = ReduceLoadWidth(N))
7093 // Handle the case where the load remains an extending load even
7094 // after truncation.
7095 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7096 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7097 if (!LN0->isVolatile() &&
7098 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7099 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7100 VT, LN0->getChain(), LN0->getBasePtr(),
7102 LN0->getMemOperand());
7103 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7108 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7109 // where ... are all 'undef'.
7110 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7111 SmallVector<EVT, 8> VTs;
7114 unsigned NumDefs = 0;
7116 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7117 SDValue X = N0.getOperand(i);
7118 if (X.getOpcode() != ISD::UNDEF) {
7123 // Stop if more than one members are non-undef.
7126 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7127 VT.getVectorElementType(),
7128 X.getValueType().getVectorNumElements()));
7132 return DAG.getUNDEF(VT);
7135 assert(V.getNode() && "The single defined operand is empty!");
7136 SmallVector<SDValue, 8> Opnds;
7137 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7139 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7142 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7143 AddToWorklist(NV.getNode());
7144 Opnds.push_back(NV);
7146 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7150 // Simplify the operands using demanded-bits information.
7151 if (!VT.isVector() &&
7152 SimplifyDemandedBits(SDValue(N, 0)))
7153 return SDValue(N, 0);
7158 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7159 SDValue Elt = N->getOperand(i);
7160 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7161 return Elt.getNode();
7162 return Elt.getOperand(Elt.getResNo()).getNode();
7165 /// build_pair (load, load) -> load
7166 /// if load locations are consecutive.
7167 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7168 assert(N->getOpcode() == ISD::BUILD_PAIR);
7170 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7171 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7172 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7173 LD1->getAddressSpace() != LD2->getAddressSpace())
7175 EVT LD1VT = LD1->getValueType(0);
7177 if (ISD::isNON_EXTLoad(LD2) &&
7179 // If both are volatile this would reduce the number of volatile loads.
7180 // If one is volatile it might be ok, but play conservative and bail out.
7181 !LD1->isVolatile() &&
7182 !LD2->isVolatile() &&
7183 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7184 unsigned Align = LD1->getAlignment();
7185 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7186 VT.getTypeForEVT(*DAG.getContext()));
7188 if (NewAlign <= Align &&
7189 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7190 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7191 LD1->getBasePtr(), LD1->getPointerInfo(),
7192 false, false, false, Align);
7198 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7199 SDValue N0 = N->getOperand(0);
7200 EVT VT = N->getValueType(0);
7202 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7203 // Only do this before legalize, since afterward the target may be depending
7204 // on the bitconvert.
7205 // First check to see if this is all constant.
7207 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7209 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7211 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7212 assert(!DestEltVT.isVector() &&
7213 "Element type of vector ValueType must not be vector!");
7215 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7218 // If the input is a constant, let getNode fold it.
7219 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7220 // If we can't allow illegal operations, we need to check that this is just
7221 // a fp -> int or int -> conversion and that the resulting operation will
7223 if (!LegalOperations ||
7224 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7225 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7226 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7227 TLI.isOperationLegal(ISD::Constant, VT)))
7228 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7231 // (conv (conv x, t1), t2) -> (conv x, t2)
7232 if (N0.getOpcode() == ISD::BITCAST)
7233 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7236 // fold (conv (load x)) -> (load (conv*)x)
7237 // If the resultant load doesn't need a higher alignment than the original!
7238 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7239 // Do not change the width of a volatile load.
7240 !cast<LoadSDNode>(N0)->isVolatile() &&
7241 // Do not remove the cast if the types differ in endian layout.
7242 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7243 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7244 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7245 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7246 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7247 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7248 VT.getTypeForEVT(*DAG.getContext()));
7249 unsigned OrigAlign = LN0->getAlignment();
7251 if (Align <= OrigAlign) {
7252 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7253 LN0->getBasePtr(), LN0->getPointerInfo(),
7254 LN0->isVolatile(), LN0->isNonTemporal(),
7255 LN0->isInvariant(), OrigAlign,
7257 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7262 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7263 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7264 // This often reduces constant pool loads.
7265 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7266 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7267 N0.getNode()->hasOneUse() && VT.isInteger() &&
7268 !VT.isVector() && !N0.getValueType().isVector()) {
7269 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7271 AddToWorklist(NewConv.getNode());
7274 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7275 if (N0.getOpcode() == ISD::FNEG)
7276 return DAG.getNode(ISD::XOR, DL, VT,
7277 NewConv, DAG.getConstant(SignBit, DL, VT));
7278 assert(N0.getOpcode() == ISD::FABS);
7279 return DAG.getNode(ISD::AND, DL, VT,
7280 NewConv, DAG.getConstant(~SignBit, DL, VT));
7283 // fold (bitconvert (fcopysign cst, x)) ->
7284 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7285 // Note that we don't handle (copysign x, cst) because this can always be
7286 // folded to an fneg or fabs.
7287 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7288 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7289 VT.isInteger() && !VT.isVector()) {
7290 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7291 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7292 if (isTypeLegal(IntXVT)) {
7293 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7294 IntXVT, N0.getOperand(1));
7295 AddToWorklist(X.getNode());
7297 // If X has a different width than the result/lhs, sext it or truncate it.
7298 unsigned VTWidth = VT.getSizeInBits();
7299 if (OrigXWidth < VTWidth) {
7300 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7301 AddToWorklist(X.getNode());
7302 } else if (OrigXWidth > VTWidth) {
7303 // To get the sign bit in the right place, we have to shift it right
7304 // before truncating.
7306 X = DAG.getNode(ISD::SRL, DL,
7307 X.getValueType(), X,
7308 DAG.getConstant(OrigXWidth-VTWidth, DL,
7310 AddToWorklist(X.getNode());
7311 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7312 AddToWorklist(X.getNode());
7315 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7316 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7317 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7318 AddToWorklist(X.getNode());
7320 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7321 VT, N0.getOperand(0));
7322 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7323 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7324 AddToWorklist(Cst.getNode());
7326 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7330 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7331 if (N0.getOpcode() == ISD::BUILD_PAIR)
7332 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7335 // Remove double bitcasts from shuffles - this is often a legacy of
7336 // XformToShuffleWithZero being used to combine bitmaskings (of
7337 // float vectors bitcast to integer vectors) into shuffles.
7338 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7339 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7340 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7341 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7342 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7343 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7345 // If operands are a bitcast, peek through if it casts the original VT.
7346 // If operands are a constant, just bitcast back to original VT.
7347 auto PeekThroughBitcast = [&](SDValue Op) {
7348 if (Op.getOpcode() == ISD::BITCAST &&
7349 Op.getOperand(0).getValueType() == VT)
7350 return SDValue(Op.getOperand(0));
7351 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7352 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7353 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7357 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7358 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7363 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7364 SmallVector<int, 8> NewMask;
7365 for (int M : SVN->getMask())
7366 for (int i = 0; i != MaskScale; ++i)
7367 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7369 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7371 std::swap(SV0, SV1);
7372 ShuffleVectorSDNode::commuteMask(NewMask);
7373 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7377 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7383 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7384 EVT VT = N->getValueType(0);
7385 return CombineConsecutiveLoads(N, VT);
7388 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7389 /// operands. DstEltVT indicates the destination element value type.
7390 SDValue DAGCombiner::
7391 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7392 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7394 // If this is already the right type, we're done.
7395 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7397 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7398 unsigned DstBitSize = DstEltVT.getSizeInBits();
7400 // If this is a conversion of N elements of one type to N elements of another
7401 // type, convert each element. This handles FP<->INT cases.
7402 if (SrcBitSize == DstBitSize) {
7403 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7404 BV->getValueType(0).getVectorNumElements());
7406 // Due to the FP element handling below calling this routine recursively,
7407 // we can end up with a scalar-to-vector node here.
7408 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7409 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7410 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7411 DstEltVT, BV->getOperand(0)));
7413 SmallVector<SDValue, 8> Ops;
7414 for (SDValue Op : BV->op_values()) {
7415 // If the vector element type is not legal, the BUILD_VECTOR operands
7416 // are promoted and implicitly truncated. Make that explicit here.
7417 if (Op.getValueType() != SrcEltVT)
7418 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7419 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7421 AddToWorklist(Ops.back().getNode());
7423 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7426 // Otherwise, we're growing or shrinking the elements. To avoid having to
7427 // handle annoying details of growing/shrinking FP values, we convert them to
7429 if (SrcEltVT.isFloatingPoint()) {
7430 // Convert the input float vector to a int vector where the elements are the
7432 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7433 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7437 // Now we know the input is an integer vector. If the output is a FP type,
7438 // convert to integer first, then to FP of the right size.
7439 if (DstEltVT.isFloatingPoint()) {
7440 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7441 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7443 // Next, convert to FP elements of the same size.
7444 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7449 // Okay, we know the src/dst types are both integers of differing types.
7450 // Handling growing first.
7451 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7452 if (SrcBitSize < DstBitSize) {
7453 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7455 SmallVector<SDValue, 8> Ops;
7456 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7457 i += NumInputsPerOutput) {
7458 bool isLE = DAG.getDataLayout().isLittleEndian();
7459 APInt NewBits = APInt(DstBitSize, 0);
7460 bool EltIsUndef = true;
7461 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7462 // Shift the previously computed bits over.
7463 NewBits <<= SrcBitSize;
7464 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7465 if (Op.getOpcode() == ISD::UNDEF) continue;
7468 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7469 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7473 Ops.push_back(DAG.getUNDEF(DstEltVT));
7475 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7478 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7479 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7482 // Finally, this must be the case where we are shrinking elements: each input
7483 // turns into multiple outputs.
7484 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7485 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7486 NumOutputsPerInput*BV->getNumOperands());
7487 SmallVector<SDValue, 8> Ops;
7489 for (const SDValue &Op : BV->op_values()) {
7490 if (Op.getOpcode() == ISD::UNDEF) {
7491 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7495 APInt OpVal = cast<ConstantSDNode>(Op)->
7496 getAPIntValue().zextOrTrunc(SrcBitSize);
7498 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7499 APInt ThisVal = OpVal.trunc(DstBitSize);
7500 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7501 OpVal = OpVal.lshr(DstBitSize);
7504 // For big endian targets, swap the order of the pieces of each element.
7505 if (DAG.getDataLayout().isBigEndian())
7506 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7509 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7512 /// Try to perform FMA combining on a given FADD node.
7513 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7514 SDValue N0 = N->getOperand(0);
7515 SDValue N1 = N->getOperand(1);
7516 EVT VT = N->getValueType(0);
7519 const TargetOptions &Options = DAG.getTarget().Options;
7521 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7523 // Floating-point multiply-add with intermediate rounding.
7524 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7526 // Floating-point multiply-add without intermediate rounding.
7528 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7529 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7531 // No valid opcode, do not combine.
7532 if (!HasFMAD && !HasFMA)
7535 // Always prefer FMAD to FMA for precision.
7536 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7537 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7538 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7540 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7541 // prefer to fold the multiply with fewer uses.
7542 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7543 N1.getOpcode() == ISD::FMUL) {
7544 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7548 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7549 if (N0.getOpcode() == ISD::FMUL &&
7550 (Aggressive || N0->hasOneUse())) {
7551 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7552 N0.getOperand(0), N0.getOperand(1), N1);
7555 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7556 // Note: Commutes FADD operands.
7557 if (N1.getOpcode() == ISD::FMUL &&
7558 (Aggressive || N1->hasOneUse())) {
7559 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7560 N1.getOperand(0), N1.getOperand(1), N0);
7563 // Look through FP_EXTEND nodes to do more combining.
7564 if (AllowFusion && LookThroughFPExt) {
7565 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7566 if (N0.getOpcode() == ISD::FP_EXTEND) {
7567 SDValue N00 = N0.getOperand(0);
7568 if (N00.getOpcode() == ISD::FMUL)
7569 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7570 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7572 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7573 N00.getOperand(1)), N1);
7576 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7577 // Note: Commutes FADD operands.
7578 if (N1.getOpcode() == ISD::FP_EXTEND) {
7579 SDValue N10 = N1.getOperand(0);
7580 if (N10.getOpcode() == ISD::FMUL)
7581 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7582 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7584 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7585 N10.getOperand(1)), N0);
7589 // More folding opportunities when target permits.
7590 if ((AllowFusion || HasFMAD) && Aggressive) {
7591 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7592 if (N0.getOpcode() == PreferredFusedOpcode &&
7593 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7594 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7595 N0.getOperand(0), N0.getOperand(1),
7596 DAG.getNode(PreferredFusedOpcode, SL, VT,
7597 N0.getOperand(2).getOperand(0),
7598 N0.getOperand(2).getOperand(1),
7602 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7603 if (N1->getOpcode() == PreferredFusedOpcode &&
7604 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7605 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7606 N1.getOperand(0), N1.getOperand(1),
7607 DAG.getNode(PreferredFusedOpcode, SL, VT,
7608 N1.getOperand(2).getOperand(0),
7609 N1.getOperand(2).getOperand(1),
7613 if (AllowFusion && LookThroughFPExt) {
7614 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7615 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7616 auto FoldFAddFMAFPExtFMul = [&] (
7617 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7618 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7619 DAG.getNode(PreferredFusedOpcode, SL, VT,
7620 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7621 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7624 if (N0.getOpcode() == PreferredFusedOpcode) {
7625 SDValue N02 = N0.getOperand(2);
7626 if (N02.getOpcode() == ISD::FP_EXTEND) {
7627 SDValue N020 = N02.getOperand(0);
7628 if (N020.getOpcode() == ISD::FMUL)
7629 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7630 N020.getOperand(0), N020.getOperand(1),
7635 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7636 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7637 // FIXME: This turns two single-precision and one double-precision
7638 // operation into two double-precision operations, which might not be
7639 // interesting for all targets, especially GPUs.
7640 auto FoldFAddFPExtFMAFMul = [&] (
7641 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7642 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7643 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7644 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7645 DAG.getNode(PreferredFusedOpcode, SL, VT,
7646 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7647 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7650 if (N0.getOpcode() == ISD::FP_EXTEND) {
7651 SDValue N00 = N0.getOperand(0);
7652 if (N00.getOpcode() == PreferredFusedOpcode) {
7653 SDValue N002 = N00.getOperand(2);
7654 if (N002.getOpcode() == ISD::FMUL)
7655 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7656 N002.getOperand(0), N002.getOperand(1),
7661 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7662 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7663 if (N1.getOpcode() == PreferredFusedOpcode) {
7664 SDValue N12 = N1.getOperand(2);
7665 if (N12.getOpcode() == ISD::FP_EXTEND) {
7666 SDValue N120 = N12.getOperand(0);
7667 if (N120.getOpcode() == ISD::FMUL)
7668 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7669 N120.getOperand(0), N120.getOperand(1),
7674 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7675 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7676 // FIXME: This turns two single-precision and one double-precision
7677 // operation into two double-precision operations, which might not be
7678 // interesting for all targets, especially GPUs.
7679 if (N1.getOpcode() == ISD::FP_EXTEND) {
7680 SDValue N10 = N1.getOperand(0);
7681 if (N10.getOpcode() == PreferredFusedOpcode) {
7682 SDValue N102 = N10.getOperand(2);
7683 if (N102.getOpcode() == ISD::FMUL)
7684 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7685 N102.getOperand(0), N102.getOperand(1),
7695 /// Try to perform FMA combining on a given FSUB node.
7696 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7697 SDValue N0 = N->getOperand(0);
7698 SDValue N1 = N->getOperand(1);
7699 EVT VT = N->getValueType(0);
7702 const TargetOptions &Options = DAG.getTarget().Options;
7704 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7706 // Floating-point multiply-add with intermediate rounding.
7707 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7709 // Floating-point multiply-add without intermediate rounding.
7711 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7712 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7714 // No valid opcode, do not combine.
7715 if (!HasFMAD && !HasFMA)
7718 // Always prefer FMAD to FMA for precision.
7719 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7720 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7721 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7723 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7724 if (N0.getOpcode() == ISD::FMUL &&
7725 (Aggressive || N0->hasOneUse())) {
7726 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7727 N0.getOperand(0), N0.getOperand(1),
7728 DAG.getNode(ISD::FNEG, SL, VT, N1));
7731 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7732 // Note: Commutes FSUB operands.
7733 if (N1.getOpcode() == ISD::FMUL &&
7734 (Aggressive || N1->hasOneUse()))
7735 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7736 DAG.getNode(ISD::FNEG, SL, VT,
7738 N1.getOperand(1), N0);
7740 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7741 if (N0.getOpcode() == ISD::FNEG &&
7742 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7743 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7744 SDValue N00 = N0.getOperand(0).getOperand(0);
7745 SDValue N01 = N0.getOperand(0).getOperand(1);
7746 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7747 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7748 DAG.getNode(ISD::FNEG, SL, VT, N1));
7751 // Look through FP_EXTEND nodes to do more combining.
7752 if (AllowFusion && LookThroughFPExt) {
7753 // fold (fsub (fpext (fmul x, y)), z)
7754 // -> (fma (fpext x), (fpext y), (fneg z))
7755 if (N0.getOpcode() == ISD::FP_EXTEND) {
7756 SDValue N00 = N0.getOperand(0);
7757 if (N00.getOpcode() == ISD::FMUL)
7758 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7759 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7761 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7763 DAG.getNode(ISD::FNEG, SL, VT, N1));
7766 // fold (fsub x, (fpext (fmul y, z)))
7767 // -> (fma (fneg (fpext y)), (fpext z), x)
7768 // Note: Commutes FSUB operands.
7769 if (N1.getOpcode() == ISD::FP_EXTEND) {
7770 SDValue N10 = N1.getOperand(0);
7771 if (N10.getOpcode() == ISD::FMUL)
7772 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7773 DAG.getNode(ISD::FNEG, SL, VT,
7774 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7775 N10.getOperand(0))),
7776 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7781 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7782 // -> (fneg (fma (fpext x), (fpext y), z))
7783 // Note: This could be removed with appropriate canonicalization of the
7784 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7785 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7786 // from implementing the canonicalization in visitFSUB.
7787 if (N0.getOpcode() == ISD::FP_EXTEND) {
7788 SDValue N00 = N0.getOperand(0);
7789 if (N00.getOpcode() == ISD::FNEG) {
7790 SDValue N000 = N00.getOperand(0);
7791 if (N000.getOpcode() == ISD::FMUL) {
7792 return DAG.getNode(ISD::FNEG, SL, VT,
7793 DAG.getNode(PreferredFusedOpcode, SL, VT,
7794 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7795 N000.getOperand(0)),
7796 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7797 N000.getOperand(1)),
7803 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7804 // -> (fneg (fma (fpext x)), (fpext y), z)
7805 // Note: This could be removed with appropriate canonicalization of the
7806 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7807 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7808 // from implementing the canonicalization in visitFSUB.
7809 if (N0.getOpcode() == ISD::FNEG) {
7810 SDValue N00 = N0.getOperand(0);
7811 if (N00.getOpcode() == ISD::FP_EXTEND) {
7812 SDValue N000 = N00.getOperand(0);
7813 if (N000.getOpcode() == ISD::FMUL) {
7814 return DAG.getNode(ISD::FNEG, SL, VT,
7815 DAG.getNode(PreferredFusedOpcode, SL, VT,
7816 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7817 N000.getOperand(0)),
7818 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7819 N000.getOperand(1)),
7827 // More folding opportunities when target permits.
7828 if ((AllowFusion || HasFMAD) && Aggressive) {
7829 // fold (fsub (fma x, y, (fmul u, v)), z)
7830 // -> (fma x, y (fma u, v, (fneg z)))
7831 if (N0.getOpcode() == PreferredFusedOpcode &&
7832 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7833 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7834 N0.getOperand(0), N0.getOperand(1),
7835 DAG.getNode(PreferredFusedOpcode, SL, VT,
7836 N0.getOperand(2).getOperand(0),
7837 N0.getOperand(2).getOperand(1),
7838 DAG.getNode(ISD::FNEG, SL, VT,
7842 // fold (fsub x, (fma y, z, (fmul u, v)))
7843 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7844 if (N1.getOpcode() == PreferredFusedOpcode &&
7845 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7846 SDValue N20 = N1.getOperand(2).getOperand(0);
7847 SDValue N21 = N1.getOperand(2).getOperand(1);
7848 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7849 DAG.getNode(ISD::FNEG, SL, VT,
7852 DAG.getNode(PreferredFusedOpcode, SL, VT,
7853 DAG.getNode(ISD::FNEG, SL, VT, N20),
7858 if (AllowFusion && LookThroughFPExt) {
7859 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7860 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7861 if (N0.getOpcode() == PreferredFusedOpcode) {
7862 SDValue N02 = N0.getOperand(2);
7863 if (N02.getOpcode() == ISD::FP_EXTEND) {
7864 SDValue N020 = N02.getOperand(0);
7865 if (N020.getOpcode() == ISD::FMUL)
7866 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7867 N0.getOperand(0), N0.getOperand(1),
7868 DAG.getNode(PreferredFusedOpcode, SL, VT,
7869 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7870 N020.getOperand(0)),
7871 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7872 N020.getOperand(1)),
7873 DAG.getNode(ISD::FNEG, SL, VT,
7878 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7879 // -> (fma (fpext x), (fpext y),
7880 // (fma (fpext u), (fpext v), (fneg z)))
7881 // FIXME: This turns two single-precision and one double-precision
7882 // operation into two double-precision operations, which might not be
7883 // interesting for all targets, especially GPUs.
7884 if (N0.getOpcode() == ISD::FP_EXTEND) {
7885 SDValue N00 = N0.getOperand(0);
7886 if (N00.getOpcode() == PreferredFusedOpcode) {
7887 SDValue N002 = N00.getOperand(2);
7888 if (N002.getOpcode() == ISD::FMUL)
7889 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7890 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7892 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7894 DAG.getNode(PreferredFusedOpcode, SL, VT,
7895 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7896 N002.getOperand(0)),
7897 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7898 N002.getOperand(1)),
7899 DAG.getNode(ISD::FNEG, SL, VT,
7904 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7905 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7906 if (N1.getOpcode() == PreferredFusedOpcode &&
7907 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7908 SDValue N120 = N1.getOperand(2).getOperand(0);
7909 if (N120.getOpcode() == ISD::FMUL) {
7910 SDValue N1200 = N120.getOperand(0);
7911 SDValue N1201 = N120.getOperand(1);
7912 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7913 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7915 DAG.getNode(PreferredFusedOpcode, SL, VT,
7916 DAG.getNode(ISD::FNEG, SL, VT,
7917 DAG.getNode(ISD::FP_EXTEND, SL,
7919 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7925 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7926 // -> (fma (fneg (fpext y)), (fpext z),
7927 // (fma (fneg (fpext u)), (fpext v), x))
7928 // FIXME: This turns two single-precision and one double-precision
7929 // operation into two double-precision operations, which might not be
7930 // interesting for all targets, especially GPUs.
7931 if (N1.getOpcode() == ISD::FP_EXTEND &&
7932 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7933 SDValue N100 = N1.getOperand(0).getOperand(0);
7934 SDValue N101 = N1.getOperand(0).getOperand(1);
7935 SDValue N102 = N1.getOperand(0).getOperand(2);
7936 if (N102.getOpcode() == ISD::FMUL) {
7937 SDValue N1020 = N102.getOperand(0);
7938 SDValue N1021 = N102.getOperand(1);
7939 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7940 DAG.getNode(ISD::FNEG, SL, VT,
7941 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7943 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7944 DAG.getNode(PreferredFusedOpcode, SL, VT,
7945 DAG.getNode(ISD::FNEG, SL, VT,
7946 DAG.getNode(ISD::FP_EXTEND, SL,
7948 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7959 /// Try to perform FMA combining on a given FMUL node.
7960 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7961 SDValue N0 = N->getOperand(0);
7962 SDValue N1 = N->getOperand(1);
7963 EVT VT = N->getValueType(0);
7966 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7968 const TargetOptions &Options = DAG.getTarget().Options;
7970 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7972 // Floating-point multiply-add with intermediate rounding.
7973 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7975 // Floating-point multiply-add without intermediate rounding.
7977 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7978 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7980 // No valid opcode, do not combine.
7981 if (!HasFMAD && !HasFMA)
7984 // Always prefer FMAD to FMA for precision.
7985 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7986 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7988 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7989 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7990 auto FuseFADD = [&](SDValue X, SDValue Y) {
7991 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7992 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7993 if (XC1 && XC1->isExactlyValue(+1.0))
7994 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7995 if (XC1 && XC1->isExactlyValue(-1.0))
7996 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7997 DAG.getNode(ISD::FNEG, SL, VT, Y));
8002 if (SDValue FMA = FuseFADD(N0, N1))
8004 if (SDValue FMA = FuseFADD(N1, N0))
8007 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8008 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8009 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8010 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8011 auto FuseFSUB = [&](SDValue X, SDValue Y) {
8012 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8013 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8014 if (XC0 && XC0->isExactlyValue(+1.0))
8015 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8016 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8018 if (XC0 && XC0->isExactlyValue(-1.0))
8019 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8020 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8021 DAG.getNode(ISD::FNEG, SL, VT, Y));
8023 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8024 if (XC1 && XC1->isExactlyValue(+1.0))
8025 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8026 DAG.getNode(ISD::FNEG, SL, VT, Y));
8027 if (XC1 && XC1->isExactlyValue(-1.0))
8028 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8033 if (SDValue FMA = FuseFSUB(N0, N1))
8035 if (SDValue FMA = FuseFSUB(N1, N0))
8041 SDValue DAGCombiner::visitFADD(SDNode *N) {
8042 SDValue N0 = N->getOperand(0);
8043 SDValue N1 = N->getOperand(1);
8044 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8045 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8046 EVT VT = N->getValueType(0);
8048 const TargetOptions &Options = DAG.getTarget().Options;
8049 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8053 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8056 // fold (fadd c1, c2) -> c1 + c2
8058 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8060 // canonicalize constant to RHS
8061 if (N0CFP && !N1CFP)
8062 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8064 // fold (fadd A, (fneg B)) -> (fsub A, B)
8065 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8066 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8067 return DAG.getNode(ISD::FSUB, DL, VT, N0,
8068 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8070 // fold (fadd (fneg A), B) -> (fsub B, A)
8071 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8072 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8073 return DAG.getNode(ISD::FSUB, DL, VT, N1,
8074 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8076 // If 'unsafe math' is enabled, fold lots of things.
8077 if (Options.UnsafeFPMath) {
8078 // No FP constant should be created after legalization as Instruction
8079 // Selection pass has a hard time dealing with FP constants.
8080 bool AllowNewConst = (Level < AfterLegalizeDAG);
8082 // fold (fadd A, 0) -> A
8083 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8087 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8088 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8089 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8090 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8091 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8095 // If allowed, fold (fadd (fneg x), x) -> 0.0
8096 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8097 return DAG.getConstantFP(0.0, DL, VT);
8099 // If allowed, fold (fadd x, (fneg x)) -> 0.0
8100 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8101 return DAG.getConstantFP(0.0, DL, VT);
8103 // We can fold chains of FADD's of the same value into multiplications.
8104 // This transform is not safe in general because we are reducing the number
8105 // of rounding steps.
8106 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8107 if (N0.getOpcode() == ISD::FMUL) {
8108 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8109 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8111 // (fadd (fmul x, c), x) -> (fmul x, c+1)
8112 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8113 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8114 DAG.getConstantFP(1.0, DL, VT), Flags);
8115 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8118 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8119 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8120 N1.getOperand(0) == N1.getOperand(1) &&
8121 N0.getOperand(0) == N1.getOperand(0)) {
8122 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8123 DAG.getConstantFP(2.0, DL, VT), Flags);
8124 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8128 if (N1.getOpcode() == ISD::FMUL) {
8129 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8130 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8132 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8133 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8134 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8135 DAG.getConstantFP(1.0, DL, VT), Flags);
8136 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8139 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8140 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8141 N0.getOperand(0) == N0.getOperand(1) &&
8142 N1.getOperand(0) == N0.getOperand(0)) {
8143 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8144 DAG.getConstantFP(2.0, DL, VT), Flags);
8145 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8149 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8150 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8151 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8152 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8153 (N0.getOperand(0) == N1)) {
8154 return DAG.getNode(ISD::FMUL, DL, VT,
8155 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8159 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8160 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8161 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8162 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8163 N1.getOperand(0) == N0) {
8164 return DAG.getNode(ISD::FMUL, DL, VT,
8165 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8169 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8170 if (AllowNewConst &&
8171 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8172 N0.getOperand(0) == N0.getOperand(1) &&
8173 N1.getOperand(0) == N1.getOperand(1) &&
8174 N0.getOperand(0) == N1.getOperand(0)) {
8175 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8176 DAG.getConstantFP(4.0, DL, VT), Flags);
8179 } // enable-unsafe-fp-math
8181 // FADD -> FMA combines:
8182 if (SDValue Fused = visitFADDForFMACombine(N)) {
8183 AddToWorklist(Fused.getNode());
8190 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8191 SDValue N0 = N->getOperand(0);
8192 SDValue N1 = N->getOperand(1);
8193 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8194 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8195 EVT VT = N->getValueType(0);
8197 const TargetOptions &Options = DAG.getTarget().Options;
8198 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8202 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8205 // fold (fsub c1, c2) -> c1-c2
8207 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8209 // fold (fsub A, (fneg B)) -> (fadd A, B)
8210 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8211 return DAG.getNode(ISD::FADD, dl, VT, N0,
8212 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8214 // If 'unsafe math' is enabled, fold lots of things.
8215 if (Options.UnsafeFPMath) {
8217 if (N1CFP && N1CFP->isZero())
8220 // (fsub 0, B) -> -B
8221 if (N0CFP && N0CFP->isZero()) {
8222 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8223 return GetNegatedExpression(N1, DAG, LegalOperations);
8224 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8225 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8228 // (fsub x, x) -> 0.0
8230 return DAG.getConstantFP(0.0f, dl, VT);
8232 // (fsub x, (fadd x, y)) -> (fneg y)
8233 // (fsub x, (fadd y, x)) -> (fneg y)
8234 if (N1.getOpcode() == ISD::FADD) {
8235 SDValue N10 = N1->getOperand(0);
8236 SDValue N11 = N1->getOperand(1);
8238 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8239 return GetNegatedExpression(N11, DAG, LegalOperations);
8241 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8242 return GetNegatedExpression(N10, DAG, LegalOperations);
8246 // FSUB -> FMA combines:
8247 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8248 AddToWorklist(Fused.getNode());
8255 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8256 SDValue N0 = N->getOperand(0);
8257 SDValue N1 = N->getOperand(1);
8258 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8259 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8260 EVT VT = N->getValueType(0);
8262 const TargetOptions &Options = DAG.getTarget().Options;
8263 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8266 if (VT.isVector()) {
8267 // This just handles C1 * C2 for vectors. Other vector folds are below.
8268 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8272 // fold (fmul c1, c2) -> c1*c2
8274 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8276 // canonicalize constant to RHS
8277 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8278 !isConstantFPBuildVectorOrConstantFP(N1))
8279 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8281 // fold (fmul A, 1.0) -> A
8282 if (N1CFP && N1CFP->isExactlyValue(1.0))
8285 if (Options.UnsafeFPMath) {
8286 // fold (fmul A, 0) -> 0
8287 if (N1CFP && N1CFP->isZero())
8290 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8291 if (N0.getOpcode() == ISD::FMUL) {
8292 // Fold scalars or any vector constants (not just splats).
8293 // This fold is done in general by InstCombine, but extra fmul insts
8294 // may have been generated during lowering.
8295 SDValue N00 = N0.getOperand(0);
8296 SDValue N01 = N0.getOperand(1);
8297 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8298 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8299 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8301 // Check 1: Make sure that the first operand of the inner multiply is NOT
8302 // a constant. Otherwise, we may induce infinite looping.
8303 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8304 // Check 2: Make sure that the second operand of the inner multiply and
8305 // the second operand of the outer multiply are constants.
8306 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8307 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8308 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8309 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8314 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8315 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8316 // during an early run of DAGCombiner can prevent folding with fmuls
8317 // inserted during lowering.
8318 if (N0.getOpcode() == ISD::FADD &&
8319 (N0.getOperand(0) == N0.getOperand(1)) &&
8321 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8322 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8323 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8327 // fold (fmul X, 2.0) -> (fadd X, X)
8328 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8329 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8331 // fold (fmul X, -1.0) -> (fneg X)
8332 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8333 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8334 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8336 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8337 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8338 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8339 // Both can be negated for free, check to see if at least one is cheaper
8341 if (LHSNeg == 2 || RHSNeg == 2)
8342 return DAG.getNode(ISD::FMUL, DL, VT,
8343 GetNegatedExpression(N0, DAG, LegalOperations),
8344 GetNegatedExpression(N1, DAG, LegalOperations),
8349 // FMUL -> FMA combines:
8350 if (SDValue Fused = visitFMULForFMACombine(N)) {
8351 AddToWorklist(Fused.getNode());
8358 SDValue DAGCombiner::visitFMA(SDNode *N) {
8359 SDValue N0 = N->getOperand(0);
8360 SDValue N1 = N->getOperand(1);
8361 SDValue N2 = N->getOperand(2);
8362 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8363 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8364 EVT VT = N->getValueType(0);
8366 const TargetOptions &Options = DAG.getTarget().Options;
8368 // Constant fold FMA.
8369 if (isa<ConstantFPSDNode>(N0) &&
8370 isa<ConstantFPSDNode>(N1) &&
8371 isa<ConstantFPSDNode>(N2)) {
8372 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8375 if (Options.UnsafeFPMath) {
8376 if (N0CFP && N0CFP->isZero())
8378 if (N1CFP && N1CFP->isZero())
8381 // TODO: The FMA node should have flags that propagate to these nodes.
8382 if (N0CFP && N0CFP->isExactlyValue(1.0))
8383 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8384 if (N1CFP && N1CFP->isExactlyValue(1.0))
8385 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8387 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8388 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8389 !isConstantFPBuildVectorOrConstantFP(N1))
8390 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8392 // TODO: FMA nodes should have flags that propagate to the created nodes.
8393 // For now, create a Flags object for use with all unsafe math transforms.
8395 Flags.setUnsafeAlgebra(true);
8397 if (Options.UnsafeFPMath) {
8398 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8399 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8400 isConstantFPBuildVectorOrConstantFP(N1) &&
8401 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8402 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8403 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8407 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8408 if (N0.getOpcode() == ISD::FMUL &&
8409 isConstantFPBuildVectorOrConstantFP(N1) &&
8410 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8411 return DAG.getNode(ISD::FMA, dl, VT,
8413 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8419 // (fma x, 1, y) -> (fadd x, y)
8420 // (fma x, -1, y) -> (fadd (fneg x), y)
8422 if (N1CFP->isExactlyValue(1.0))
8423 // TODO: The FMA node should have flags that propagate to this node.
8424 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8426 if (N1CFP->isExactlyValue(-1.0) &&
8427 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8428 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8429 AddToWorklist(RHSNeg.getNode());
8430 // TODO: The FMA node should have flags that propagate to this node.
8431 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8435 if (Options.UnsafeFPMath) {
8436 // (fma x, c, x) -> (fmul x, (c+1))
8437 if (N1CFP && N0 == N2) {
8438 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8439 DAG.getNode(ISD::FADD, dl, VT,
8440 N1, DAG.getConstantFP(1.0, dl, VT),
8444 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8445 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8446 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8447 DAG.getNode(ISD::FADD, dl, VT,
8448 N1, DAG.getConstantFP(-1.0, dl, VT),
8456 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8458 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8459 // Notice that this is not always beneficial. One reason is different target
8460 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8461 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8462 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8463 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8464 if (!DAG.getTarget().Options.UnsafeFPMath)
8467 // Skip if current node is a reciprocal.
8468 SDValue N0 = N->getOperand(0);
8469 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8470 if (N0CFP && N0CFP->isExactlyValue(1.0))
8473 // Exit early if the target does not want this transform or if there can't
8474 // possibly be enough uses of the divisor to make the transform worthwhile.
8475 SDValue N1 = N->getOperand(1);
8476 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8477 if (!MinUses || N1->use_size() < MinUses)
8480 // Find all FDIV users of the same divisor.
8481 // Use a set because duplicates may be present in the user list.
8482 SetVector<SDNode *> Users;
8483 for (auto *U : N1->uses())
8484 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8487 // Now that we have the actual number of divisor uses, make sure it meets
8488 // the minimum threshold specified by the target.
8489 if (Users.size() < MinUses)
8492 EVT VT = N->getValueType(0);
8494 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8495 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8496 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8498 // Dividend / Divisor -> Dividend * Reciprocal
8499 for (auto *U : Users) {
8500 SDValue Dividend = U->getOperand(0);
8501 if (Dividend != FPOne) {
8502 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8504 CombineTo(U, NewNode);
8505 } else if (U != Reciprocal.getNode()) {
8506 // In the absence of fast-math-flags, this user node is always the
8507 // same node as Reciprocal, but with FMF they may be different nodes.
8508 CombineTo(U, Reciprocal);
8511 return SDValue(N, 0); // N was replaced.
8514 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8515 SDValue N0 = N->getOperand(0);
8516 SDValue N1 = N->getOperand(1);
8517 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8518 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8519 EVT VT = N->getValueType(0);
8521 const TargetOptions &Options = DAG.getTarget().Options;
8522 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8526 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8529 // fold (fdiv c1, c2) -> c1/c2
8531 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8533 if (Options.UnsafeFPMath) {
8534 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8536 // Compute the reciprocal 1.0 / c2.
8537 APFloat N1APF = N1CFP->getValueAPF();
8538 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8539 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8540 // Only do the transform if the reciprocal is a legal fp immediate that
8541 // isn't too nasty (eg NaN, denormal, ...).
8542 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8543 (!LegalOperations ||
8544 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8545 // backend)... we should handle this gracefully after Legalize.
8546 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8547 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8548 TLI.isFPImmLegal(Recip, VT)))
8549 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8550 DAG.getConstantFP(Recip, DL, VT), Flags);
8553 // If this FDIV is part of a reciprocal square root, it may be folded
8554 // into a target-specific square root estimate instruction.
8555 if (N1.getOpcode() == ISD::FSQRT) {
8556 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8557 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8559 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8560 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8561 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8563 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8564 AddToWorklist(RV.getNode());
8565 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8567 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8568 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8569 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8571 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8572 AddToWorklist(RV.getNode());
8573 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8575 } else if (N1.getOpcode() == ISD::FMUL) {
8576 // Look through an FMUL. Even though this won't remove the FDIV directly,
8577 // it's still worthwhile to get rid of the FSQRT if possible.
8580 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8581 SqrtOp = N1.getOperand(0);
8582 OtherOp = N1.getOperand(1);
8583 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8584 SqrtOp = N1.getOperand(1);
8585 OtherOp = N1.getOperand(0);
8587 if (SqrtOp.getNode()) {
8588 // We found a FSQRT, so try to make this fold:
8589 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8590 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8591 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8592 AddToWorklist(RV.getNode());
8593 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8598 // Fold into a reciprocal estimate and multiply instead of a real divide.
8599 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8600 AddToWorklist(RV.getNode());
8601 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8605 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8606 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8607 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8608 // Both can be negated for free, check to see if at least one is cheaper
8610 if (LHSNeg == 2 || RHSNeg == 2)
8611 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8612 GetNegatedExpression(N0, DAG, LegalOperations),
8613 GetNegatedExpression(N1, DAG, LegalOperations),
8618 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8619 return CombineRepeatedDivisors;
8624 SDValue DAGCombiner::visitFREM(SDNode *N) {
8625 SDValue N0 = N->getOperand(0);
8626 SDValue N1 = N->getOperand(1);
8627 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8628 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8629 EVT VT = N->getValueType(0);
8631 // fold (frem c1, c2) -> fmod(c1,c2)
8633 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8634 &cast<BinaryWithFlagsSDNode>(N)->Flags);
8639 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8640 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8643 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8644 // For now, create a Flags object for use with all unsafe math transforms.
8646 Flags.setUnsafeAlgebra(true);
8648 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8649 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8653 EVT VT = RV.getValueType();
8655 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8656 AddToWorklist(RV.getNode());
8658 // Unfortunately, RV is now NaN if the input was exactly 0.
8659 // Select out this case and force the answer to 0.
8660 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8661 EVT CCVT = getSetCCResultType(VT);
8662 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8663 AddToWorklist(ZeroCmp.getNode());
8664 AddToWorklist(RV.getNode());
8666 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8670 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8671 SDValue N0 = N->getOperand(0);
8672 SDValue N1 = N->getOperand(1);
8673 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8674 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8675 EVT VT = N->getValueType(0);
8677 if (N0CFP && N1CFP) // Constant fold
8678 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8681 const APFloat& V = N1CFP->getValueAPF();
8682 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8683 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8684 if (!V.isNegative()) {
8685 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8686 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8688 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8689 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8690 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8694 // copysign(fabs(x), y) -> copysign(x, y)
8695 // copysign(fneg(x), y) -> copysign(x, y)
8696 // copysign(copysign(x,z), y) -> copysign(x, y)
8697 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8698 N0.getOpcode() == ISD::FCOPYSIGN)
8699 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8700 N0.getOperand(0), N1);
8702 // copysign(x, abs(y)) -> abs(x)
8703 if (N1.getOpcode() == ISD::FABS)
8704 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8706 // copysign(x, copysign(y,z)) -> copysign(x, z)
8707 if (N1.getOpcode() == ISD::FCOPYSIGN)
8708 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8709 N0, N1.getOperand(1));
8711 // copysign(x, fp_extend(y)) -> copysign(x, y)
8712 // copysign(x, fp_round(y)) -> copysign(x, y)
8713 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8714 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8715 N0, N1.getOperand(0));
8720 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8721 SDValue N0 = N->getOperand(0);
8722 EVT VT = N->getValueType(0);
8723 EVT OpVT = N0.getValueType();
8725 // fold (sint_to_fp c1) -> c1fp
8726 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8727 // ...but only if the target supports immediate floating-point values
8728 (!LegalOperations ||
8729 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8730 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8732 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8733 // but UINT_TO_FP is legal on this target, try to convert.
8734 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8735 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8736 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8737 if (DAG.SignBitIsZero(N0))
8738 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8741 // The next optimizations are desirable only if SELECT_CC can be lowered.
8742 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8743 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8744 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8746 (!LegalOperations ||
8747 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8750 { N0.getOperand(0), N0.getOperand(1),
8751 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8753 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8756 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8757 // (select_cc x, y, 1.0, 0.0,, cc)
8758 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8759 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8760 (!LegalOperations ||
8761 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8764 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8765 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8766 N0.getOperand(0).getOperand(2) };
8767 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8774 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8775 SDValue N0 = N->getOperand(0);
8776 EVT VT = N->getValueType(0);
8777 EVT OpVT = N0.getValueType();
8779 // fold (uint_to_fp c1) -> c1fp
8780 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8781 // ...but only if the target supports immediate floating-point values
8782 (!LegalOperations ||
8783 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8784 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8786 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8787 // but SINT_TO_FP is legal on this target, try to convert.
8788 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8789 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8790 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8791 if (DAG.SignBitIsZero(N0))
8792 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8795 // The next optimizations are desirable only if SELECT_CC can be lowered.
8796 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8797 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8799 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8800 (!LegalOperations ||
8801 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8804 { N0.getOperand(0), N0.getOperand(1),
8805 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8807 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8814 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8815 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8816 SDValue N0 = N->getOperand(0);
8817 EVT VT = N->getValueType(0);
8819 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8822 SDValue Src = N0.getOperand(0);
8823 EVT SrcVT = Src.getValueType();
8824 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8825 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8827 // We can safely assume the conversion won't overflow the output range,
8828 // because (for example) (uint8_t)18293.f is undefined behavior.
8830 // Since we can assume the conversion won't overflow, our decision as to
8831 // whether the input will fit in the float should depend on the minimum
8832 // of the input range and output range.
8834 // This means this is also safe for a signed input and unsigned output, since
8835 // a negative input would lead to undefined behavior.
8836 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8837 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8838 unsigned ActualSize = std::min(InputSize, OutputSize);
8839 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8841 // We can only fold away the float conversion if the input range can be
8842 // represented exactly in the float range.
8843 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8844 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8845 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8847 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8849 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8850 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8853 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8858 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8859 SDValue N0 = N->getOperand(0);
8860 EVT VT = N->getValueType(0);
8862 // fold (fp_to_sint c1fp) -> c1
8863 if (isConstantFPBuildVectorOrConstantFP(N0))
8864 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8866 return FoldIntToFPToInt(N, DAG);
8869 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8870 SDValue N0 = N->getOperand(0);
8871 EVT VT = N->getValueType(0);
8873 // fold (fp_to_uint c1fp) -> c1
8874 if (isConstantFPBuildVectorOrConstantFP(N0))
8875 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8877 return FoldIntToFPToInt(N, DAG);
8880 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8881 SDValue N0 = N->getOperand(0);
8882 SDValue N1 = N->getOperand(1);
8883 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8884 EVT VT = N->getValueType(0);
8886 // fold (fp_round c1fp) -> c1fp
8888 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8890 // fold (fp_round (fp_extend x)) -> x
8891 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8892 return N0.getOperand(0);
8894 // fold (fp_round (fp_round x)) -> (fp_round x)
8895 if (N0.getOpcode() == ISD::FP_ROUND) {
8896 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8897 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8898 // If the first fp_round isn't a value preserving truncation, it might
8899 // introduce a tie in the second fp_round, that wouldn't occur in the
8900 // single-step fp_round we want to fold to.
8901 // In other words, double rounding isn't the same as rounding.
8902 // Also, this is a value preserving truncation iff both fp_round's are.
8903 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8905 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8906 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8910 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8911 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8912 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8913 N0.getOperand(0), N1);
8914 AddToWorklist(Tmp.getNode());
8915 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8916 Tmp, N0.getOperand(1));
8922 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8923 SDValue N0 = N->getOperand(0);
8924 EVT VT = N->getValueType(0);
8925 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8926 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8928 // fold (fp_round_inreg c1fp) -> c1fp
8929 if (N0CFP && isTypeLegal(EVT)) {
8931 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8932 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8938 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8939 SDValue N0 = N->getOperand(0);
8940 EVT VT = N->getValueType(0);
8942 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8943 if (N->hasOneUse() &&
8944 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8947 // fold (fp_extend c1fp) -> c1fp
8948 if (isConstantFPBuildVectorOrConstantFP(N0))
8949 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8951 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8952 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8953 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8954 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8956 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8958 if (N0.getOpcode() == ISD::FP_ROUND
8959 && N0.getNode()->getConstantOperandVal(1) == 1) {
8960 SDValue In = N0.getOperand(0);
8961 if (In.getValueType() == VT) return In;
8962 if (VT.bitsLT(In.getValueType()))
8963 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8964 In, N0.getOperand(1));
8965 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8968 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8969 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8970 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8971 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8972 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8974 LN0->getBasePtr(), N0.getValueType(),
8975 LN0->getMemOperand());
8976 CombineTo(N, ExtLoad);
8977 CombineTo(N0.getNode(),
8978 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8979 N0.getValueType(), ExtLoad,
8980 DAG.getIntPtrConstant(1, SDLoc(N0))),
8981 ExtLoad.getValue(1));
8982 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8988 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8989 SDValue N0 = N->getOperand(0);
8990 EVT VT = N->getValueType(0);
8992 // fold (fceil c1) -> fceil(c1)
8993 if (isConstantFPBuildVectorOrConstantFP(N0))
8994 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8999 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9000 SDValue N0 = N->getOperand(0);
9001 EVT VT = N->getValueType(0);
9003 // fold (ftrunc c1) -> ftrunc(c1)
9004 if (isConstantFPBuildVectorOrConstantFP(N0))
9005 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9010 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9011 SDValue N0 = N->getOperand(0);
9012 EVT VT = N->getValueType(0);
9014 // fold (ffloor c1) -> ffloor(c1)
9015 if (isConstantFPBuildVectorOrConstantFP(N0))
9016 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9021 // FIXME: FNEG and FABS have a lot in common; refactor.
9022 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9023 SDValue N0 = N->getOperand(0);
9024 EVT VT = N->getValueType(0);
9026 // Constant fold FNEG.
9027 if (isConstantFPBuildVectorOrConstantFP(N0))
9028 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9030 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9031 &DAG.getTarget().Options))
9032 return GetNegatedExpression(N0, DAG, LegalOperations);
9034 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9035 // constant pool values.
9036 if (!TLI.isFNegFree(VT) &&
9037 N0.getOpcode() == ISD::BITCAST &&
9038 N0.getNode()->hasOneUse()) {
9039 SDValue Int = N0.getOperand(0);
9040 EVT IntVT = Int.getValueType();
9041 if (IntVT.isInteger() && !IntVT.isVector()) {
9043 if (N0.getValueType().isVector()) {
9044 // For a vector, get a mask such as 0x80... per scalar element
9046 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9047 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9049 // For a scalar, just generate 0x80...
9050 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9053 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9054 DAG.getConstant(SignMask, DL0, IntVT));
9055 AddToWorklist(Int.getNode());
9056 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9060 // (fneg (fmul c, x)) -> (fmul -c, x)
9061 if (N0.getOpcode() == ISD::FMUL &&
9062 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9063 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9065 APFloat CVal = CFP1->getValueAPF();
9067 if (Level >= AfterLegalizeDAG &&
9068 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9069 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9070 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9071 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9073 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9080 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9081 SDValue N0 = N->getOperand(0);
9082 SDValue N1 = N->getOperand(1);
9083 EVT VT = N->getValueType(0);
9084 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9085 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9087 if (N0CFP && N1CFP) {
9088 const APFloat &C0 = N0CFP->getValueAPF();
9089 const APFloat &C1 = N1CFP->getValueAPF();
9090 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9093 // Canonicalize to constant on RHS.
9094 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9095 !isConstantFPBuildVectorOrConstantFP(N1))
9096 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9101 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9102 SDValue N0 = N->getOperand(0);
9103 SDValue N1 = N->getOperand(1);
9104 EVT VT = N->getValueType(0);
9105 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9106 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9108 if (N0CFP && N1CFP) {
9109 const APFloat &C0 = N0CFP->getValueAPF();
9110 const APFloat &C1 = N1CFP->getValueAPF();
9111 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9114 // Canonicalize to constant on RHS.
9115 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9116 !isConstantFPBuildVectorOrConstantFP(N1))
9117 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9122 SDValue DAGCombiner::visitFABS(SDNode *N) {
9123 SDValue N0 = N->getOperand(0);
9124 EVT VT = N->getValueType(0);
9126 // fold (fabs c1) -> fabs(c1)
9127 if (isConstantFPBuildVectorOrConstantFP(N0))
9128 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9130 // fold (fabs (fabs x)) -> (fabs x)
9131 if (N0.getOpcode() == ISD::FABS)
9132 return N->getOperand(0);
9134 // fold (fabs (fneg x)) -> (fabs x)
9135 // fold (fabs (fcopysign x, y)) -> (fabs x)
9136 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9137 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9139 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9140 // constant pool values.
9141 if (!TLI.isFAbsFree(VT) &&
9142 N0.getOpcode() == ISD::BITCAST &&
9143 N0.getNode()->hasOneUse()) {
9144 SDValue Int = N0.getOperand(0);
9145 EVT IntVT = Int.getValueType();
9146 if (IntVT.isInteger() && !IntVT.isVector()) {
9148 if (N0.getValueType().isVector()) {
9149 // For a vector, get a mask such as 0x7f... per scalar element
9151 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9152 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9154 // For a scalar, just generate 0x7f...
9155 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9158 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9159 DAG.getConstant(SignMask, DL, IntVT));
9160 AddToWorklist(Int.getNode());
9161 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9168 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9169 SDValue Chain = N->getOperand(0);
9170 SDValue N1 = N->getOperand(1);
9171 SDValue N2 = N->getOperand(2);
9173 // If N is a constant we could fold this into a fallthrough or unconditional
9174 // branch. However that doesn't happen very often in normal code, because
9175 // Instcombine/SimplifyCFG should have handled the available opportunities.
9176 // If we did this folding here, it would be necessary to update the
9177 // MachineBasicBlock CFG, which is awkward.
9179 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9181 if (N1.getOpcode() == ISD::SETCC &&
9182 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9183 N1.getOperand(0).getValueType())) {
9184 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9185 Chain, N1.getOperand(2),
9186 N1.getOperand(0), N1.getOperand(1), N2);
9189 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9190 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9191 (N1.getOperand(0).hasOneUse() &&
9192 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9193 SDNode *Trunc = nullptr;
9194 if (N1.getOpcode() == ISD::TRUNCATE) {
9195 // Look pass the truncate.
9196 Trunc = N1.getNode();
9197 N1 = N1.getOperand(0);
9200 // Match this pattern so that we can generate simpler code:
9203 // %b = and i32 %a, 2
9204 // %c = srl i32 %b, 1
9205 // brcond i32 %c ...
9210 // %b = and i32 %a, 2
9211 // %c = setcc eq %b, 0
9214 // This applies only when the AND constant value has one bit set and the
9215 // SRL constant is equal to the log2 of the AND constant. The back-end is
9216 // smart enough to convert the result into a TEST/JMP sequence.
9217 SDValue Op0 = N1.getOperand(0);
9218 SDValue Op1 = N1.getOperand(1);
9220 if (Op0.getOpcode() == ISD::AND &&
9221 Op1.getOpcode() == ISD::Constant) {
9222 SDValue AndOp1 = Op0.getOperand(1);
9224 if (AndOp1.getOpcode() == ISD::Constant) {
9225 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9227 if (AndConst.isPowerOf2() &&
9228 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9232 getSetCCResultType(Op0.getValueType()),
9233 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9236 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9237 MVT::Other, Chain, SetCC, N2);
9238 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9239 // will convert it back to (X & C1) >> C2.
9240 CombineTo(N, NewBRCond, false);
9241 // Truncate is dead.
9243 deleteAndRecombine(Trunc);
9244 // Replace the uses of SRL with SETCC
9245 WorklistRemover DeadNodes(*this);
9246 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9247 deleteAndRecombine(N1.getNode());
9248 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9254 // Restore N1 if the above transformation doesn't match.
9255 N1 = N->getOperand(1);
9258 // Transform br(xor(x, y)) -> br(x != y)
9259 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9260 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9261 SDNode *TheXor = N1.getNode();
9262 SDValue Op0 = TheXor->getOperand(0);
9263 SDValue Op1 = TheXor->getOperand(1);
9264 if (Op0.getOpcode() == Op1.getOpcode()) {
9265 // Avoid missing important xor optimizations.
9266 if (SDValue Tmp = visitXOR(TheXor)) {
9267 if (Tmp.getNode() != TheXor) {
9268 DEBUG(dbgs() << "\nReplacing.8 ";
9270 dbgs() << "\nWith: ";
9271 Tmp.getNode()->dump(&DAG);
9273 WorklistRemover DeadNodes(*this);
9274 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9275 deleteAndRecombine(TheXor);
9276 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9277 MVT::Other, Chain, Tmp, N2);
9280 // visitXOR has changed XOR's operands or replaced the XOR completely,
9282 return SDValue(N, 0);
9286 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9288 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9289 Op0.getOpcode() == ISD::XOR) {
9290 TheXor = Op0.getNode();
9294 EVT SetCCVT = N1.getValueType();
9296 SetCCVT = getSetCCResultType(SetCCVT);
9297 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9300 Equal ? ISD::SETEQ : ISD::SETNE);
9301 // Replace the uses of XOR with SETCC
9302 WorklistRemover DeadNodes(*this);
9303 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9304 deleteAndRecombine(N1.getNode());
9305 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9306 MVT::Other, Chain, SetCC, N2);
9313 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9315 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9316 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9317 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9319 // If N is a constant we could fold this into a fallthrough or unconditional
9320 // branch. However that doesn't happen very often in normal code, because
9321 // Instcombine/SimplifyCFG should have handled the available opportunities.
9322 // If we did this folding here, it would be necessary to update the
9323 // MachineBasicBlock CFG, which is awkward.
9325 // Use SimplifySetCC to simplify SETCC's.
9326 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9327 CondLHS, CondRHS, CC->get(), SDLoc(N),
9329 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9331 // fold to a simpler setcc
9332 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9333 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9334 N->getOperand(0), Simp.getOperand(2),
9335 Simp.getOperand(0), Simp.getOperand(1),
9341 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9342 /// and that N may be folded in the load / store addressing mode.
9343 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9345 const TargetLowering &TLI) {
9349 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9350 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9352 VT = LD->getMemoryVT();
9353 AS = LD->getAddressSpace();
9354 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9355 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9357 VT = ST->getMemoryVT();
9358 AS = ST->getAddressSpace();
9362 TargetLowering::AddrMode AM;
9363 if (N->getOpcode() == ISD::ADD) {
9364 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9367 AM.BaseOffs = Offset->getSExtValue();
9371 } else if (N->getOpcode() == ISD::SUB) {
9372 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9375 AM.BaseOffs = -Offset->getSExtValue();
9382 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9383 VT.getTypeForEVT(*DAG.getContext()), AS);
9386 /// Try turning a load/store into a pre-indexed load/store when the base
9387 /// pointer is an add or subtract and it has other uses besides the load/store.
9388 /// After the transformation, the new indexed load/store has effectively folded
9389 /// the add/subtract in and all of its other uses are redirected to the
9391 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9392 if (Level < AfterLegalizeDAG)
9398 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9399 if (LD->isIndexed())
9401 VT = LD->getMemoryVT();
9402 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9403 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9405 Ptr = LD->getBasePtr();
9406 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9407 if (ST->isIndexed())
9409 VT = ST->getMemoryVT();
9410 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9411 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9413 Ptr = ST->getBasePtr();
9419 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9420 // out. There is no reason to make this a preinc/predec.
9421 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9422 Ptr.getNode()->hasOneUse())
9425 // Ask the target to do addressing mode selection.
9428 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9429 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9432 // Backends without true r+i pre-indexed forms may need to pass a
9433 // constant base with a variable offset so that constant coercion
9434 // will work with the patterns in canonical form.
9435 bool Swapped = false;
9436 if (isa<ConstantSDNode>(BasePtr)) {
9437 std::swap(BasePtr, Offset);
9441 // Don't create a indexed load / store with zero offset.
9442 if (isNullConstant(Offset))
9445 // Try turning it into a pre-indexed load / store except when:
9446 // 1) The new base ptr is a frame index.
9447 // 2) If N is a store and the new base ptr is either the same as or is a
9448 // predecessor of the value being stored.
9449 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9450 // that would create a cycle.
9451 // 4) All uses are load / store ops that use it as old base ptr.
9453 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9454 // (plus the implicit offset) to a register to preinc anyway.
9455 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9460 SDValue Val = cast<StoreSDNode>(N)->getValue();
9461 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9465 // If the offset is a constant, there may be other adds of constants that
9466 // can be folded with this one. We should do this to avoid having to keep
9467 // a copy of the original base pointer.
9468 SmallVector<SDNode *, 16> OtherUses;
9469 if (isa<ConstantSDNode>(Offset))
9470 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9471 UE = BasePtr.getNode()->use_end();
9473 SDUse &Use = UI.getUse();
9474 // Skip the use that is Ptr and uses of other results from BasePtr's
9475 // node (important for nodes that return multiple results).
9476 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9479 if (Use.getUser()->isPredecessorOf(N))
9482 if (Use.getUser()->getOpcode() != ISD::ADD &&
9483 Use.getUser()->getOpcode() != ISD::SUB) {
9488 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9489 if (!isa<ConstantSDNode>(Op1)) {
9494 // FIXME: In some cases, we can be smarter about this.
9495 if (Op1.getValueType() != Offset.getValueType()) {
9500 OtherUses.push_back(Use.getUser());
9504 std::swap(BasePtr, Offset);
9506 // Now check for #3 and #4.
9507 bool RealUse = false;
9509 // Caches for hasPredecessorHelper
9510 SmallPtrSet<const SDNode *, 32> Visited;
9511 SmallVector<const SDNode *, 16> Worklist;
9513 for (SDNode *Use : Ptr.getNode()->uses()) {
9516 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9519 // If Ptr may be folded in addressing mode of other use, then it's
9520 // not profitable to do this transformation.
9521 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9530 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9531 BasePtr, Offset, AM);
9533 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9534 BasePtr, Offset, AM);
9537 DEBUG(dbgs() << "\nReplacing.4 ";
9539 dbgs() << "\nWith: ";
9540 Result.getNode()->dump(&DAG);
9542 WorklistRemover DeadNodes(*this);
9544 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9545 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9547 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9550 // Finally, since the node is now dead, remove it from the graph.
9551 deleteAndRecombine(N);
9554 std::swap(BasePtr, Offset);
9556 // Replace other uses of BasePtr that can be updated to use Ptr
9557 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9558 unsigned OffsetIdx = 1;
9559 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9561 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9562 BasePtr.getNode() && "Expected BasePtr operand");
9564 // We need to replace ptr0 in the following expression:
9565 // x0 * offset0 + y0 * ptr0 = t0
9567 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9569 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9570 // indexed load/store and the expresion that needs to be re-written.
9572 // Therefore, we have:
9573 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9575 ConstantSDNode *CN =
9576 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9578 APInt Offset0 = CN->getAPIntValue();
9579 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9581 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9582 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9583 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9584 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9586 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9588 APInt CNV = Offset0;
9589 if (X0 < 0) CNV = -CNV;
9590 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9591 else CNV = CNV - Offset1;
9593 SDLoc DL(OtherUses[i]);
9595 // We can now generate the new expression.
9596 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9597 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9599 SDValue NewUse = DAG.getNode(Opcode,
9601 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9602 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9603 deleteAndRecombine(OtherUses[i]);
9606 // Replace the uses of Ptr with uses of the updated base value.
9607 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9608 deleteAndRecombine(Ptr.getNode());
9613 /// Try to combine a load/store with a add/sub of the base pointer node into a
9614 /// post-indexed load/store. The transformation folded the add/subtract into the
9615 /// new indexed load/store effectively and all of its uses are redirected to the
9617 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9618 if (Level < AfterLegalizeDAG)
9624 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9625 if (LD->isIndexed())
9627 VT = LD->getMemoryVT();
9628 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9629 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9631 Ptr = LD->getBasePtr();
9632 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9633 if (ST->isIndexed())
9635 VT = ST->getMemoryVT();
9636 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9637 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9639 Ptr = ST->getBasePtr();
9645 if (Ptr.getNode()->hasOneUse())
9648 for (SDNode *Op : Ptr.getNode()->uses()) {
9650 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9655 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9656 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9657 // Don't create a indexed load / store with zero offset.
9658 if (isNullConstant(Offset))
9661 // Try turning it into a post-indexed load / store except when
9662 // 1) All uses are load / store ops that use it as base ptr (and
9663 // it may be folded as addressing mmode).
9664 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9665 // nor a successor of N. Otherwise, if Op is folded that would
9668 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9672 bool TryNext = false;
9673 for (SDNode *Use : BasePtr.getNode()->uses()) {
9674 if (Use == Ptr.getNode())
9677 // If all the uses are load / store addresses, then don't do the
9679 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9680 bool RealUse = false;
9681 for (SDNode *UseUse : Use->uses()) {
9682 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9697 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9698 SDValue Result = isLoad
9699 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9700 BasePtr, Offset, AM)
9701 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9702 BasePtr, Offset, AM);
9705 DEBUG(dbgs() << "\nReplacing.5 ";
9707 dbgs() << "\nWith: ";
9708 Result.getNode()->dump(&DAG);
9710 WorklistRemover DeadNodes(*this);
9712 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9713 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9715 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9718 // Finally, since the node is now dead, remove it from the graph.
9719 deleteAndRecombine(N);
9721 // Replace the uses of Use with uses of the updated base value.
9722 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9723 Result.getValue(isLoad ? 1 : 0));
9724 deleteAndRecombine(Op);
9733 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9734 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9735 ISD::MemIndexedMode AM = LD->getAddressingMode();
9736 assert(AM != ISD::UNINDEXED);
9737 SDValue BP = LD->getOperand(1);
9738 SDValue Inc = LD->getOperand(2);
9740 // Some backends use TargetConstants for load offsets, but don't expect
9741 // TargetConstants in general ADD nodes. We can convert these constants into
9742 // regular Constants (if the constant is not opaque).
9743 assert((Inc.getOpcode() != ISD::TargetConstant ||
9744 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9745 "Cannot split out indexing using opaque target constants");
9746 if (Inc.getOpcode() == ISD::TargetConstant) {
9747 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9748 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9749 ConstInc->getValueType(0));
9753 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9754 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9757 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9758 LoadSDNode *LD = cast<LoadSDNode>(N);
9759 SDValue Chain = LD->getChain();
9760 SDValue Ptr = LD->getBasePtr();
9762 // If load is not volatile and there are no uses of the loaded value (and
9763 // the updated indexed value in case of indexed loads), change uses of the
9764 // chain value into uses of the chain input (i.e. delete the dead load).
9765 if (!LD->isVolatile()) {
9766 if (N->getValueType(1) == MVT::Other) {
9768 if (!N->hasAnyUseOfValue(0)) {
9769 // It's not safe to use the two value CombineTo variant here. e.g.
9770 // v1, chain2 = load chain1, loc
9771 // v2, chain3 = load chain2, loc
9773 // Now we replace use of chain2 with chain1. This makes the second load
9774 // isomorphic to the one we are deleting, and thus makes this load live.
9775 DEBUG(dbgs() << "\nReplacing.6 ";
9777 dbgs() << "\nWith chain: ";
9778 Chain.getNode()->dump(&DAG);
9780 WorklistRemover DeadNodes(*this);
9781 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9784 deleteAndRecombine(N);
9786 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9790 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9792 // If this load has an opaque TargetConstant offset, then we cannot split
9793 // the indexing into an add/sub directly (that TargetConstant may not be
9794 // valid for a different type of node, and we cannot convert an opaque
9795 // target constant into a regular constant).
9796 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9797 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9799 if (!N->hasAnyUseOfValue(0) &&
9800 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9801 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9803 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9804 Index = SplitIndexingFromLoad(LD);
9805 // Try to fold the base pointer arithmetic into subsequent loads and
9807 AddUsersToWorklist(N);
9809 Index = DAG.getUNDEF(N->getValueType(1));
9810 DEBUG(dbgs() << "\nReplacing.7 ";
9812 dbgs() << "\nWith: ";
9813 Undef.getNode()->dump(&DAG);
9814 dbgs() << " and 2 other values\n");
9815 WorklistRemover DeadNodes(*this);
9816 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9817 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9818 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9819 deleteAndRecombine(N);
9820 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9825 // If this load is directly stored, replace the load value with the stored
9827 // TODO: Handle store large -> read small portion.
9828 // TODO: Handle TRUNCSTORE/LOADEXT
9829 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9830 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9831 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9832 if (PrevST->getBasePtr() == Ptr &&
9833 PrevST->getValue().getValueType() == N->getValueType(0))
9834 return CombineTo(N, Chain.getOperand(1), Chain);
9838 // Try to infer better alignment information than the load already has.
9839 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9840 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9841 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9843 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9844 LD->getValueType(0),
9845 Chain, Ptr, LD->getPointerInfo(),
9847 LD->isVolatile(), LD->isNonTemporal(),
9848 LD->isInvariant(), Align, LD->getAAInfo());
9849 if (NewLoad.getNode() != N)
9850 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9855 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9856 : DAG.getSubtarget().useAA();
9858 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9859 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9862 if (UseAA && LD->isUnindexed()) {
9863 // Walk up chain skipping non-aliasing memory nodes.
9864 SDValue BetterChain = FindBetterChain(N, Chain);
9866 // If there is a better chain.
9867 if (Chain != BetterChain) {
9870 // Replace the chain to void dependency.
9871 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9872 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9873 BetterChain, Ptr, LD->getMemOperand());
9875 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9876 LD->getValueType(0),
9877 BetterChain, Ptr, LD->getMemoryVT(),
9878 LD->getMemOperand());
9881 // Create token factor to keep old chain connected.
9882 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9883 MVT::Other, Chain, ReplLoad.getValue(1));
9885 // Make sure the new and old chains are cleaned up.
9886 AddToWorklist(Token.getNode());
9888 // Replace uses with load result and token factor. Don't add users
9890 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9894 // Try transforming N to an indexed load.
9895 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9896 return SDValue(N, 0);
9898 // Try to slice up N to more direct loads if the slices are mapped to
9899 // different register banks or pairing can take place.
9901 return SDValue(N, 0);
9907 /// \brief Helper structure used to slice a load in smaller loads.
9908 /// Basically a slice is obtained from the following sequence:
9909 /// Origin = load Ty1, Base
9910 /// Shift = srl Ty1 Origin, CstTy Amount
9911 /// Inst = trunc Shift to Ty2
9913 /// Then, it will be rewriten into:
9914 /// Slice = load SliceTy, Base + SliceOffset
9915 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9917 /// SliceTy is deduced from the number of bits that are actually used to
9919 struct LoadedSlice {
9920 /// \brief Helper structure used to compute the cost of a slice.
9922 /// Are we optimizing for code size.
9927 unsigned CrossRegisterBanksCopies;
9931 Cost(bool ForCodeSize = false)
9932 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9933 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9935 /// \brief Get the cost of one isolated slice.
9936 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9937 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9938 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9939 EVT TruncType = LS.Inst->getValueType(0);
9940 EVT LoadedType = LS.getLoadedType();
9941 if (TruncType != LoadedType &&
9942 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9946 /// \brief Account for slicing gain in the current cost.
9947 /// Slicing provide a few gains like removing a shift or a
9948 /// truncate. This method allows to grow the cost of the original
9949 /// load with the gain from this slice.
9950 void addSliceGain(const LoadedSlice &LS) {
9951 // Each slice saves a truncate.
9952 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9953 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9954 LS.Inst->getValueType(0)))
9956 // If there is a shift amount, this slice gets rid of it.
9959 // If this slice can merge a cross register bank copy, account for it.
9960 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9961 ++CrossRegisterBanksCopies;
9964 Cost &operator+=(const Cost &RHS) {
9966 Truncates += RHS.Truncates;
9967 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9973 bool operator==(const Cost &RHS) const {
9974 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9975 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9976 ZExts == RHS.ZExts && Shift == RHS.Shift;
9979 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9981 bool operator<(const Cost &RHS) const {
9982 // Assume cross register banks copies are as expensive as loads.
9983 // FIXME: Do we want some more target hooks?
9984 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9985 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9986 // Unless we are optimizing for code size, consider the
9987 // expensive operation first.
9988 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9989 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9990 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9991 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9994 bool operator>(const Cost &RHS) const { return RHS < *this; }
9996 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9998 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10000 // The last instruction that represent the slice. This should be a
10001 // truncate instruction.
10003 // The original load instruction.
10004 LoadSDNode *Origin;
10005 // The right shift amount in bits from the original load.
10007 // The DAG from which Origin came from.
10008 // This is used to get some contextual information about legal types, etc.
10011 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10012 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10013 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10015 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10016 /// \return Result is \p BitWidth and has used bits set to 1 and
10017 /// not used bits set to 0.
10018 APInt getUsedBits() const {
10019 // Reproduce the trunc(lshr) sequence:
10020 // - Start from the truncated value.
10021 // - Zero extend to the desired bit width.
10023 assert(Origin && "No original load to compare against.");
10024 unsigned BitWidth = Origin->getValueSizeInBits(0);
10025 assert(Inst && "This slice is not bound to an instruction");
10026 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10027 "Extracted slice is bigger than the whole type!");
10028 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10029 UsedBits.setAllBits();
10030 UsedBits = UsedBits.zext(BitWidth);
10031 UsedBits <<= Shift;
10035 /// \brief Get the size of the slice to be loaded in bytes.
10036 unsigned getLoadedSize() const {
10037 unsigned SliceSize = getUsedBits().countPopulation();
10038 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10039 return SliceSize / 8;
10042 /// \brief Get the type that will be loaded for this slice.
10043 /// Note: This may not be the final type for the slice.
10044 EVT getLoadedType() const {
10045 assert(DAG && "Missing context");
10046 LLVMContext &Ctxt = *DAG->getContext();
10047 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10050 /// \brief Get the alignment of the load used for this slice.
10051 unsigned getAlignment() const {
10052 unsigned Alignment = Origin->getAlignment();
10053 unsigned Offset = getOffsetFromBase();
10055 Alignment = MinAlign(Alignment, Alignment + Offset);
10059 /// \brief Check if this slice can be rewritten with legal operations.
10060 bool isLegal() const {
10061 // An invalid slice is not legal.
10062 if (!Origin || !Inst || !DAG)
10065 // Offsets are for indexed load only, we do not handle that.
10066 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10069 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10071 // Check that the type is legal.
10072 EVT SliceType = getLoadedType();
10073 if (!TLI.isTypeLegal(SliceType))
10076 // Check that the load is legal for this type.
10077 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10080 // Check that the offset can be computed.
10081 // 1. Check its type.
10082 EVT PtrType = Origin->getBasePtr().getValueType();
10083 if (PtrType == MVT::Untyped || PtrType.isExtended())
10086 // 2. Check that it fits in the immediate.
10087 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10090 // 3. Check that the computation is legal.
10091 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10094 // Check that the zext is legal if it needs one.
10095 EVT TruncateType = Inst->getValueType(0);
10096 if (TruncateType != SliceType &&
10097 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10103 /// \brief Get the offset in bytes of this slice in the original chunk of
10105 /// \pre DAG != nullptr.
10106 uint64_t getOffsetFromBase() const {
10107 assert(DAG && "Missing context.");
10108 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10109 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10110 uint64_t Offset = Shift / 8;
10111 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10112 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10113 "The size of the original loaded type is not a multiple of a"
10115 // If Offset is bigger than TySizeInBytes, it means we are loading all
10116 // zeros. This should have been optimized before in the process.
10117 assert(TySizeInBytes > Offset &&
10118 "Invalid shift amount for given loaded size");
10120 Offset = TySizeInBytes - Offset - getLoadedSize();
10124 /// \brief Generate the sequence of instructions to load the slice
10125 /// represented by this object and redirect the uses of this slice to
10126 /// this new sequence of instructions.
10127 /// \pre this->Inst && this->Origin are valid Instructions and this
10128 /// object passed the legal check: LoadedSlice::isLegal returned true.
10129 /// \return The last instruction of the sequence used to load the slice.
10130 SDValue loadSlice() const {
10131 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10132 const SDValue &OldBaseAddr = Origin->getBasePtr();
10133 SDValue BaseAddr = OldBaseAddr;
10134 // Get the offset in that chunk of bytes w.r.t. the endianess.
10135 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10136 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10138 // BaseAddr = BaseAddr + Offset.
10139 EVT ArithType = BaseAddr.getValueType();
10141 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10142 DAG->getConstant(Offset, DL, ArithType));
10145 // Create the type of the loaded slice according to its size.
10146 EVT SliceType = getLoadedType();
10148 // Create the load for the slice.
10149 SDValue LastInst = DAG->getLoad(
10150 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10151 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10152 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10153 // If the final type is not the same as the loaded type, this means that
10154 // we have to pad with zero. Create a zero extend for that.
10155 EVT FinalType = Inst->getValueType(0);
10156 if (SliceType != FinalType)
10158 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10162 /// \brief Check if this slice can be merged with an expensive cross register
10163 /// bank copy. E.g.,
10165 /// f = bitcast i32 i to float
10166 bool canMergeExpensiveCrossRegisterBankCopy() const {
10167 if (!Inst || !Inst->hasOneUse())
10169 SDNode *Use = *Inst->use_begin();
10170 if (Use->getOpcode() != ISD::BITCAST)
10172 assert(DAG && "Missing context");
10173 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10174 EVT ResVT = Use->getValueType(0);
10175 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10176 const TargetRegisterClass *ArgRC =
10177 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10178 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10181 // At this point, we know that we perform a cross-register-bank copy.
10182 // Check if it is expensive.
10183 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10184 // Assume bitcasts are cheap, unless both register classes do not
10185 // explicitly share a common sub class.
10186 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10189 // Check if it will be merged with the load.
10190 // 1. Check the alignment constraint.
10191 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10192 ResVT.getTypeForEVT(*DAG->getContext()));
10194 if (RequiredAlignment > getAlignment())
10197 // 2. Check that the load is a legal operation for that type.
10198 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10201 // 3. Check that we do not have a zext in the way.
10202 if (Inst->getValueType(0) != getLoadedType())
10210 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10211 /// \p UsedBits looks like 0..0 1..1 0..0.
10212 static bool areUsedBitsDense(const APInt &UsedBits) {
10213 // If all the bits are one, this is dense!
10214 if (UsedBits.isAllOnesValue())
10217 // Get rid of the unused bits on the right.
10218 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10219 // Get rid of the unused bits on the left.
10220 if (NarrowedUsedBits.countLeadingZeros())
10221 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10222 // Check that the chunk of bits is completely used.
10223 return NarrowedUsedBits.isAllOnesValue();
10226 /// \brief Check whether or not \p First and \p Second are next to each other
10227 /// in memory. This means that there is no hole between the bits loaded
10228 /// by \p First and the bits loaded by \p Second.
10229 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10230 const LoadedSlice &Second) {
10231 assert(First.Origin == Second.Origin && First.Origin &&
10232 "Unable to match different memory origins.");
10233 APInt UsedBits = First.getUsedBits();
10234 assert((UsedBits & Second.getUsedBits()) == 0 &&
10235 "Slices are not supposed to overlap.");
10236 UsedBits |= Second.getUsedBits();
10237 return areUsedBitsDense(UsedBits);
10240 /// \brief Adjust the \p GlobalLSCost according to the target
10241 /// paring capabilities and the layout of the slices.
10242 /// \pre \p GlobalLSCost should account for at least as many loads as
10243 /// there is in the slices in \p LoadedSlices.
10244 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10245 LoadedSlice::Cost &GlobalLSCost) {
10246 unsigned NumberOfSlices = LoadedSlices.size();
10247 // If there is less than 2 elements, no pairing is possible.
10248 if (NumberOfSlices < 2)
10251 // Sort the slices so that elements that are likely to be next to each
10252 // other in memory are next to each other in the list.
10253 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10254 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10255 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10256 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10258 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10259 // First (resp. Second) is the first (resp. Second) potentially candidate
10260 // to be placed in a paired load.
10261 const LoadedSlice *First = nullptr;
10262 const LoadedSlice *Second = nullptr;
10263 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10264 // Set the beginning of the pair.
10267 Second = &LoadedSlices[CurrSlice];
10269 // If First is NULL, it means we start a new pair.
10270 // Get to the next slice.
10274 EVT LoadedType = First->getLoadedType();
10276 // If the types of the slices are different, we cannot pair them.
10277 if (LoadedType != Second->getLoadedType())
10280 // Check if the target supplies paired loads for this type.
10281 unsigned RequiredAlignment = 0;
10282 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10283 // move to the next pair, this type is hopeless.
10287 // Check if we meet the alignment requirement.
10288 if (RequiredAlignment > First->getAlignment())
10291 // Check that both loads are next to each other in memory.
10292 if (!areSlicesNextToEachOther(*First, *Second))
10295 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10296 --GlobalLSCost.Loads;
10297 // Move to the next pair.
10302 /// \brief Check the profitability of all involved LoadedSlice.
10303 /// Currently, it is considered profitable if there is exactly two
10304 /// involved slices (1) which are (2) next to each other in memory, and
10305 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10307 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10308 /// the elements themselves.
10310 /// FIXME: When the cost model will be mature enough, we can relax
10311 /// constraints (1) and (2).
10312 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10313 const APInt &UsedBits, bool ForCodeSize) {
10314 unsigned NumberOfSlices = LoadedSlices.size();
10315 if (StressLoadSlicing)
10316 return NumberOfSlices > 1;
10319 if (NumberOfSlices != 2)
10323 if (!areUsedBitsDense(UsedBits))
10327 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10328 // The original code has one big load.
10329 OrigCost.Loads = 1;
10330 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10331 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10332 // Accumulate the cost of all the slices.
10333 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10334 GlobalSlicingCost += SliceCost;
10336 // Account as cost in the original configuration the gain obtained
10337 // with the current slices.
10338 OrigCost.addSliceGain(LS);
10341 // If the target supports paired load, adjust the cost accordingly.
10342 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10343 return OrigCost > GlobalSlicingCost;
10346 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10347 /// operations, split it in the various pieces being extracted.
10349 /// This sort of thing is introduced by SROA.
10350 /// This slicing takes care not to insert overlapping loads.
10351 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10352 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10353 if (Level < AfterLegalizeDAG)
10356 LoadSDNode *LD = cast<LoadSDNode>(N);
10357 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10358 !LD->getValueType(0).isInteger())
10361 // Keep track of already used bits to detect overlapping values.
10362 // In that case, we will just abort the transformation.
10363 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10365 SmallVector<LoadedSlice, 4> LoadedSlices;
10367 // Check if this load is used as several smaller chunks of bits.
10368 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10369 // of computation for each trunc.
10370 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10371 UI != UIEnd; ++UI) {
10372 // Skip the uses of the chain.
10373 if (UI.getUse().getResNo() != 0)
10376 SDNode *User = *UI;
10377 unsigned Shift = 0;
10379 // Check if this is a trunc(lshr).
10380 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10381 isa<ConstantSDNode>(User->getOperand(1))) {
10382 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10383 User = *User->use_begin();
10386 // At this point, User is a Truncate, iff we encountered, trunc or
10388 if (User->getOpcode() != ISD::TRUNCATE)
10391 // The width of the type must be a power of 2 and greater than 8-bits.
10392 // Otherwise the load cannot be represented in LLVM IR.
10393 // Moreover, if we shifted with a non-8-bits multiple, the slice
10394 // will be across several bytes. We do not support that.
10395 unsigned Width = User->getValueSizeInBits(0);
10396 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10399 // Build the slice for this chain of computations.
10400 LoadedSlice LS(User, LD, Shift, &DAG);
10401 APInt CurrentUsedBits = LS.getUsedBits();
10403 // Check if this slice overlaps with another.
10404 if ((CurrentUsedBits & UsedBits) != 0)
10406 // Update the bits used globally.
10407 UsedBits |= CurrentUsedBits;
10409 // Check if the new slice would be legal.
10413 // Record the slice.
10414 LoadedSlices.push_back(LS);
10417 // Abort slicing if it does not seem to be profitable.
10418 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10423 // Rewrite each chain to use an independent load.
10424 // By construction, each chain can be represented by a unique load.
10426 // Prepare the argument for the new token factor for all the slices.
10427 SmallVector<SDValue, 8> ArgChains;
10428 for (SmallVectorImpl<LoadedSlice>::const_iterator
10429 LSIt = LoadedSlices.begin(),
10430 LSItEnd = LoadedSlices.end();
10431 LSIt != LSItEnd; ++LSIt) {
10432 SDValue SliceInst = LSIt->loadSlice();
10433 CombineTo(LSIt->Inst, SliceInst, true);
10434 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10435 SliceInst = SliceInst.getOperand(0);
10436 assert(SliceInst->getOpcode() == ISD::LOAD &&
10437 "It takes more than a zext to get to the loaded slice!!");
10438 ArgChains.push_back(SliceInst.getValue(1));
10441 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10443 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10447 /// Check to see if V is (and load (ptr), imm), where the load is having
10448 /// specific bytes cleared out. If so, return the byte size being masked out
10449 /// and the shift amount.
10450 static std::pair<unsigned, unsigned>
10451 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10452 std::pair<unsigned, unsigned> Result(0, 0);
10454 // Check for the structure we're looking for.
10455 if (V->getOpcode() != ISD::AND ||
10456 !isa<ConstantSDNode>(V->getOperand(1)) ||
10457 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10460 // Check the chain and pointer.
10461 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10462 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10464 // The store should be chained directly to the load or be an operand of a
10466 if (LD == Chain.getNode())
10468 else if (Chain->getOpcode() != ISD::TokenFactor)
10469 return Result; // Fail.
10472 for (const SDValue &ChainOp : Chain->op_values())
10473 if (ChainOp.getNode() == LD) {
10477 if (!isOk) return Result;
10480 // This only handles simple types.
10481 if (V.getValueType() != MVT::i16 &&
10482 V.getValueType() != MVT::i32 &&
10483 V.getValueType() != MVT::i64)
10486 // Check the constant mask. Invert it so that the bits being masked out are
10487 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10488 // follow the sign bit for uniformity.
10489 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10490 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10491 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10492 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10493 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10494 if (NotMaskLZ == 64) return Result; // All zero mask.
10496 // See if we have a continuous run of bits. If so, we have 0*1+0*
10497 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10500 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10501 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10502 NotMaskLZ -= 64-V.getValueSizeInBits();
10504 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10505 switch (MaskedBytes) {
10509 default: return Result; // All one mask, or 5-byte mask.
10512 // Verify that the first bit starts at a multiple of mask so that the access
10513 // is aligned the same as the access width.
10514 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10516 Result.first = MaskedBytes;
10517 Result.second = NotMaskTZ/8;
10522 /// Check to see if IVal is something that provides a value as specified by
10523 /// MaskInfo. If so, replace the specified store with a narrower store of
10524 /// truncated IVal.
10526 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10527 SDValue IVal, StoreSDNode *St,
10529 unsigned NumBytes = MaskInfo.first;
10530 unsigned ByteShift = MaskInfo.second;
10531 SelectionDAG &DAG = DC->getDAG();
10533 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10534 // that uses this. If not, this is not a replacement.
10535 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10536 ByteShift*8, (ByteShift+NumBytes)*8);
10537 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10539 // Check that it is legal on the target to do this. It is legal if the new
10540 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10542 MVT VT = MVT::getIntegerVT(NumBytes*8);
10543 if (!DC->isTypeLegal(VT))
10546 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10547 // shifted by ByteShift and truncated down to NumBytes.
10550 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10551 DAG.getConstant(ByteShift*8, DL,
10552 DC->getShiftAmountTy(IVal.getValueType())));
10555 // Figure out the offset for the store and the alignment of the access.
10557 unsigned NewAlign = St->getAlignment();
10559 if (DAG.getDataLayout().isLittleEndian())
10560 StOffset = ByteShift;
10562 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10564 SDValue Ptr = St->getBasePtr();
10567 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10568 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10569 NewAlign = MinAlign(NewAlign, StOffset);
10572 // Truncate down to the new size.
10573 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10576 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10577 St->getPointerInfo().getWithOffset(StOffset),
10578 false, false, NewAlign).getNode();
10582 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10583 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10584 /// narrowing the load and store if it would end up being a win for performance
10586 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10587 StoreSDNode *ST = cast<StoreSDNode>(N);
10588 if (ST->isVolatile())
10591 SDValue Chain = ST->getChain();
10592 SDValue Value = ST->getValue();
10593 SDValue Ptr = ST->getBasePtr();
10594 EVT VT = Value.getValueType();
10596 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10599 unsigned Opc = Value.getOpcode();
10601 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10602 // is a byte mask indicating a consecutive number of bytes, check to see if
10603 // Y is known to provide just those bytes. If so, we try to replace the
10604 // load + replace + store sequence with a single (narrower) store, which makes
10606 if (Opc == ISD::OR) {
10607 std::pair<unsigned, unsigned> MaskedLoad;
10608 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10609 if (MaskedLoad.first)
10610 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10611 Value.getOperand(1), ST,this))
10612 return SDValue(NewST, 0);
10614 // Or is commutative, so try swapping X and Y.
10615 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10616 if (MaskedLoad.first)
10617 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10618 Value.getOperand(0), ST,this))
10619 return SDValue(NewST, 0);
10622 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10623 Value.getOperand(1).getOpcode() != ISD::Constant)
10626 SDValue N0 = Value.getOperand(0);
10627 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10628 Chain == SDValue(N0.getNode(), 1)) {
10629 LoadSDNode *LD = cast<LoadSDNode>(N0);
10630 if (LD->getBasePtr() != Ptr ||
10631 LD->getPointerInfo().getAddrSpace() !=
10632 ST->getPointerInfo().getAddrSpace())
10635 // Find the type to narrow it the load / op / store to.
10636 SDValue N1 = Value.getOperand(1);
10637 unsigned BitWidth = N1.getValueSizeInBits();
10638 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10639 if (Opc == ISD::AND)
10640 Imm ^= APInt::getAllOnesValue(BitWidth);
10641 if (Imm == 0 || Imm.isAllOnesValue())
10643 unsigned ShAmt = Imm.countTrailingZeros();
10644 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10645 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10646 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10647 // The narrowing should be profitable, the load/store operation should be
10648 // legal (or custom) and the store size should be equal to the NewVT width.
10649 while (NewBW < BitWidth &&
10650 (NewVT.getStoreSizeInBits() != NewBW ||
10651 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10652 !TLI.isNarrowingProfitable(VT, NewVT))) {
10653 NewBW = NextPowerOf2(NewBW);
10654 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10656 if (NewBW >= BitWidth)
10659 // If the lsb changed does not start at the type bitwidth boundary,
10660 // start at the previous one.
10662 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10663 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10664 std::min(BitWidth, ShAmt + NewBW));
10665 if ((Imm & Mask) == Imm) {
10666 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10667 if (Opc == ISD::AND)
10668 NewImm ^= APInt::getAllOnesValue(NewBW);
10669 uint64_t PtrOff = ShAmt / 8;
10670 // For big endian targets, we need to adjust the offset to the pointer to
10671 // load the correct bytes.
10672 if (DAG.getDataLayout().isBigEndian())
10673 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10675 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10676 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10677 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10680 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10681 Ptr.getValueType(), Ptr,
10682 DAG.getConstant(PtrOff, SDLoc(LD),
10683 Ptr.getValueType()));
10684 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10685 LD->getChain(), NewPtr,
10686 LD->getPointerInfo().getWithOffset(PtrOff),
10687 LD->isVolatile(), LD->isNonTemporal(),
10688 LD->isInvariant(), NewAlign,
10690 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10691 DAG.getConstant(NewImm, SDLoc(Value),
10693 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10695 ST->getPointerInfo().getWithOffset(PtrOff),
10696 false, false, NewAlign);
10698 AddToWorklist(NewPtr.getNode());
10699 AddToWorklist(NewLD.getNode());
10700 AddToWorklist(NewVal.getNode());
10701 WorklistRemover DeadNodes(*this);
10702 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10711 /// For a given floating point load / store pair, if the load value isn't used
10712 /// by any other operations, then consider transforming the pair to integer
10713 /// load / store operations if the target deems the transformation profitable.
10714 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10715 StoreSDNode *ST = cast<StoreSDNode>(N);
10716 SDValue Chain = ST->getChain();
10717 SDValue Value = ST->getValue();
10718 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10719 Value.hasOneUse() &&
10720 Chain == SDValue(Value.getNode(), 1)) {
10721 LoadSDNode *LD = cast<LoadSDNode>(Value);
10722 EVT VT = LD->getMemoryVT();
10723 if (!VT.isFloatingPoint() ||
10724 VT != ST->getMemoryVT() ||
10725 LD->isNonTemporal() ||
10726 ST->isNonTemporal() ||
10727 LD->getPointerInfo().getAddrSpace() != 0 ||
10728 ST->getPointerInfo().getAddrSpace() != 0)
10731 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10732 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10733 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10734 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10735 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10738 unsigned LDAlign = LD->getAlignment();
10739 unsigned STAlign = ST->getAlignment();
10740 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10741 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10742 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10745 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10746 LD->getChain(), LD->getBasePtr(),
10747 LD->getPointerInfo(),
10748 false, false, false, LDAlign);
10750 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10751 NewLD, ST->getBasePtr(),
10752 ST->getPointerInfo(),
10753 false, false, STAlign);
10755 AddToWorklist(NewLD.getNode());
10756 AddToWorklist(NewST.getNode());
10757 WorklistRemover DeadNodes(*this);
10758 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10767 /// Helper struct to parse and store a memory address as base + index + offset.
10768 /// We ignore sign extensions when it is safe to do so.
10769 /// The following two expressions are not equivalent. To differentiate we need
10770 /// to store whether there was a sign extension involved in the index
10772 /// (load (i64 add (i64 copyfromreg %c)
10773 /// (i64 signextend (add (i8 load %index)
10777 /// (load (i64 add (i64 copyfromreg %c)
10778 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10780 struct BaseIndexOffset {
10784 bool IsIndexSignExt;
10786 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10788 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10789 bool IsIndexSignExt) :
10790 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10792 bool equalBaseIndex(const BaseIndexOffset &Other) {
10793 return Other.Base == Base && Other.Index == Index &&
10794 Other.IsIndexSignExt == IsIndexSignExt;
10797 /// Parses tree in Ptr for base, index, offset addresses.
10798 static BaseIndexOffset match(SDValue Ptr) {
10799 bool IsIndexSignExt = false;
10801 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10802 // instruction, then it could be just the BASE or everything else we don't
10803 // know how to handle. Just use Ptr as BASE and give up.
10804 if (Ptr->getOpcode() != ISD::ADD)
10805 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10807 // We know that we have at least an ADD instruction. Try to pattern match
10808 // the simple case of BASE + OFFSET.
10809 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10810 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10811 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10815 // Inside a loop the current BASE pointer is calculated using an ADD and a
10816 // MUL instruction. In this case Ptr is the actual BASE pointer.
10817 // (i64 add (i64 %array_ptr)
10818 // (i64 mul (i64 %induction_var)
10819 // (i64 %element_size)))
10820 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10821 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10823 // Look at Base + Index + Offset cases.
10824 SDValue Base = Ptr->getOperand(0);
10825 SDValue IndexOffset = Ptr->getOperand(1);
10827 // Skip signextends.
10828 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10829 IndexOffset = IndexOffset->getOperand(0);
10830 IsIndexSignExt = true;
10833 // Either the case of Base + Index (no offset) or something else.
10834 if (IndexOffset->getOpcode() != ISD::ADD)
10835 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10837 // Now we have the case of Base + Index + offset.
10838 SDValue Index = IndexOffset->getOperand(0);
10839 SDValue Offset = IndexOffset->getOperand(1);
10841 if (!isa<ConstantSDNode>(Offset))
10842 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10844 // Ignore signextends.
10845 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10846 Index = Index->getOperand(0);
10847 IsIndexSignExt = true;
10848 } else IsIndexSignExt = false;
10850 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10851 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10856 // This is a helper function for visitMUL to check the profitability
10857 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
10858 // MulNode is the original multiply, AddNode is (add x, c1),
10859 // and ConstNode is c2.
10861 // If the (add x, c1) has multiple uses, we could increase
10862 // the number of adds if we make this transformation.
10863 // It would only be worth doing this if we can remove a
10864 // multiply in the process. Check for that here.
10868 // We're checking for cases where we have common "c3 * A" expressions.
10869 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
10871 SDValue &ConstNode) {
10874 // If the add only has one use, this would be OK to do.
10875 if (AddNode.getNode()->hasOneUse())
10878 // Walk all the users of the constant with which we're multiplying.
10879 for (SDNode *Use : ConstNode->uses()) {
10881 if (Use == MulNode) // This use is the one we're on right now. Skip it.
10884 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
10886 SDNode *MulVar = AddNode.getOperand(0).getNode();
10888 // OtherOp is what we're multiplying against the constant.
10889 if (Use->getOperand(0) == ConstNode)
10890 OtherOp = Use->getOperand(1).getNode();
10892 OtherOp = Use->getOperand(0).getNode();
10894 // Check to see if multiply is with the same operand of our "add".
10896 // ConstNode = CONST
10897 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
10899 // AddNode = (A + c1) <-- MulVar is A.
10900 // = AddNode * ConstNode <-- current visiting instruction.
10902 // If we make this transformation, we will have a common
10903 // multiply (ConstNode * A) that we can save.
10904 if (OtherOp == MulVar)
10907 // Now check to see if a future expansion will give us a common
10910 // ConstNode = CONST
10911 // AddNode = (A + c1)
10912 // ... = AddNode * ConstNode <-- current visiting instruction.
10914 // OtherOp = (A + c2)
10915 // Use = OtherOp * ConstNode <-- visiting Use.
10917 // If we make this transformation, we will have a common
10918 // multiply (CONST * A) after we also do the same transformation
10919 // to the "t2" instruction.
10920 if (OtherOp->getOpcode() == ISD::ADD &&
10921 isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
10922 OtherOp->getOperand(0).getNode() == MulVar)
10927 // Didn't find a case where this would be profitable.
10931 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10933 ArrayRef<MemOpLink> Stores,
10934 SmallVectorImpl<SDValue> &Chains,
10936 SmallVector<SDValue, 8> BuildVector;
10938 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10939 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10940 Chains.push_back(St->getChain());
10941 BuildVector.push_back(St->getValue());
10944 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10947 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10948 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10949 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10950 // Make sure we have something to merge.
10954 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10955 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10956 unsigned LatestNodeUsed = 0;
10958 for (unsigned i=0; i < NumStores; ++i) {
10959 // Find a chain for the new wide-store operand. Notice that some
10960 // of the store nodes that we found may not be selected for inclusion
10961 // in the wide store. The chain we use needs to be the chain of the
10962 // latest store node which is *used* and replaced by the wide store.
10963 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10964 LatestNodeUsed = i;
10967 SmallVector<SDValue, 8> Chains;
10969 // The latest Node in the DAG.
10970 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10971 SDLoc DL(StoreNodes[0].MemNode);
10975 bool IsVec = MemVT.isVector();
10976 unsigned Elts = NumStores;
10978 // When merging vector stores, get the total number of elements.
10979 Elts *= MemVT.getVectorNumElements();
10981 // Get the type for the merged vector store.
10982 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10983 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10985 if (IsConstantSrc) {
10986 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10988 SmallVector<SDValue, 8> Ops;
10989 for (unsigned i = 0; i < NumStores; ++i) {
10990 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10991 SDValue Val = St->getValue();
10992 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10993 if (Val.getValueType() != MemVT)
10995 Ops.push_back(Val);
10996 Chains.push_back(St->getChain());
10999 // Build the extracted vector elements back into a vector.
11000 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11003 // We should always use a vector store when merging extracted vector
11004 // elements, so this path implies a store of constants.
11005 assert(IsConstantSrc && "Merged vector elements should use vector store");
11007 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11008 APInt StoreInt(SizeInBits, 0);
11010 // Construct a single integer constant which is made of the smaller
11011 // constant inputs.
11012 bool IsLE = DAG.getDataLayout().isLittleEndian();
11013 for (unsigned i = 0; i < NumStores; ++i) {
11014 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11015 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11016 Chains.push_back(St->getChain());
11018 SDValue Val = St->getValue();
11019 StoreInt <<= ElementSizeBytes * 8;
11020 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11021 StoreInt |= C->getAPIntValue().zext(SizeInBits);
11022 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11023 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11025 llvm_unreachable("Invalid constant element type");
11029 // Create the new Load and Store operations.
11030 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11031 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11034 assert(!Chains.empty());
11036 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11037 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11038 FirstInChain->getBasePtr(),
11039 FirstInChain->getPointerInfo(),
11041 FirstInChain->getAlignment());
11043 // Replace the last store with the new store
11044 CombineTo(LatestOp, NewStore);
11045 // Erase all other stores.
11046 for (unsigned i = 0; i < NumStores; ++i) {
11047 if (StoreNodes[i].MemNode == LatestOp)
11049 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11050 // ReplaceAllUsesWith will replace all uses that existed when it was
11051 // called, but graph optimizations may cause new ones to appear. For
11052 // example, the case in pr14333 looks like
11054 // St's chain -> St -> another store -> X
11056 // And the only difference from St to the other store is the chain.
11057 // When we change it's chain to be St's chain they become identical,
11058 // get CSEed and the net result is that X is now a use of St.
11059 // Since we know that St is redundant, just iterate.
11060 while (!St->use_empty())
11061 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11062 deleteAndRecombine(St);
11068 void DAGCombiner::getStoreMergeAndAliasCandidates(
11069 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11070 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11071 // This holds the base pointer, index, and the offset in bytes from the base
11073 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11075 // We must have a base and an offset.
11076 if (!BasePtr.Base.getNode())
11079 // Do not handle stores to undef base pointers.
11080 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11083 // Walk up the chain and look for nodes with offsets from the same
11084 // base pointer. Stop when reaching an instruction with a different kind
11085 // or instruction which has a different base pointer.
11086 EVT MemVT = St->getMemoryVT();
11088 StoreSDNode *Index = St;
11091 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11092 : DAG.getSubtarget().useAA();
11095 // Look at other users of the same chain. Stores on the same chain do not
11096 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11097 // to be on the same chain, so don't bother looking at adjacent chains.
11099 SDValue Chain = St->getChain();
11100 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11101 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11102 if (I.getOperandNo() != 0)
11105 if (OtherST->isVolatile() || OtherST->isIndexed())
11108 if (OtherST->getMemoryVT() != MemVT)
11111 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11113 if (Ptr.equalBaseIndex(BasePtr))
11114 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11122 // If the chain has more than one use, then we can't reorder the mem ops.
11123 if (Index != St && !SDValue(Index, 0)->hasOneUse())
11126 // Find the base pointer and offset for this memory node.
11127 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11129 // Check that the base pointer is the same as the original one.
11130 if (!Ptr.equalBaseIndex(BasePtr))
11133 // The memory operands must not be volatile.
11134 if (Index->isVolatile() || Index->isIndexed())
11138 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11139 if (St->isTruncatingStore())
11142 // The stored memory type must be the same.
11143 if (Index->getMemoryVT() != MemVT)
11146 // We found a potential memory operand to merge.
11147 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11149 // Find the next memory operand in the chain. If the next operand in the
11150 // chain is a store then move up and continue the scan with the next
11151 // memory operand. If the next operand is a load save it and use alias
11152 // information to check if it interferes with anything.
11153 SDNode *NextInChain = Index->getChain().getNode();
11155 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11156 // We found a store node. Use it for the next iteration.
11159 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11160 if (Ldn->isVolatile()) {
11165 // Save the load node for later. Continue the scan.
11166 AliasLoadNodes.push_back(Ldn);
11167 NextInChain = Ldn->getChain().getNode();
11177 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11178 if (OptLevel == CodeGenOpt::None)
11181 EVT MemVT = St->getMemoryVT();
11182 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11183 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11184 Attribute::NoImplicitFloat);
11186 // This function cannot currently deal with non-byte-sized memory sizes.
11187 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11190 if (!MemVT.isSimple())
11193 // Perform an early exit check. Do not bother looking at stored values that
11194 // are not constants, loads, or extracted vector elements.
11195 SDValue StoredVal = St->getValue();
11196 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11197 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11198 isa<ConstantFPSDNode>(StoredVal);
11199 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11200 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11202 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11205 // Don't merge vectors into wider vectors if the source data comes from loads.
11206 // TODO: This restriction can be lifted by using logic similar to the
11207 // ExtractVecSrc case.
11208 if (MemVT.isVector() && IsLoadSrc)
11211 // Only look at ends of store sequences.
11212 SDValue Chain = SDValue(St, 0);
11213 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11216 // Save the LoadSDNodes that we find in the chain.
11217 // We need to make sure that these nodes do not interfere with
11218 // any of the store nodes.
11219 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11221 // Save the StoreSDNodes that we find in the chain.
11222 SmallVector<MemOpLink, 8> StoreNodes;
11224 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11226 // Check if there is anything to merge.
11227 if (StoreNodes.size() < 2)
11230 // Sort the memory operands according to their distance from the base pointer.
11231 std::sort(StoreNodes.begin(), StoreNodes.end(),
11232 [](MemOpLink LHS, MemOpLink RHS) {
11233 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11234 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11235 LHS.SequenceNum > RHS.SequenceNum);
11238 // Scan the memory operations on the chain and find the first non-consecutive
11239 // store memory address.
11240 unsigned LastConsecutiveStore = 0;
11241 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11242 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11244 // Check that the addresses are consecutive starting from the second
11245 // element in the list of stores.
11247 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11248 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11252 bool Alias = false;
11253 // Check if this store interferes with any of the loads that we found.
11254 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11255 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11259 // We found a load that alias with this store. Stop the sequence.
11263 // Mark this node as useful.
11264 LastConsecutiveStore = i;
11267 // The node with the lowest store address.
11268 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11269 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11270 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11271 LLVMContext &Context = *DAG.getContext();
11272 const DataLayout &DL = DAG.getDataLayout();
11274 // Store the constants into memory as one consecutive store.
11275 if (IsConstantSrc) {
11276 unsigned LastLegalType = 0;
11277 unsigned LastLegalVectorType = 0;
11278 bool NonZero = false;
11279 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11280 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11281 SDValue StoredVal = St->getValue();
11283 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11284 NonZero |= !C->isNullValue();
11285 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11286 NonZero |= !C->getConstantFPValue()->isNullValue();
11292 // Find a legal type for the constant store.
11293 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11294 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11296 if (TLI.isTypeLegal(StoreTy) &&
11297 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11298 FirstStoreAlign, &IsFast) && IsFast) {
11299 LastLegalType = i+1;
11300 // Or check whether a truncstore is legal.
11301 } else if (TLI.getTypeAction(Context, StoreTy) ==
11302 TargetLowering::TypePromoteInteger) {
11303 EVT LegalizedStoredValueTy =
11304 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11305 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11306 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11307 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11309 LastLegalType = i + 1;
11313 // We only use vectors if the constant is known to be zero or the target
11314 // allows it and the function is not marked with the noimplicitfloat
11316 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11319 // Find a legal type for the vector store.
11320 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11321 if (TLI.isTypeLegal(Ty) &&
11322 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11323 FirstStoreAlign, &IsFast) && IsFast)
11324 LastLegalVectorType = i + 1;
11328 // Check if we found a legal integer type to store.
11329 if (LastLegalType == 0 && LastLegalVectorType == 0)
11332 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11333 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11335 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11339 // When extracting multiple vector elements, try to store them
11340 // in one vector store rather than a sequence of scalar stores.
11341 if (IsExtractVecSrc) {
11342 unsigned NumStoresToMerge = 0;
11343 bool IsVec = MemVT.isVector();
11344 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11345 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11346 unsigned StoreValOpcode = St->getValue().getOpcode();
11347 // This restriction could be loosened.
11348 // Bail out if any stored values are not elements extracted from a vector.
11349 // It should be possible to handle mixed sources, but load sources need
11350 // more careful handling (see the block of code below that handles
11351 // consecutive loads).
11352 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11353 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11356 // Find a legal type for the vector store.
11357 unsigned Elts = i + 1;
11359 // When merging vector stores, get the total number of elements.
11360 Elts *= MemVT.getVectorNumElements();
11362 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11364 if (TLI.isTypeLegal(Ty) &&
11365 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11366 FirstStoreAlign, &IsFast) && IsFast)
11367 NumStoresToMerge = i + 1;
11370 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11374 // Below we handle the case of multiple consecutive stores that
11375 // come from multiple consecutive loads. We merge them into a single
11376 // wide load and a single wide store.
11378 // Look for load nodes which are used by the stored values.
11379 SmallVector<MemOpLink, 8> LoadNodes;
11381 // Find acceptable loads. Loads need to have the same chain (token factor),
11382 // must not be zext, volatile, indexed, and they must be consecutive.
11383 BaseIndexOffset LdBasePtr;
11384 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11385 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11386 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11389 // Loads must only have one use.
11390 if (!Ld->hasNUsesOfValue(1, 0))
11393 // The memory operands must not be volatile.
11394 if (Ld->isVolatile() || Ld->isIndexed())
11397 // We do not accept ext loads.
11398 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11401 // The stored memory type must be the same.
11402 if (Ld->getMemoryVT() != MemVT)
11405 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11406 // If this is not the first ptr that we check.
11407 if (LdBasePtr.Base.getNode()) {
11408 // The base ptr must be the same.
11409 if (!LdPtr.equalBaseIndex(LdBasePtr))
11412 // Check that all other base pointers are the same as this one.
11416 // We found a potential memory operand to merge.
11417 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11420 if (LoadNodes.size() < 2)
11423 // If we have load/store pair instructions and we only have two values,
11425 unsigned RequiredAlignment;
11426 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11427 St->getAlignment() >= RequiredAlignment)
11430 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11431 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11432 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11434 // Scan the memory operations on the chain and find the first non-consecutive
11435 // load memory address. These variables hold the index in the store node
11437 unsigned LastConsecutiveLoad = 0;
11438 // This variable refers to the size and not index in the array.
11439 unsigned LastLegalVectorType = 0;
11440 unsigned LastLegalIntegerType = 0;
11441 StartAddress = LoadNodes[0].OffsetFromBase;
11442 SDValue FirstChain = FirstLoad->getChain();
11443 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11444 // All loads much share the same chain.
11445 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11448 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11449 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11451 LastConsecutiveLoad = i;
11452 // Find a legal type for the vector store.
11453 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11454 bool IsFastSt, IsFastLd;
11455 if (TLI.isTypeLegal(StoreTy) &&
11456 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11457 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11458 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11459 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11460 LastLegalVectorType = i + 1;
11463 // Find a legal type for the integer store.
11464 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11465 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11466 if (TLI.isTypeLegal(StoreTy) &&
11467 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11468 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11469 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11470 FirstLoadAlign, &IsFastLd) && IsFastLd)
11471 LastLegalIntegerType = i + 1;
11472 // Or check whether a truncstore and extload is legal.
11473 else if (TLI.getTypeAction(Context, StoreTy) ==
11474 TargetLowering::TypePromoteInteger) {
11475 EVT LegalizedStoredValueTy =
11476 TLI.getTypeToTransformTo(Context, StoreTy);
11477 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11478 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11479 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11480 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11481 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11482 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11484 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11485 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11487 LastLegalIntegerType = i+1;
11491 // Only use vector types if the vector type is larger than the integer type.
11492 // If they are the same, use integers.
11493 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11494 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11496 // We add +1 here because the LastXXX variables refer to location while
11497 // the NumElem refers to array/index size.
11498 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11499 NumElem = std::min(LastLegalType, NumElem);
11504 // Collect the chains from all merged stores.
11505 SmallVector<SDValue, 8> MergeStoreChains;
11506 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11508 // The latest Node in the DAG.
11509 unsigned LatestNodeUsed = 0;
11510 for (unsigned i=1; i<NumElem; ++i) {
11511 // Find a chain for the new wide-store operand. Notice that some
11512 // of the store nodes that we found may not be selected for inclusion
11513 // in the wide store. The chain we use needs to be the chain of the
11514 // latest store node which is *used* and replaced by the wide store.
11515 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11516 LatestNodeUsed = i;
11518 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11521 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11523 // Find if it is better to use vectors or integers to load and store
11527 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11529 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11530 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11533 SDLoc LoadDL(LoadNodes[0].MemNode);
11534 SDLoc StoreDL(StoreNodes[0].MemNode);
11536 // The merged loads are required to have the same chain, so using the first's
11537 // chain is acceptable.
11538 SDValue NewLoad = DAG.getLoad(
11539 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11540 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11542 SDValue NewStoreChain =
11543 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11545 SDValue NewStore = DAG.getStore(
11546 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11547 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11549 // Replace one of the loads with the new load.
11550 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11551 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11552 SDValue(NewLoad.getNode(), 1));
11554 // Remove the rest of the load chains.
11555 for (unsigned i = 1; i < NumElem ; ++i) {
11556 // Replace all chain users of the old load nodes with the chain of the new
11558 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11559 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11562 // Replace the last store with the new store.
11563 CombineTo(LatestOp, NewStore);
11564 // Erase all other stores.
11565 for (unsigned i = 0; i < NumElem ; ++i) {
11566 // Remove all Store nodes.
11567 if (StoreNodes[i].MemNode == LatestOp)
11569 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11570 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11571 deleteAndRecombine(St);
11577 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11581 // Replace the chain to avoid dependency.
11582 if (ST->isTruncatingStore()) {
11583 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11584 ST->getBasePtr(), ST->getMemoryVT(),
11585 ST->getMemOperand());
11587 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11588 ST->getMemOperand());
11591 // Create token to keep both nodes around.
11592 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11593 MVT::Other, ST->getChain(), ReplStore);
11595 // Make sure the new and old chains are cleaned up.
11596 AddToWorklist(Token.getNode());
11598 // Don't add users to work list.
11599 return CombineTo(ST, Token, false);
11602 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11603 SDValue Value = ST->getValue();
11604 if (Value.getOpcode() == ISD::TargetConstantFP)
11609 SDValue Chain = ST->getChain();
11610 SDValue Ptr = ST->getBasePtr();
11612 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11614 // NOTE: If the original store is volatile, this transform must not increase
11615 // the number of stores. For example, on x86-32 an f64 can be stored in one
11616 // processor operation but an i64 (which is not legal) requires two. So the
11617 // transform should not be done in this case.
11620 switch (CFP->getSimpleValueType(0).SimpleTy) {
11622 llvm_unreachable("Unknown FP type");
11623 case MVT::f16: // We don't do this for these yet.
11629 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11630 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11632 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11633 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11635 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11640 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11641 !ST->isVolatile()) ||
11642 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11644 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11645 getZExtValue(), SDLoc(CFP), MVT::i64);
11646 return DAG.getStore(Chain, DL, Tmp,
11647 Ptr, ST->getMemOperand());
11650 if (!ST->isVolatile() &&
11651 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11652 // Many FP stores are not made apparent until after legalize, e.g. for
11653 // argument passing. Since this is so common, custom legalize the
11654 // 64-bit integer store into two 32-bit stores.
11655 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11656 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11657 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11658 if (DAG.getDataLayout().isBigEndian())
11661 unsigned Alignment = ST->getAlignment();
11662 bool isVolatile = ST->isVolatile();
11663 bool isNonTemporal = ST->isNonTemporal();
11664 AAMDNodes AAInfo = ST->getAAInfo();
11666 SDValue St0 = DAG.getStore(Chain, DL, Lo,
11667 Ptr, ST->getPointerInfo(),
11668 isVolatile, isNonTemporal,
11669 ST->getAlignment(), AAInfo);
11670 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11671 DAG.getConstant(4, DL, Ptr.getValueType()));
11672 Alignment = MinAlign(Alignment, 4U);
11673 SDValue St1 = DAG.getStore(Chain, DL, Hi,
11674 Ptr, ST->getPointerInfo().getWithOffset(4),
11675 isVolatile, isNonTemporal,
11676 Alignment, AAInfo);
11677 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11685 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11686 StoreSDNode *ST = cast<StoreSDNode>(N);
11687 SDValue Chain = ST->getChain();
11688 SDValue Value = ST->getValue();
11689 SDValue Ptr = ST->getBasePtr();
11691 // If this is a store of a bit convert, store the input value if the
11692 // resultant store does not need a higher alignment than the original.
11693 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11694 ST->isUnindexed()) {
11695 unsigned OrigAlign = ST->getAlignment();
11696 EVT SVT = Value.getOperand(0).getValueType();
11697 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11698 SVT.getTypeForEVT(*DAG.getContext()));
11699 if (Align <= OrigAlign &&
11700 ((!LegalOperations && !ST->isVolatile()) ||
11701 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11702 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11703 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11704 ST->isNonTemporal(), OrigAlign,
11708 // Turn 'store undef, Ptr' -> nothing.
11709 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11712 // Try to infer better alignment information than the store already has.
11713 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11714 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11715 if (Align > ST->getAlignment()) {
11717 DAG.getTruncStore(Chain, SDLoc(N), Value,
11718 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11719 ST->isVolatile(), ST->isNonTemporal(), Align,
11721 if (NewStore.getNode() != N)
11722 return CombineTo(ST, NewStore, true);
11727 // Try transforming a pair floating point load / store ops to integer
11728 // load / store ops.
11729 if (SDValue NewST = TransformFPLoadStorePair(N))
11732 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11733 : DAG.getSubtarget().useAA();
11735 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11736 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11739 if (UseAA && ST->isUnindexed()) {
11740 // FIXME: We should do this even without AA enabled. AA will just allow
11741 // FindBetterChain to work in more situations. The problem with this is that
11742 // any combine that expects memory operations to be on consecutive chains
11743 // first needs to be updated to look for users of the same chain.
11745 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11746 // adjacent stores.
11747 if (findBetterNeighborChains(ST)) {
11748 // replaceStoreChain uses CombineTo, which handled all of the worklist
11749 // manipulation. Return the original node to not do anything else.
11750 return SDValue(ST, 0);
11754 // Try transforming N to an indexed store.
11755 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11756 return SDValue(N, 0);
11758 // FIXME: is there such a thing as a truncating indexed store?
11759 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11760 Value.getValueType().isInteger()) {
11761 // See if we can simplify the input to this truncstore with knowledge that
11762 // only the low bits are being used. For example:
11763 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11765 GetDemandedBits(Value,
11766 APInt::getLowBitsSet(
11767 Value.getValueType().getScalarType().getSizeInBits(),
11768 ST->getMemoryVT().getScalarType().getSizeInBits()));
11769 AddToWorklist(Value.getNode());
11770 if (Shorter.getNode())
11771 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11772 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11774 // Otherwise, see if we can simplify the operation with
11775 // SimplifyDemandedBits, which only works if the value has a single use.
11776 if (SimplifyDemandedBits(Value,
11777 APInt::getLowBitsSet(
11778 Value.getValueType().getScalarType().getSizeInBits(),
11779 ST->getMemoryVT().getScalarType().getSizeInBits())))
11780 return SDValue(N, 0);
11783 // If this is a load followed by a store to the same location, then the store
11785 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11786 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11787 ST->isUnindexed() && !ST->isVolatile() &&
11788 // There can't be any side effects between the load and store, such as
11789 // a call or store.
11790 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11791 // The store is dead, remove it.
11796 // If this is a store followed by a store with the same value to the same
11797 // location, then the store is dead/noop.
11798 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11799 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11800 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11801 ST1->isUnindexed() && !ST1->isVolatile()) {
11802 // The store is dead, remove it.
11807 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11808 // truncating store. We can do this even if this is already a truncstore.
11809 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11810 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11811 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11812 ST->getMemoryVT())) {
11813 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11814 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11817 // Only perform this optimization before the types are legal, because we
11818 // don't want to perform this optimization on every DAGCombine invocation.
11820 bool EverChanged = false;
11823 // There can be multiple store sequences on the same chain.
11824 // Keep trying to merge store sequences until we are unable to do so
11825 // or until we merge the last store on the chain.
11826 bool Changed = MergeConsecutiveStores(ST);
11827 EverChanged |= Changed;
11828 if (!Changed) break;
11829 } while (ST->getOpcode() != ISD::DELETED_NODE);
11832 return SDValue(N, 0);
11835 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11837 // Make sure to do this only after attempting to merge stores in order to
11838 // avoid changing the types of some subset of stores due to visit order,
11839 // preventing their merging.
11840 if (isa<ConstantFPSDNode>(Value)) {
11841 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11845 return ReduceLoadOpStoreWidth(N);
11848 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11849 SDValue InVec = N->getOperand(0);
11850 SDValue InVal = N->getOperand(1);
11851 SDValue EltNo = N->getOperand(2);
11854 // If the inserted element is an UNDEF, just use the input vector.
11855 if (InVal.getOpcode() == ISD::UNDEF)
11858 EVT VT = InVec.getValueType();
11860 // If we can't generate a legal BUILD_VECTOR, exit
11861 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11864 // Check that we know which element is being inserted
11865 if (!isa<ConstantSDNode>(EltNo))
11867 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11869 // Canonicalize insert_vector_elt dag nodes.
11871 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11872 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11874 // Do this only if the child insert_vector node has one use; also
11875 // do this only if indices are both constants and Idx1 < Idx0.
11876 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11877 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11878 unsigned OtherElt =
11879 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11880 if (Elt < OtherElt) {
11882 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11883 InVec.getOperand(0), InVal, EltNo);
11884 AddToWorklist(NewOp.getNode());
11885 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11886 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11890 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11891 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11892 // vector elements.
11893 SmallVector<SDValue, 8> Ops;
11894 // Do not combine these two vectors if the output vector will not replace
11895 // the input vector.
11896 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11897 Ops.append(InVec.getNode()->op_begin(),
11898 InVec.getNode()->op_end());
11899 } else if (InVec.getOpcode() == ISD::UNDEF) {
11900 unsigned NElts = VT.getVectorNumElements();
11901 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11906 // Insert the element
11907 if (Elt < Ops.size()) {
11908 // All the operands of BUILD_VECTOR must have the same type;
11909 // we enforce that here.
11910 EVT OpVT = Ops[0].getValueType();
11911 if (InVal.getValueType() != OpVT)
11912 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11913 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11914 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11918 // Return the new vector
11919 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11922 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11923 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11924 EVT ResultVT = EVE->getValueType(0);
11925 EVT VecEltVT = InVecVT.getVectorElementType();
11926 unsigned Align = OriginalLoad->getAlignment();
11927 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11928 VecEltVT.getTypeForEVT(*DAG.getContext()));
11930 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11935 SDValue NewPtr = OriginalLoad->getBasePtr();
11937 EVT PtrType = NewPtr.getValueType();
11938 MachinePointerInfo MPI;
11940 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11941 int Elt = ConstEltNo->getZExtValue();
11942 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11943 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11944 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11946 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11947 Offset = DAG.getNode(
11948 ISD::MUL, DL, PtrType, Offset,
11949 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11950 MPI = OriginalLoad->getPointerInfo();
11952 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11954 // The replacement we need to do here is a little tricky: we need to
11955 // replace an extractelement of a load with a load.
11956 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11957 // Note that this replacement assumes that the extractvalue is the only
11958 // use of the load; that's okay because we don't want to perform this
11959 // transformation in other cases anyway.
11962 if (ResultVT.bitsGT(VecEltVT)) {
11963 // If the result type of vextract is wider than the load, then issue an
11964 // extending load instead.
11965 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11969 Load = DAG.getExtLoad(
11970 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11971 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11972 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11973 Chain = Load.getValue(1);
11975 Load = DAG.getLoad(
11976 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11977 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11978 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11979 Chain = Load.getValue(1);
11980 if (ResultVT.bitsLT(VecEltVT))
11981 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11983 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11985 WorklistRemover DeadNodes(*this);
11986 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11987 SDValue To[] = { Load, Chain };
11988 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11989 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11990 // worklist explicitly as well.
11991 AddToWorklist(Load.getNode());
11992 AddUsersToWorklist(Load.getNode()); // Add users too
11993 // Make sure to revisit this node to clean it up; it will usually be dead.
11994 AddToWorklist(EVE);
11996 return SDValue(EVE, 0);
11999 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12000 // (vextract (scalar_to_vector val, 0) -> val
12001 SDValue InVec = N->getOperand(0);
12002 EVT VT = InVec.getValueType();
12003 EVT NVT = N->getValueType(0);
12005 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12006 // Check if the result type doesn't match the inserted element type. A
12007 // SCALAR_TO_VECTOR may truncate the inserted element and the
12008 // EXTRACT_VECTOR_ELT may widen the extracted vector.
12009 SDValue InOp = InVec.getOperand(0);
12010 if (InOp.getValueType() != NVT) {
12011 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12012 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12017 SDValue EltNo = N->getOperand(1);
12018 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12020 // extract_vector_elt (build_vector x, y), 1 -> y
12022 InVec.getOpcode() == ISD::BUILD_VECTOR &&
12023 TLI.isTypeLegal(VT) &&
12024 (InVec.hasOneUse() ||
12025 TLI.aggressivelyPreferBuildVectorSources(VT))) {
12026 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12027 EVT InEltVT = Elt.getValueType();
12029 // Sometimes build_vector's scalar input types do not match result type.
12030 if (NVT == InEltVT)
12033 // TODO: It may be useful to truncate if free if the build_vector implicitly
12037 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12038 // We only perform this optimization before the op legalization phase because
12039 // we may introduce new vector instructions which are not backed by TD
12040 // patterns. For example on AVX, extracting elements from a wide vector
12041 // without using extract_subvector. However, if we can find an underlying
12042 // scalar value, then we can always use that.
12043 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12044 int NumElem = VT.getVectorNumElements();
12045 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12046 // Find the new index to extract from.
12047 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12049 // Extracting an undef index is undef.
12051 return DAG.getUNDEF(NVT);
12053 // Select the right vector half to extract from.
12055 if (OrigElt < NumElem) {
12056 SVInVec = InVec->getOperand(0);
12058 SVInVec = InVec->getOperand(1);
12059 OrigElt -= NumElem;
12062 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12063 SDValue InOp = SVInVec.getOperand(OrigElt);
12064 if (InOp.getValueType() != NVT) {
12065 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12066 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12072 // FIXME: We should handle recursing on other vector shuffles and
12073 // scalar_to_vector here as well.
12075 if (!LegalOperations) {
12076 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12077 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12078 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12082 bool BCNumEltsChanged = false;
12083 EVT ExtVT = VT.getVectorElementType();
12086 // If the result of load has to be truncated, then it's not necessarily
12088 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12091 if (InVec.getOpcode() == ISD::BITCAST) {
12092 // Don't duplicate a load with other uses.
12093 if (!InVec.hasOneUse())
12096 EVT BCVT = InVec.getOperand(0).getValueType();
12097 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12099 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12100 BCNumEltsChanged = true;
12101 InVec = InVec.getOperand(0);
12102 ExtVT = BCVT.getVectorElementType();
12105 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12106 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12107 ISD::isNormalLoad(InVec.getNode()) &&
12108 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12109 SDValue Index = N->getOperand(1);
12110 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12111 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12115 // Perform only after legalization to ensure build_vector / vector_shuffle
12116 // optimizations have already been done.
12117 if (!LegalOperations) return SDValue();
12119 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12120 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12121 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12124 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12126 LoadSDNode *LN0 = nullptr;
12127 const ShuffleVectorSDNode *SVN = nullptr;
12128 if (ISD::isNormalLoad(InVec.getNode())) {
12129 LN0 = cast<LoadSDNode>(InVec);
12130 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12131 InVec.getOperand(0).getValueType() == ExtVT &&
12132 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12133 // Don't duplicate a load with other uses.
12134 if (!InVec.hasOneUse())
12137 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12138 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12139 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12141 // (load $addr+1*size)
12143 // Don't duplicate a load with other uses.
12144 if (!InVec.hasOneUse())
12147 // If the bit convert changed the number of elements, it is unsafe
12148 // to examine the mask.
12149 if (BCNumEltsChanged)
12152 // Select the input vector, guarding against out of range extract vector.
12153 unsigned NumElems = VT.getVectorNumElements();
12154 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12155 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12157 if (InVec.getOpcode() == ISD::BITCAST) {
12158 // Don't duplicate a load with other uses.
12159 if (!InVec.hasOneUse())
12162 InVec = InVec.getOperand(0);
12164 if (ISD::isNormalLoad(InVec.getNode())) {
12165 LN0 = cast<LoadSDNode>(InVec);
12166 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12167 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12171 // Make sure we found a non-volatile load and the extractelement is
12173 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12176 // If Idx was -1 above, Elt is going to be -1, so just return undef.
12178 return DAG.getUNDEF(LVT);
12180 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12186 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12187 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12188 // We perform this optimization post type-legalization because
12189 // the type-legalizer often scalarizes integer-promoted vectors.
12190 // Performing this optimization before may create bit-casts which
12191 // will be type-legalized to complex code sequences.
12192 // We perform this optimization only before the operation legalizer because we
12193 // may introduce illegal operations.
12194 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12197 unsigned NumInScalars = N->getNumOperands();
12199 EVT VT = N->getValueType(0);
12201 // Check to see if this is a BUILD_VECTOR of a bunch of values
12202 // which come from any_extend or zero_extend nodes. If so, we can create
12203 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12204 // optimizations. We do not handle sign-extend because we can't fill the sign
12206 EVT SourceType = MVT::Other;
12207 bool AllAnyExt = true;
12209 for (unsigned i = 0; i != NumInScalars; ++i) {
12210 SDValue In = N->getOperand(i);
12211 // Ignore undef inputs.
12212 if (In.getOpcode() == ISD::UNDEF) continue;
12214 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
12215 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12217 // Abort if the element is not an extension.
12218 if (!ZeroExt && !AnyExt) {
12219 SourceType = MVT::Other;
12223 // The input is a ZeroExt or AnyExt. Check the original type.
12224 EVT InTy = In.getOperand(0).getValueType();
12226 // Check that all of the widened source types are the same.
12227 if (SourceType == MVT::Other)
12230 else if (InTy != SourceType) {
12231 // Multiple income types. Abort.
12232 SourceType = MVT::Other;
12236 // Check if all of the extends are ANY_EXTENDs.
12237 AllAnyExt &= AnyExt;
12240 // In order to have valid types, all of the inputs must be extended from the
12241 // same source type and all of the inputs must be any or zero extend.
12242 // Scalar sizes must be a power of two.
12243 EVT OutScalarTy = VT.getScalarType();
12244 bool ValidTypes = SourceType != MVT::Other &&
12245 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12246 isPowerOf2_32(SourceType.getSizeInBits());
12248 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12249 // turn into a single shuffle instruction.
12253 bool isLE = DAG.getDataLayout().isLittleEndian();
12254 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12255 assert(ElemRatio > 1 && "Invalid element size ratio");
12256 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12257 DAG.getConstant(0, SDLoc(N), SourceType);
12259 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12260 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12262 // Populate the new build_vector
12263 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12264 SDValue Cast = N->getOperand(i);
12265 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12266 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12267 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12269 if (Cast.getOpcode() == ISD::UNDEF)
12270 In = DAG.getUNDEF(SourceType);
12272 In = Cast->getOperand(0);
12273 unsigned Index = isLE ? (i * ElemRatio) :
12274 (i * ElemRatio + (ElemRatio - 1));
12276 assert(Index < Ops.size() && "Invalid index");
12280 // The type of the new BUILD_VECTOR node.
12281 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12282 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12283 "Invalid vector size");
12284 // Check if the new vector type is legal.
12285 if (!isTypeLegal(VecVT)) return SDValue();
12287 // Make the new BUILD_VECTOR.
12288 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12290 // The new BUILD_VECTOR node has the potential to be further optimized.
12291 AddToWorklist(BV.getNode());
12292 // Bitcast to the desired type.
12293 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12296 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12297 EVT VT = N->getValueType(0);
12299 unsigned NumInScalars = N->getNumOperands();
12302 EVT SrcVT = MVT::Other;
12303 unsigned Opcode = ISD::DELETED_NODE;
12304 unsigned NumDefs = 0;
12306 for (unsigned i = 0; i != NumInScalars; ++i) {
12307 SDValue In = N->getOperand(i);
12308 unsigned Opc = In.getOpcode();
12310 if (Opc == ISD::UNDEF)
12313 // If all scalar values are floats and converted from integers.
12314 if (Opcode == ISD::DELETED_NODE &&
12315 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12322 EVT InVT = In.getOperand(0).getValueType();
12324 // If all scalar values are typed differently, bail out. It's chosen to
12325 // simplify BUILD_VECTOR of integer types.
12326 if (SrcVT == MVT::Other)
12333 // If the vector has just one element defined, it's not worth to fold it into
12334 // a vectorized one.
12338 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12339 && "Should only handle conversion from integer to float.");
12340 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12342 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12344 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12347 // Just because the floating-point vector type is legal does not necessarily
12348 // mean that the corresponding integer vector type is.
12349 if (!isTypeLegal(NVT))
12352 SmallVector<SDValue, 8> Opnds;
12353 for (unsigned i = 0; i != NumInScalars; ++i) {
12354 SDValue In = N->getOperand(i);
12356 if (In.getOpcode() == ISD::UNDEF)
12357 Opnds.push_back(DAG.getUNDEF(SrcVT));
12359 Opnds.push_back(In.getOperand(0));
12361 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12362 AddToWorklist(BV.getNode());
12364 return DAG.getNode(Opcode, dl, VT, BV);
12367 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12368 unsigned NumInScalars = N->getNumOperands();
12370 EVT VT = N->getValueType(0);
12372 // A vector built entirely of undefs is undef.
12373 if (ISD::allOperandsUndef(N))
12374 return DAG.getUNDEF(VT);
12376 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12379 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12382 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12383 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12384 // at most two distinct vectors, turn this into a shuffle node.
12386 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12387 if (!isTypeLegal(VT))
12390 // May only combine to shuffle after legalize if shuffle is legal.
12391 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12394 SDValue VecIn1, VecIn2;
12395 bool UsesZeroVector = false;
12396 for (unsigned i = 0; i != NumInScalars; ++i) {
12397 SDValue Op = N->getOperand(i);
12398 // Ignore undef inputs.
12399 if (Op.getOpcode() == ISD::UNDEF) continue;
12401 // See if we can combine this build_vector into a blend with a zero vector.
12402 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12403 UsesZeroVector = true;
12407 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12408 // constant index, bail out.
12409 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12410 !isa<ConstantSDNode>(Op.getOperand(1))) {
12411 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12415 // We allow up to two distinct input vectors.
12416 SDValue ExtractedFromVec = Op.getOperand(0);
12417 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12420 if (!VecIn1.getNode()) {
12421 VecIn1 = ExtractedFromVec;
12422 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12423 VecIn2 = ExtractedFromVec;
12425 // Too many inputs.
12426 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12431 // If everything is good, we can make a shuffle operation.
12432 if (VecIn1.getNode()) {
12433 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12434 SmallVector<int, 8> Mask;
12435 for (unsigned i = 0; i != NumInScalars; ++i) {
12436 unsigned Opcode = N->getOperand(i).getOpcode();
12437 if (Opcode == ISD::UNDEF) {
12438 Mask.push_back(-1);
12442 // Operands can also be zero.
12443 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12444 assert(UsesZeroVector &&
12445 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12446 "Unexpected node found!");
12447 Mask.push_back(NumInScalars+i);
12451 // If extracting from the first vector, just use the index directly.
12452 SDValue Extract = N->getOperand(i);
12453 SDValue ExtVal = Extract.getOperand(1);
12454 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12455 if (Extract.getOperand(0) == VecIn1) {
12456 Mask.push_back(ExtIndex);
12460 // Otherwise, use InIdx + InputVecSize
12461 Mask.push_back(InNumElements + ExtIndex);
12464 // Avoid introducing illegal shuffles with zero.
12465 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12468 // We can't generate a shuffle node with mismatched input and output types.
12469 // Attempt to transform a single input vector to the correct type.
12470 if ((VT != VecIn1.getValueType())) {
12471 // If the input vector type has a different base type to the output
12472 // vector type, bail out.
12473 EVT VTElemType = VT.getVectorElementType();
12474 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12475 (VecIn2.getNode() &&
12476 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12479 // If the input vector is too small, widen it.
12480 // We only support widening of vectors which are half the size of the
12481 // output registers. For example XMM->YMM widening on X86 with AVX.
12482 EVT VecInT = VecIn1.getValueType();
12483 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12484 // If we only have one small input, widen it by adding undef values.
12485 if (!VecIn2.getNode())
12486 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12487 DAG.getUNDEF(VecIn1.getValueType()));
12488 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12489 // If we have two small inputs of the same type, try to concat them.
12490 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12491 VecIn2 = SDValue(nullptr, 0);
12494 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12495 // If the input vector is too large, try to split it.
12496 // We don't support having two input vectors that are too large.
12497 // If the zero vector was used, we can not split the vector,
12498 // since we'd need 3 inputs.
12499 if (UsesZeroVector || VecIn2.getNode())
12502 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12505 // Try to replace VecIn1 with two extract_subvectors
12506 // No need to update the masks, they should still be correct.
12507 VecIn2 = DAG.getNode(
12508 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12509 DAG.getConstant(VT.getVectorNumElements(), dl,
12510 TLI.getVectorIdxTy(DAG.getDataLayout())));
12511 VecIn1 = DAG.getNode(
12512 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12513 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12518 if (UsesZeroVector)
12519 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12520 DAG.getConstantFP(0.0, dl, VT);
12522 // If VecIn2 is unused then change it to undef.
12523 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12525 // Check that we were able to transform all incoming values to the same
12527 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12528 VecIn1.getValueType() != VT)
12531 // Return the new VECTOR_SHUFFLE node.
12535 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12541 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12542 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12543 EVT OpVT = N->getOperand(0).getValueType();
12545 // If the operands are legal vectors, leave them alone.
12546 if (TLI.isTypeLegal(OpVT))
12550 EVT VT = N->getValueType(0);
12551 SmallVector<SDValue, 8> Ops;
12553 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12554 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12556 // Keep track of what we encounter.
12557 bool AnyInteger = false;
12558 bool AnyFP = false;
12559 for (const SDValue &Op : N->ops()) {
12560 if (ISD::BITCAST == Op.getOpcode() &&
12561 !Op.getOperand(0).getValueType().isVector())
12562 Ops.push_back(Op.getOperand(0));
12563 else if (ISD::UNDEF == Op.getOpcode())
12564 Ops.push_back(ScalarUndef);
12568 // Note whether we encounter an integer or floating point scalar.
12569 // If it's neither, bail out, it could be something weird like x86mmx.
12570 EVT LastOpVT = Ops.back().getValueType();
12571 if (LastOpVT.isFloatingPoint())
12573 else if (LastOpVT.isInteger())
12579 // If any of the operands is a floating point scalar bitcast to a vector,
12580 // use floating point types throughout, and bitcast everything.
12581 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12583 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12584 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12586 for (SDValue &Op : Ops) {
12587 if (Op.getValueType() == SVT)
12589 if (Op.getOpcode() == ISD::UNDEF)
12592 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12597 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12598 VT.getSizeInBits() / SVT.getSizeInBits());
12599 return DAG.getNode(ISD::BITCAST, DL, VT,
12600 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12603 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12604 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12605 // most two distinct vectors the same size as the result, attempt to turn this
12606 // into a legal shuffle.
12607 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12608 EVT VT = N->getValueType(0);
12609 EVT OpVT = N->getOperand(0).getValueType();
12610 int NumElts = VT.getVectorNumElements();
12611 int NumOpElts = OpVT.getVectorNumElements();
12613 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12614 SmallVector<int, 8> Mask;
12616 for (SDValue Op : N->ops()) {
12617 // Peek through any bitcast.
12618 while (Op.getOpcode() == ISD::BITCAST)
12619 Op = Op.getOperand(0);
12621 // UNDEF nodes convert to UNDEF shuffle mask values.
12622 if (Op.getOpcode() == ISD::UNDEF) {
12623 Mask.append((unsigned)NumOpElts, -1);
12627 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12630 // What vector are we extracting the subvector from and at what index?
12631 SDValue ExtVec = Op.getOperand(0);
12633 // We want the EVT of the original extraction to correctly scale the
12634 // extraction index.
12635 EVT ExtVT = ExtVec.getValueType();
12637 // Peek through any bitcast.
12638 while (ExtVec.getOpcode() == ISD::BITCAST)
12639 ExtVec = ExtVec.getOperand(0);
12641 // UNDEF nodes convert to UNDEF shuffle mask values.
12642 if (ExtVec.getOpcode() == ISD::UNDEF) {
12643 Mask.append((unsigned)NumOpElts, -1);
12647 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12649 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12651 // Ensure that we are extracting a subvector from a vector the same
12652 // size as the result.
12653 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12656 // Scale the subvector index to account for any bitcast.
12657 int NumExtElts = ExtVT.getVectorNumElements();
12658 if (0 == (NumExtElts % NumElts))
12659 ExtIdx /= (NumExtElts / NumElts);
12660 else if (0 == (NumElts % NumExtElts))
12661 ExtIdx *= (NumElts / NumExtElts);
12665 // At most we can reference 2 inputs in the final shuffle.
12666 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12668 for (int i = 0; i != NumOpElts; ++i)
12669 Mask.push_back(i + ExtIdx);
12670 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12672 for (int i = 0; i != NumOpElts; ++i)
12673 Mask.push_back(i + ExtIdx + NumElts);
12679 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12682 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12683 DAG.getBitcast(VT, SV1), Mask);
12686 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12687 // If we only have one input vector, we don't need to do any concatenation.
12688 if (N->getNumOperands() == 1)
12689 return N->getOperand(0);
12691 // Check if all of the operands are undefs.
12692 EVT VT = N->getValueType(0);
12693 if (ISD::allOperandsUndef(N))
12694 return DAG.getUNDEF(VT);
12696 // Optimize concat_vectors where all but the first of the vectors are undef.
12697 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12698 return Op.getOpcode() == ISD::UNDEF;
12700 SDValue In = N->getOperand(0);
12701 assert(In.getValueType().isVector() && "Must concat vectors");
12703 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12704 if (In->getOpcode() == ISD::BITCAST &&
12705 !In->getOperand(0)->getValueType(0).isVector()) {
12706 SDValue Scalar = In->getOperand(0);
12708 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12709 // look through the trunc so we can still do the transform:
12710 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12711 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12712 !TLI.isTypeLegal(Scalar.getValueType()) &&
12713 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12714 Scalar = Scalar->getOperand(0);
12716 EVT SclTy = Scalar->getValueType(0);
12718 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12721 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12722 VT.getSizeInBits() / SclTy.getSizeInBits());
12723 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12726 SDLoc dl = SDLoc(N);
12727 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12728 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12732 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12733 // We have already tested above for an UNDEF only concatenation.
12734 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12735 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12736 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12737 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12739 bool AllBuildVectorsOrUndefs =
12740 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12741 if (AllBuildVectorsOrUndefs) {
12742 SmallVector<SDValue, 8> Opnds;
12743 EVT SVT = VT.getScalarType();
12746 if (!SVT.isFloatingPoint()) {
12747 // If BUILD_VECTOR are from built from integer, they may have different
12748 // operand types. Get the smallest type and truncate all operands to it.
12749 bool FoundMinVT = false;
12750 for (const SDValue &Op : N->ops())
12751 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12752 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12753 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12756 assert(FoundMinVT && "Concat vector type mismatch");
12759 for (const SDValue &Op : N->ops()) {
12760 EVT OpVT = Op.getValueType();
12761 unsigned NumElts = OpVT.getVectorNumElements();
12763 if (ISD::UNDEF == Op.getOpcode())
12764 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12766 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12767 if (SVT.isFloatingPoint()) {
12768 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12769 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12771 for (unsigned i = 0; i != NumElts; ++i)
12773 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12778 assert(VT.getVectorNumElements() == Opnds.size() &&
12779 "Concat vector type mismatch");
12780 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12783 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12784 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12787 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12788 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12789 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12792 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12793 // nodes often generate nop CONCAT_VECTOR nodes.
12794 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12795 // place the incoming vectors at the exact same location.
12796 SDValue SingleSource = SDValue();
12797 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12799 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12800 SDValue Op = N->getOperand(i);
12802 if (Op.getOpcode() == ISD::UNDEF)
12805 // Check if this is the identity extract:
12806 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12809 // Find the single incoming vector for the extract_subvector.
12810 if (SingleSource.getNode()) {
12811 if (Op.getOperand(0) != SingleSource)
12814 SingleSource = Op.getOperand(0);
12816 // Check the source type is the same as the type of the result.
12817 // If not, this concat may extend the vector, so we can not
12818 // optimize it away.
12819 if (SingleSource.getValueType() != N->getValueType(0))
12823 unsigned IdentityIndex = i * PartNumElem;
12824 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12825 // The extract index must be constant.
12829 // Check that we are reading from the identity index.
12830 if (CS->getZExtValue() != IdentityIndex)
12834 if (SingleSource.getNode())
12835 return SingleSource;
12840 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12841 EVT NVT = N->getValueType(0);
12842 SDValue V = N->getOperand(0);
12844 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12846 // (extract_subvec (concat V1, V2, ...), i)
12849 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12851 if (V->getOperand(0).getValueType() != NVT)
12853 unsigned Idx = N->getConstantOperandVal(1);
12854 unsigned NumElems = NVT.getVectorNumElements();
12855 assert((Idx % NumElems) == 0 &&
12856 "IDX in concat is not a multiple of the result vector length.");
12857 return V->getOperand(Idx / NumElems);
12861 if (V->getOpcode() == ISD::BITCAST)
12862 V = V.getOperand(0);
12864 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12866 // Handle only simple case where vector being inserted and vector
12867 // being extracted are of same type, and are half size of larger vectors.
12868 EVT BigVT = V->getOperand(0).getValueType();
12869 EVT SmallVT = V->getOperand(1).getValueType();
12870 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12873 // Only handle cases where both indexes are constants with the same type.
12874 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12875 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12877 if (InsIdx && ExtIdx &&
12878 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12879 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12881 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12883 // indices are equal or bit offsets are equal => V1
12884 // otherwise => (extract_subvec V1, ExtIdx)
12885 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12886 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12887 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12888 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12889 DAG.getNode(ISD::BITCAST, dl,
12890 N->getOperand(0).getValueType(),
12891 V->getOperand(0)), N->getOperand(1));
12898 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12899 SDValue V, SelectionDAG &DAG) {
12901 EVT VT = V.getValueType();
12903 switch (V.getOpcode()) {
12907 case ISD::CONCAT_VECTORS: {
12908 EVT OpVT = V->getOperand(0).getValueType();
12909 int OpSize = OpVT.getVectorNumElements();
12910 SmallBitVector OpUsedElements(OpSize, false);
12911 bool FoundSimplification = false;
12912 SmallVector<SDValue, 4> NewOps;
12913 NewOps.reserve(V->getNumOperands());
12914 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12915 SDValue Op = V->getOperand(i);
12916 bool OpUsed = false;
12917 for (int j = 0; j < OpSize; ++j)
12918 if (UsedElements[i * OpSize + j]) {
12919 OpUsedElements[j] = true;
12923 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12924 : DAG.getUNDEF(OpVT));
12925 FoundSimplification |= Op == NewOps.back();
12926 OpUsedElements.reset();
12928 if (FoundSimplification)
12929 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12933 case ISD::INSERT_SUBVECTOR: {
12934 SDValue BaseV = V->getOperand(0);
12935 SDValue SubV = V->getOperand(1);
12936 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12940 int SubSize = SubV.getValueType().getVectorNumElements();
12941 int Idx = IdxN->getZExtValue();
12942 bool SubVectorUsed = false;
12943 SmallBitVector SubUsedElements(SubSize, false);
12944 for (int i = 0; i < SubSize; ++i)
12945 if (UsedElements[i + Idx]) {
12946 SubVectorUsed = true;
12947 SubUsedElements[i] = true;
12948 UsedElements[i + Idx] = false;
12951 // Now recurse on both the base and sub vectors.
12952 SDValue SimplifiedSubV =
12954 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12955 : DAG.getUNDEF(SubV.getValueType());
12956 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12957 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12958 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12959 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12965 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12966 SDValue N1, SelectionDAG &DAG) {
12967 EVT VT = SVN->getValueType(0);
12968 int NumElts = VT.getVectorNumElements();
12969 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12970 for (int M : SVN->getMask())
12971 if (M >= 0 && M < NumElts)
12972 N0UsedElements[M] = true;
12973 else if (M >= NumElts)
12974 N1UsedElements[M - NumElts] = true;
12976 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12977 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12978 if (S0 == N0 && S1 == N1)
12981 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12984 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12985 // or turn a shuffle of a single concat into simpler shuffle then concat.
12986 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12987 EVT VT = N->getValueType(0);
12988 unsigned NumElts = VT.getVectorNumElements();
12990 SDValue N0 = N->getOperand(0);
12991 SDValue N1 = N->getOperand(1);
12992 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12994 SmallVector<SDValue, 4> Ops;
12995 EVT ConcatVT = N0.getOperand(0).getValueType();
12996 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12997 unsigned NumConcats = NumElts / NumElemsPerConcat;
12999 // Special case: shuffle(concat(A,B)) can be more efficiently represented
13000 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13001 // half vector elements.
13002 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
13003 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13004 SVN->getMask().end(), [](int i) { return i == -1; })) {
13005 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13006 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13007 N1 = DAG.getUNDEF(ConcatVT);
13008 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13011 // Look at every vector that's inserted. We're looking for exact
13012 // subvector-sized copies from a concatenated vector
13013 for (unsigned I = 0; I != NumConcats; ++I) {
13014 // Make sure we're dealing with a copy.
13015 unsigned Begin = I * NumElemsPerConcat;
13016 bool AllUndef = true, NoUndef = true;
13017 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13018 if (SVN->getMaskElt(J) >= 0)
13025 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13028 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13029 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13032 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13033 if (FirstElt < N0.getNumOperands())
13034 Ops.push_back(N0.getOperand(FirstElt));
13036 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13038 } else if (AllUndef) {
13039 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13040 } else { // Mixed with general masks and undefs, can't do optimization.
13045 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13048 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13049 EVT VT = N->getValueType(0);
13050 unsigned NumElts = VT.getVectorNumElements();
13052 SDValue N0 = N->getOperand(0);
13053 SDValue N1 = N->getOperand(1);
13055 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13057 // Canonicalize shuffle undef, undef -> undef
13058 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13059 return DAG.getUNDEF(VT);
13061 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13063 // Canonicalize shuffle v, v -> v, undef
13065 SmallVector<int, 8> NewMask;
13066 for (unsigned i = 0; i != NumElts; ++i) {
13067 int Idx = SVN->getMaskElt(i);
13068 if (Idx >= (int)NumElts) Idx -= NumElts;
13069 NewMask.push_back(Idx);
13071 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13075 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
13076 if (N0.getOpcode() == ISD::UNDEF) {
13077 SmallVector<int, 8> NewMask;
13078 for (unsigned i = 0; i != NumElts; ++i) {
13079 int Idx = SVN->getMaskElt(i);
13081 if (Idx >= (int)NumElts)
13084 Idx = -1; // remove reference to lhs
13086 NewMask.push_back(Idx);
13088 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13092 // Remove references to rhs if it is undef
13093 if (N1.getOpcode() == ISD::UNDEF) {
13094 bool Changed = false;
13095 SmallVector<int, 8> NewMask;
13096 for (unsigned i = 0; i != NumElts; ++i) {
13097 int Idx = SVN->getMaskElt(i);
13098 if (Idx >= (int)NumElts) {
13102 NewMask.push_back(Idx);
13105 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13108 // If it is a splat, check if the argument vector is another splat or a
13110 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13111 SDNode *V = N0.getNode();
13113 // If this is a bit convert that changes the element type of the vector but
13114 // not the number of vector elements, look through it. Be careful not to
13115 // look though conversions that change things like v4f32 to v2f64.
13116 if (V->getOpcode() == ISD::BITCAST) {
13117 SDValue ConvInput = V->getOperand(0);
13118 if (ConvInput.getValueType().isVector() &&
13119 ConvInput.getValueType().getVectorNumElements() == NumElts)
13120 V = ConvInput.getNode();
13123 if (V->getOpcode() == ISD::BUILD_VECTOR) {
13124 assert(V->getNumOperands() == NumElts &&
13125 "BUILD_VECTOR has wrong number of operands");
13127 bool AllSame = true;
13128 for (unsigned i = 0; i != NumElts; ++i) {
13129 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13130 Base = V->getOperand(i);
13134 // Splat of <u, u, u, u>, return <u, u, u, u>
13135 if (!Base.getNode())
13137 for (unsigned i = 0; i != NumElts; ++i) {
13138 if (V->getOperand(i) != Base) {
13143 // Splat of <x, x, x, x>, return <x, x, x, x>
13147 // Canonicalize any other splat as a build_vector.
13148 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13149 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13150 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13151 V->getValueType(0), Ops);
13153 // We may have jumped through bitcasts, so the type of the
13154 // BUILD_VECTOR may not match the type of the shuffle.
13155 if (V->getValueType(0) != VT)
13156 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13161 // There are various patterns used to build up a vector from smaller vectors,
13162 // subvectors, or elements. Scan chains of these and replace unused insertions
13163 // or components with undef.
13164 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13167 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13168 Level < AfterLegalizeVectorOps &&
13169 (N1.getOpcode() == ISD::UNDEF ||
13170 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13171 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13172 SDValue V = partitionShuffleOfConcats(N, DAG);
13178 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13179 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13180 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13181 SmallVector<SDValue, 8> Ops;
13182 for (int M : SVN->getMask()) {
13183 SDValue Op = DAG.getUNDEF(VT.getScalarType());
13185 int Idx = M % NumElts;
13186 SDValue &S = (M < (int)NumElts ? N0 : N1);
13187 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13188 Op = S.getOperand(Idx);
13189 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13191 Op = S.getOperand(0);
13193 // Operand can't be combined - bail out.
13199 if (Ops.size() == VT.getVectorNumElements()) {
13200 // BUILD_VECTOR requires all inputs to be of the same type, find the
13201 // maximum type and extend them all.
13202 EVT SVT = VT.getScalarType();
13203 if (SVT.isInteger())
13204 for (SDValue &Op : Ops)
13205 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13206 if (SVT != VT.getScalarType())
13207 for (SDValue &Op : Ops)
13208 Op = TLI.isZExtFree(Op.getValueType(), SVT)
13209 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13210 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13211 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13215 // If this shuffle only has a single input that is a bitcasted shuffle,
13216 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13217 // back to their original types.
13218 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13219 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13220 TLI.isTypeLegal(VT)) {
13222 // Peek through the bitcast only if there is one user.
13224 while (BC0.getOpcode() == ISD::BITCAST) {
13225 if (!BC0.hasOneUse())
13227 BC0 = BC0.getOperand(0);
13230 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13232 return SmallVector<int, 8>(Mask.begin(), Mask.end());
13234 SmallVector<int, 8> NewMask;
13236 for (int s = 0; s != Scale; ++s)
13237 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13241 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13242 EVT SVT = VT.getScalarType();
13243 EVT InnerVT = BC0->getValueType(0);
13244 EVT InnerSVT = InnerVT.getScalarType();
13246 // Determine which shuffle works with the smaller scalar type.
13247 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13248 EVT ScaleSVT = ScaleVT.getScalarType();
13250 if (TLI.isTypeLegal(ScaleVT) &&
13251 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13252 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13254 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13255 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13257 // Scale the shuffle masks to the smaller scalar type.
13258 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13259 SmallVector<int, 8> InnerMask =
13260 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13261 SmallVector<int, 8> OuterMask =
13262 ScaleShuffleMask(SVN->getMask(), OuterScale);
13264 // Merge the shuffle masks.
13265 SmallVector<int, 8> NewMask;
13266 for (int M : OuterMask)
13267 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13269 // Test for shuffle mask legality over both commutations.
13270 SDValue SV0 = BC0->getOperand(0);
13271 SDValue SV1 = BC0->getOperand(1);
13272 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13274 std::swap(SV0, SV1);
13275 ShuffleVectorSDNode::commuteMask(NewMask);
13276 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13280 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13281 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13282 return DAG.getNode(
13283 ISD::BITCAST, SDLoc(N), VT,
13284 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13290 // Canonicalize shuffles according to rules:
13291 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13292 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13293 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13294 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13295 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13296 TLI.isTypeLegal(VT)) {
13297 // The incoming shuffle must be of the same type as the result of the
13298 // current shuffle.
13299 assert(N1->getOperand(0).getValueType() == VT &&
13300 "Shuffle types don't match");
13302 SDValue SV0 = N1->getOperand(0);
13303 SDValue SV1 = N1->getOperand(1);
13304 bool HasSameOp0 = N0 == SV0;
13305 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13306 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13307 // Commute the operands of this shuffle so that next rule
13309 return DAG.getCommutedVectorShuffle(*SVN);
13312 // Try to fold according to rules:
13313 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13314 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13315 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13316 // Don't try to fold shuffles with illegal type.
13317 // Only fold if this shuffle is the only user of the other shuffle.
13318 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13319 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13320 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13322 // The incoming shuffle must be of the same type as the result of the
13323 // current shuffle.
13324 assert(OtherSV->getOperand(0).getValueType() == VT &&
13325 "Shuffle types don't match");
13328 SmallVector<int, 4> Mask;
13329 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13330 // operand, and SV1 as the second operand.
13331 for (unsigned i = 0; i != NumElts; ++i) {
13332 int Idx = SVN->getMaskElt(i);
13334 // Propagate Undef.
13335 Mask.push_back(Idx);
13339 SDValue CurrentVec;
13340 if (Idx < (int)NumElts) {
13341 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13342 // shuffle mask to identify which vector is actually referenced.
13343 Idx = OtherSV->getMaskElt(Idx);
13345 // Propagate Undef.
13346 Mask.push_back(Idx);
13350 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13351 : OtherSV->getOperand(1);
13353 // This shuffle index references an element within N1.
13357 // Simple case where 'CurrentVec' is UNDEF.
13358 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13359 Mask.push_back(-1);
13363 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13364 // will be the first or second operand of the combined shuffle.
13365 Idx = Idx % NumElts;
13366 if (!SV0.getNode() || SV0 == CurrentVec) {
13367 // Ok. CurrentVec is the left hand side.
13368 // Update the mask accordingly.
13370 Mask.push_back(Idx);
13374 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13375 if (SV1.getNode() && SV1 != CurrentVec)
13378 // Ok. CurrentVec is the right hand side.
13379 // Update the mask accordingly.
13381 Mask.push_back(Idx + NumElts);
13384 // Check if all indices in Mask are Undef. In case, propagate Undef.
13385 bool isUndefMask = true;
13386 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13387 isUndefMask &= Mask[i] < 0;
13390 return DAG.getUNDEF(VT);
13392 if (!SV0.getNode())
13393 SV0 = DAG.getUNDEF(VT);
13394 if (!SV1.getNode())
13395 SV1 = DAG.getUNDEF(VT);
13397 // Avoid introducing shuffles with illegal mask.
13398 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13399 ShuffleVectorSDNode::commuteMask(Mask);
13401 if (!TLI.isShuffleMaskLegal(Mask, VT))
13404 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13405 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13406 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13407 std::swap(SV0, SV1);
13410 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13411 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13412 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13413 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13419 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13420 SDValue InVal = N->getOperand(0);
13421 EVT VT = N->getValueType(0);
13423 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13424 // with a VECTOR_SHUFFLE.
13425 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13426 SDValue InVec = InVal->getOperand(0);
13427 SDValue EltNo = InVal->getOperand(1);
13429 // FIXME: We could support implicit truncation if the shuffle can be
13430 // scaled to a smaller vector scalar type.
13431 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13432 if (C0 && VT == InVec.getValueType() &&
13433 VT.getScalarType() == InVal.getValueType()) {
13434 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13435 int Elt = C0->getZExtValue();
13438 if (TLI.isShuffleMaskLegal(NewMask, VT))
13439 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13447 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13448 SDValue N0 = N->getOperand(0);
13449 SDValue N2 = N->getOperand(2);
13451 // If the input vector is a concatenation, and the insert replaces
13452 // one of the halves, we can optimize into a single concat_vectors.
13453 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13454 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13455 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13456 EVT VT = N->getValueType(0);
13458 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13459 // (concat_vectors Z, Y)
13461 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13462 N->getOperand(1), N0.getOperand(1));
13464 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13465 // (concat_vectors X, Z)
13466 if (InsIdx == VT.getVectorNumElements()/2)
13467 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13468 N0.getOperand(0), N->getOperand(1));
13474 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13475 SDValue N0 = N->getOperand(0);
13477 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13478 if (N0->getOpcode() == ISD::FP16_TO_FP)
13479 return N0->getOperand(0);
13484 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13485 SDValue N0 = N->getOperand(0);
13487 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13488 if (N0->getOpcode() == ISD::AND) {
13489 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13490 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13491 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13499 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13500 /// with the destination vector and a zero vector.
13501 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13502 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13503 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13504 EVT VT = N->getValueType(0);
13505 SDValue LHS = N->getOperand(0);
13506 SDValue RHS = N->getOperand(1);
13509 // Make sure we're not running after operation legalization where it
13510 // may have custom lowered the vector shuffles.
13511 if (LegalOperations)
13514 if (N->getOpcode() != ISD::AND)
13517 if (RHS.getOpcode() == ISD::BITCAST)
13518 RHS = RHS.getOperand(0);
13520 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13523 EVT RVT = RHS.getValueType();
13524 unsigned NumElts = RHS.getNumOperands();
13526 // Attempt to create a valid clear mask, splitting the mask into
13527 // sub elements and checking to see if each is
13528 // all zeros or all ones - suitable for shuffle masking.
13529 auto BuildClearMask = [&](int Split) {
13530 int NumSubElts = NumElts * Split;
13531 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13533 SmallVector<int, 8> Indices;
13534 for (int i = 0; i != NumSubElts; ++i) {
13535 int EltIdx = i / Split;
13536 int SubIdx = i % Split;
13537 SDValue Elt = RHS.getOperand(EltIdx);
13538 if (Elt.getOpcode() == ISD::UNDEF) {
13539 Indices.push_back(-1);
13544 if (isa<ConstantSDNode>(Elt))
13545 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13546 else if (isa<ConstantFPSDNode>(Elt))
13547 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13551 // Extract the sub element from the constant bit mask.
13552 if (DAG.getDataLayout().isBigEndian()) {
13553 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13555 Bits = Bits.lshr(SubIdx * NumSubBits);
13559 Bits = Bits.trunc(NumSubBits);
13561 if (Bits.isAllOnesValue())
13562 Indices.push_back(i);
13563 else if (Bits == 0)
13564 Indices.push_back(i + NumSubElts);
13569 // Let's see if the target supports this vector_shuffle.
13570 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13571 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13572 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13575 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13576 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13577 DAG.getBitcast(ClearVT, LHS),
13578 Zero, &Indices[0]));
13581 // Determine maximum split level (byte level masking).
13583 if (RVT.getScalarSizeInBits() % 8 == 0)
13584 MaxSplit = RVT.getScalarSizeInBits() / 8;
13586 for (int Split = 1; Split <= MaxSplit; ++Split)
13587 if (RVT.getScalarSizeInBits() % Split == 0)
13588 if (SDValue S = BuildClearMask(Split))
13594 /// Visit a binary vector operation, like ADD.
13595 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13596 assert(N->getValueType(0).isVector() &&
13597 "SimplifyVBinOp only works on vectors!");
13599 SDValue LHS = N->getOperand(0);
13600 SDValue RHS = N->getOperand(1);
13601 SDValue Ops[] = {LHS, RHS};
13603 // See if we can constant fold the vector operation.
13604 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13605 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13608 // Try to convert a constant mask AND into a shuffle clear mask.
13609 if (SDValue Shuffle = XformToShuffleWithZero(N))
13612 // Type legalization might introduce new shuffles in the DAG.
13613 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13614 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13615 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13616 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13617 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13618 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13619 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13620 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13622 if (SVN0->getMask().equals(SVN1->getMask())) {
13623 EVT VT = N->getValueType(0);
13624 SDValue UndefVector = LHS.getOperand(1);
13625 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13626 LHS.getOperand(0), RHS.getOperand(0),
13628 AddUsersToWorklist(N);
13629 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13630 &SVN0->getMask()[0]);
13637 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13638 SDValue N1, SDValue N2){
13639 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13641 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13642 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13644 // If we got a simplified select_cc node back from SimplifySelectCC, then
13645 // break it down into a new SETCC node, and a new SELECT node, and then return
13646 // the SELECT node, since we were called with a SELECT node.
13647 if (SCC.getNode()) {
13648 // Check to see if we got a select_cc back (to turn into setcc/select).
13649 // Otherwise, just return whatever node we got back, like fabs.
13650 if (SCC.getOpcode() == ISD::SELECT_CC) {
13651 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13653 SCC.getOperand(0), SCC.getOperand(1),
13654 SCC.getOperand(4));
13655 AddToWorklist(SETCC.getNode());
13656 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13657 SCC.getOperand(2), SCC.getOperand(3));
13665 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13666 /// being selected between, see if we can simplify the select. Callers of this
13667 /// should assume that TheSelect is deleted if this returns true. As such, they
13668 /// should return the appropriate thing (e.g. the node) back to the top-level of
13669 /// the DAG combiner loop to avoid it being looked at.
13670 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13673 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13674 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13675 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13676 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13677 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13678 SDValue Sqrt = RHS;
13681 const ConstantFPSDNode *NegZero = nullptr;
13683 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13684 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13685 CmpLHS = TheSelect->getOperand(0);
13686 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13688 // SELECT or VSELECT
13689 SDValue Cmp = TheSelect->getOperand(0);
13690 if (Cmp.getOpcode() == ISD::SETCC) {
13691 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13692 CmpLHS = Cmp.getOperand(0);
13693 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13696 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13697 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13698 CC == ISD::SETULT || CC == ISD::SETLT)) {
13699 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13700 CombineTo(TheSelect, Sqrt);
13705 // Cannot simplify select with vector condition
13706 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13708 // If this is a select from two identical things, try to pull the operation
13709 // through the select.
13710 if (LHS.getOpcode() != RHS.getOpcode() ||
13711 !LHS.hasOneUse() || !RHS.hasOneUse())
13714 // If this is a load and the token chain is identical, replace the select
13715 // of two loads with a load through a select of the address to load from.
13716 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13717 // constants have been dropped into the constant pool.
13718 if (LHS.getOpcode() == ISD::LOAD) {
13719 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13720 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13722 // Token chains must be identical.
13723 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13724 // Do not let this transformation reduce the number of volatile loads.
13725 LLD->isVolatile() || RLD->isVolatile() ||
13726 // FIXME: If either is a pre/post inc/dec load,
13727 // we'd need to split out the address adjustment.
13728 LLD->isIndexed() || RLD->isIndexed() ||
13729 // If this is an EXTLOAD, the VT's must match.
13730 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13731 // If this is an EXTLOAD, the kind of extension must match.
13732 (LLD->getExtensionType() != RLD->getExtensionType() &&
13733 // The only exception is if one of the extensions is anyext.
13734 LLD->getExtensionType() != ISD::EXTLOAD &&
13735 RLD->getExtensionType() != ISD::EXTLOAD) ||
13736 // FIXME: this discards src value information. This is
13737 // over-conservative. It would be beneficial to be able to remember
13738 // both potential memory locations. Since we are discarding
13739 // src value info, don't do the transformation if the memory
13740 // locations are not in the default address space.
13741 LLD->getPointerInfo().getAddrSpace() != 0 ||
13742 RLD->getPointerInfo().getAddrSpace() != 0 ||
13743 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13744 LLD->getBasePtr().getValueType()))
13747 // Check that the select condition doesn't reach either load. If so,
13748 // folding this will induce a cycle into the DAG. If not, this is safe to
13749 // xform, so create a select of the addresses.
13751 if (TheSelect->getOpcode() == ISD::SELECT) {
13752 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13753 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13754 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13756 // The loads must not depend on one another.
13757 if (LLD->isPredecessorOf(RLD) ||
13758 RLD->isPredecessorOf(LLD))
13760 Addr = DAG.getSelect(SDLoc(TheSelect),
13761 LLD->getBasePtr().getValueType(),
13762 TheSelect->getOperand(0), LLD->getBasePtr(),
13763 RLD->getBasePtr());
13764 } else { // Otherwise SELECT_CC
13765 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13766 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13768 if ((LLD->hasAnyUseOfValue(1) &&
13769 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13770 (RLD->hasAnyUseOfValue(1) &&
13771 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13774 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13775 LLD->getBasePtr().getValueType(),
13776 TheSelect->getOperand(0),
13777 TheSelect->getOperand(1),
13778 LLD->getBasePtr(), RLD->getBasePtr(),
13779 TheSelect->getOperand(4));
13783 // It is safe to replace the two loads if they have different alignments,
13784 // but the new load must be the minimum (most restrictive) alignment of the
13786 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13787 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13788 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13789 Load = DAG.getLoad(TheSelect->getValueType(0),
13791 // FIXME: Discards pointer and AA info.
13792 LLD->getChain(), Addr, MachinePointerInfo(),
13793 LLD->isVolatile(), LLD->isNonTemporal(),
13794 isInvariant, Alignment);
13796 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13797 RLD->getExtensionType() : LLD->getExtensionType(),
13799 TheSelect->getValueType(0),
13800 // FIXME: Discards pointer and AA info.
13801 LLD->getChain(), Addr, MachinePointerInfo(),
13802 LLD->getMemoryVT(), LLD->isVolatile(),
13803 LLD->isNonTemporal(), isInvariant, Alignment);
13806 // Users of the select now use the result of the load.
13807 CombineTo(TheSelect, Load);
13809 // Users of the old loads now use the new load's chain. We know the
13810 // old-load value is dead now.
13811 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13812 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13819 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13820 /// where 'cond' is the comparison specified by CC.
13821 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13822 SDValue N2, SDValue N3,
13823 ISD::CondCode CC, bool NotExtCompare) {
13824 // (x ? y : y) -> y.
13825 if (N2 == N3) return N2;
13827 EVT VT = N2.getValueType();
13828 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13829 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13831 // Determine if the condition we're dealing with is constant
13832 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13833 N0, N1, CC, DL, false);
13834 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13836 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13837 // fold select_cc true, x, y -> x
13838 // fold select_cc false, x, y -> y
13839 return !SCCC->isNullValue() ? N2 : N3;
13842 // Check to see if we can simplify the select into an fabs node
13843 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13844 // Allow either -0.0 or 0.0
13845 if (CFP->isZero()) {
13846 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13847 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13848 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13849 N2 == N3.getOperand(0))
13850 return DAG.getNode(ISD::FABS, DL, VT, N0);
13852 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13853 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13854 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13855 N2.getOperand(0) == N3)
13856 return DAG.getNode(ISD::FABS, DL, VT, N3);
13860 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13861 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13862 // in it. This is a win when the constant is not otherwise available because
13863 // it replaces two constant pool loads with one. We only do this if the FP
13864 // type is known to be legal, because if it isn't, then we are before legalize
13865 // types an we want the other legalization to happen first (e.g. to avoid
13866 // messing with soft float) and if the ConstantFP is not legal, because if
13867 // it is legal, we may not need to store the FP constant in a constant pool.
13868 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13869 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13870 if (TLI.isTypeLegal(N2.getValueType()) &&
13871 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13872 TargetLowering::Legal &&
13873 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13874 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13875 // If both constants have multiple uses, then we won't need to do an
13876 // extra load, they are likely around in registers for other users.
13877 (TV->hasOneUse() || FV->hasOneUse())) {
13878 Constant *Elts[] = {
13879 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13880 const_cast<ConstantFP*>(TV->getConstantFPValue())
13882 Type *FPTy = Elts[0]->getType();
13883 const DataLayout &TD = DAG.getDataLayout();
13885 // Create a ConstantArray of the two constants.
13886 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13888 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13889 TD.getPrefTypeAlignment(FPTy));
13890 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13892 // Get the offsets to the 0 and 1 element of the array so that we can
13893 // select between them.
13894 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13895 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13896 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13898 SDValue Cond = DAG.getSetCC(DL,
13899 getSetCCResultType(N0.getValueType()),
13901 AddToWorklist(Cond.getNode());
13902 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13904 AddToWorklist(CstOffset.getNode());
13905 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13907 AddToWorklist(CPIdx.getNode());
13908 return DAG.getLoad(
13909 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13910 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13911 false, false, false, Alignment);
13915 // Check to see if we can perform the "gzip trick", transforming
13916 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13917 if (isNullConstant(N3) && CC == ISD::SETLT &&
13918 (isNullConstant(N1) || // (a < 0) ? b : 0
13919 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13920 EVT XType = N0.getValueType();
13921 EVT AType = N2.getValueType();
13922 if (XType.bitsGE(AType)) {
13923 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13924 // single-bit constant.
13925 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13926 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13927 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13928 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13929 getShiftAmountTy(N0.getValueType()));
13930 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13932 AddToWorklist(Shift.getNode());
13934 if (XType.bitsGT(AType)) {
13935 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13936 AddToWorklist(Shift.getNode());
13939 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13942 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13944 DAG.getConstant(XType.getSizeInBits() - 1,
13946 getShiftAmountTy(N0.getValueType())));
13947 AddToWorklist(Shift.getNode());
13949 if (XType.bitsGT(AType)) {
13950 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13951 AddToWorklist(Shift.getNode());
13954 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13958 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13959 // where y is has a single bit set.
13960 // A plaintext description would be, we can turn the SELECT_CC into an AND
13961 // when the condition can be materialized as an all-ones register. Any
13962 // single bit-test can be materialized as an all-ones register with
13963 // shift-left and shift-right-arith.
13964 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13965 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13966 SDValue AndLHS = N0->getOperand(0);
13967 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13968 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13969 // Shift the tested bit over the sign bit.
13970 APInt AndMask = ConstAndRHS->getAPIntValue();
13972 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13973 getShiftAmountTy(AndLHS.getValueType()));
13974 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13976 // Now arithmetic right shift it all the way over, so the result is either
13977 // all-ones, or zero.
13979 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13980 getShiftAmountTy(Shl.getValueType()));
13981 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13983 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13987 // fold select C, 16, 0 -> shl C, 4
13988 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13989 TLI.getBooleanContents(N0.getValueType()) ==
13990 TargetLowering::ZeroOrOneBooleanContent) {
13992 // If the caller doesn't want us to simplify this into a zext of a compare,
13994 if (NotExtCompare && N2C->isOne())
13997 // Get a SetCC of the condition
13998 // NOTE: Don't create a SETCC if it's not legal on this target.
13999 if (!LegalOperations ||
14000 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14002 // cast from setcc result type to select result type
14004 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14006 if (N2.getValueType().bitsLT(SCC.getValueType()))
14007 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14008 N2.getValueType());
14010 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14011 N2.getValueType(), SCC);
14013 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14014 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14015 N2.getValueType(), SCC);
14018 AddToWorklist(SCC.getNode());
14019 AddToWorklist(Temp.getNode());
14024 // shl setcc result by log2 n2c
14025 return DAG.getNode(
14026 ISD::SHL, DL, N2.getValueType(), Temp,
14027 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14028 getShiftAmountTy(Temp.getValueType())));
14032 // Check to see if this is an integer abs.
14033 // select_cc setg[te] X, 0, X, -X ->
14034 // select_cc setgt X, -1, X, -X ->
14035 // select_cc setl[te] X, 0, -X, X ->
14036 // select_cc setlt X, 1, -X, X ->
14037 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14039 ConstantSDNode *SubC = nullptr;
14040 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14041 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14042 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14043 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14044 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14045 (N1C->isOne() && CC == ISD::SETLT)) &&
14046 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14047 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14049 EVT XType = N0.getValueType();
14050 if (SubC && SubC->isNullValue() && XType.isInteger()) {
14052 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14054 DAG.getConstant(XType.getSizeInBits() - 1, DL,
14055 getShiftAmountTy(N0.getValueType())));
14056 SDValue Add = DAG.getNode(ISD::ADD, DL,
14058 AddToWorklist(Shift.getNode());
14059 AddToWorklist(Add.getNode());
14060 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14067 /// This is a stub for TargetLowering::SimplifySetCC.
14068 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14069 SDValue N1, ISD::CondCode Cond,
14070 SDLoc DL, bool foldBooleans) {
14071 TargetLowering::DAGCombinerInfo
14072 DagCombineInfo(DAG, Level, false, this);
14073 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14076 /// Given an ISD::SDIV node expressing a divide by constant, return
14077 /// a DAG expression to select that will generate the same value by multiplying
14078 /// by a magic number.
14079 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14080 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14081 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14085 // Avoid division by zero.
14086 if (C->isNullValue())
14089 std::vector<SDNode*> Built;
14091 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14093 for (SDNode *N : Built)
14098 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14099 /// DAG expression that will generate the same value by right shifting.
14100 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14101 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14105 // Avoid division by zero.
14106 if (C->isNullValue())
14109 std::vector<SDNode *> Built;
14110 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14112 for (SDNode *N : Built)
14117 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14118 /// expression that will generate the same value by multiplying by a magic
14120 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14121 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14122 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14126 // Avoid division by zero.
14127 if (C->isNullValue())
14130 std::vector<SDNode*> Built;
14132 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14134 for (SDNode *N : Built)
14139 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14140 if (Level >= AfterLegalizeDAG)
14143 // Expose the DAG combiner to the target combiner implementations.
14144 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14146 unsigned Iterations = 0;
14147 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14149 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14150 // For the reciprocal, we need to find the zero of the function:
14151 // F(X) = A X - 1 [which has a zero at X = 1/A]
14153 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14154 // does not require additional intermediate precision]
14155 EVT VT = Op.getValueType();
14157 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14159 AddToWorklist(Est.getNode());
14161 // Newton iterations: Est = Est + Est (1 - Arg * Est)
14162 for (unsigned i = 0; i < Iterations; ++i) {
14163 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14164 AddToWorklist(NewEst.getNode());
14166 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14167 AddToWorklist(NewEst.getNode());
14169 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14170 AddToWorklist(NewEst.getNode());
14172 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14173 AddToWorklist(Est.getNode());
14182 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14183 /// For the reciprocal sqrt, we need to find the zero of the function:
14184 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14186 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14187 /// As a result, we precompute A/2 prior to the iteration loop.
14188 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14189 unsigned Iterations,
14190 SDNodeFlags *Flags) {
14191 EVT VT = Arg.getValueType();
14193 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14195 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14196 // this entire sequence requires only one FP constant.
14197 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14198 AddToWorklist(HalfArg.getNode());
14200 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14201 AddToWorklist(HalfArg.getNode());
14203 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14204 for (unsigned i = 0; i < Iterations; ++i) {
14205 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14206 AddToWorklist(NewEst.getNode());
14208 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14209 AddToWorklist(NewEst.getNode());
14211 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14212 AddToWorklist(NewEst.getNode());
14214 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14215 AddToWorklist(Est.getNode());
14220 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14221 /// For the reciprocal sqrt, we need to find the zero of the function:
14222 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14224 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14225 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14226 unsigned Iterations,
14227 SDNodeFlags *Flags) {
14228 EVT VT = Arg.getValueType();
14230 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14231 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14233 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14234 for (unsigned i = 0; i < Iterations; ++i) {
14235 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14236 AddToWorklist(HalfEst.getNode());
14238 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14239 AddToWorklist(Est.getNode());
14241 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14242 AddToWorklist(Est.getNode());
14244 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14245 AddToWorklist(Est.getNode());
14247 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14248 AddToWorklist(Est.getNode());
14253 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14254 if (Level >= AfterLegalizeDAG)
14257 // Expose the DAG combiner to the target combiner implementations.
14258 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14259 unsigned Iterations = 0;
14260 bool UseOneConstNR = false;
14261 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14262 AddToWorklist(Est.getNode());
14264 Est = UseOneConstNR ?
14265 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14266 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14274 /// Return true if base is a frame index, which is known not to alias with
14275 /// anything but itself. Provides base object and offset as results.
14276 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14277 const GlobalValue *&GV, const void *&CV) {
14278 // Assume it is a primitive operation.
14279 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14281 // If it's an adding a simple constant then integrate the offset.
14282 if (Base.getOpcode() == ISD::ADD) {
14283 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14284 Base = Base.getOperand(0);
14285 Offset += C->getZExtValue();
14289 // Return the underlying GlobalValue, and update the Offset. Return false
14290 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14291 // by multiple nodes with different offsets.
14292 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14293 GV = G->getGlobal();
14294 Offset += G->getOffset();
14298 // Return the underlying Constant value, and update the Offset. Return false
14299 // for ConstantSDNodes since the same constant pool entry may be represented
14300 // by multiple nodes with different offsets.
14301 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14302 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14303 : (const void *)C->getConstVal();
14304 Offset += C->getOffset();
14307 // If it's any of the following then it can't alias with anything but itself.
14308 return isa<FrameIndexSDNode>(Base);
14311 /// Return true if there is any possibility that the two addresses overlap.
14312 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14313 // If they are the same then they must be aliases.
14314 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14316 // If they are both volatile then they cannot be reordered.
14317 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14319 // If one operation reads from invariant memory, and the other may store, they
14320 // cannot alias. These should really be checking the equivalent of mayWrite,
14321 // but it only matters for memory nodes other than load /store.
14322 if (Op0->isInvariant() && Op1->writeMem())
14325 if (Op1->isInvariant() && Op0->writeMem())
14328 // Gather base node and offset information.
14329 SDValue Base1, Base2;
14330 int64_t Offset1, Offset2;
14331 const GlobalValue *GV1, *GV2;
14332 const void *CV1, *CV2;
14333 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14334 Base1, Offset1, GV1, CV1);
14335 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14336 Base2, Offset2, GV2, CV2);
14338 // If they have a same base address then check to see if they overlap.
14339 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14340 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14341 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14343 // It is possible for different frame indices to alias each other, mostly
14344 // when tail call optimization reuses return address slots for arguments.
14345 // To catch this case, look up the actual index of frame indices to compute
14346 // the real alias relationship.
14347 if (isFrameIndex1 && isFrameIndex2) {
14348 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14349 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14350 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14351 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14352 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14355 // Otherwise, if we know what the bases are, and they aren't identical, then
14356 // we know they cannot alias.
14357 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14360 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14361 // compared to the size and offset of the access, we may be able to prove they
14362 // do not alias. This check is conservative for now to catch cases created by
14363 // splitting vector types.
14364 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14365 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14366 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14367 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14368 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14369 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14370 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14372 // There is no overlap between these relatively aligned accesses of similar
14373 // size, return no alias.
14374 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14375 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14379 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14381 : DAG.getSubtarget().useAA();
14383 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14384 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14388 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14389 // Use alias analysis information.
14390 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14391 Op1->getSrcValueOffset());
14392 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14393 Op0->getSrcValueOffset() - MinOffset;
14394 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14395 Op1->getSrcValueOffset() - MinOffset;
14396 AliasResult AAResult =
14397 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14398 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14399 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14400 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14401 if (AAResult == NoAlias)
14405 // Otherwise we have to assume they alias.
14409 /// Walk up chain skipping non-aliasing memory nodes,
14410 /// looking for aliasing nodes and adding them to the Aliases vector.
14411 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14412 SmallVectorImpl<SDValue> &Aliases) {
14413 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14414 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14416 // Get alias information for node.
14417 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14420 Chains.push_back(OriginalChain);
14421 unsigned Depth = 0;
14423 // Look at each chain and determine if it is an alias. If so, add it to the
14424 // aliases list. If not, then continue up the chain looking for the next
14426 while (!Chains.empty()) {
14427 SDValue Chain = Chains.pop_back_val();
14429 // For TokenFactor nodes, look at each operand and only continue up the
14430 // chain until we reach the depth limit.
14432 // FIXME: The depth check could be made to return the last non-aliasing
14433 // chain we found before we hit a tokenfactor rather than the original
14437 Aliases.push_back(OriginalChain);
14441 // Don't bother if we've been before.
14442 if (!Visited.insert(Chain.getNode()).second)
14445 switch (Chain.getOpcode()) {
14446 case ISD::EntryToken:
14447 // Entry token is ideal chain operand, but handled in FindBetterChain.
14452 // Get alias information for Chain.
14453 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14454 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14456 // If chain is alias then stop here.
14457 if (!(IsLoad && IsOpLoad) &&
14458 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14459 Aliases.push_back(Chain);
14461 // Look further up the chain.
14462 Chains.push_back(Chain.getOperand(0));
14468 case ISD::TokenFactor:
14469 // We have to check each of the operands of the token factor for "small"
14470 // token factors, so we queue them up. Adding the operands to the queue
14471 // (stack) in reverse order maintains the original order and increases the
14472 // likelihood that getNode will find a matching token factor (CSE.)
14473 if (Chain.getNumOperands() > 16) {
14474 Aliases.push_back(Chain);
14477 for (unsigned n = Chain.getNumOperands(); n;)
14478 Chains.push_back(Chain.getOperand(--n));
14483 // For all other instructions we will just have to take what we can get.
14484 Aliases.push_back(Chain);
14489 // We need to be careful here to also search for aliases through the
14490 // value operand of a store, etc. Consider the following situation:
14492 // L1 = load Token1, %52
14493 // S1 = store Token1, L1, %51
14494 // L2 = load Token1, %52+8
14495 // S2 = store Token1, L2, %51+8
14496 // Token2 = Token(S1, S2)
14497 // L3 = load Token2, %53
14498 // S3 = store Token2, L3, %52
14499 // L4 = load Token2, %53+8
14500 // S4 = store Token2, L4, %52+8
14501 // If we search for aliases of S3 (which loads address %52), and we look
14502 // only through the chain, then we'll miss the trivial dependence on L1
14503 // (which also loads from %52). We then might change all loads and
14504 // stores to use Token1 as their chain operand, which could result in
14505 // copying %53 into %52 before copying %52 into %51 (which should
14508 // The problem is, however, that searching for such data dependencies
14509 // can become expensive, and the cost is not directly related to the
14510 // chain depth. Instead, we'll rule out such configurations here by
14511 // insisting that we've visited all chain users (except for users
14512 // of the original chain, which is not necessary). When doing this,
14513 // we need to look through nodes we don't care about (otherwise, things
14514 // like register copies will interfere with trivial cases).
14516 SmallVector<const SDNode *, 16> Worklist;
14517 for (const SDNode *N : Visited)
14518 if (N != OriginalChain.getNode())
14519 Worklist.push_back(N);
14521 while (!Worklist.empty()) {
14522 const SDNode *M = Worklist.pop_back_val();
14524 // We have already visited M, and want to make sure we've visited any uses
14525 // of M that we care about. For uses that we've not visisted, and don't
14526 // care about, queue them to the worklist.
14528 for (SDNode::use_iterator UI = M->use_begin(),
14529 UIE = M->use_end(); UI != UIE; ++UI)
14530 if (UI.getUse().getValueType() == MVT::Other &&
14531 Visited.insert(*UI).second) {
14532 if (isa<MemSDNode>(*UI)) {
14533 // We've not visited this use, and we care about it (it could have an
14534 // ordering dependency with the original node).
14536 Aliases.push_back(OriginalChain);
14540 // We've not visited this use, but we don't care about it. Mark it as
14541 // visited and enqueue it to the worklist.
14542 Worklist.push_back(*UI);
14547 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14548 /// (aliasing node.)
14549 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14550 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14552 // Accumulate all the aliases to this node.
14553 GatherAllAliases(N, OldChain, Aliases);
14555 // If no operands then chain to entry token.
14556 if (Aliases.size() == 0)
14557 return DAG.getEntryNode();
14559 // If a single operand then chain to it. We don't need to revisit it.
14560 if (Aliases.size() == 1)
14563 // Construct a custom tailored token factor.
14564 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14567 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14568 // This holds the base pointer, index, and the offset in bytes from the base
14570 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14572 // We must have a base and an offset.
14573 if (!BasePtr.Base.getNode())
14576 // Do not handle stores to undef base pointers.
14577 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14580 SmallVector<StoreSDNode *, 8> ChainedStores;
14581 ChainedStores.push_back(St);
14583 // Walk up the chain and look for nodes with offsets from the same
14584 // base pointer. Stop when reaching an instruction with a different kind
14585 // or instruction which has a different base pointer.
14586 StoreSDNode *Index = St;
14588 // If the chain has more than one use, then we can't reorder the mem ops.
14589 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14592 if (Index->isVolatile() || Index->isIndexed())
14595 // Find the base pointer and offset for this memory node.
14596 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14598 // Check that the base pointer is the same as the original one.
14599 if (!Ptr.equalBaseIndex(BasePtr))
14602 // Find the next memory operand in the chain. If the next operand in the
14603 // chain is a store then move up and continue the scan with the next
14604 // memory operand. If the next operand is a load save it and use alias
14605 // information to check if it interferes with anything.
14606 SDNode *NextInChain = Index->getChain().getNode();
14608 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14609 // We found a store node. Use it for the next iteration.
14610 ChainedStores.push_back(STn);
14613 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14614 NextInChain = Ldn->getChain().getNode();
14623 bool MadeChange = false;
14624 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14626 for (StoreSDNode *ChainedStore : ChainedStores) {
14627 SDValue Chain = ChainedStore->getChain();
14628 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14630 if (Chain != BetterChain) {
14632 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14636 // Do all replacements after finding the replacements to make to avoid making
14637 // the chains more complicated by introducing new TokenFactors.
14638 for (auto Replacement : BetterChains)
14639 replaceStoreChain(Replacement.first, Replacement.second);
14644 /// This is the entry point for the file.
14645 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14646 CodeGenOpt::Level OptLevel) {
14647 /// This is the main entry point to this class.
14648 DAGCombiner(*this, AA, OptLevel).Run(Level);