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 MergeStoresOfConstantsOrVecElts. Returns a
407 /// constant build_vector of the stored constant values in Stores.
408 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
410 ArrayRef<MemOpLink> Stores,
411 SmallVectorImpl<SDValue> &Chains,
414 /// This is a helper function for MergeConsecutiveStores. When the source
415 /// elements of the consecutive stores are all constants or all extracted
416 /// vector elements, try to merge them into one larger store.
417 /// \return True if a merged store was created.
418 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
419 EVT MemVT, unsigned NumStores,
420 bool IsConstantSrc, bool UseVector);
422 /// This is a helper function for MergeConsecutiveStores.
423 /// Stores that may be merged are placed in StoreNodes.
424 /// Loads that may alias with those stores are placed in AliasLoadNodes.
425 void getStoreMergeAndAliasCandidates(
426 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
427 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
429 /// Merge consecutive store operations into a wide store.
430 /// This optimization uses wide integers or vectors when possible.
431 /// \return True if some memory operations were changed.
432 bool MergeConsecutiveStores(StoreSDNode *N);
434 /// \brief Try to transform a truncation where C is a constant:
435 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
437 /// \p N needs to be a truncation and its first operand an AND. Other
438 /// requirements are checked by the function (e.g. that trunc is
439 /// single-use) and if missed an empty SDValue is returned.
440 SDValue distributeTruncateThroughAnd(SDNode *N);
443 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
444 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
445 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
446 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
449 /// Runs the dag combiner on all nodes in the work list
450 void Run(CombineLevel AtLevel);
452 SelectionDAG &getDAG() const { return DAG; }
454 /// Returns a type large enough to hold any valid shift amount - before type
455 /// legalization these can be huge.
456 EVT getShiftAmountTy(EVT LHSTy) {
457 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
458 if (LHSTy.isVector())
460 auto &DL = DAG.getDataLayout();
461 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
462 : TLI.getPointerTy(DL);
465 /// This method returns true if we are running before type legalization or
466 /// if the specified VT is legal.
467 bool isTypeLegal(const EVT &VT) {
468 if (!LegalTypes) return true;
469 return TLI.isTypeLegal(VT);
472 /// Convenience wrapper around TargetLowering::getSetCCResultType
473 EVT getSetCCResultType(EVT VT) const {
474 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
481 /// This class is a DAGUpdateListener that removes any deleted
482 /// nodes from the worklist.
483 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
486 explicit WorklistRemover(DAGCombiner &dc)
487 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
489 void NodeDeleted(SDNode *N, SDNode *E) override {
490 DC.removeFromWorklist(N);
495 //===----------------------------------------------------------------------===//
496 // TargetLowering::DAGCombinerInfo implementation
497 //===----------------------------------------------------------------------===//
499 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
500 ((DAGCombiner*)DC)->AddToWorklist(N);
503 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
504 ((DAGCombiner*)DC)->removeFromWorklist(N);
507 SDValue TargetLowering::DAGCombinerInfo::
508 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
509 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
512 SDValue TargetLowering::DAGCombinerInfo::
513 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
514 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
518 SDValue TargetLowering::DAGCombinerInfo::
519 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
520 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
523 void TargetLowering::DAGCombinerInfo::
524 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
525 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
528 //===----------------------------------------------------------------------===//
530 //===----------------------------------------------------------------------===//
532 void DAGCombiner::deleteAndRecombine(SDNode *N) {
533 removeFromWorklist(N);
535 // If the operands of this node are only used by the node, they will now be
536 // dead. Make sure to re-visit them and recursively delete dead nodes.
537 for (const SDValue &Op : N->ops())
538 // For an operand generating multiple values, one of the values may
539 // become dead allowing further simplification (e.g. split index
540 // arithmetic from an indexed load).
541 if (Op->hasOneUse() || Op->getNumValues() > 1)
542 AddToWorklist(Op.getNode());
547 /// Return 1 if we can compute the negated form of the specified expression for
548 /// the same cost as the expression itself, or 2 if we can compute the negated
549 /// form more cheaply than the expression itself.
550 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
551 const TargetLowering &TLI,
552 const TargetOptions *Options,
553 unsigned Depth = 0) {
554 // fneg is removable even if it has multiple uses.
555 if (Op.getOpcode() == ISD::FNEG) return 2;
557 // Don't allow anything with multiple uses.
558 if (!Op.hasOneUse()) return 0;
560 // Don't recurse exponentially.
561 if (Depth > 6) return 0;
563 switch (Op.getOpcode()) {
564 default: return false;
565 case ISD::ConstantFP:
566 // Don't invert constant FP values after legalize. The negated constant
567 // isn't necessarily legal.
568 return LegalOperations ? 0 : 1;
570 // FIXME: determine better conditions for this xform.
571 if (!Options->UnsafeFPMath) return 0;
573 // After operation legalization, it might not be legal to create new FSUBs.
574 if (LegalOperations &&
575 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
578 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
579 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
582 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
583 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
586 // We can't turn -(A-B) into B-A when we honor signed zeros.
587 if (!Options->UnsafeFPMath) return 0;
589 // fold (fneg (fsub A, B)) -> (fsub B, A)
594 if (Options->HonorSignDependentRoundingFPMath()) return 0;
596 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
597 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
601 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
607 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
612 /// If isNegatibleForFree returns true, return the newly negated expression.
613 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
614 bool LegalOperations, unsigned Depth = 0) {
615 const TargetOptions &Options = DAG.getTarget().Options;
616 // fneg is removable even if it has multiple uses.
617 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
619 // Don't allow anything with multiple uses.
620 assert(Op.hasOneUse() && "Unknown reuse!");
622 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
624 const SDNodeFlags *Flags = Op.getNode()->getFlags();
626 switch (Op.getOpcode()) {
627 default: llvm_unreachable("Unknown code");
628 case ISD::ConstantFP: {
629 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
631 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
634 // FIXME: determine better conditions for this xform.
635 assert(Options.UnsafeFPMath);
637 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
638 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
639 DAG.getTargetLoweringInfo(), &Options, Depth+1))
640 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
641 GetNegatedExpression(Op.getOperand(0), DAG,
642 LegalOperations, Depth+1),
643 Op.getOperand(1), Flags);
644 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
645 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
646 GetNegatedExpression(Op.getOperand(1), DAG,
647 LegalOperations, Depth+1),
648 Op.getOperand(0), Flags);
650 // We can't turn -(A-B) into B-A when we honor signed zeros.
651 assert(Options.UnsafeFPMath);
653 // fold (fneg (fsub 0, B)) -> B
654 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
656 return Op.getOperand(1);
658 // fold (fneg (fsub A, B)) -> (fsub B, A)
659 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
660 Op.getOperand(1), Op.getOperand(0), Flags);
664 assert(!Options.HonorSignDependentRoundingFPMath());
666 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
667 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
668 DAG.getTargetLoweringInfo(), &Options, Depth+1))
669 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
670 GetNegatedExpression(Op.getOperand(0), DAG,
671 LegalOperations, Depth+1),
672 Op.getOperand(1), Flags);
674 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
675 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
677 GetNegatedExpression(Op.getOperand(1), DAG,
678 LegalOperations, Depth+1), Flags);
682 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
683 GetNegatedExpression(Op.getOperand(0), DAG,
684 LegalOperations, Depth+1));
686 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
687 GetNegatedExpression(Op.getOperand(0), DAG,
688 LegalOperations, Depth+1),
693 // Return true if this node is a setcc, or is a select_cc
694 // that selects between the target values used for true and false, making it
695 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
696 // the appropriate nodes based on the type of node we are checking. This
697 // simplifies life a bit for the callers.
698 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
700 if (N.getOpcode() == ISD::SETCC) {
701 LHS = N.getOperand(0);
702 RHS = N.getOperand(1);
703 CC = N.getOperand(2);
707 if (N.getOpcode() != ISD::SELECT_CC ||
708 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
709 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
712 if (TLI.getBooleanContents(N.getValueType()) ==
713 TargetLowering::UndefinedBooleanContent)
716 LHS = N.getOperand(0);
717 RHS = N.getOperand(1);
718 CC = N.getOperand(4);
722 /// Return true if this is a SetCC-equivalent operation with only one use.
723 /// If this is true, it allows the users to invert the operation for free when
724 /// it is profitable to do so.
725 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
727 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
732 /// Returns true if N is a BUILD_VECTOR node whose
733 /// elements are all the same constant or undefined.
734 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
735 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
740 unsigned SplatBitSize;
742 EVT EltVT = N->getValueType(0).getVectorElementType();
743 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
745 EltVT.getSizeInBits() >= SplatBitSize);
748 // \brief Returns the SDNode if it is a constant integer BuildVector
749 // or constant integer.
750 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
751 if (isa<ConstantSDNode>(N))
753 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
758 // \brief Returns the SDNode if it is a constant float BuildVector
759 // or constant float.
760 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
761 if (isa<ConstantFPSDNode>(N))
763 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
768 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
770 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
771 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
774 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
775 BitVector UndefElements;
776 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
778 // BuildVectors can truncate their operands. Ignore that case here.
779 // FIXME: We blindly ignore splats which include undef which is overly
781 if (CN && UndefElements.none() &&
782 CN->getValueType(0) == N.getValueType().getScalarType())
789 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
791 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
792 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
795 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
796 BitVector UndefElements;
797 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
799 if (CN && UndefElements.none())
806 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
807 SDValue N0, SDValue N1) {
808 EVT VT = N0.getValueType();
809 if (N0.getOpcode() == Opc) {
810 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
811 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
812 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
813 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
814 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
817 if (N0.hasOneUse()) {
818 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
820 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
821 if (!OpNode.getNode())
823 AddToWorklist(OpNode.getNode());
824 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
829 if (N1.getOpcode() == Opc) {
830 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
831 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
832 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
833 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
834 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
837 if (N1.hasOneUse()) {
838 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
840 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
841 if (!OpNode.getNode())
843 AddToWorklist(OpNode.getNode());
844 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
852 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
854 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
856 DEBUG(dbgs() << "\nReplacing.1 ";
858 dbgs() << "\nWith: ";
859 To[0].getNode()->dump(&DAG);
860 dbgs() << " and " << NumTo-1 << " other values\n");
861 for (unsigned i = 0, e = NumTo; i != e; ++i)
862 assert((!To[i].getNode() ||
863 N->getValueType(i) == To[i].getValueType()) &&
864 "Cannot combine value to value of different type!");
866 WorklistRemover DeadNodes(*this);
867 DAG.ReplaceAllUsesWith(N, To);
869 // Push the new nodes and any users onto the worklist
870 for (unsigned i = 0, e = NumTo; i != e; ++i) {
871 if (To[i].getNode()) {
872 AddToWorklist(To[i].getNode());
873 AddUsersToWorklist(To[i].getNode());
878 // Finally, if the node is now dead, remove it from the graph. The node
879 // may not be dead if the replacement process recursively simplified to
880 // something else needing this node.
882 deleteAndRecombine(N);
883 return SDValue(N, 0);
887 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
888 // Replace all uses. If any nodes become isomorphic to other nodes and
889 // are deleted, make sure to remove them from our worklist.
890 WorklistRemover DeadNodes(*this);
891 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
893 // Push the new node and any (possibly new) users onto the worklist.
894 AddToWorklist(TLO.New.getNode());
895 AddUsersToWorklist(TLO.New.getNode());
897 // Finally, if the node is now dead, remove it from the graph. The node
898 // may not be dead if the replacement process recursively simplified to
899 // something else needing this node.
900 if (TLO.Old.getNode()->use_empty())
901 deleteAndRecombine(TLO.Old.getNode());
904 /// Check the specified integer node value to see if it can be simplified or if
905 /// things it uses can be simplified by bit propagation. If so, return true.
906 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
907 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
908 APInt KnownZero, KnownOne;
909 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
913 AddToWorklist(Op.getNode());
915 // Replace the old value with the new one.
917 DEBUG(dbgs() << "\nReplacing.2 ";
918 TLO.Old.getNode()->dump(&DAG);
919 dbgs() << "\nWith: ";
920 TLO.New.getNode()->dump(&DAG);
923 CommitTargetLoweringOpt(TLO);
927 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
929 EVT VT = Load->getValueType(0);
930 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
932 DEBUG(dbgs() << "\nReplacing.9 ";
934 dbgs() << "\nWith: ";
935 Trunc.getNode()->dump(&DAG);
937 WorklistRemover DeadNodes(*this);
938 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
939 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
940 deleteAndRecombine(Load);
941 AddToWorklist(Trunc.getNode());
944 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
947 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
948 EVT MemVT = LD->getMemoryVT();
949 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
950 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
952 : LD->getExtensionType();
954 return DAG.getExtLoad(ExtType, dl, PVT,
955 LD->getChain(), LD->getBasePtr(),
956 MemVT, LD->getMemOperand());
959 unsigned Opc = Op.getOpcode();
962 case ISD::AssertSext:
963 return DAG.getNode(ISD::AssertSext, dl, PVT,
964 SExtPromoteOperand(Op.getOperand(0), PVT),
966 case ISD::AssertZext:
967 return DAG.getNode(ISD::AssertZext, dl, PVT,
968 ZExtPromoteOperand(Op.getOperand(0), PVT),
970 case ISD::Constant: {
972 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
973 return DAG.getNode(ExtOpc, dl, PVT, Op);
977 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
979 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
982 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
983 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
985 EVT OldVT = Op.getValueType();
987 bool Replace = false;
988 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
989 if (!NewOp.getNode())
991 AddToWorklist(NewOp.getNode());
994 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
995 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
996 DAG.getValueType(OldVT));
999 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1000 EVT OldVT = Op.getValueType();
1002 bool Replace = false;
1003 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1004 if (!NewOp.getNode())
1006 AddToWorklist(NewOp.getNode());
1009 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1010 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1013 /// Promote the specified integer binary operation if the target indicates it is
1014 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1015 /// i32 since i16 instructions are longer.
1016 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1017 if (!LegalOperations)
1020 EVT VT = Op.getValueType();
1021 if (VT.isVector() || !VT.isInteger())
1024 // If operation type is 'undesirable', e.g. i16 on x86, consider
1026 unsigned Opc = Op.getOpcode();
1027 if (TLI.isTypeDesirableForOp(Opc, VT))
1031 // Consult target whether it is a good idea to promote this operation and
1032 // what's the right type to promote it to.
1033 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1034 assert(PVT != VT && "Don't know what type to promote to!");
1036 bool Replace0 = false;
1037 SDValue N0 = Op.getOperand(0);
1038 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1042 bool Replace1 = false;
1043 SDValue N1 = Op.getOperand(1);
1048 NN1 = PromoteOperand(N1, PVT, Replace1);
1053 AddToWorklist(NN0.getNode());
1055 AddToWorklist(NN1.getNode());
1058 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1060 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1062 DEBUG(dbgs() << "\nPromoting ";
1063 Op.getNode()->dump(&DAG));
1065 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1066 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1071 /// Promote the specified integer shift operation if the target indicates it is
1072 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1073 /// i32 since i16 instructions are longer.
1074 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1075 if (!LegalOperations)
1078 EVT VT = Op.getValueType();
1079 if (VT.isVector() || !VT.isInteger())
1082 // If operation type is 'undesirable', e.g. i16 on x86, consider
1084 unsigned Opc = Op.getOpcode();
1085 if (TLI.isTypeDesirableForOp(Opc, VT))
1089 // Consult target whether it is a good idea to promote this operation and
1090 // what's the right type to promote it to.
1091 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1092 assert(PVT != VT && "Don't know what type to promote to!");
1094 bool Replace = false;
1095 SDValue N0 = Op.getOperand(0);
1096 if (Opc == ISD::SRA)
1097 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1098 else if (Opc == ISD::SRL)
1099 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1101 N0 = PromoteOperand(N0, PVT, Replace);
1105 AddToWorklist(N0.getNode());
1107 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1109 DEBUG(dbgs() << "\nPromoting ";
1110 Op.getNode()->dump(&DAG));
1112 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1113 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1118 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1119 if (!LegalOperations)
1122 EVT VT = Op.getValueType();
1123 if (VT.isVector() || !VT.isInteger())
1126 // If operation type is 'undesirable', e.g. i16 on x86, consider
1128 unsigned Opc = Op.getOpcode();
1129 if (TLI.isTypeDesirableForOp(Opc, VT))
1133 // Consult target whether it is a good idea to promote this operation and
1134 // what's the right type to promote it to.
1135 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1136 assert(PVT != VT && "Don't know what type to promote to!");
1137 // fold (aext (aext x)) -> (aext x)
1138 // fold (aext (zext x)) -> (zext x)
1139 // fold (aext (sext x)) -> (sext x)
1140 DEBUG(dbgs() << "\nPromoting ";
1141 Op.getNode()->dump(&DAG));
1142 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1147 bool DAGCombiner::PromoteLoad(SDValue Op) {
1148 if (!LegalOperations)
1151 EVT VT = Op.getValueType();
1152 if (VT.isVector() || !VT.isInteger())
1155 // If operation type is 'undesirable', e.g. i16 on x86, consider
1157 unsigned Opc = Op.getOpcode();
1158 if (TLI.isTypeDesirableForOp(Opc, VT))
1162 // Consult target whether it is a good idea to promote this operation and
1163 // what's the right type to promote it to.
1164 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1165 assert(PVT != VT && "Don't know what type to promote to!");
1168 SDNode *N = Op.getNode();
1169 LoadSDNode *LD = cast<LoadSDNode>(N);
1170 EVT MemVT = LD->getMemoryVT();
1171 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1172 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1174 : LD->getExtensionType();
1175 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1176 LD->getChain(), LD->getBasePtr(),
1177 MemVT, LD->getMemOperand());
1178 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1180 DEBUG(dbgs() << "\nPromoting ";
1183 Result.getNode()->dump(&DAG);
1185 WorklistRemover DeadNodes(*this);
1186 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1187 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1188 deleteAndRecombine(N);
1189 AddToWorklist(Result.getNode());
1195 /// \brief Recursively delete a node which has no uses and any operands for
1196 /// which it is the only use.
1198 /// Note that this both deletes the nodes and removes them from the worklist.
1199 /// It also adds any nodes who have had a user deleted to the worklist as they
1200 /// may now have only one use and subject to other combines.
1201 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1202 if (!N->use_empty())
1205 SmallSetVector<SDNode *, 16> Nodes;
1208 N = Nodes.pop_back_val();
1212 if (N->use_empty()) {
1213 for (const SDValue &ChildN : N->op_values())
1214 Nodes.insert(ChildN.getNode());
1216 removeFromWorklist(N);
1221 } while (!Nodes.empty());
1225 //===----------------------------------------------------------------------===//
1226 // Main DAG Combiner implementation
1227 //===----------------------------------------------------------------------===//
1229 void DAGCombiner::Run(CombineLevel AtLevel) {
1230 // set the instance variables, so that the various visit routines may use it.
1232 LegalOperations = Level >= AfterLegalizeVectorOps;
1233 LegalTypes = Level >= AfterLegalizeTypes;
1235 // Add all the dag nodes to the worklist.
1236 for (SDNode &Node : DAG.allnodes())
1237 AddToWorklist(&Node);
1239 // Create a dummy node (which is not added to allnodes), that adds a reference
1240 // to the root node, preventing it from being deleted, and tracking any
1241 // changes of the root.
1242 HandleSDNode Dummy(DAG.getRoot());
1244 // while the worklist isn't empty, find a node and
1245 // try and combine it.
1246 while (!WorklistMap.empty()) {
1248 // The Worklist holds the SDNodes in order, but it may contain null entries.
1250 N = Worklist.pop_back_val();
1253 bool GoodWorklistEntry = WorklistMap.erase(N);
1254 (void)GoodWorklistEntry;
1255 assert(GoodWorklistEntry &&
1256 "Found a worklist entry without a corresponding map entry!");
1258 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1259 // N is deleted from the DAG, since they too may now be dead or may have a
1260 // reduced number of uses, allowing other xforms.
1261 if (recursivelyDeleteUnusedNodes(N))
1264 WorklistRemover DeadNodes(*this);
1266 // If this combine is running after legalizing the DAG, re-legalize any
1267 // nodes pulled off the worklist.
1268 if (Level == AfterLegalizeDAG) {
1269 SmallSetVector<SDNode *, 16> UpdatedNodes;
1270 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1272 for (SDNode *LN : UpdatedNodes) {
1274 AddUsersToWorklist(LN);
1280 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1282 // Add any operands of the new node which have not yet been combined to the
1283 // worklist as well. Because the worklist uniques things already, this
1284 // won't repeatedly process the same operand.
1285 CombinedNodes.insert(N);
1286 for (const SDValue &ChildN : N->op_values())
1287 if (!CombinedNodes.count(ChildN.getNode()))
1288 AddToWorklist(ChildN.getNode());
1290 SDValue RV = combine(N);
1297 // If we get back the same node we passed in, rather than a new node or
1298 // zero, we know that the node must have defined multiple values and
1299 // CombineTo was used. Since CombineTo takes care of the worklist
1300 // mechanics for us, we have no work to do in this case.
1301 if (RV.getNode() == N)
1304 assert(N->getOpcode() != ISD::DELETED_NODE &&
1305 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1306 "Node was deleted but visit returned new node!");
1308 DEBUG(dbgs() << " ... into: ";
1309 RV.getNode()->dump(&DAG));
1311 // Transfer debug value.
1312 DAG.TransferDbgValues(SDValue(N, 0), RV);
1313 if (N->getNumValues() == RV.getNode()->getNumValues())
1314 DAG.ReplaceAllUsesWith(N, RV.getNode());
1316 assert(N->getValueType(0) == RV.getValueType() &&
1317 N->getNumValues() == 1 && "Type mismatch");
1319 DAG.ReplaceAllUsesWith(N, &OpV);
1322 // Push the new node and any users onto the worklist
1323 AddToWorklist(RV.getNode());
1324 AddUsersToWorklist(RV.getNode());
1326 // Finally, if the node is now dead, remove it from the graph. The node
1327 // may not be dead if the replacement process recursively simplified to
1328 // something else needing this node. This will also take care of adding any
1329 // operands which have lost a user to the worklist.
1330 recursivelyDeleteUnusedNodes(N);
1333 // If the root changed (e.g. it was a dead load, update the root).
1334 DAG.setRoot(Dummy.getValue());
1335 DAG.RemoveDeadNodes();
1338 SDValue DAGCombiner::visit(SDNode *N) {
1339 switch (N->getOpcode()) {
1341 case ISD::TokenFactor: return visitTokenFactor(N);
1342 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1343 case ISD::ADD: return visitADD(N);
1344 case ISD::SUB: return visitSUB(N);
1345 case ISD::ADDC: return visitADDC(N);
1346 case ISD::SUBC: return visitSUBC(N);
1347 case ISD::ADDE: return visitADDE(N);
1348 case ISD::SUBE: return visitSUBE(N);
1349 case ISD::MUL: return visitMUL(N);
1350 case ISD::SDIV: return visitSDIV(N);
1351 case ISD::UDIV: return visitUDIV(N);
1353 case ISD::UREM: return visitREM(N);
1354 case ISD::MULHU: return visitMULHU(N);
1355 case ISD::MULHS: return visitMULHS(N);
1356 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1357 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1358 case ISD::SMULO: return visitSMULO(N);
1359 case ISD::UMULO: return visitUMULO(N);
1363 case ISD::UMAX: return visitIMINMAX(N);
1364 case ISD::AND: return visitAND(N);
1365 case ISD::OR: return visitOR(N);
1366 case ISD::XOR: return visitXOR(N);
1367 case ISD::SHL: return visitSHL(N);
1368 case ISD::SRA: return visitSRA(N);
1369 case ISD::SRL: return visitSRL(N);
1371 case ISD::ROTL: return visitRotate(N);
1372 case ISD::BSWAP: return visitBSWAP(N);
1373 case ISD::CTLZ: return visitCTLZ(N);
1374 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1375 case ISD::CTTZ: return visitCTTZ(N);
1376 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1377 case ISD::CTPOP: return visitCTPOP(N);
1378 case ISD::SELECT: return visitSELECT(N);
1379 case ISD::VSELECT: return visitVSELECT(N);
1380 case ISD::SELECT_CC: return visitSELECT_CC(N);
1381 case ISD::SETCC: return visitSETCC(N);
1382 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1383 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1384 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1385 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1386 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1387 case ISD::TRUNCATE: return visitTRUNCATE(N);
1388 case ISD::BITCAST: return visitBITCAST(N);
1389 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1390 case ISD::FADD: return visitFADD(N);
1391 case ISD::FSUB: return visitFSUB(N);
1392 case ISD::FMUL: return visitFMUL(N);
1393 case ISD::FMA: return visitFMA(N);
1394 case ISD::FDIV: return visitFDIV(N);
1395 case ISD::FREM: return visitFREM(N);
1396 case ISD::FSQRT: return visitFSQRT(N);
1397 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1398 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1399 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1400 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1401 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1402 case ISD::FP_ROUND: return visitFP_ROUND(N);
1403 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1404 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1405 case ISD::FNEG: return visitFNEG(N);
1406 case ISD::FABS: return visitFABS(N);
1407 case ISD::FFLOOR: return visitFFLOOR(N);
1408 case ISD::FMINNUM: return visitFMINNUM(N);
1409 case ISD::FMAXNUM: return visitFMAXNUM(N);
1410 case ISD::FCEIL: return visitFCEIL(N);
1411 case ISD::FTRUNC: return visitFTRUNC(N);
1412 case ISD::BRCOND: return visitBRCOND(N);
1413 case ISD::BR_CC: return visitBR_CC(N);
1414 case ISD::LOAD: return visitLOAD(N);
1415 case ISD::STORE: return visitSTORE(N);
1416 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1417 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1418 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1419 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1420 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1421 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1422 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1423 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1424 case ISD::MGATHER: return visitMGATHER(N);
1425 case ISD::MLOAD: return visitMLOAD(N);
1426 case ISD::MSCATTER: return visitMSCATTER(N);
1427 case ISD::MSTORE: return visitMSTORE(N);
1428 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1429 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1434 SDValue DAGCombiner::combine(SDNode *N) {
1435 SDValue RV = visit(N);
1437 // If nothing happened, try a target-specific DAG combine.
1438 if (!RV.getNode()) {
1439 assert(N->getOpcode() != ISD::DELETED_NODE &&
1440 "Node was deleted but visit returned NULL!");
1442 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1443 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1445 // Expose the DAG combiner to the target combiner impls.
1446 TargetLowering::DAGCombinerInfo
1447 DagCombineInfo(DAG, Level, false, this);
1449 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1453 // If nothing happened still, try promoting the operation.
1454 if (!RV.getNode()) {
1455 switch (N->getOpcode()) {
1463 RV = PromoteIntBinOp(SDValue(N, 0));
1468 RV = PromoteIntShiftOp(SDValue(N, 0));
1470 case ISD::SIGN_EXTEND:
1471 case ISD::ZERO_EXTEND:
1472 case ISD::ANY_EXTEND:
1473 RV = PromoteExtend(SDValue(N, 0));
1476 if (PromoteLoad(SDValue(N, 0)))
1482 // If N is a commutative binary node, try commuting it to enable more
1484 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1485 N->getNumValues() == 1) {
1486 SDValue N0 = N->getOperand(0);
1487 SDValue N1 = N->getOperand(1);
1489 // Constant operands are canonicalized to RHS.
1490 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1491 SDValue Ops[] = {N1, N0};
1492 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1495 return SDValue(CSENode, 0);
1502 /// Given a node, return its input chain if it has one, otherwise return a null
1504 static SDValue getInputChainForNode(SDNode *N) {
1505 if (unsigned NumOps = N->getNumOperands()) {
1506 if (N->getOperand(0).getValueType() == MVT::Other)
1507 return N->getOperand(0);
1508 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1509 return N->getOperand(NumOps-1);
1510 for (unsigned i = 1; i < NumOps-1; ++i)
1511 if (N->getOperand(i).getValueType() == MVT::Other)
1512 return N->getOperand(i);
1517 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1518 // If N has two operands, where one has an input chain equal to the other,
1519 // the 'other' chain is redundant.
1520 if (N->getNumOperands() == 2) {
1521 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1522 return N->getOperand(0);
1523 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1524 return N->getOperand(1);
1527 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1528 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1529 SmallPtrSet<SDNode*, 16> SeenOps;
1530 bool Changed = false; // If we should replace this token factor.
1532 // Start out with this token factor.
1535 // Iterate through token factors. The TFs grows when new token factors are
1537 for (unsigned i = 0; i < TFs.size(); ++i) {
1538 SDNode *TF = TFs[i];
1540 // Check each of the operands.
1541 for (const SDValue &Op : TF->op_values()) {
1543 switch (Op.getOpcode()) {
1544 case ISD::EntryToken:
1545 // Entry tokens don't need to be added to the list. They are
1550 case ISD::TokenFactor:
1551 if (Op.hasOneUse() &&
1552 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1553 // Queue up for processing.
1554 TFs.push_back(Op.getNode());
1555 // Clean up in case the token factor is removed.
1556 AddToWorklist(Op.getNode());
1563 // Only add if it isn't already in the list.
1564 if (SeenOps.insert(Op.getNode()).second)
1575 // If we've changed things around then replace token factor.
1578 // The entry token is the only possible outcome.
1579 Result = DAG.getEntryNode();
1581 // New and improved token factor.
1582 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1585 // Add users to worklist if AA is enabled, since it may introduce
1586 // a lot of new chained token factors while removing memory deps.
1587 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1588 : DAG.getSubtarget().useAA();
1589 return CombineTo(N, Result, UseAA /*add to worklist*/);
1595 /// MERGE_VALUES can always be eliminated.
1596 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1597 WorklistRemover DeadNodes(*this);
1598 // Replacing results may cause a different MERGE_VALUES to suddenly
1599 // be CSE'd with N, and carry its uses with it. Iterate until no
1600 // uses remain, to ensure that the node can be safely deleted.
1601 // First add the users of this node to the work list so that they
1602 // can be tried again once they have new operands.
1603 AddUsersToWorklist(N);
1605 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1606 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1607 } while (!N->use_empty());
1608 deleteAndRecombine(N);
1609 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1612 static bool isNullConstant(SDValue V) {
1613 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1614 return Const != nullptr && Const->isNullValue();
1617 static bool isNullFPConstant(SDValue V) {
1618 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1619 return Const != nullptr && Const->isZero() && !Const->isNegative();
1622 static bool isAllOnesConstant(SDValue V) {
1623 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1624 return Const != nullptr && Const->isAllOnesValue();
1627 static bool isOneConstant(SDValue V) {
1628 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1629 return Const != nullptr && Const->isOne();
1632 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1633 /// ContantSDNode pointer else nullptr.
1634 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1635 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1636 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1639 SDValue DAGCombiner::visitADD(SDNode *N) {
1640 SDValue N0 = N->getOperand(0);
1641 SDValue N1 = N->getOperand(1);
1642 EVT VT = N0.getValueType();
1645 if (VT.isVector()) {
1646 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1649 // fold (add x, 0) -> x, vector edition
1650 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1652 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1656 // fold (add x, undef) -> undef
1657 if (N0.getOpcode() == ISD::UNDEF)
1659 if (N1.getOpcode() == ISD::UNDEF)
1661 // fold (add c1, c2) -> c1+c2
1662 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1663 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1665 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1666 // canonicalize constant to RHS
1667 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1668 !isConstantIntBuildVectorOrConstantInt(N1))
1669 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1670 // fold (add x, 0) -> x
1671 if (isNullConstant(N1))
1673 // fold (add Sym, c) -> Sym+c
1674 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1675 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1676 GA->getOpcode() == ISD::GlobalAddress)
1677 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1679 (uint64_t)N1C->getSExtValue());
1680 // fold ((c1-A)+c2) -> (c1+c2)-A
1681 if (N1C && N0.getOpcode() == ISD::SUB)
1682 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1684 return DAG.getNode(ISD::SUB, DL, VT,
1685 DAG.getConstant(N1C->getAPIntValue()+
1686 N0C->getAPIntValue(), DL, VT),
1690 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1692 // fold ((0-A) + B) -> B-A
1693 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1694 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1695 // fold (A + (0-B)) -> A-B
1696 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1697 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1698 // fold (A+(B-A)) -> B
1699 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1700 return N1.getOperand(0);
1701 // fold ((B-A)+A) -> B
1702 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1703 return N0.getOperand(0);
1704 // fold (A+(B-(A+C))) to (B-C)
1705 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1706 N0 == N1.getOperand(1).getOperand(0))
1707 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1708 N1.getOperand(1).getOperand(1));
1709 // fold (A+(B-(C+A))) to (B-C)
1710 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1711 N0 == N1.getOperand(1).getOperand(1))
1712 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1713 N1.getOperand(1).getOperand(0));
1714 // fold (A+((B-A)+or-C)) to (B+or-C)
1715 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1716 N1.getOperand(0).getOpcode() == ISD::SUB &&
1717 N0 == N1.getOperand(0).getOperand(1))
1718 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1719 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1721 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1722 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1723 SDValue N00 = N0.getOperand(0);
1724 SDValue N01 = N0.getOperand(1);
1725 SDValue N10 = N1.getOperand(0);
1726 SDValue N11 = N1.getOperand(1);
1728 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1729 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1730 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1731 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1734 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1735 return SDValue(N, 0);
1737 // fold (a+b) -> (a|b) iff a and b share no bits.
1738 if (VT.isInteger() && !VT.isVector()) {
1739 APInt LHSZero, LHSOne;
1740 APInt RHSZero, RHSOne;
1741 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1743 if (LHSZero.getBoolValue()) {
1744 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1746 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1747 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1748 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1749 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1750 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1755 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1756 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1757 isNullConstant(N1.getOperand(0).getOperand(0)))
1758 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1759 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1760 N1.getOperand(0).getOperand(1),
1762 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1763 isNullConstant(N0.getOperand(0).getOperand(0)))
1764 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1765 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1766 N0.getOperand(0).getOperand(1),
1769 if (N1.getOpcode() == ISD::AND) {
1770 SDValue AndOp0 = N1.getOperand(0);
1771 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1772 unsigned DestBits = VT.getScalarType().getSizeInBits();
1774 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1775 // and similar xforms where the inner op is either ~0 or 0.
1776 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1778 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1782 // add (sext i1), X -> sub X, (zext i1)
1783 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1784 N0.getOperand(0).getValueType() == MVT::i1 &&
1785 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1787 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1788 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1791 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1792 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1793 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1794 if (TN->getVT() == MVT::i1) {
1796 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1797 DAG.getConstant(1, DL, VT));
1798 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1805 SDValue DAGCombiner::visitADDC(SDNode *N) {
1806 SDValue N0 = N->getOperand(0);
1807 SDValue N1 = N->getOperand(1);
1808 EVT VT = N0.getValueType();
1810 // If the flag result is dead, turn this into an ADD.
1811 if (!N->hasAnyUseOfValue(1))
1812 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1813 DAG.getNode(ISD::CARRY_FALSE,
1814 SDLoc(N), MVT::Glue));
1816 // canonicalize constant to RHS.
1817 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1818 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1820 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1822 // fold (addc x, 0) -> x + no carry out
1823 if (isNullConstant(N1))
1824 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1825 SDLoc(N), MVT::Glue));
1827 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1828 APInt LHSZero, LHSOne;
1829 APInt RHSZero, RHSOne;
1830 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1832 if (LHSZero.getBoolValue()) {
1833 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1835 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1836 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1837 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1838 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1839 DAG.getNode(ISD::CARRY_FALSE,
1840 SDLoc(N), MVT::Glue));
1846 SDValue DAGCombiner::visitADDE(SDNode *N) {
1847 SDValue N0 = N->getOperand(0);
1848 SDValue N1 = N->getOperand(1);
1849 SDValue CarryIn = N->getOperand(2);
1851 // canonicalize constant to RHS
1852 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1853 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1855 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1858 // fold (adde x, y, false) -> (addc x, y)
1859 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1860 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1865 // Since it may not be valid to emit a fold to zero for vector initializers
1866 // check if we can before folding.
1867 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1869 bool LegalOperations, bool LegalTypes) {
1871 return DAG.getConstant(0, DL, VT);
1872 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1873 return DAG.getConstant(0, DL, VT);
1877 SDValue DAGCombiner::visitSUB(SDNode *N) {
1878 SDValue N0 = N->getOperand(0);
1879 SDValue N1 = N->getOperand(1);
1880 EVT VT = N0.getValueType();
1883 if (VT.isVector()) {
1884 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1887 // fold (sub x, 0) -> x, vector edition
1888 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1892 // fold (sub x, x) -> 0
1893 // FIXME: Refactor this and xor and other similar operations together.
1895 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1896 // fold (sub c1, c2) -> c1-c2
1897 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1898 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1900 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1901 // fold (sub x, c) -> (add x, -c)
1904 return DAG.getNode(ISD::ADD, DL, VT, N0,
1905 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1907 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1908 if (isAllOnesConstant(N0))
1909 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1910 // fold A-(A-B) -> B
1911 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1912 return N1.getOperand(1);
1913 // fold (A+B)-A -> B
1914 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1915 return N0.getOperand(1);
1916 // fold (A+B)-B -> A
1917 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1918 return N0.getOperand(0);
1919 // fold C2-(A+C1) -> (C2-C1)-A
1920 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1921 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1922 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1924 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1926 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1929 // fold ((A+(B+or-C))-B) -> A+or-C
1930 if (N0.getOpcode() == ISD::ADD &&
1931 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1932 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1933 N0.getOperand(1).getOperand(0) == N1)
1934 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1935 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1936 // fold ((A+(C+B))-B) -> A+C
1937 if (N0.getOpcode() == ISD::ADD &&
1938 N0.getOperand(1).getOpcode() == ISD::ADD &&
1939 N0.getOperand(1).getOperand(1) == N1)
1940 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1941 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1942 // fold ((A-(B-C))-C) -> A-B
1943 if (N0.getOpcode() == ISD::SUB &&
1944 N0.getOperand(1).getOpcode() == ISD::SUB &&
1945 N0.getOperand(1).getOperand(1) == N1)
1946 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1947 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1949 // If either operand of a sub is undef, the result is undef
1950 if (N0.getOpcode() == ISD::UNDEF)
1952 if (N1.getOpcode() == ISD::UNDEF)
1955 // If the relocation model supports it, consider symbol offsets.
1956 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1957 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1958 // fold (sub Sym, c) -> Sym-c
1959 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1960 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1962 (uint64_t)N1C->getSExtValue());
1963 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1964 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1965 if (GA->getGlobal() == GB->getGlobal())
1966 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1970 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1971 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1972 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1973 if (TN->getVT() == MVT::i1) {
1975 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1976 DAG.getConstant(1, DL, VT));
1977 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1984 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1985 SDValue N0 = N->getOperand(0);
1986 SDValue N1 = N->getOperand(1);
1987 EVT VT = N0.getValueType();
1990 // If the flag result is dead, turn this into an SUB.
1991 if (!N->hasAnyUseOfValue(1))
1992 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1993 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1995 // fold (subc x, x) -> 0 + no borrow
1997 return CombineTo(N, DAG.getConstant(0, DL, VT),
1998 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2000 // fold (subc x, 0) -> x + no borrow
2001 if (isNullConstant(N1))
2002 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2004 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2005 if (isAllOnesConstant(N0))
2006 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2007 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2012 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2013 SDValue N0 = N->getOperand(0);
2014 SDValue N1 = N->getOperand(1);
2015 SDValue CarryIn = N->getOperand(2);
2017 // fold (sube x, y, false) -> (subc x, y)
2018 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2019 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2024 SDValue DAGCombiner::visitMUL(SDNode *N) {
2025 SDValue N0 = N->getOperand(0);
2026 SDValue N1 = N->getOperand(1);
2027 EVT VT = N0.getValueType();
2029 // fold (mul x, undef) -> 0
2030 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2031 return DAG.getConstant(0, SDLoc(N), VT);
2033 bool N0IsConst = false;
2034 bool N1IsConst = false;
2035 bool N1IsOpaqueConst = false;
2036 bool N0IsOpaqueConst = false;
2037 APInt ConstValue0, ConstValue1;
2039 if (VT.isVector()) {
2040 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2043 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2044 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2046 N0IsConst = isa<ConstantSDNode>(N0);
2048 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2049 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2051 N1IsConst = isa<ConstantSDNode>(N1);
2053 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2054 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2058 // fold (mul c1, c2) -> c1*c2
2059 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2060 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2061 N0.getNode(), N1.getNode());
2063 // canonicalize constant to RHS (vector doesn't have to splat)
2064 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2065 !isConstantIntBuildVectorOrConstantInt(N1))
2066 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2067 // fold (mul x, 0) -> 0
2068 if (N1IsConst && ConstValue1 == 0)
2070 // We require a splat of the entire scalar bit width for non-contiguous
2073 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2074 // fold (mul x, 1) -> x
2075 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2077 // fold (mul x, -1) -> 0-x
2078 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2080 return DAG.getNode(ISD::SUB, DL, VT,
2081 DAG.getConstant(0, DL, VT), N0);
2083 // fold (mul x, (1 << c)) -> x << c
2084 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2087 return DAG.getNode(ISD::SHL, DL, VT, N0,
2088 DAG.getConstant(ConstValue1.logBase2(), DL,
2089 getShiftAmountTy(N0.getValueType())));
2091 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2092 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2094 unsigned Log2Val = (-ConstValue1).logBase2();
2096 // FIXME: If the input is something that is easily negated (e.g. a
2097 // single-use add), we should put the negate there.
2098 return DAG.getNode(ISD::SUB, DL, VT,
2099 DAG.getConstant(0, DL, VT),
2100 DAG.getNode(ISD::SHL, DL, VT, N0,
2101 DAG.getConstant(Log2Val, DL,
2102 getShiftAmountTy(N0.getValueType()))));
2106 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2107 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2108 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2109 isa<ConstantSDNode>(N0.getOperand(1)))) {
2110 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2111 N1, N0.getOperand(1));
2112 AddToWorklist(C3.getNode());
2113 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2114 N0.getOperand(0), C3);
2117 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2120 SDValue Sh(nullptr,0), Y(nullptr,0);
2121 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2122 if (N0.getOpcode() == ISD::SHL &&
2123 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2124 isa<ConstantSDNode>(N0.getOperand(1))) &&
2125 N0.getNode()->hasOneUse()) {
2127 } else if (N1.getOpcode() == ISD::SHL &&
2128 isa<ConstantSDNode>(N1.getOperand(1)) &&
2129 N1.getNode()->hasOneUse()) {
2134 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2135 Sh.getOperand(0), Y);
2136 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2137 Mul, Sh.getOperand(1));
2141 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2142 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2143 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2144 isa<ConstantSDNode>(N0.getOperand(1))))
2145 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2146 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2147 N0.getOperand(0), N1),
2148 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2149 N0.getOperand(1), N1));
2152 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2158 /// Return true if divmod libcall is available.
2159 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2160 const TargetLowering &TLI) {
2162 switch (Node->getSimpleValueType(0).SimpleTy) {
2163 default: return false; // No libcall for vector types.
2164 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2165 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2166 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2167 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2168 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2171 return TLI.getLibcallName(LC) != nullptr;
2174 /// Issue divrem if both quotient and remainder are needed.
2175 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2176 if (Node->use_empty())
2177 return SDValue(); // This is a dead node, leave it alone.
2179 EVT VT = Node->getValueType(0);
2180 if (!TLI.isTypeLegal(VT))
2183 unsigned Opcode = Node->getOpcode();
2184 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2186 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2187 // If DIVREM is going to get expanded into a libcall,
2188 // but there is no libcall available, then don't combine.
2189 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2190 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2193 // If div is legal, it's better to do the normal expansion
2194 unsigned OtherOpcode = 0;
2195 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2196 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2197 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2200 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2201 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2205 SDValue Op0 = Node->getOperand(0);
2206 SDValue Op1 = Node->getOperand(1);
2208 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2209 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2211 if (User == Node || User->use_empty())
2213 // Convert the other matching node(s), too;
2214 // otherwise, the DIVREM may get target-legalized into something
2215 // target-specific that we won't be able to recognize.
2216 unsigned UserOpc = User->getOpcode();
2217 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2218 User->getOperand(0) == Op0 &&
2219 User->getOperand(1) == Op1) {
2221 if (UserOpc == OtherOpcode) {
2222 SDVTList VTs = DAG.getVTList(VT, VT);
2223 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2224 } else if (UserOpc == DivRemOpc) {
2225 combined = SDValue(User, 0);
2227 assert(UserOpc == Opcode);
2231 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2232 CombineTo(User, combined);
2233 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2234 CombineTo(User, combined.getValue(1));
2240 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2241 SDValue N0 = N->getOperand(0);
2242 SDValue N1 = N->getOperand(1);
2243 EVT VT = N->getValueType(0);
2247 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2252 // fold (sdiv c1, c2) -> c1/c2
2253 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2254 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2255 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2256 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2257 // fold (sdiv X, 1) -> X
2258 if (N1C && N1C->isOne())
2260 // fold (sdiv X, -1) -> 0-X
2261 if (N1C && N1C->isAllOnesValue())
2262 return DAG.getNode(ISD::SUB, DL, VT,
2263 DAG.getConstant(0, DL, VT), N0);
2265 // If we know the sign bits of both operands are zero, strength reduce to a
2266 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2267 if (!VT.isVector()) {
2268 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2269 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2272 // fold (sdiv X, pow2) -> simple ops after legalize
2273 // FIXME: We check for the exact bit here because the generic lowering gives
2274 // better results in that case. The target-specific lowering should learn how
2275 // to handle exact sdivs efficiently.
2276 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2277 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2278 (N1C->getAPIntValue().isPowerOf2() ||
2279 (-N1C->getAPIntValue()).isPowerOf2())) {
2280 // Target-specific implementation of sdiv x, pow2.
2281 if (SDValue Res = BuildSDIVPow2(N))
2284 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2286 // Splat the sign bit into the register
2288 DAG.getNode(ISD::SRA, DL, VT, N0,
2289 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2290 getShiftAmountTy(N0.getValueType())));
2291 AddToWorklist(SGN.getNode());
2293 // Add (N0 < 0) ? abs2 - 1 : 0;
2295 DAG.getNode(ISD::SRL, DL, VT, SGN,
2296 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2297 getShiftAmountTy(SGN.getValueType())));
2298 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2299 AddToWorklist(SRL.getNode());
2300 AddToWorklist(ADD.getNode()); // Divide by pow2
2301 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2302 DAG.getConstant(lg2, DL,
2303 getShiftAmountTy(ADD.getValueType())));
2305 // If we're dividing by a positive value, we're done. Otherwise, we must
2306 // negate the result.
2307 if (N1C->getAPIntValue().isNonNegative())
2310 AddToWorklist(SRA.getNode());
2311 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2314 // If integer divide is expensive and we satisfy the requirements, emit an
2315 // alternate sequence. Targets may check function attributes for size/speed
2317 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2318 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2319 if (SDValue Op = BuildSDIV(N))
2322 // sdiv, srem -> sdivrem
2323 if (SDValue DivRem = useDivRem(N))
2327 if (N0.getOpcode() == ISD::UNDEF)
2328 return DAG.getConstant(0, DL, VT);
2329 // X / undef -> undef
2330 if (N1.getOpcode() == ISD::UNDEF)
2336 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2337 SDValue N0 = N->getOperand(0);
2338 SDValue N1 = N->getOperand(1);
2339 EVT VT = N->getValueType(0);
2343 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2348 // fold (udiv c1, c2) -> c1/c2
2349 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2350 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2352 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2355 // fold (udiv x, (1 << c)) -> x >>u c
2356 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2357 return DAG.getNode(ISD::SRL, DL, VT, N0,
2358 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2359 getShiftAmountTy(N0.getValueType())));
2361 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2362 if (N1.getOpcode() == ISD::SHL) {
2363 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2364 if (SHC->getAPIntValue().isPowerOf2()) {
2365 EVT ADDVT = N1.getOperand(1).getValueType();
2366 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2368 DAG.getConstant(SHC->getAPIntValue()
2371 AddToWorklist(Add.getNode());
2372 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2377 // fold (udiv x, c) -> alternate
2378 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2379 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2380 if (SDValue Op = BuildUDIV(N))
2383 // sdiv, srem -> sdivrem
2384 if (SDValue DivRem = useDivRem(N))
2388 if (N0.getOpcode() == ISD::UNDEF)
2389 return DAG.getConstant(0, DL, VT);
2390 // X / undef -> undef
2391 if (N1.getOpcode() == ISD::UNDEF)
2397 // handles ISD::SREM and ISD::UREM
2398 SDValue DAGCombiner::visitREM(SDNode *N) {
2399 unsigned Opcode = N->getOpcode();
2400 SDValue N0 = N->getOperand(0);
2401 SDValue N1 = N->getOperand(1);
2402 EVT VT = N->getValueType(0);
2403 bool isSigned = (Opcode == ISD::SREM);
2406 // fold (rem c1, c2) -> c1%c2
2407 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2408 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2410 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2414 // If we know the sign bits of both operands are zero, strength reduce to a
2415 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2416 if (!VT.isVector()) {
2417 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2418 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2421 // fold (urem x, pow2) -> (and x, pow2-1)
2422 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2423 N1C->getAPIntValue().isPowerOf2()) {
2424 return DAG.getNode(ISD::AND, DL, VT, N0,
2425 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2427 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2428 if (N1.getOpcode() == ISD::SHL) {
2429 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2430 if (SHC->getAPIntValue().isPowerOf2()) {
2432 DAG.getNode(ISD::ADD, DL, VT, N1,
2433 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2435 AddToWorklist(Add.getNode());
2436 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2442 // If X/C can be simplified by the division-by-constant logic, lower
2443 // X%C to the equivalent of X-X/C*C.
2444 if (N1C && !N1C->isNullValue()) {
2445 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2446 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2447 AddToWorklist(Div.getNode());
2448 SDValue OptimizedDiv = combine(Div.getNode());
2449 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2450 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2451 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2452 AddToWorklist(Mul.getNode());
2457 // sdiv, srem -> sdivrem
2458 if (SDValue DivRem = useDivRem(N))
2459 return DivRem.getValue(1);
2462 if (N0.getOpcode() == ISD::UNDEF)
2463 return DAG.getConstant(0, DL, VT);
2464 // X % undef -> undef
2465 if (N1.getOpcode() == ISD::UNDEF)
2471 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2472 SDValue N0 = N->getOperand(0);
2473 SDValue N1 = N->getOperand(1);
2474 EVT VT = N->getValueType(0);
2477 // fold (mulhs x, 0) -> 0
2478 if (isNullConstant(N1))
2480 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2481 if (isOneConstant(N1)) {
2483 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2484 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2486 getShiftAmountTy(N0.getValueType())));
2488 // fold (mulhs x, undef) -> 0
2489 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2490 return DAG.getConstant(0, SDLoc(N), VT);
2492 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2494 if (VT.isSimple() && !VT.isVector()) {
2495 MVT Simple = VT.getSimpleVT();
2496 unsigned SimpleSize = Simple.getSizeInBits();
2497 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2498 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2499 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2500 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2501 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2502 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2503 DAG.getConstant(SimpleSize, DL,
2504 getShiftAmountTy(N1.getValueType())));
2505 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2512 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2513 SDValue N0 = N->getOperand(0);
2514 SDValue N1 = N->getOperand(1);
2515 EVT VT = N->getValueType(0);
2518 // fold (mulhu x, 0) -> 0
2519 if (isNullConstant(N1))
2521 // fold (mulhu x, 1) -> 0
2522 if (isOneConstant(N1))
2523 return DAG.getConstant(0, DL, N0.getValueType());
2524 // fold (mulhu x, undef) -> 0
2525 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2526 return DAG.getConstant(0, DL, VT);
2528 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2530 if (VT.isSimple() && !VT.isVector()) {
2531 MVT Simple = VT.getSimpleVT();
2532 unsigned SimpleSize = Simple.getSizeInBits();
2533 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2534 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2535 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2536 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2537 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2538 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2539 DAG.getConstant(SimpleSize, DL,
2540 getShiftAmountTy(N1.getValueType())));
2541 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2548 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2549 /// give the opcodes for the two computations that are being performed. Return
2550 /// true if a simplification was made.
2551 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2553 // If the high half is not needed, just compute the low half.
2554 bool HiExists = N->hasAnyUseOfValue(1);
2556 (!LegalOperations ||
2557 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2558 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2559 return CombineTo(N, Res, Res);
2562 // If the low half is not needed, just compute the high half.
2563 bool LoExists = N->hasAnyUseOfValue(0);
2565 (!LegalOperations ||
2566 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2567 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2568 return CombineTo(N, Res, Res);
2571 // If both halves are used, return as it is.
2572 if (LoExists && HiExists)
2575 // If the two computed results can be simplified separately, separate them.
2577 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2578 AddToWorklist(Lo.getNode());
2579 SDValue LoOpt = combine(Lo.getNode());
2580 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2581 (!LegalOperations ||
2582 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2583 return CombineTo(N, LoOpt, LoOpt);
2587 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2588 AddToWorklist(Hi.getNode());
2589 SDValue HiOpt = combine(Hi.getNode());
2590 if (HiOpt.getNode() && HiOpt != Hi &&
2591 (!LegalOperations ||
2592 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2593 return CombineTo(N, HiOpt, HiOpt);
2599 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2600 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2603 EVT VT = N->getValueType(0);
2606 // If the type is twice as wide is legal, transform the mulhu to a wider
2607 // multiply plus a shift.
2608 if (VT.isSimple() && !VT.isVector()) {
2609 MVT Simple = VT.getSimpleVT();
2610 unsigned SimpleSize = Simple.getSizeInBits();
2611 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2612 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2613 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2614 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2615 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2616 // Compute the high part as N1.
2617 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2618 DAG.getConstant(SimpleSize, DL,
2619 getShiftAmountTy(Lo.getValueType())));
2620 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2621 // Compute the low part as N0.
2622 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2623 return CombineTo(N, Lo, Hi);
2630 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2631 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2634 EVT VT = N->getValueType(0);
2637 // If the type is twice as wide is legal, transform the mulhu to a wider
2638 // multiply plus a shift.
2639 if (VT.isSimple() && !VT.isVector()) {
2640 MVT Simple = VT.getSimpleVT();
2641 unsigned SimpleSize = Simple.getSizeInBits();
2642 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2643 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2644 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2645 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2646 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2647 // Compute the high part as N1.
2648 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2649 DAG.getConstant(SimpleSize, DL,
2650 getShiftAmountTy(Lo.getValueType())));
2651 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2652 // Compute the low part as N0.
2653 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2654 return CombineTo(N, Lo, Hi);
2661 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2662 // (smulo x, 2) -> (saddo x, x)
2663 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2664 if (C2->getAPIntValue() == 2)
2665 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2666 N->getOperand(0), N->getOperand(0));
2671 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2672 // (umulo x, 2) -> (uaddo x, x)
2673 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2674 if (C2->getAPIntValue() == 2)
2675 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2676 N->getOperand(0), N->getOperand(0));
2681 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2682 SDValue N0 = N->getOperand(0);
2683 SDValue N1 = N->getOperand(1);
2684 EVT VT = N0.getValueType();
2688 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2691 // fold (add c1, c2) -> c1+c2
2692 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2693 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2695 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2697 // canonicalize constant to RHS
2698 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2699 !isConstantIntBuildVectorOrConstantInt(N1))
2700 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2705 /// If this is a binary operator with two operands of the same opcode, try to
2707 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2708 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2709 EVT VT = N0.getValueType();
2710 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2712 // Bail early if none of these transforms apply.
2713 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2715 // For each of OP in AND/OR/XOR:
2716 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2717 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2718 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2719 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2720 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2722 // do not sink logical op inside of a vector extend, since it may combine
2724 EVT Op0VT = N0.getOperand(0).getValueType();
2725 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2726 N0.getOpcode() == ISD::SIGN_EXTEND ||
2727 N0.getOpcode() == ISD::BSWAP ||
2728 // Avoid infinite looping with PromoteIntBinOp.
2729 (N0.getOpcode() == ISD::ANY_EXTEND &&
2730 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2731 (N0.getOpcode() == ISD::TRUNCATE &&
2732 (!TLI.isZExtFree(VT, Op0VT) ||
2733 !TLI.isTruncateFree(Op0VT, VT)) &&
2734 TLI.isTypeLegal(Op0VT))) &&
2736 Op0VT == N1.getOperand(0).getValueType() &&
2737 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2738 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2739 N0.getOperand(0).getValueType(),
2740 N0.getOperand(0), N1.getOperand(0));
2741 AddToWorklist(ORNode.getNode());
2742 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2745 // For each of OP in SHL/SRL/SRA/AND...
2746 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2747 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2748 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2749 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2750 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2751 N0.getOperand(1) == N1.getOperand(1)) {
2752 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2753 N0.getOperand(0).getValueType(),
2754 N0.getOperand(0), N1.getOperand(0));
2755 AddToWorklist(ORNode.getNode());
2756 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2757 ORNode, N0.getOperand(1));
2760 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2761 // Only perform this optimization after type legalization and before
2762 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2763 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2764 // we don't want to undo this promotion.
2765 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2767 if ((N0.getOpcode() == ISD::BITCAST ||
2768 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2769 Level == AfterLegalizeTypes) {
2770 SDValue In0 = N0.getOperand(0);
2771 SDValue In1 = N1.getOperand(0);
2772 EVT In0Ty = In0.getValueType();
2773 EVT In1Ty = In1.getValueType();
2775 // If both incoming values are integers, and the original types are the
2777 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2778 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2779 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2780 AddToWorklist(Op.getNode());
2785 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2786 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2787 // If both shuffles use the same mask, and both shuffle within a single
2788 // vector, then it is worthwhile to move the swizzle after the operation.
2789 // The type-legalizer generates this pattern when loading illegal
2790 // vector types from memory. In many cases this allows additional shuffle
2792 // There are other cases where moving the shuffle after the xor/and/or
2793 // is profitable even if shuffles don't perform a swizzle.
2794 // If both shuffles use the same mask, and both shuffles have the same first
2795 // or second operand, then it might still be profitable to move the shuffle
2796 // after the xor/and/or operation.
2797 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2798 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2799 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2801 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2802 "Inputs to shuffles are not the same type");
2804 // Check that both shuffles use the same mask. The masks are known to be of
2805 // the same length because the result vector type is the same.
2806 // Check also that shuffles have only one use to avoid introducing extra
2808 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2809 SVN0->getMask().equals(SVN1->getMask())) {
2810 SDValue ShOp = N0->getOperand(1);
2812 // Don't try to fold this node if it requires introducing a
2813 // build vector of all zeros that might be illegal at this stage.
2814 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2816 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2821 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2822 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2823 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2824 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2825 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2826 N0->getOperand(0), N1->getOperand(0));
2827 AddToWorklist(NewNode.getNode());
2828 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2829 &SVN0->getMask()[0]);
2832 // Don't try to fold this node if it requires introducing a
2833 // build vector of all zeros that might be illegal at this stage.
2834 ShOp = N0->getOperand(0);
2835 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2837 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2842 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2843 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2844 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2845 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2846 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2847 N0->getOperand(1), N1->getOperand(1));
2848 AddToWorklist(NewNode.getNode());
2849 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2850 &SVN0->getMask()[0]);
2858 /// This contains all DAGCombine rules which reduce two values combined by
2859 /// an And operation to a single value. This makes them reusable in the context
2860 /// of visitSELECT(). Rules involving constants are not included as
2861 /// visitSELECT() already handles those cases.
2862 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2863 SDNode *LocReference) {
2864 EVT VT = N1.getValueType();
2866 // fold (and x, undef) -> 0
2867 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2868 return DAG.getConstant(0, SDLoc(LocReference), VT);
2869 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2870 SDValue LL, LR, RL, RR, CC0, CC1;
2871 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2872 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2873 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2875 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2876 LL.getValueType().isInteger()) {
2877 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2878 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2879 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2880 LR.getValueType(), LL, RL);
2881 AddToWorklist(ORNode.getNode());
2882 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2884 if (isAllOnesConstant(LR)) {
2885 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2886 if (Op1 == ISD::SETEQ) {
2887 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2888 LR.getValueType(), LL, RL);
2889 AddToWorklist(ANDNode.getNode());
2890 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2892 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2893 if (Op1 == ISD::SETGT) {
2894 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2895 LR.getValueType(), LL, RL);
2896 AddToWorklist(ORNode.getNode());
2897 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2901 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2902 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2903 Op0 == Op1 && LL.getValueType().isInteger() &&
2904 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2905 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2907 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2908 LL, DAG.getConstant(1, DL,
2909 LL.getValueType()));
2910 AddToWorklist(ADDNode.getNode());
2911 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2912 DAG.getConstant(2, DL, LL.getValueType()),
2915 // canonicalize equivalent to ll == rl
2916 if (LL == RR && LR == RL) {
2917 Op1 = ISD::getSetCCSwappedOperands(Op1);
2920 if (LL == RL && LR == RR) {
2921 bool isInteger = LL.getValueType().isInteger();
2922 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2923 if (Result != ISD::SETCC_INVALID &&
2924 (!LegalOperations ||
2925 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2926 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2927 EVT CCVT = getSetCCResultType(LL.getValueType());
2928 if (N0.getValueType() == CCVT ||
2929 (!LegalOperations && N0.getValueType() == MVT::i1))
2930 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2936 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2937 VT.getSizeInBits() <= 64) {
2938 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2939 APInt ADDC = ADDI->getAPIntValue();
2940 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2941 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2942 // immediate for an add, but it is legal if its top c2 bits are set,
2943 // transform the ADD so the immediate doesn't need to be materialized
2945 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2946 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2947 SRLI->getZExtValue());
2948 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2950 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2953 DAG.getNode(ISD::ADD, DL, VT,
2954 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2955 CombineTo(N0.getNode(), NewAdd);
2956 // Return N so it doesn't get rechecked!
2957 return SDValue(LocReference, 0);
2968 SDValue DAGCombiner::visitAND(SDNode *N) {
2969 SDValue N0 = N->getOperand(0);
2970 SDValue N1 = N->getOperand(1);
2971 EVT VT = N1.getValueType();
2974 if (VT.isVector()) {
2975 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2978 // fold (and x, 0) -> 0, vector edition
2979 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2980 // do not return N0, because undef node may exist in N0
2981 return DAG.getConstant(
2982 APInt::getNullValue(
2983 N0.getValueType().getScalarType().getSizeInBits()),
2984 SDLoc(N), N0.getValueType());
2985 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2986 // do not return N1, because undef node may exist in N1
2987 return DAG.getConstant(
2988 APInt::getNullValue(
2989 N1.getValueType().getScalarType().getSizeInBits()),
2990 SDLoc(N), N1.getValueType());
2992 // fold (and x, -1) -> x, vector edition
2993 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2995 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2999 // fold (and c1, c2) -> c1&c2
3000 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3001 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3002 if (N0C && N1C && !N1C->isOpaque())
3003 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3004 // canonicalize constant to RHS
3005 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3006 !isConstantIntBuildVectorOrConstantInt(N1))
3007 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3008 // fold (and x, -1) -> x
3009 if (isAllOnesConstant(N1))
3011 // if (and x, c) is known to be zero, return 0
3012 unsigned BitWidth = VT.getScalarType().getSizeInBits();
3013 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3014 APInt::getAllOnesValue(BitWidth)))
3015 return DAG.getConstant(0, SDLoc(N), VT);
3017 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3019 // fold (and (or x, C), D) -> D if (C & D) == D
3020 if (N1C && N0.getOpcode() == ISD::OR)
3021 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3022 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3024 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3025 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3026 SDValue N0Op0 = N0.getOperand(0);
3027 APInt Mask = ~N1C->getAPIntValue();
3028 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3029 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3030 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3031 N0.getValueType(), N0Op0);
3033 // Replace uses of the AND with uses of the Zero extend node.
3036 // We actually want to replace all uses of the any_extend with the
3037 // zero_extend, to avoid duplicating things. This will later cause this
3038 // AND to be folded.
3039 CombineTo(N0.getNode(), Zext);
3040 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3043 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3044 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3045 // already be zero by virtue of the width of the base type of the load.
3047 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3049 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3050 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3051 N0.getOpcode() == ISD::LOAD) {
3052 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3053 N0 : N0.getOperand(0) );
3055 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3056 // This can be a pure constant or a vector splat, in which case we treat the
3057 // vector as a scalar and use the splat value.
3058 APInt Constant = APInt::getNullValue(1);
3059 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3060 Constant = C->getAPIntValue();
3061 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3062 APInt SplatValue, SplatUndef;
3063 unsigned SplatBitSize;
3065 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3066 SplatBitSize, HasAnyUndefs);
3068 // Undef bits can contribute to a possible optimisation if set, so
3070 SplatValue |= SplatUndef;
3072 // The splat value may be something like "0x00FFFFFF", which means 0 for
3073 // the first vector value and FF for the rest, repeating. We need a mask
3074 // that will apply equally to all members of the vector, so AND all the
3075 // lanes of the constant together.
3076 EVT VT = Vector->getValueType(0);
3077 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3079 // If the splat value has been compressed to a bitlength lower
3080 // than the size of the vector lane, we need to re-expand it to
3082 if (BitWidth > SplatBitSize)
3083 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3084 SplatBitSize < BitWidth;
3085 SplatBitSize = SplatBitSize * 2)
3086 SplatValue |= SplatValue.shl(SplatBitSize);
3088 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3089 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3090 if (SplatBitSize % BitWidth == 0) {
3091 Constant = APInt::getAllOnesValue(BitWidth);
3092 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3093 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3098 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3099 // actually legal and isn't going to get expanded, else this is a false
3101 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3102 Load->getValueType(0),
3103 Load->getMemoryVT());
3105 // Resize the constant to the same size as the original memory access before
3106 // extension. If it is still the AllOnesValue then this AND is completely
3109 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3112 switch (Load->getExtensionType()) {
3113 default: B = false; break;
3114 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3116 case ISD::NON_EXTLOAD: B = true; break;
3119 if (B && Constant.isAllOnesValue()) {
3120 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3121 // preserve semantics once we get rid of the AND.
3122 SDValue NewLoad(Load, 0);
3123 if (Load->getExtensionType() == ISD::EXTLOAD) {
3124 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3125 Load->getValueType(0), SDLoc(Load),
3126 Load->getChain(), Load->getBasePtr(),
3127 Load->getOffset(), Load->getMemoryVT(),
3128 Load->getMemOperand());
3129 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3130 if (Load->getNumValues() == 3) {
3131 // PRE/POST_INC loads have 3 values.
3132 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3133 NewLoad.getValue(2) };
3134 CombineTo(Load, To, 3, true);
3136 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3140 // Fold the AND away, taking care not to fold to the old load node if we
3142 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3148 // fold (and (load x), 255) -> (zextload x, i8)
3149 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3150 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3151 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3152 (N0.getOpcode() == ISD::ANY_EXTEND &&
3153 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3154 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3155 LoadSDNode *LN0 = HasAnyExt
3156 ? cast<LoadSDNode>(N0.getOperand(0))
3157 : cast<LoadSDNode>(N0);
3158 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3159 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3160 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3161 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3162 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3163 EVT LoadedVT = LN0->getMemoryVT();
3164 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3166 if (ExtVT == LoadedVT &&
3167 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3171 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3172 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3173 LN0->getMemOperand());
3175 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3176 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3179 // Do not change the width of a volatile load.
3180 // Do not generate loads of non-round integer types since these can
3181 // be expensive (and would be wrong if the type is not byte sized).
3182 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3183 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3185 EVT PtrType = LN0->getOperand(1).getValueType();
3187 unsigned Alignment = LN0->getAlignment();
3188 SDValue NewPtr = LN0->getBasePtr();
3190 // For big endian targets, we need to add an offset to the pointer
3191 // to load the correct bytes. For little endian systems, we merely
3192 // need to read fewer bytes from the same pointer.
3193 if (DAG.getDataLayout().isBigEndian()) {
3194 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3195 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3196 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3198 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3199 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3200 Alignment = MinAlign(Alignment, PtrOff);
3203 AddToWorklist(NewPtr.getNode());
3206 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3207 LN0->getChain(), NewPtr,
3208 LN0->getPointerInfo(),
3209 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3210 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3212 CombineTo(LN0, Load, Load.getValue(1));
3213 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3219 if (SDValue Combined = visitANDLike(N0, N1, N))
3222 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3223 if (N0.getOpcode() == N1.getOpcode())
3224 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3227 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3228 // fold (and (sra)) -> (and (srl)) when possible.
3229 if (!VT.isVector() &&
3230 SimplifyDemandedBits(SDValue(N, 0)))
3231 return SDValue(N, 0);
3233 // fold (zext_inreg (extload x)) -> (zextload x)
3234 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3235 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3236 EVT MemVT = LN0->getMemoryVT();
3237 // If we zero all the possible extended bits, then we can turn this into
3238 // a zextload if we are running before legalize or the operation is legal.
3239 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3240 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3241 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3242 ((!LegalOperations && !LN0->isVolatile()) ||
3243 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3244 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3245 LN0->getChain(), LN0->getBasePtr(),
3246 MemVT, LN0->getMemOperand());
3248 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3249 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3252 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3253 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3255 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3256 EVT MemVT = LN0->getMemoryVT();
3257 // If we zero all the possible extended bits, then we can turn this into
3258 // a zextload if we are running before legalize or the operation is legal.
3259 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3260 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3261 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3262 ((!LegalOperations && !LN0->isVolatile()) ||
3263 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3264 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3265 LN0->getChain(), LN0->getBasePtr(),
3266 MemVT, LN0->getMemOperand());
3268 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3269 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3272 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3273 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3274 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3275 N0.getOperand(1), false);
3276 if (BSwap.getNode())
3283 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3284 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3285 bool DemandHighBits) {
3286 if (!LegalOperations)
3289 EVT VT = N->getValueType(0);
3290 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3292 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3295 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3296 bool LookPassAnd0 = false;
3297 bool LookPassAnd1 = false;
3298 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3300 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3302 if (N0.getOpcode() == ISD::AND) {
3303 if (!N0.getNode()->hasOneUse())
3305 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3306 if (!N01C || N01C->getZExtValue() != 0xFF00)
3308 N0 = N0.getOperand(0);
3309 LookPassAnd0 = true;
3312 if (N1.getOpcode() == ISD::AND) {
3313 if (!N1.getNode()->hasOneUse())
3315 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3316 if (!N11C || N11C->getZExtValue() != 0xFF)
3318 N1 = N1.getOperand(0);
3319 LookPassAnd1 = true;
3322 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3324 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3326 if (!N0.getNode()->hasOneUse() ||
3327 !N1.getNode()->hasOneUse())
3330 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3331 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3334 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3337 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3338 SDValue N00 = N0->getOperand(0);
3339 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3340 if (!N00.getNode()->hasOneUse())
3342 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3343 if (!N001C || N001C->getZExtValue() != 0xFF)
3345 N00 = N00.getOperand(0);
3346 LookPassAnd0 = true;
3349 SDValue N10 = N1->getOperand(0);
3350 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3351 if (!N10.getNode()->hasOneUse())
3353 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3354 if (!N101C || N101C->getZExtValue() != 0xFF00)
3356 N10 = N10.getOperand(0);
3357 LookPassAnd1 = true;
3363 // Make sure everything beyond the low halfword gets set to zero since the SRL
3364 // 16 will clear the top bits.
3365 unsigned OpSizeInBits = VT.getSizeInBits();
3366 if (DemandHighBits && OpSizeInBits > 16) {
3367 // If the left-shift isn't masked out then the only way this is a bswap is
3368 // if all bits beyond the low 8 are 0. In that case the entire pattern
3369 // reduces to a left shift anyway: leave it for other parts of the combiner.
3373 // However, if the right shift isn't masked out then it might be because
3374 // it's not needed. See if we can spot that too.
3375 if (!LookPassAnd1 &&
3376 !DAG.MaskedValueIsZero(
3377 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3381 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3382 if (OpSizeInBits > 16) {
3384 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3385 DAG.getConstant(OpSizeInBits - 16, DL,
3386 getShiftAmountTy(VT)));
3391 /// Return true if the specified node is an element that makes up a 32-bit
3392 /// packed halfword byteswap.
3393 /// ((x & 0x000000ff) << 8) |
3394 /// ((x & 0x0000ff00) >> 8) |
3395 /// ((x & 0x00ff0000) << 8) |
3396 /// ((x & 0xff000000) >> 8)
3397 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3398 if (!N.getNode()->hasOneUse())
3401 unsigned Opc = N.getOpcode();
3402 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3405 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3410 switch (N1C->getZExtValue()) {
3413 case 0xFF: Num = 0; break;
3414 case 0xFF00: Num = 1; break;
3415 case 0xFF0000: Num = 2; break;
3416 case 0xFF000000: Num = 3; break;
3419 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3420 SDValue N0 = N.getOperand(0);
3421 if (Opc == ISD::AND) {
3422 if (Num == 0 || Num == 2) {
3424 // (x >> 8) & 0xff0000
3425 if (N0.getOpcode() != ISD::SRL)
3427 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3428 if (!C || C->getZExtValue() != 8)
3431 // (x << 8) & 0xff00
3432 // (x << 8) & 0xff000000
3433 if (N0.getOpcode() != ISD::SHL)
3435 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3436 if (!C || C->getZExtValue() != 8)
3439 } else if (Opc == ISD::SHL) {
3441 // (x & 0xff0000) << 8
3442 if (Num != 0 && Num != 2)
3444 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3445 if (!C || C->getZExtValue() != 8)
3447 } else { // Opc == ISD::SRL
3448 // (x & 0xff00) >> 8
3449 // (x & 0xff000000) >> 8
3450 if (Num != 1 && Num != 3)
3452 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3453 if (!C || C->getZExtValue() != 8)
3460 Parts[Num] = N0.getOperand(0).getNode();
3464 /// Match a 32-bit packed halfword bswap. That is
3465 /// ((x & 0x000000ff) << 8) |
3466 /// ((x & 0x0000ff00) >> 8) |
3467 /// ((x & 0x00ff0000) << 8) |
3468 /// ((x & 0xff000000) >> 8)
3469 /// => (rotl (bswap x), 16)
3470 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3471 if (!LegalOperations)
3474 EVT VT = N->getValueType(0);
3477 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3481 // (or (or (and), (and)), (or (and), (and)))
3482 // (or (or (or (and), (and)), (and)), (and))
3483 if (N0.getOpcode() != ISD::OR)
3485 SDValue N00 = N0.getOperand(0);
3486 SDValue N01 = N0.getOperand(1);
3487 SDNode *Parts[4] = {};
3489 if (N1.getOpcode() == ISD::OR &&
3490 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3491 // (or (or (and), (and)), (or (and), (and)))
3492 SDValue N000 = N00.getOperand(0);
3493 if (!isBSwapHWordElement(N000, Parts))
3496 SDValue N001 = N00.getOperand(1);
3497 if (!isBSwapHWordElement(N001, Parts))
3499 SDValue N010 = N01.getOperand(0);
3500 if (!isBSwapHWordElement(N010, Parts))
3502 SDValue N011 = N01.getOperand(1);
3503 if (!isBSwapHWordElement(N011, Parts))
3506 // (or (or (or (and), (and)), (and)), (and))
3507 if (!isBSwapHWordElement(N1, Parts))
3509 if (!isBSwapHWordElement(N01, Parts))
3511 if (N00.getOpcode() != ISD::OR)
3513 SDValue N000 = N00.getOperand(0);
3514 if (!isBSwapHWordElement(N000, Parts))
3516 SDValue N001 = N00.getOperand(1);
3517 if (!isBSwapHWordElement(N001, Parts))
3521 // Make sure the parts are all coming from the same node.
3522 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3526 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3527 SDValue(Parts[0], 0));
3529 // Result of the bswap should be rotated by 16. If it's not legal, then
3530 // do (x << 16) | (x >> 16).
3531 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3532 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3533 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3534 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3535 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3536 return DAG.getNode(ISD::OR, DL, VT,
3537 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3538 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3541 /// This contains all DAGCombine rules which reduce two values combined by
3542 /// an Or operation to a single value \see visitANDLike().
3543 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3544 EVT VT = N1.getValueType();
3545 // fold (or x, undef) -> -1
3546 if (!LegalOperations &&
3547 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3548 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3549 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3550 SDLoc(LocReference), VT);
3552 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3553 SDValue LL, LR, RL, RR, CC0, CC1;
3554 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3555 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3556 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3558 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3559 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3560 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3561 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3562 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3563 LR.getValueType(), LL, RL);
3564 AddToWorklist(ORNode.getNode());
3565 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3567 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3568 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3569 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3570 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3571 LR.getValueType(), LL, RL);
3572 AddToWorklist(ANDNode.getNode());
3573 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3576 // canonicalize equivalent to ll == rl
3577 if (LL == RR && LR == RL) {
3578 Op1 = ISD::getSetCCSwappedOperands(Op1);
3581 if (LL == RL && LR == RR) {
3582 bool isInteger = LL.getValueType().isInteger();
3583 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3584 if (Result != ISD::SETCC_INVALID &&
3585 (!LegalOperations ||
3586 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3587 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3588 EVT CCVT = getSetCCResultType(LL.getValueType());
3589 if (N0.getValueType() == CCVT ||
3590 (!LegalOperations && N0.getValueType() == MVT::i1))
3591 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3597 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3598 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3599 // Don't increase # computations.
3600 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3601 // We can only do this xform if we know that bits from X that are set in C2
3602 // but not in C1 are already zero. Likewise for Y.
3603 if (const ConstantSDNode *N0O1C =
3604 getAsNonOpaqueConstant(N0.getOperand(1))) {
3605 if (const ConstantSDNode *N1O1C =
3606 getAsNonOpaqueConstant(N1.getOperand(1))) {
3607 // We can only do this xform if we know that bits from X that are set in
3608 // C2 but not in C1 are already zero. Likewise for Y.
3609 const APInt &LHSMask = N0O1C->getAPIntValue();
3610 const APInt &RHSMask = N1O1C->getAPIntValue();
3612 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3613 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3614 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3615 N0.getOperand(0), N1.getOperand(0));
3616 SDLoc DL(LocReference);
3617 return DAG.getNode(ISD::AND, DL, VT, X,
3618 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3624 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3625 if (N0.getOpcode() == ISD::AND &&
3626 N1.getOpcode() == ISD::AND &&
3627 N0.getOperand(0) == N1.getOperand(0) &&
3628 // Don't increase # computations.
3629 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3630 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3631 N0.getOperand(1), N1.getOperand(1));
3632 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3638 SDValue DAGCombiner::visitOR(SDNode *N) {
3639 SDValue N0 = N->getOperand(0);
3640 SDValue N1 = N->getOperand(1);
3641 EVT VT = N1.getValueType();
3644 if (VT.isVector()) {
3645 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3648 // fold (or x, 0) -> x, vector edition
3649 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3651 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3654 // fold (or x, -1) -> -1, vector edition
3655 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3656 // do not return N0, because undef node may exist in N0
3657 return DAG.getConstant(
3658 APInt::getAllOnesValue(
3659 N0.getValueType().getScalarType().getSizeInBits()),
3660 SDLoc(N), N0.getValueType());
3661 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3662 // do not return N1, because undef node may exist in N1
3663 return DAG.getConstant(
3664 APInt::getAllOnesValue(
3665 N1.getValueType().getScalarType().getSizeInBits()),
3666 SDLoc(N), N1.getValueType());
3668 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3669 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3670 // Do this only if the resulting shuffle is legal.
3671 if (isa<ShuffleVectorSDNode>(N0) &&
3672 isa<ShuffleVectorSDNode>(N1) &&
3673 // Avoid folding a node with illegal type.
3674 TLI.isTypeLegal(VT) &&
3675 N0->getOperand(1) == N1->getOperand(1) &&
3676 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3677 bool CanFold = true;
3678 unsigned NumElts = VT.getVectorNumElements();
3679 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3680 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3681 // We construct two shuffle masks:
3682 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3683 // and N1 as the second operand.
3684 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3685 // and N0 as the second operand.
3686 // We do this because OR is commutable and therefore there might be
3687 // two ways to fold this node into a shuffle.
3688 SmallVector<int,4> Mask1;
3689 SmallVector<int,4> Mask2;
3691 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3692 int M0 = SV0->getMaskElt(i);
3693 int M1 = SV1->getMaskElt(i);
3695 // Both shuffle indexes are undef. Propagate Undef.
3696 if (M0 < 0 && M1 < 0) {
3697 Mask1.push_back(M0);
3698 Mask2.push_back(M0);
3702 if (M0 < 0 || M1 < 0 ||
3703 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3704 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3709 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3710 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3714 // Fold this sequence only if the resulting shuffle is 'legal'.
3715 if (TLI.isShuffleMaskLegal(Mask1, VT))
3716 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3717 N1->getOperand(0), &Mask1[0]);
3718 if (TLI.isShuffleMaskLegal(Mask2, VT))
3719 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3720 N0->getOperand(0), &Mask2[0]);
3725 // fold (or c1, c2) -> c1|c2
3726 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3727 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3728 if (N0C && N1C && !N1C->isOpaque())
3729 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3730 // canonicalize constant to RHS
3731 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3732 !isConstantIntBuildVectorOrConstantInt(N1))
3733 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3734 // fold (or x, 0) -> x
3735 if (isNullConstant(N1))
3737 // fold (or x, -1) -> -1
3738 if (isAllOnesConstant(N1))
3740 // fold (or x, c) -> c iff (x & ~c) == 0
3741 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3744 if (SDValue Combined = visitORLike(N0, N1, N))
3747 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3748 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3750 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3754 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3756 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3757 // iff (c1 & c2) == 0.
3758 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3759 isa<ConstantSDNode>(N0.getOperand(1))) {
3760 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3761 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3762 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3765 ISD::AND, SDLoc(N), VT,
3766 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3770 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3771 if (N0.getOpcode() == N1.getOpcode())
3772 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3775 // See if this is some rotate idiom.
3776 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3777 return SDValue(Rot, 0);
3779 // Simplify the operands using demanded-bits information.
3780 if (!VT.isVector() &&
3781 SimplifyDemandedBits(SDValue(N, 0)))
3782 return SDValue(N, 0);
3787 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3788 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3789 if (Op.getOpcode() == ISD::AND) {
3790 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3791 Mask = Op.getOperand(1);
3792 Op = Op.getOperand(0);
3798 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3806 // Return true if we can prove that, whenever Neg and Pos are both in the
3807 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3808 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3810 // (or (shift1 X, Neg), (shift2 X, Pos))
3812 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3813 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3814 // to consider shift amounts with defined behavior.
3815 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3816 // If OpSize is a power of 2 then:
3818 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3819 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3821 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3822 // for the stronger condition:
3824 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3826 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3827 // we can just replace Neg with Neg' for the rest of the function.
3829 // In other cases we check for the even stronger condition:
3831 // Neg == OpSize - Pos [B]
3833 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3834 // behavior if Pos == 0 (and consequently Neg == OpSize).
3836 // We could actually use [A] whenever OpSize is a power of 2, but the
3837 // only extra cases that it would match are those uninteresting ones
3838 // where Neg and Pos are never in range at the same time. E.g. for
3839 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3840 // as well as (sub 32, Pos), but:
3842 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3844 // always invokes undefined behavior for 32-bit X.
3846 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3847 unsigned MaskLoBits = 0;
3848 if (Neg.getOpcode() == ISD::AND &&
3849 isPowerOf2_64(OpSize) &&
3850 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3851 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3852 Neg = Neg.getOperand(0);
3853 MaskLoBits = Log2_64(OpSize);
3856 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3857 if (Neg.getOpcode() != ISD::SUB)
3859 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3862 SDValue NegOp1 = Neg.getOperand(1);
3864 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3865 // Pos'. The truncation is redundant for the purpose of the equality.
3867 Pos.getOpcode() == ISD::AND &&
3868 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3869 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3870 Pos = Pos.getOperand(0);
3872 // The condition we need is now:
3874 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3876 // If NegOp1 == Pos then we need:
3878 // OpSize & Mask == NegC & Mask
3880 // (because "x & Mask" is a truncation and distributes through subtraction).
3883 Width = NegC->getAPIntValue();
3884 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3885 // Then the condition we want to prove becomes:
3887 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3889 // which, again because "x & Mask" is a truncation, becomes:
3891 // NegC & Mask == (OpSize - PosC) & Mask
3892 // OpSize & Mask == (NegC + PosC) & Mask
3893 else if (Pos.getOpcode() == ISD::ADD &&
3894 Pos.getOperand(0) == NegOp1 &&
3895 Pos.getOperand(1).getOpcode() == ISD::Constant)
3896 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3897 NegC->getAPIntValue());
3901 // Now we just need to check that OpSize & Mask == Width & Mask.
3903 // Opsize & Mask is 0 since Mask is Opsize - 1.
3904 return Width.getLoBits(MaskLoBits) == 0;
3905 return Width == OpSize;
3908 // A subroutine of MatchRotate used once we have found an OR of two opposite
3909 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3910 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3911 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3912 // Neg with outer conversions stripped away.
3913 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3914 SDValue Neg, SDValue InnerPos,
3915 SDValue InnerNeg, unsigned PosOpcode,
3916 unsigned NegOpcode, SDLoc DL) {
3917 // fold (or (shl x, (*ext y)),
3918 // (srl x, (*ext (sub 32, y)))) ->
3919 // (rotl x, y) or (rotr x, (sub 32, y))
3921 // fold (or (shl x, (*ext (sub 32, y))),
3922 // (srl x, (*ext y))) ->
3923 // (rotr x, y) or (rotl x, (sub 32, y))
3924 EVT VT = Shifted.getValueType();
3925 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3926 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3927 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3928 HasPos ? Pos : Neg).getNode();
3934 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3935 // idioms for rotate, and if the target supports rotation instructions, generate
3937 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3938 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3939 EVT VT = LHS.getValueType();
3940 if (!TLI.isTypeLegal(VT)) return nullptr;
3942 // The target must have at least one rotate flavor.
3943 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3944 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3945 if (!HasROTL && !HasROTR) return nullptr;
3947 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3948 SDValue LHSShift; // The shift.
3949 SDValue LHSMask; // AND value if any.
3950 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3951 return nullptr; // Not part of a rotate.
3953 SDValue RHSShift; // The shift.
3954 SDValue RHSMask; // AND value if any.
3955 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3956 return nullptr; // Not part of a rotate.
3958 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3959 return nullptr; // Not shifting the same value.
3961 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3962 return nullptr; // Shifts must disagree.
3964 // Canonicalize shl to left side in a shl/srl pair.
3965 if (RHSShift.getOpcode() == ISD::SHL) {
3966 std::swap(LHS, RHS);
3967 std::swap(LHSShift, RHSShift);
3968 std::swap(LHSMask , RHSMask );
3971 unsigned OpSizeInBits = VT.getSizeInBits();
3972 SDValue LHSShiftArg = LHSShift.getOperand(0);
3973 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3974 SDValue RHSShiftArg = RHSShift.getOperand(0);
3975 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3977 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3978 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3979 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3980 RHSShiftAmt.getOpcode() == ISD::Constant) {
3981 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3982 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3983 if ((LShVal + RShVal) != OpSizeInBits)
3986 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3987 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3989 // If there is an AND of either shifted operand, apply it to the result.
3990 if (LHSMask.getNode() || RHSMask.getNode()) {
3991 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3993 if (LHSMask.getNode()) {
3994 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3995 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3997 if (RHSMask.getNode()) {
3998 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3999 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
4002 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
4005 return Rot.getNode();
4008 // If there is a mask here, and we have a variable shift, we can't be sure
4009 // that we're masking out the right stuff.
4010 if (LHSMask.getNode() || RHSMask.getNode())
4013 // If the shift amount is sign/zext/any-extended just peel it off.
4014 SDValue LExtOp0 = LHSShiftAmt;
4015 SDValue RExtOp0 = RHSShiftAmt;
4016 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4017 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4018 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4019 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4020 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4021 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4022 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4023 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4024 LExtOp0 = LHSShiftAmt.getOperand(0);
4025 RExtOp0 = RHSShiftAmt.getOperand(0);
4028 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4029 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4033 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4034 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4041 SDValue DAGCombiner::visitXOR(SDNode *N) {
4042 SDValue N0 = N->getOperand(0);
4043 SDValue N1 = N->getOperand(1);
4044 EVT VT = N0.getValueType();
4047 if (VT.isVector()) {
4048 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4051 // fold (xor x, 0) -> x, vector edition
4052 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4054 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4058 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4059 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4060 return DAG.getConstant(0, SDLoc(N), VT);
4061 // fold (xor x, undef) -> undef
4062 if (N0.getOpcode() == ISD::UNDEF)
4064 if (N1.getOpcode() == ISD::UNDEF)
4066 // fold (xor c1, c2) -> c1^c2
4067 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4068 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4070 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4071 // canonicalize constant to RHS
4072 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4073 !isConstantIntBuildVectorOrConstantInt(N1))
4074 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4075 // fold (xor x, 0) -> x
4076 if (isNullConstant(N1))
4079 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4082 // fold !(x cc y) -> (x !cc y)
4083 SDValue LHS, RHS, CC;
4084 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4085 bool isInt = LHS.getValueType().isInteger();
4086 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4089 if (!LegalOperations ||
4090 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4091 switch (N0.getOpcode()) {
4093 llvm_unreachable("Unhandled SetCC Equivalent!");
4095 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4096 case ISD::SELECT_CC:
4097 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4098 N0.getOperand(3), NotCC);
4103 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4104 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4105 N0.getNode()->hasOneUse() &&
4106 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4107 SDValue V = N0.getOperand(0);
4109 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4110 DAG.getConstant(1, DL, V.getValueType()));
4111 AddToWorklist(V.getNode());
4112 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4115 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4116 if (isOneConstant(N1) && VT == MVT::i1 &&
4117 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4118 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4119 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4120 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4121 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4122 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4123 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4124 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4127 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4128 if (isAllOnesConstant(N1) &&
4129 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4130 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4131 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4132 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4133 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4134 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4135 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4136 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4139 // fold (xor (and x, y), y) -> (and (not x), y)
4140 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4141 N0->getOperand(1) == N1) {
4142 SDValue X = N0->getOperand(0);
4143 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4144 AddToWorklist(NotX.getNode());
4145 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4147 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4148 if (N1C && N0.getOpcode() == ISD::XOR) {
4149 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4151 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4152 DAG.getConstant(N1C->getAPIntValue() ^
4153 N00C->getAPIntValue(), DL, VT));
4155 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4157 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4158 DAG.getConstant(N1C->getAPIntValue() ^
4159 N01C->getAPIntValue(), DL, VT));
4162 // fold (xor x, x) -> 0
4164 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4166 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4167 // Here is a concrete example of this equivalence:
4169 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4170 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4174 // i16 ~1 == 0b1111111111111110
4175 // i16 rol(~1, 14) == 0b1011111111111111
4177 // Some additional tips to help conceptualize this transform:
4178 // - Try to see the operation as placing a single zero in a value of all ones.
4179 // - There exists no value for x which would allow the result to contain zero.
4180 // - Values of x larger than the bitwidth are undefined and do not require a
4181 // consistent result.
4182 // - Pushing the zero left requires shifting one bits in from the right.
4183 // A rotate left of ~1 is a nice way of achieving the desired result.
4184 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4185 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4187 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4191 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4192 if (N0.getOpcode() == N1.getOpcode())
4193 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4196 // Simplify the expression using non-local knowledge.
4197 if (!VT.isVector() &&
4198 SimplifyDemandedBits(SDValue(N, 0)))
4199 return SDValue(N, 0);
4204 /// Handle transforms common to the three shifts, when the shift amount is a
4206 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4207 SDNode *LHS = N->getOperand(0).getNode();
4208 if (!LHS->hasOneUse()) return SDValue();
4210 // We want to pull some binops through shifts, so that we have (and (shift))
4211 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4212 // thing happens with address calculations, so it's important to canonicalize
4214 bool HighBitSet = false; // Can we transform this if the high bit is set?
4216 switch (LHS->getOpcode()) {
4217 default: return SDValue();
4220 HighBitSet = false; // We can only transform sra if the high bit is clear.
4223 HighBitSet = true; // We can only transform sra if the high bit is set.
4226 if (N->getOpcode() != ISD::SHL)
4227 return SDValue(); // only shl(add) not sr[al](add).
4228 HighBitSet = false; // We can only transform sra if the high bit is clear.
4232 // We require the RHS of the binop to be a constant and not opaque as well.
4233 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4234 if (!BinOpCst) return SDValue();
4236 // FIXME: disable this unless the input to the binop is a shift by a constant.
4237 // If it is not a shift, it pessimizes some common cases like:
4239 // void foo(int *X, int i) { X[i & 1235] = 1; }
4240 // int bar(int *X, int i) { return X[i & 255]; }
4241 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4242 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4243 BinOpLHSVal->getOpcode() != ISD::SRA &&
4244 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4245 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4248 EVT VT = N->getValueType(0);
4250 // If this is a signed shift right, and the high bit is modified by the
4251 // logical operation, do not perform the transformation. The highBitSet
4252 // boolean indicates the value of the high bit of the constant which would
4253 // cause it to be modified for this operation.
4254 if (N->getOpcode() == ISD::SRA) {
4255 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4256 if (BinOpRHSSignSet != HighBitSet)
4260 if (!TLI.isDesirableToCommuteWithShift(LHS))
4263 // Fold the constants, shifting the binop RHS by the shift amount.
4264 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4266 LHS->getOperand(1), N->getOperand(1));
4267 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4269 // Create the new shift.
4270 SDValue NewShift = DAG.getNode(N->getOpcode(),
4271 SDLoc(LHS->getOperand(0)),
4272 VT, LHS->getOperand(0), N->getOperand(1));
4274 // Create the new binop.
4275 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4278 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4279 assert(N->getOpcode() == ISD::TRUNCATE);
4280 assert(N->getOperand(0).getOpcode() == ISD::AND);
4282 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4283 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4284 SDValue N01 = N->getOperand(0).getOperand(1);
4286 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4287 if (!N01C->isOpaque()) {
4288 EVT TruncVT = N->getValueType(0);
4289 SDValue N00 = N->getOperand(0).getOperand(0);
4290 APInt TruncC = N01C->getAPIntValue();
4291 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4294 return DAG.getNode(ISD::AND, DL, TruncVT,
4295 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4296 DAG.getConstant(TruncC, DL, TruncVT));
4304 SDValue DAGCombiner::visitRotate(SDNode *N) {
4305 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4306 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4307 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4308 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4309 if (NewOp1.getNode())
4310 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4311 N->getOperand(0), NewOp1);
4316 SDValue DAGCombiner::visitSHL(SDNode *N) {
4317 SDValue N0 = N->getOperand(0);
4318 SDValue N1 = N->getOperand(1);
4319 EVT VT = N0.getValueType();
4320 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4323 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4324 if (VT.isVector()) {
4325 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4328 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4329 // If setcc produces all-one true value then:
4330 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4331 if (N1CV && N1CV->isConstant()) {
4332 if (N0.getOpcode() == ISD::AND) {
4333 SDValue N00 = N0->getOperand(0);
4334 SDValue N01 = N0->getOperand(1);
4335 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4337 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4338 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4339 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4340 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4342 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4345 N1C = isConstOrConstSplat(N1);
4350 // fold (shl c1, c2) -> c1<<c2
4351 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4352 if (N0C && N1C && !N1C->isOpaque())
4353 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4354 // fold (shl 0, x) -> 0
4355 if (isNullConstant(N0))
4357 // fold (shl x, c >= size(x)) -> undef
4358 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4359 return DAG.getUNDEF(VT);
4360 // fold (shl x, 0) -> x
4361 if (N1C && N1C->isNullValue())
4363 // fold (shl undef, x) -> 0
4364 if (N0.getOpcode() == ISD::UNDEF)
4365 return DAG.getConstant(0, SDLoc(N), VT);
4366 // if (shl x, c) is known to be zero, return 0
4367 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4368 APInt::getAllOnesValue(OpSizeInBits)))
4369 return DAG.getConstant(0, SDLoc(N), VT);
4370 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4371 if (N1.getOpcode() == ISD::TRUNCATE &&
4372 N1.getOperand(0).getOpcode() == ISD::AND) {
4373 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4374 if (NewOp1.getNode())
4375 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4378 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4379 return SDValue(N, 0);
4381 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4382 if (N1C && N0.getOpcode() == ISD::SHL) {
4383 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4384 uint64_t c1 = N0C1->getZExtValue();
4385 uint64_t c2 = N1C->getZExtValue();
4387 if (c1 + c2 >= OpSizeInBits)
4388 return DAG.getConstant(0, DL, VT);
4389 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4390 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4394 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4395 // For this to be valid, the second form must not preserve any of the bits
4396 // that are shifted out by the inner shift in the first form. This means
4397 // the outer shift size must be >= the number of bits added by the ext.
4398 // As a corollary, we don't care what kind of ext it is.
4399 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4400 N0.getOpcode() == ISD::ANY_EXTEND ||
4401 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4402 N0.getOperand(0).getOpcode() == ISD::SHL) {
4403 SDValue N0Op0 = N0.getOperand(0);
4404 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4405 uint64_t c1 = N0Op0C1->getZExtValue();
4406 uint64_t c2 = N1C->getZExtValue();
4407 EVT InnerShiftVT = N0Op0.getValueType();
4408 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4409 if (c2 >= OpSizeInBits - InnerShiftSize) {
4411 if (c1 + c2 >= OpSizeInBits)
4412 return DAG.getConstant(0, DL, VT);
4413 return DAG.getNode(ISD::SHL, DL, VT,
4414 DAG.getNode(N0.getOpcode(), DL, VT,
4415 N0Op0->getOperand(0)),
4416 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4421 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4422 // Only fold this if the inner zext has no other uses to avoid increasing
4423 // the total number of instructions.
4424 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4425 N0.getOperand(0).getOpcode() == ISD::SRL) {
4426 SDValue N0Op0 = N0.getOperand(0);
4427 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4428 uint64_t c1 = N0Op0C1->getZExtValue();
4429 if (c1 < VT.getScalarSizeInBits()) {
4430 uint64_t c2 = N1C->getZExtValue();
4432 SDValue NewOp0 = N0.getOperand(0);
4433 EVT CountVT = NewOp0.getOperand(1).getValueType();
4435 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4437 DAG.getConstant(c2, DL, CountVT));
4438 AddToWorklist(NewSHL.getNode());
4439 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4445 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4446 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4447 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4448 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4449 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4450 uint64_t C1 = N0C1->getZExtValue();
4451 uint64_t C2 = N1C->getZExtValue();
4454 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4455 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4456 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4457 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4461 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4462 // (and (srl x, (sub c1, c2), MASK)
4463 // Only fold this if the inner shift has no other uses -- if it does, folding
4464 // this will increase the total number of instructions.
4465 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4466 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4467 uint64_t c1 = N0C1->getZExtValue();
4468 if (c1 < OpSizeInBits) {
4469 uint64_t c2 = N1C->getZExtValue();
4470 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4473 Mask = Mask.shl(c2 - c1);
4475 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4476 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4478 Mask = Mask.lshr(c1 - c2);
4480 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4481 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4484 return DAG.getNode(ISD::AND, DL, VT, Shift,
4485 DAG.getConstant(Mask, DL, VT));
4489 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4490 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4491 unsigned BitSize = VT.getScalarSizeInBits();
4493 SDValue HiBitsMask =
4494 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4495 BitSize - N1C->getZExtValue()),
4497 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4501 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4502 // Variant of version done on multiply, except mul by a power of 2 is turned
4505 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4506 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4507 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4508 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4509 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4510 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4513 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4514 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4515 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4516 if (SDValue Folded =
4517 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4518 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4522 if (N1C && !N1C->isOpaque())
4523 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4529 SDValue DAGCombiner::visitSRA(SDNode *N) {
4530 SDValue N0 = N->getOperand(0);
4531 SDValue N1 = N->getOperand(1);
4532 EVT VT = N0.getValueType();
4533 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4536 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4537 if (VT.isVector()) {
4538 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4541 N1C = isConstOrConstSplat(N1);
4544 // fold (sra c1, c2) -> (sra c1, c2)
4545 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4546 if (N0C && N1C && !N1C->isOpaque())
4547 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4548 // fold (sra 0, x) -> 0
4549 if (isNullConstant(N0))
4551 // fold (sra -1, x) -> -1
4552 if (isAllOnesConstant(N0))
4554 // fold (sra x, (setge c, size(x))) -> undef
4555 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4556 return DAG.getUNDEF(VT);
4557 // fold (sra x, 0) -> x
4558 if (N1C && N1C->isNullValue())
4560 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4562 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4563 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4564 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4566 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4567 ExtVT, VT.getVectorNumElements());
4568 if ((!LegalOperations ||
4569 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4570 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4571 N0.getOperand(0), DAG.getValueType(ExtVT));
4574 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4575 if (N1C && N0.getOpcode() == ISD::SRA) {
4576 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4577 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4578 if (Sum >= OpSizeInBits)
4579 Sum = OpSizeInBits - 1;
4581 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4582 DAG.getConstant(Sum, DL, N1.getValueType()));
4586 // fold (sra (shl X, m), (sub result_size, n))
4587 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4588 // result_size - n != m.
4589 // If truncate is free for the target sext(shl) is likely to result in better
4591 if (N0.getOpcode() == ISD::SHL && N1C) {
4592 // Get the two constanst of the shifts, CN0 = m, CN = n.
4593 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4595 LLVMContext &Ctx = *DAG.getContext();
4596 // Determine what the truncate's result bitsize and type would be.
4597 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4600 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4602 // Determine the residual right-shift amount.
4603 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4605 // If the shift is not a no-op (in which case this should be just a sign
4606 // extend already), the truncated to type is legal, sign_extend is legal
4607 // on that type, and the truncate to that type is both legal and free,
4608 // perform the transform.
4609 if ((ShiftAmt > 0) &&
4610 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4611 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4612 TLI.isTruncateFree(VT, TruncVT)) {
4615 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4616 getShiftAmountTy(N0.getOperand(0).getValueType()));
4617 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4618 N0.getOperand(0), Amt);
4619 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4621 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4622 N->getValueType(0), Trunc);
4627 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4628 if (N1.getOpcode() == ISD::TRUNCATE &&
4629 N1.getOperand(0).getOpcode() == ISD::AND) {
4630 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4631 if (NewOp1.getNode())
4632 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4635 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4636 // if c1 is equal to the number of bits the trunc removes
4637 if (N0.getOpcode() == ISD::TRUNCATE &&
4638 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4639 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4640 N0.getOperand(0).hasOneUse() &&
4641 N0.getOperand(0).getOperand(1).hasOneUse() &&
4643 SDValue N0Op0 = N0.getOperand(0);
4644 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4645 unsigned LargeShiftVal = LargeShift->getZExtValue();
4646 EVT LargeVT = N0Op0.getValueType();
4648 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4651 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4652 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4653 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4654 N0Op0.getOperand(0), Amt);
4655 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4660 // Simplify, based on bits shifted out of the LHS.
4661 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4662 return SDValue(N, 0);
4665 // If the sign bit is known to be zero, switch this to a SRL.
4666 if (DAG.SignBitIsZero(N0))
4667 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4669 if (N1C && !N1C->isOpaque())
4670 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4676 SDValue DAGCombiner::visitSRL(SDNode *N) {
4677 SDValue N0 = N->getOperand(0);
4678 SDValue N1 = N->getOperand(1);
4679 EVT VT = N0.getValueType();
4680 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4683 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4684 if (VT.isVector()) {
4685 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4688 N1C = isConstOrConstSplat(N1);
4691 // fold (srl c1, c2) -> c1 >>u c2
4692 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4693 if (N0C && N1C && !N1C->isOpaque())
4694 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4695 // fold (srl 0, x) -> 0
4696 if (isNullConstant(N0))
4698 // fold (srl x, c >= size(x)) -> undef
4699 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4700 return DAG.getUNDEF(VT);
4701 // fold (srl x, 0) -> x
4702 if (N1C && N1C->isNullValue())
4704 // if (srl x, c) is known to be zero, return 0
4705 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4706 APInt::getAllOnesValue(OpSizeInBits)))
4707 return DAG.getConstant(0, SDLoc(N), VT);
4709 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4710 if (N1C && N0.getOpcode() == ISD::SRL) {
4711 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4712 uint64_t c1 = N01C->getZExtValue();
4713 uint64_t c2 = N1C->getZExtValue();
4715 if (c1 + c2 >= OpSizeInBits)
4716 return DAG.getConstant(0, DL, VT);
4717 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4718 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4722 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4723 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4724 N0.getOperand(0).getOpcode() == ISD::SRL &&
4725 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4727 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4728 uint64_t c2 = N1C->getZExtValue();
4729 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4730 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4731 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4732 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4733 if (c1 + OpSizeInBits == InnerShiftSize) {
4735 if (c1 + c2 >= InnerShiftSize)
4736 return DAG.getConstant(0, DL, VT);
4737 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4738 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4739 N0.getOperand(0)->getOperand(0),
4740 DAG.getConstant(c1 + c2, DL,
4745 // fold (srl (shl x, c), c) -> (and x, cst2)
4746 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4747 unsigned BitSize = N0.getScalarValueSizeInBits();
4748 if (BitSize <= 64) {
4749 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4751 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4752 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4756 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4757 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4758 // Shifting in all undef bits?
4759 EVT SmallVT = N0.getOperand(0).getValueType();
4760 unsigned BitSize = SmallVT.getScalarSizeInBits();
4761 if (N1C->getZExtValue() >= BitSize)
4762 return DAG.getUNDEF(VT);
4764 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4765 uint64_t ShiftAmt = N1C->getZExtValue();
4767 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4769 DAG.getConstant(ShiftAmt, DL0,
4770 getShiftAmountTy(SmallVT)));
4771 AddToWorklist(SmallShift.getNode());
4772 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4774 return DAG.getNode(ISD::AND, DL, VT,
4775 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4776 DAG.getConstant(Mask, DL, VT));
4780 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4781 // bit, which is unmodified by sra.
4782 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4783 if (N0.getOpcode() == ISD::SRA)
4784 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4787 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4788 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4789 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4790 APInt KnownZero, KnownOne;
4791 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4793 // If any of the input bits are KnownOne, then the input couldn't be all
4794 // zeros, thus the result of the srl will always be zero.
4795 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4797 // If all of the bits input the to ctlz node are known to be zero, then
4798 // the result of the ctlz is "32" and the result of the shift is one.
4799 APInt UnknownBits = ~KnownZero;
4800 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4802 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4803 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4804 // Okay, we know that only that the single bit specified by UnknownBits
4805 // could be set on input to the CTLZ node. If this bit is set, the SRL
4806 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4807 // to an SRL/XOR pair, which is likely to simplify more.
4808 unsigned ShAmt = UnknownBits.countTrailingZeros();
4809 SDValue Op = N0.getOperand(0);
4813 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4814 DAG.getConstant(ShAmt, DL,
4815 getShiftAmountTy(Op.getValueType())));
4816 AddToWorklist(Op.getNode());
4820 return DAG.getNode(ISD::XOR, DL, VT,
4821 Op, DAG.getConstant(1, DL, VT));
4825 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4826 if (N1.getOpcode() == ISD::TRUNCATE &&
4827 N1.getOperand(0).getOpcode() == ISD::AND) {
4828 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4829 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4832 // fold operands of srl based on knowledge that the low bits are not
4834 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4835 return SDValue(N, 0);
4837 if (N1C && !N1C->isOpaque())
4838 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4841 // Attempt to convert a srl of a load into a narrower zero-extending load.
4842 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4845 // Here is a common situation. We want to optimize:
4848 // %b = and i32 %a, 2
4849 // %c = srl i32 %b, 1
4850 // brcond i32 %c ...
4856 // %c = setcc eq %b, 0
4859 // However when after the source operand of SRL is optimized into AND, the SRL
4860 // itself may not be optimized further. Look for it and add the BRCOND into
4862 if (N->hasOneUse()) {
4863 SDNode *Use = *N->use_begin();
4864 if (Use->getOpcode() == ISD::BRCOND)
4866 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4867 // Also look pass the truncate.
4868 Use = *Use->use_begin();
4869 if (Use->getOpcode() == ISD::BRCOND)
4877 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4878 SDValue N0 = N->getOperand(0);
4879 EVT VT = N->getValueType(0);
4881 // fold (bswap c1) -> c2
4882 if (isConstantIntBuildVectorOrConstantInt(N0))
4883 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4884 // fold (bswap (bswap x)) -> x
4885 if (N0.getOpcode() == ISD::BSWAP)
4886 return N0->getOperand(0);
4890 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4891 SDValue N0 = N->getOperand(0);
4892 EVT VT = N->getValueType(0);
4894 // fold (ctlz c1) -> c2
4895 if (isConstantIntBuildVectorOrConstantInt(N0))
4896 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4900 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4901 SDValue N0 = N->getOperand(0);
4902 EVT VT = N->getValueType(0);
4904 // fold (ctlz_zero_undef c1) -> c2
4905 if (isConstantIntBuildVectorOrConstantInt(N0))
4906 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4910 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4911 SDValue N0 = N->getOperand(0);
4912 EVT VT = N->getValueType(0);
4914 // fold (cttz c1) -> c2
4915 if (isConstantIntBuildVectorOrConstantInt(N0))
4916 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4920 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4921 SDValue N0 = N->getOperand(0);
4922 EVT VT = N->getValueType(0);
4924 // fold (cttz_zero_undef c1) -> c2
4925 if (isConstantIntBuildVectorOrConstantInt(N0))
4926 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4930 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4931 SDValue N0 = N->getOperand(0);
4932 EVT VT = N->getValueType(0);
4934 // fold (ctpop c1) -> c2
4935 if (isConstantIntBuildVectorOrConstantInt(N0))
4936 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4941 /// \brief Generate Min/Max node
4942 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4943 SDValue True, SDValue False,
4944 ISD::CondCode CC, const TargetLowering &TLI,
4945 SelectionDAG &DAG) {
4946 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4956 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4957 if (TLI.isOperationLegal(Opcode, VT))
4958 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4967 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4968 if (TLI.isOperationLegal(Opcode, VT))
4969 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4977 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4978 SDValue N0 = N->getOperand(0);
4979 SDValue N1 = N->getOperand(1);
4980 SDValue N2 = N->getOperand(2);
4981 EVT VT = N->getValueType(0);
4982 EVT VT0 = N0.getValueType();
4984 // fold (select C, X, X) -> X
4987 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4988 // fold (select true, X, Y) -> X
4989 // fold (select false, X, Y) -> Y
4990 return !N0C->isNullValue() ? N1 : N2;
4992 // fold (select C, 1, X) -> (or C, X)
4993 if (VT == MVT::i1 && isOneConstant(N1))
4994 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4995 // fold (select C, 0, 1) -> (xor C, 1)
4996 // We can't do this reliably if integer based booleans have different contents
4997 // to floating point based booleans. This is because we can't tell whether we
4998 // have an integer-based boolean or a floating-point-based boolean unless we
4999 // can find the SETCC that produced it and inspect its operands. This is
5000 // fairly easy if C is the SETCC node, but it can potentially be
5001 // undiscoverable (or not reasonably discoverable). For example, it could be
5002 // in another basic block or it could require searching a complicated
5004 if (VT.isInteger() &&
5005 (VT0 == MVT::i1 || (VT0.isInteger() &&
5006 TLI.getBooleanContents(false, false) ==
5007 TLI.getBooleanContents(false, true) &&
5008 TLI.getBooleanContents(false, false) ==
5009 TargetLowering::ZeroOrOneBooleanContent)) &&
5010 isNullConstant(N1) && isOneConstant(N2)) {
5014 return DAG.getNode(ISD::XOR, DL, VT0,
5015 N0, DAG.getConstant(1, DL, VT0));
5018 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5019 N0, DAG.getConstant(1, DL0, VT0));
5020 AddToWorklist(XORNode.getNode());
5022 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5023 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5025 // fold (select C, 0, X) -> (and (not C), X)
5026 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5027 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5028 AddToWorklist(NOTNode.getNode());
5029 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5031 // fold (select C, X, 1) -> (or (not C), X)
5032 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5033 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5034 AddToWorklist(NOTNode.getNode());
5035 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5037 // fold (select C, X, 0) -> (and C, X)
5038 if (VT == MVT::i1 && isNullConstant(N2))
5039 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5040 // fold (select X, X, Y) -> (or X, Y)
5041 // fold (select X, 1, Y) -> (or X, Y)
5042 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5043 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5044 // fold (select X, Y, X) -> (and X, Y)
5045 // fold (select X, Y, 0) -> (and X, Y)
5046 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5047 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5049 // If we can fold this based on the true/false value, do so.
5050 if (SimplifySelectOps(N, N1, N2))
5051 return SDValue(N, 0); // Don't revisit N.
5053 if (VT0 == MVT::i1) {
5054 // The code in this block deals with the following 2 equivalences:
5055 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5056 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5057 // The target can specify its prefered form with the
5058 // shouldNormalizeToSelectSequence() callback. However we always transform
5059 // to the right anyway if we find the inner select exists in the DAG anyway
5060 // and we always transform to the left side if we know that we can further
5061 // optimize the combination of the conditions.
5062 bool normalizeToSequence
5063 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5064 // select (and Cond0, Cond1), X, Y
5065 // -> select Cond0, (select Cond1, X, Y), Y
5066 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5067 SDValue Cond0 = N0->getOperand(0);
5068 SDValue Cond1 = N0->getOperand(1);
5069 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5070 N1.getValueType(), Cond1, N1, N2);
5071 if (normalizeToSequence || !InnerSelect.use_empty())
5072 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5075 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5076 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5077 SDValue Cond0 = N0->getOperand(0);
5078 SDValue Cond1 = N0->getOperand(1);
5079 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5080 N1.getValueType(), Cond1, N1, N2);
5081 if (normalizeToSequence || !InnerSelect.use_empty())
5082 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5086 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5087 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5088 SDValue N1_0 = N1->getOperand(0);
5089 SDValue N1_1 = N1->getOperand(1);
5090 SDValue N1_2 = N1->getOperand(2);
5091 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5092 // Create the actual and node if we can generate good code for it.
5093 if (!normalizeToSequence) {
5094 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5096 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5099 // Otherwise see if we can optimize the "and" to a better pattern.
5100 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5101 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5105 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5106 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5107 SDValue N2_0 = N2->getOperand(0);
5108 SDValue N2_1 = N2->getOperand(1);
5109 SDValue N2_2 = N2->getOperand(2);
5110 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5111 // Create the actual or node if we can generate good code for it.
5112 if (!normalizeToSequence) {
5113 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5115 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5118 // Otherwise see if we can optimize to a better pattern.
5119 if (SDValue Combined = visitORLike(N0, N2_0, N))
5120 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5126 // fold selects based on a setcc into other things, such as min/max/abs
5127 if (N0.getOpcode() == ISD::SETCC) {
5128 // select x, y (fcmp lt x, y) -> fminnum x, y
5129 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5131 // This is OK if we don't care about what happens if either operand is a
5135 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5136 // no signed zeros as well as no nans.
5137 const TargetOptions &Options = DAG.getTarget().Options;
5138 if (Options.UnsafeFPMath &&
5139 VT.isFloatingPoint() && N0.hasOneUse() &&
5140 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5141 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5143 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5144 N0.getOperand(1), N1, N2, CC,
5149 if ((!LegalOperations &&
5150 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5151 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5152 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5153 N0.getOperand(0), N0.getOperand(1),
5154 N1, N2, N0.getOperand(2));
5155 return SimplifySelect(SDLoc(N), N0, N1, N2);
5162 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5165 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5167 // Split the inputs.
5168 SDValue Lo, Hi, LL, LH, RL, RH;
5169 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5170 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5172 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5173 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5175 return std::make_pair(Lo, Hi);
5178 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5179 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5180 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5182 SDValue Cond = N->getOperand(0);
5183 SDValue LHS = N->getOperand(1);
5184 SDValue RHS = N->getOperand(2);
5185 EVT VT = N->getValueType(0);
5186 int NumElems = VT.getVectorNumElements();
5187 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5188 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5189 Cond.getOpcode() == ISD::BUILD_VECTOR);
5191 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5192 // binary ones here.
5193 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5196 // We're sure we have an even number of elements due to the
5197 // concat_vectors we have as arguments to vselect.
5198 // Skip BV elements until we find one that's not an UNDEF
5199 // After we find an UNDEF element, keep looping until we get to half the
5200 // length of the BV and see if all the non-undef nodes are the same.
5201 ConstantSDNode *BottomHalf = nullptr;
5202 for (int i = 0; i < NumElems / 2; ++i) {
5203 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5206 if (BottomHalf == nullptr)
5207 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5208 else if (Cond->getOperand(i).getNode() != BottomHalf)
5212 // Do the same for the second half of the BuildVector
5213 ConstantSDNode *TopHalf = nullptr;
5214 for (int i = NumElems / 2; i < NumElems; ++i) {
5215 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5218 if (TopHalf == nullptr)
5219 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5220 else if (Cond->getOperand(i).getNode() != TopHalf)
5224 assert(TopHalf && BottomHalf &&
5225 "One half of the selector was all UNDEFs and the other was all the "
5226 "same value. This should have been addressed before this function.");
5228 ISD::CONCAT_VECTORS, dl, VT,
5229 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5230 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5233 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5235 if (Level >= AfterLegalizeTypes)
5238 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5239 SDValue Mask = MSC->getMask();
5240 SDValue Data = MSC->getValue();
5243 // If the MSCATTER data type requires splitting and the mask is provided by a
5244 // SETCC, then split both nodes and its operands before legalization. This
5245 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5246 // and enables future optimizations (e.g. min/max pattern matching on X86).
5247 if (Mask.getOpcode() != ISD::SETCC)
5250 // Check if any splitting is required.
5251 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5252 TargetLowering::TypeSplitVector)
5254 SDValue MaskLo, MaskHi, Lo, Hi;
5255 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5258 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5260 SDValue Chain = MSC->getChain();
5262 EVT MemoryVT = MSC->getMemoryVT();
5263 unsigned Alignment = MSC->getOriginalAlignment();
5265 EVT LoMemVT, HiMemVT;
5266 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5268 SDValue DataLo, DataHi;
5269 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5271 SDValue BasePtr = MSC->getBasePtr();
5272 SDValue IndexLo, IndexHi;
5273 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5275 MachineMemOperand *MMO = DAG.getMachineFunction().
5276 getMachineMemOperand(MSC->getPointerInfo(),
5277 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5278 Alignment, MSC->getAAInfo(), MSC->getRanges());
5280 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5281 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5284 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5285 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5288 AddToWorklist(Lo.getNode());
5289 AddToWorklist(Hi.getNode());
5291 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5294 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5296 if (Level >= AfterLegalizeTypes)
5299 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5300 SDValue Mask = MST->getMask();
5301 SDValue Data = MST->getValue();
5304 // If the MSTORE data type requires splitting and the mask is provided by a
5305 // SETCC, then split both nodes and its operands before legalization. This
5306 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5307 // and enables future optimizations (e.g. min/max pattern matching on X86).
5308 if (Mask.getOpcode() == ISD::SETCC) {
5310 // Check if any splitting is required.
5311 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5312 TargetLowering::TypeSplitVector)
5315 SDValue MaskLo, MaskHi, Lo, Hi;
5316 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5319 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5321 SDValue Chain = MST->getChain();
5322 SDValue Ptr = MST->getBasePtr();
5324 EVT MemoryVT = MST->getMemoryVT();
5325 unsigned Alignment = MST->getOriginalAlignment();
5327 // if Alignment is equal to the vector size,
5328 // take the half of it for the second part
5329 unsigned SecondHalfAlignment =
5330 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5331 Alignment/2 : Alignment;
5333 EVT LoMemVT, HiMemVT;
5334 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5336 SDValue DataLo, DataHi;
5337 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5339 MachineMemOperand *MMO = DAG.getMachineFunction().
5340 getMachineMemOperand(MST->getPointerInfo(),
5341 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5342 Alignment, MST->getAAInfo(), MST->getRanges());
5344 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5345 MST->isTruncatingStore());
5347 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5348 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5349 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5351 MMO = DAG.getMachineFunction().
5352 getMachineMemOperand(MST->getPointerInfo(),
5353 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5354 SecondHalfAlignment, MST->getAAInfo(),
5357 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5358 MST->isTruncatingStore());
5360 AddToWorklist(Lo.getNode());
5361 AddToWorklist(Hi.getNode());
5363 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5368 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5370 if (Level >= AfterLegalizeTypes)
5373 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5374 SDValue Mask = MGT->getMask();
5377 // If the MGATHER result requires splitting and the mask is provided by a
5378 // SETCC, then split both nodes and its operands before legalization. This
5379 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5380 // and enables future optimizations (e.g. min/max pattern matching on X86).
5382 if (Mask.getOpcode() != ISD::SETCC)
5385 EVT VT = N->getValueType(0);
5387 // Check if any splitting is required.
5388 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5389 TargetLowering::TypeSplitVector)
5392 SDValue MaskLo, MaskHi, Lo, Hi;
5393 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5395 SDValue Src0 = MGT->getValue();
5396 SDValue Src0Lo, Src0Hi;
5397 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5400 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5402 SDValue Chain = MGT->getChain();
5403 EVT MemoryVT = MGT->getMemoryVT();
5404 unsigned Alignment = MGT->getOriginalAlignment();
5406 EVT LoMemVT, HiMemVT;
5407 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5409 SDValue BasePtr = MGT->getBasePtr();
5410 SDValue Index = MGT->getIndex();
5411 SDValue IndexLo, IndexHi;
5412 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5414 MachineMemOperand *MMO = DAG.getMachineFunction().
5415 getMachineMemOperand(MGT->getPointerInfo(),
5416 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5417 Alignment, MGT->getAAInfo(), MGT->getRanges());
5419 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5420 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5423 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5424 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5427 AddToWorklist(Lo.getNode());
5428 AddToWorklist(Hi.getNode());
5430 // Build a factor node to remember that this load is independent of the
5432 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5435 // Legalized the chain result - switch anything that used the old chain to
5437 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5439 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5441 SDValue RetOps[] = { GatherRes, Chain };
5442 return DAG.getMergeValues(RetOps, DL);
5445 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5447 if (Level >= AfterLegalizeTypes)
5450 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5451 SDValue Mask = MLD->getMask();
5454 // If the MLOAD result requires splitting and the mask is provided by a
5455 // SETCC, then split both nodes and its operands before legalization. This
5456 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5457 // and enables future optimizations (e.g. min/max pattern matching on X86).
5459 if (Mask.getOpcode() == ISD::SETCC) {
5460 EVT VT = N->getValueType(0);
5462 // Check if any splitting is required.
5463 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5464 TargetLowering::TypeSplitVector)
5467 SDValue MaskLo, MaskHi, Lo, Hi;
5468 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5470 SDValue Src0 = MLD->getSrc0();
5471 SDValue Src0Lo, Src0Hi;
5472 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5475 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5477 SDValue Chain = MLD->getChain();
5478 SDValue Ptr = MLD->getBasePtr();
5479 EVT MemoryVT = MLD->getMemoryVT();
5480 unsigned Alignment = MLD->getOriginalAlignment();
5482 // if Alignment is equal to the vector size,
5483 // take the half of it for the second part
5484 unsigned SecondHalfAlignment =
5485 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5486 Alignment/2 : Alignment;
5488 EVT LoMemVT, HiMemVT;
5489 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5491 MachineMemOperand *MMO = DAG.getMachineFunction().
5492 getMachineMemOperand(MLD->getPointerInfo(),
5493 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5494 Alignment, MLD->getAAInfo(), MLD->getRanges());
5496 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5499 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5500 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5501 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5503 MMO = DAG.getMachineFunction().
5504 getMachineMemOperand(MLD->getPointerInfo(),
5505 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5506 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5508 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5511 AddToWorklist(Lo.getNode());
5512 AddToWorklist(Hi.getNode());
5514 // Build a factor node to remember that this load is independent of the
5516 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5519 // Legalized the chain result - switch anything that used the old chain to
5521 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5523 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5525 SDValue RetOps[] = { LoadRes, Chain };
5526 return DAG.getMergeValues(RetOps, DL);
5531 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5532 SDValue N0 = N->getOperand(0);
5533 SDValue N1 = N->getOperand(1);
5534 SDValue N2 = N->getOperand(2);
5537 // Canonicalize integer abs.
5538 // vselect (setg[te] X, 0), X, -X ->
5539 // vselect (setgt X, -1), X, -X ->
5540 // vselect (setl[te] X, 0), -X, X ->
5541 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5542 if (N0.getOpcode() == ISD::SETCC) {
5543 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5544 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5546 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5548 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5549 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5550 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5551 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5552 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5553 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5554 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5557 EVT VT = LHS.getValueType();
5558 SDValue Shift = DAG.getNode(
5559 ISD::SRA, DL, VT, LHS,
5560 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5561 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5562 AddToWorklist(Shift.getNode());
5563 AddToWorklist(Add.getNode());
5564 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5568 if (SimplifySelectOps(N, N1, N2))
5569 return SDValue(N, 0); // Don't revisit N.
5571 // If the VSELECT result requires splitting and the mask is provided by a
5572 // SETCC, then split both nodes and its operands before legalization. This
5573 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5574 // and enables future optimizations (e.g. min/max pattern matching on X86).
5575 if (N0.getOpcode() == ISD::SETCC) {
5576 EVT VT = N->getValueType(0);
5578 // Check if any splitting is required.
5579 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5580 TargetLowering::TypeSplitVector)
5583 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5584 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5585 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5586 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5588 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5589 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5591 // Add the new VSELECT nodes to the work list in case they need to be split
5593 AddToWorklist(Lo.getNode());
5594 AddToWorklist(Hi.getNode());
5596 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5599 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5600 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5602 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5603 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5606 // The ConvertSelectToConcatVector function is assuming both the above
5607 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5609 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5610 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5611 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5612 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5619 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5620 SDValue N0 = N->getOperand(0);
5621 SDValue N1 = N->getOperand(1);
5622 SDValue N2 = N->getOperand(2);
5623 SDValue N3 = N->getOperand(3);
5624 SDValue N4 = N->getOperand(4);
5625 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5627 // fold select_cc lhs, rhs, x, x, cc -> x
5631 // Determine if the condition we're dealing with is constant
5632 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5633 N0, N1, CC, SDLoc(N), false);
5634 if (SCC.getNode()) {
5635 AddToWorklist(SCC.getNode());
5637 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5638 if (!SCCC->isNullValue())
5639 return N2; // cond always true -> true val
5641 return N3; // cond always false -> false val
5642 } else if (SCC->getOpcode() == ISD::UNDEF) {
5643 // When the condition is UNDEF, just return the first operand. This is
5644 // coherent the DAG creation, no setcc node is created in this case
5646 } else if (SCC.getOpcode() == ISD::SETCC) {
5647 // Fold to a simpler select_cc
5648 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5649 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5654 // If we can fold this based on the true/false value, do so.
5655 if (SimplifySelectOps(N, N2, N3))
5656 return SDValue(N, 0); // Don't revisit N.
5658 // fold select_cc into other things, such as min/max/abs
5659 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5662 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5663 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5664 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5668 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5669 /// a build_vector of constants.
5670 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5671 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5672 /// Vector extends are not folded if operations are legal; this is to
5673 /// avoid introducing illegal build_vector dag nodes.
5674 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5675 SelectionDAG &DAG, bool LegalTypes,
5676 bool LegalOperations) {
5677 unsigned Opcode = N->getOpcode();
5678 SDValue N0 = N->getOperand(0);
5679 EVT VT = N->getValueType(0);
5681 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5682 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5683 && "Expected EXTEND dag node in input!");
5685 // fold (sext c1) -> c1
5686 // fold (zext c1) -> c1
5687 // fold (aext c1) -> c1
5688 if (isa<ConstantSDNode>(N0))
5689 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5691 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5692 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5693 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5694 EVT SVT = VT.getScalarType();
5695 if (!(VT.isVector() &&
5696 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5697 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5700 // We can fold this node into a build_vector.
5701 unsigned VTBits = SVT.getSizeInBits();
5702 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5703 SmallVector<SDValue, 8> Elts;
5704 unsigned NumElts = VT.getVectorNumElements();
5707 for (unsigned i=0; i != NumElts; ++i) {
5708 SDValue Op = N0->getOperand(i);
5709 if (Op->getOpcode() == ISD::UNDEF) {
5710 Elts.push_back(DAG.getUNDEF(SVT));
5715 // Get the constant value and if needed trunc it to the size of the type.
5716 // Nodes like build_vector might have constants wider than the scalar type.
5717 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5718 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5719 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5721 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5724 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5727 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5728 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5729 // transformation. Returns true if extension are possible and the above
5730 // mentioned transformation is profitable.
5731 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5733 SmallVectorImpl<SDNode *> &ExtendNodes,
5734 const TargetLowering &TLI) {
5735 bool HasCopyToRegUses = false;
5736 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5737 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5738 UE = N0.getNode()->use_end();
5743 if (UI.getUse().getResNo() != N0.getResNo())
5745 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5746 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5747 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5748 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5749 // Sign bits will be lost after a zext.
5752 for (unsigned i = 0; i != 2; ++i) {
5753 SDValue UseOp = User->getOperand(i);
5756 if (!isa<ConstantSDNode>(UseOp))
5761 ExtendNodes.push_back(User);
5764 // If truncates aren't free and there are users we can't
5765 // extend, it isn't worthwhile.
5768 // Remember if this value is live-out.
5769 if (User->getOpcode() == ISD::CopyToReg)
5770 HasCopyToRegUses = true;
5773 if (HasCopyToRegUses) {
5774 bool BothLiveOut = false;
5775 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5777 SDUse &Use = UI.getUse();
5778 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5784 // Both unextended and extended values are live out. There had better be
5785 // a good reason for the transformation.
5786 return ExtendNodes.size();
5791 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5792 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5793 ISD::NodeType ExtType) {
5794 // Extend SetCC uses if necessary.
5795 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5796 SDNode *SetCC = SetCCs[i];
5797 SmallVector<SDValue, 4> Ops;
5799 for (unsigned j = 0; j != 2; ++j) {
5800 SDValue SOp = SetCC->getOperand(j);
5802 Ops.push_back(ExtLoad);
5804 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5807 Ops.push_back(SetCC->getOperand(2));
5808 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5812 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5813 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5814 SDValue N0 = N->getOperand(0);
5815 EVT DstVT = N->getValueType(0);
5816 EVT SrcVT = N0.getValueType();
5818 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5819 N->getOpcode() == ISD::ZERO_EXTEND) &&
5820 "Unexpected node type (not an extend)!");
5822 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5823 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5824 // (v8i32 (sext (v8i16 (load x))))
5826 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5827 // (v4i32 (sextload (x + 16)))))
5828 // Where uses of the original load, i.e.:
5830 // are replaced with:
5832 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5833 // (v4i32 (sextload (x + 16)))))))
5835 // This combine is only applicable to illegal, but splittable, vectors.
5836 // All legal types, and illegal non-vector types, are handled elsewhere.
5837 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5839 if (N0->getOpcode() != ISD::LOAD)
5842 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5844 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5845 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5846 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5849 SmallVector<SDNode *, 4> SetCCs;
5850 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5853 ISD::LoadExtType ExtType =
5854 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5856 // Try to split the vector types to get down to legal types.
5857 EVT SplitSrcVT = SrcVT;
5858 EVT SplitDstVT = DstVT;
5859 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5860 SplitSrcVT.getVectorNumElements() > 1) {
5861 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5862 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5865 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5869 const unsigned NumSplits =
5870 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5871 const unsigned Stride = SplitSrcVT.getStoreSize();
5872 SmallVector<SDValue, 4> Loads;
5873 SmallVector<SDValue, 4> Chains;
5875 SDValue BasePtr = LN0->getBasePtr();
5876 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5877 const unsigned Offset = Idx * Stride;
5878 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5880 SDValue SplitLoad = DAG.getExtLoad(
5881 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5882 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5883 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5884 Align, LN0->getAAInfo());
5886 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5887 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5889 Loads.push_back(SplitLoad.getValue(0));
5890 Chains.push_back(SplitLoad.getValue(1));
5893 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5894 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5896 CombineTo(N, NewValue);
5898 // Replace uses of the original load (before extension)
5899 // with a truncate of the concatenated sextloaded vectors.
5901 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5902 CombineTo(N0.getNode(), Trunc, NewChain);
5903 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5904 (ISD::NodeType)N->getOpcode());
5905 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5908 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5909 SDValue N0 = N->getOperand(0);
5910 EVT VT = N->getValueType(0);
5912 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5914 return SDValue(Res, 0);
5916 // fold (sext (sext x)) -> (sext x)
5917 // fold (sext (aext x)) -> (sext x)
5918 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5919 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5922 if (N0.getOpcode() == ISD::TRUNCATE) {
5923 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5924 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5925 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5926 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5927 if (NarrowLoad.getNode() != N0.getNode()) {
5928 CombineTo(N0.getNode(), NarrowLoad);
5929 // CombineTo deleted the truncate, if needed, but not what's under it.
5932 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5935 // See if the value being truncated is already sign extended. If so, just
5936 // eliminate the trunc/sext pair.
5937 SDValue Op = N0.getOperand(0);
5938 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5939 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5940 unsigned DestBits = VT.getScalarType().getSizeInBits();
5941 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5943 if (OpBits == DestBits) {
5944 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5945 // bits, it is already ready.
5946 if (NumSignBits > DestBits-MidBits)
5948 } else if (OpBits < DestBits) {
5949 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5950 // bits, just sext from i32.
5951 if (NumSignBits > OpBits-MidBits)
5952 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5954 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5955 // bits, just truncate to i32.
5956 if (NumSignBits > OpBits-MidBits)
5957 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5960 // fold (sext (truncate x)) -> (sextinreg x).
5961 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5962 N0.getValueType())) {
5963 if (OpBits < DestBits)
5964 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5965 else if (OpBits > DestBits)
5966 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5967 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5968 DAG.getValueType(N0.getValueType()));
5972 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5973 // Only generate vector extloads when 1) they're legal, and 2) they are
5974 // deemed desirable by the target.
5975 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5976 ((!LegalOperations && !VT.isVector() &&
5977 !cast<LoadSDNode>(N0)->isVolatile()) ||
5978 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5979 bool DoXform = true;
5980 SmallVector<SDNode*, 4> SetCCs;
5981 if (!N0.hasOneUse())
5982 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5984 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5986 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5987 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5989 LN0->getBasePtr(), N0.getValueType(),
5990 LN0->getMemOperand());
5991 CombineTo(N, ExtLoad);
5992 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5993 N0.getValueType(), ExtLoad);
5994 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5995 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5997 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6001 // fold (sext (load x)) to multiple smaller sextloads.
6002 // Only on illegal but splittable vectors.
6003 if (SDValue ExtLoad = CombineExtLoad(N))
6006 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6007 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6008 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6009 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6010 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6011 EVT MemVT = LN0->getMemoryVT();
6012 if ((!LegalOperations && !LN0->isVolatile()) ||
6013 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6014 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6016 LN0->getBasePtr(), MemVT,
6017 LN0->getMemOperand());
6018 CombineTo(N, ExtLoad);
6019 CombineTo(N0.getNode(),
6020 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6021 N0.getValueType(), ExtLoad),
6022 ExtLoad.getValue(1));
6023 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6027 // fold (sext (and/or/xor (load x), cst)) ->
6028 // (and/or/xor (sextload x), (sext cst))
6029 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6030 N0.getOpcode() == ISD::XOR) &&
6031 isa<LoadSDNode>(N0.getOperand(0)) &&
6032 N0.getOperand(1).getOpcode() == ISD::Constant &&
6033 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6034 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6035 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6036 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6037 bool DoXform = true;
6038 SmallVector<SDNode*, 4> SetCCs;
6039 if (!N0.hasOneUse())
6040 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6043 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6044 LN0->getChain(), LN0->getBasePtr(),
6046 LN0->getMemOperand());
6047 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6048 Mask = Mask.sext(VT.getSizeInBits());
6050 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6051 ExtLoad, DAG.getConstant(Mask, DL, VT));
6052 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6053 SDLoc(N0.getOperand(0)),
6054 N0.getOperand(0).getValueType(), ExtLoad);
6056 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6057 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6059 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6064 if (N0.getOpcode() == ISD::SETCC) {
6065 EVT N0VT = N0.getOperand(0).getValueType();
6066 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6067 // Only do this before legalize for now.
6068 if (VT.isVector() && !LegalOperations &&
6069 TLI.getBooleanContents(N0VT) ==
6070 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6071 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6072 // of the same size as the compared operands. Only optimize sext(setcc())
6073 // if this is the case.
6074 EVT SVT = getSetCCResultType(N0VT);
6076 // We know that the # elements of the results is the same as the
6077 // # elements of the compare (and the # elements of the compare result
6078 // for that matter). Check to see that they are the same size. If so,
6079 // we know that the element size of the sext'd result matches the
6080 // element size of the compare operands.
6081 if (VT.getSizeInBits() == SVT.getSizeInBits())
6082 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6084 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6086 // If the desired elements are smaller or larger than the source
6087 // elements we can use a matching integer vector type and then
6088 // truncate/sign extend
6089 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6090 if (SVT == MatchingVectorType) {
6091 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6092 N0.getOperand(0), N0.getOperand(1),
6093 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6094 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6098 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6099 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6102 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6104 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6105 NegOne, DAG.getConstant(0, DL, VT),
6106 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6107 if (SCC.getNode()) return SCC;
6109 if (!VT.isVector()) {
6110 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6111 if (!LegalOperations ||
6112 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6114 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6115 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6116 N0.getOperand(0), N0.getOperand(1), CC);
6117 return DAG.getSelect(DL, VT, SetCC,
6118 NegOne, DAG.getConstant(0, DL, VT));
6123 // fold (sext x) -> (zext x) if the sign bit is known zero.
6124 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6125 DAG.SignBitIsZero(N0))
6126 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6131 // isTruncateOf - If N is a truncate of some other value, return true, record
6132 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6133 // This function computes KnownZero to avoid a duplicated call to
6134 // computeKnownBits in the caller.
6135 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6138 if (N->getOpcode() == ISD::TRUNCATE) {
6139 Op = N->getOperand(0);
6140 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6144 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6145 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6148 SDValue Op0 = N->getOperand(0);
6149 SDValue Op1 = N->getOperand(1);
6150 assert(Op0.getValueType() == Op1.getValueType());
6152 if (isNullConstant(Op0))
6154 else if (isNullConstant(Op1))
6159 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6161 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6167 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6168 SDValue N0 = N->getOperand(0);
6169 EVT VT = N->getValueType(0);
6171 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6173 return SDValue(Res, 0);
6175 // fold (zext (zext x)) -> (zext x)
6176 // fold (zext (aext x)) -> (zext x)
6177 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6178 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6181 // fold (zext (truncate x)) -> (zext x) or
6182 // (zext (truncate x)) -> (truncate x)
6183 // This is valid when the truncated bits of x are already zero.
6184 // FIXME: We should extend this to work for vectors too.
6187 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6188 APInt TruncatedBits =
6189 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6190 APInt(Op.getValueSizeInBits(), 0) :
6191 APInt::getBitsSet(Op.getValueSizeInBits(),
6192 N0.getValueSizeInBits(),
6193 std::min(Op.getValueSizeInBits(),
6194 VT.getSizeInBits()));
6195 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6196 if (VT.bitsGT(Op.getValueType()))
6197 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6198 if (VT.bitsLT(Op.getValueType()))
6199 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6205 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6206 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6207 if (N0.getOpcode() == ISD::TRUNCATE) {
6208 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6209 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6210 if (NarrowLoad.getNode() != N0.getNode()) {
6211 CombineTo(N0.getNode(), NarrowLoad);
6212 // CombineTo deleted the truncate, if needed, but not what's under it.
6215 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6219 // fold (zext (truncate x)) -> (and x, mask)
6220 if (N0.getOpcode() == ISD::TRUNCATE) {
6221 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6222 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6223 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6224 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6225 if (NarrowLoad.getNode() != N0.getNode()) {
6226 CombineTo(N0.getNode(), NarrowLoad);
6227 // CombineTo deleted the truncate, if needed, but not what's under it.
6230 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6233 EVT SrcVT = N0.getOperand(0).getValueType();
6234 EVT MinVT = N0.getValueType();
6236 // Try to mask before the extension to avoid having to generate a larger mask,
6237 // possibly over several sub-vectors.
6238 if (SrcVT.bitsLT(VT)) {
6239 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6240 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6241 SDValue Op = N0.getOperand(0);
6242 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6243 AddToWorklist(Op.getNode());
6244 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6248 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6249 SDValue Op = N0.getOperand(0);
6250 if (SrcVT.bitsLT(VT)) {
6251 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6252 AddToWorklist(Op.getNode());
6253 } else if (SrcVT.bitsGT(VT)) {
6254 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6255 AddToWorklist(Op.getNode());
6257 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6261 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6262 // if either of the casts is not free.
6263 if (N0.getOpcode() == ISD::AND &&
6264 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6265 N0.getOperand(1).getOpcode() == ISD::Constant &&
6266 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6267 N0.getValueType()) ||
6268 !TLI.isZExtFree(N0.getValueType(), VT))) {
6269 SDValue X = N0.getOperand(0).getOperand(0);
6270 if (X.getValueType().bitsLT(VT)) {
6271 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6272 } else if (X.getValueType().bitsGT(VT)) {
6273 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6275 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6276 Mask = Mask.zext(VT.getSizeInBits());
6278 return DAG.getNode(ISD::AND, DL, VT,
6279 X, DAG.getConstant(Mask, DL, VT));
6282 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6283 // Only generate vector extloads when 1) they're legal, and 2) they are
6284 // deemed desirable by the target.
6285 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6286 ((!LegalOperations && !VT.isVector() &&
6287 !cast<LoadSDNode>(N0)->isVolatile()) ||
6288 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6289 bool DoXform = true;
6290 SmallVector<SDNode*, 4> SetCCs;
6291 if (!N0.hasOneUse())
6292 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6294 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6296 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6297 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6299 LN0->getBasePtr(), N0.getValueType(),
6300 LN0->getMemOperand());
6301 CombineTo(N, ExtLoad);
6302 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6303 N0.getValueType(), ExtLoad);
6304 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6306 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6308 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6312 // fold (zext (load x)) to multiple smaller zextloads.
6313 // Only on illegal but splittable vectors.
6314 if (SDValue ExtLoad = CombineExtLoad(N))
6317 // fold (zext (and/or/xor (load x), cst)) ->
6318 // (and/or/xor (zextload x), (zext cst))
6319 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6320 N0.getOpcode() == ISD::XOR) &&
6321 isa<LoadSDNode>(N0.getOperand(0)) &&
6322 N0.getOperand(1).getOpcode() == ISD::Constant &&
6323 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6324 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6325 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6326 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6327 bool DoXform = true;
6328 SmallVector<SDNode*, 4> SetCCs;
6329 if (!N0.hasOneUse())
6330 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6333 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6334 LN0->getChain(), LN0->getBasePtr(),
6336 LN0->getMemOperand());
6337 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6338 Mask = Mask.zext(VT.getSizeInBits());
6340 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6341 ExtLoad, DAG.getConstant(Mask, DL, VT));
6342 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6343 SDLoc(N0.getOperand(0)),
6344 N0.getOperand(0).getValueType(), ExtLoad);
6346 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6347 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6349 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6354 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6355 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6356 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6357 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6358 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6359 EVT MemVT = LN0->getMemoryVT();
6360 if ((!LegalOperations && !LN0->isVolatile()) ||
6361 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6362 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6364 LN0->getBasePtr(), MemVT,
6365 LN0->getMemOperand());
6366 CombineTo(N, ExtLoad);
6367 CombineTo(N0.getNode(),
6368 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6370 ExtLoad.getValue(1));
6371 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6375 if (N0.getOpcode() == ISD::SETCC) {
6376 if (!LegalOperations && VT.isVector() &&
6377 N0.getValueType().getVectorElementType() == MVT::i1) {
6378 EVT N0VT = N0.getOperand(0).getValueType();
6379 if (getSetCCResultType(N0VT) == N0.getValueType())
6382 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6383 // Only do this before legalize for now.
6384 EVT EltVT = VT.getVectorElementType();
6386 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6387 DAG.getConstant(1, DL, EltVT));
6388 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6389 // We know that the # elements of the results is the same as the
6390 // # elements of the compare (and the # elements of the compare result
6391 // for that matter). Check to see that they are the same size. If so,
6392 // we know that the element size of the sext'd result matches the
6393 // element size of the compare operands.
6394 return DAG.getNode(ISD::AND, DL, VT,
6395 DAG.getSetCC(DL, VT, N0.getOperand(0),
6397 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6398 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6401 // If the desired elements are smaller or larger than the source
6402 // elements we can use a matching integer vector type and then
6403 // truncate/sign extend
6404 EVT MatchingElementType =
6405 EVT::getIntegerVT(*DAG.getContext(),
6406 N0VT.getScalarType().getSizeInBits());
6407 EVT MatchingVectorType =
6408 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6409 N0VT.getVectorNumElements());
6411 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6413 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6414 return DAG.getNode(ISD::AND, DL, VT,
6415 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6416 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6419 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6422 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6423 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6424 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6425 if (SCC.getNode()) return SCC;
6428 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6429 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6430 isa<ConstantSDNode>(N0.getOperand(1)) &&
6431 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6433 SDValue ShAmt = N0.getOperand(1);
6434 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6435 if (N0.getOpcode() == ISD::SHL) {
6436 SDValue InnerZExt = N0.getOperand(0);
6437 // If the original shl may be shifting out bits, do not perform this
6439 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6440 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6441 if (ShAmtVal > KnownZeroBits)
6447 // Ensure that the shift amount is wide enough for the shifted value.
6448 if (VT.getSizeInBits() >= 256)
6449 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6451 return DAG.getNode(N0.getOpcode(), DL, VT,
6452 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6459 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6460 SDValue N0 = N->getOperand(0);
6461 EVT VT = N->getValueType(0);
6463 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6465 return SDValue(Res, 0);
6467 // fold (aext (aext x)) -> (aext x)
6468 // fold (aext (zext x)) -> (zext x)
6469 // fold (aext (sext x)) -> (sext x)
6470 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6471 N0.getOpcode() == ISD::ZERO_EXTEND ||
6472 N0.getOpcode() == ISD::SIGN_EXTEND)
6473 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6475 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6476 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6477 if (N0.getOpcode() == ISD::TRUNCATE) {
6478 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6479 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6480 if (NarrowLoad.getNode() != N0.getNode()) {
6481 CombineTo(N0.getNode(), NarrowLoad);
6482 // CombineTo deleted the truncate, if needed, but not what's under it.
6485 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6489 // fold (aext (truncate x))
6490 if (N0.getOpcode() == ISD::TRUNCATE) {
6491 SDValue TruncOp = N0.getOperand(0);
6492 if (TruncOp.getValueType() == VT)
6493 return TruncOp; // x iff x size == zext size.
6494 if (TruncOp.getValueType().bitsGT(VT))
6495 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6496 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6499 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6500 // if the trunc is not free.
6501 if (N0.getOpcode() == ISD::AND &&
6502 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6503 N0.getOperand(1).getOpcode() == ISD::Constant &&
6504 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6505 N0.getValueType())) {
6506 SDValue X = N0.getOperand(0).getOperand(0);
6507 if (X.getValueType().bitsLT(VT)) {
6508 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6509 } else if (X.getValueType().bitsGT(VT)) {
6510 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6512 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6513 Mask = Mask.zext(VT.getSizeInBits());
6515 return DAG.getNode(ISD::AND, DL, VT,
6516 X, DAG.getConstant(Mask, DL, VT));
6519 // fold (aext (load x)) -> (aext (truncate (extload x)))
6520 // None of the supported targets knows how to perform load and any_ext
6521 // on vectors in one instruction. We only perform this transformation on
6523 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6524 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6525 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6526 bool DoXform = true;
6527 SmallVector<SDNode*, 4> SetCCs;
6528 if (!N0.hasOneUse())
6529 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6531 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6532 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6534 LN0->getBasePtr(), N0.getValueType(),
6535 LN0->getMemOperand());
6536 CombineTo(N, ExtLoad);
6537 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6538 N0.getValueType(), ExtLoad);
6539 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6540 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6542 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6546 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6547 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6548 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6549 if (N0.getOpcode() == ISD::LOAD &&
6550 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6552 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6553 ISD::LoadExtType ExtType = LN0->getExtensionType();
6554 EVT MemVT = LN0->getMemoryVT();
6555 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6556 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6557 VT, LN0->getChain(), LN0->getBasePtr(),
6558 MemVT, LN0->getMemOperand());
6559 CombineTo(N, ExtLoad);
6560 CombineTo(N0.getNode(),
6561 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6562 N0.getValueType(), ExtLoad),
6563 ExtLoad.getValue(1));
6564 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6568 if (N0.getOpcode() == ISD::SETCC) {
6570 // aext(setcc) -> vsetcc
6571 // aext(setcc) -> truncate(vsetcc)
6572 // aext(setcc) -> aext(vsetcc)
6573 // Only do this before legalize for now.
6574 if (VT.isVector() && !LegalOperations) {
6575 EVT N0VT = N0.getOperand(0).getValueType();
6576 // We know that the # elements of the results is the same as the
6577 // # elements of the compare (and the # elements of the compare result
6578 // for that matter). Check to see that they are the same size. If so,
6579 // we know that the element size of the sext'd result matches the
6580 // element size of the compare operands.
6581 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6582 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6584 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6585 // If the desired elements are smaller or larger than the source
6586 // elements we can use a matching integer vector type and then
6587 // truncate/any extend
6589 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6591 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6593 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6594 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6598 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6601 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6602 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6603 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6611 /// See if the specified operand can be simplified with the knowledge that only
6612 /// the bits specified by Mask are used. If so, return the simpler operand,
6613 /// otherwise return a null SDValue.
6614 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6615 switch (V.getOpcode()) {
6617 case ISD::Constant: {
6618 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6619 assert(CV && "Const value should be ConstSDNode.");
6620 const APInt &CVal = CV->getAPIntValue();
6621 APInt NewVal = CVal & Mask;
6623 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6628 // If the LHS or RHS don't contribute bits to the or, drop them.
6629 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6630 return V.getOperand(1);
6631 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6632 return V.getOperand(0);
6635 // Only look at single-use SRLs.
6636 if (!V.getNode()->hasOneUse())
6638 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6639 // See if we can recursively simplify the LHS.
6640 unsigned Amt = RHSC->getZExtValue();
6642 // Watch out for shift count overflow though.
6643 if (Amt >= Mask.getBitWidth()) break;
6644 APInt NewMask = Mask << Amt;
6645 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6646 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6647 SimplifyLHS, V.getOperand(1));
6653 /// If the result of a wider load is shifted to right of N bits and then
6654 /// truncated to a narrower type and where N is a multiple of number of bits of
6655 /// the narrower type, transform it to a narrower load from address + N / num of
6656 /// bits of new type. If the result is to be extended, also fold the extension
6657 /// to form a extending load.
6658 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6659 unsigned Opc = N->getOpcode();
6661 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6662 SDValue N0 = N->getOperand(0);
6663 EVT VT = N->getValueType(0);
6666 // This transformation isn't valid for vector loads.
6670 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6672 if (Opc == ISD::SIGN_EXTEND_INREG) {
6673 ExtType = ISD::SEXTLOAD;
6674 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6675 } else if (Opc == ISD::SRL) {
6676 // Another special-case: SRL is basically zero-extending a narrower value.
6677 ExtType = ISD::ZEXTLOAD;
6679 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6680 if (!N01) return SDValue();
6681 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6682 VT.getSizeInBits() - N01->getZExtValue());
6684 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6687 unsigned EVTBits = ExtVT.getSizeInBits();
6689 // Do not generate loads of non-round integer types since these can
6690 // be expensive (and would be wrong if the type is not byte sized).
6691 if (!ExtVT.isRound())
6695 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6696 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6697 ShAmt = N01->getZExtValue();
6698 // Is the shift amount a multiple of size of VT?
6699 if ((ShAmt & (EVTBits-1)) == 0) {
6700 N0 = N0.getOperand(0);
6701 // Is the load width a multiple of size of VT?
6702 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6706 // At this point, we must have a load or else we can't do the transform.
6707 if (!isa<LoadSDNode>(N0)) return SDValue();
6709 // Because a SRL must be assumed to *need* to zero-extend the high bits
6710 // (as opposed to anyext the high bits), we can't combine the zextload
6711 // lowering of SRL and an sextload.
6712 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6715 // If the shift amount is larger than the input type then we're not
6716 // accessing any of the loaded bytes. If the load was a zextload/extload
6717 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6718 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6723 // If the load is shifted left (and the result isn't shifted back right),
6724 // we can fold the truncate through the shift.
6725 unsigned ShLeftAmt = 0;
6726 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6727 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6728 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6729 ShLeftAmt = N01->getZExtValue();
6730 N0 = N0.getOperand(0);
6734 // If we haven't found a load, we can't narrow it. Don't transform one with
6735 // multiple uses, this would require adding a new load.
6736 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6739 // Don't change the width of a volatile load.
6740 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6741 if (LN0->isVolatile())
6744 // Verify that we are actually reducing a load width here.
6745 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6748 // For the transform to be legal, the load must produce only two values
6749 // (the value loaded and the chain). Don't transform a pre-increment
6750 // load, for example, which produces an extra value. Otherwise the
6751 // transformation is not equivalent, and the downstream logic to replace
6752 // uses gets things wrong.
6753 if (LN0->getNumValues() > 2)
6756 // If the load that we're shrinking is an extload and we're not just
6757 // discarding the extension we can't simply shrink the load. Bail.
6758 // TODO: It would be possible to merge the extensions in some cases.
6759 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6760 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6763 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6766 EVT PtrType = N0.getOperand(1).getValueType();
6768 if (PtrType == MVT::Untyped || PtrType.isExtended())
6769 // It's not possible to generate a constant of extended or untyped type.
6772 // For big endian targets, we need to adjust the offset to the pointer to
6773 // load the correct bytes.
6774 if (DAG.getDataLayout().isBigEndian()) {
6775 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6776 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6777 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6780 uint64_t PtrOff = ShAmt / 8;
6781 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6783 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6784 PtrType, LN0->getBasePtr(),
6785 DAG.getConstant(PtrOff, DL, PtrType));
6786 AddToWorklist(NewPtr.getNode());
6789 if (ExtType == ISD::NON_EXTLOAD)
6790 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6791 LN0->getPointerInfo().getWithOffset(PtrOff),
6792 LN0->isVolatile(), LN0->isNonTemporal(),
6793 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6795 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6796 LN0->getPointerInfo().getWithOffset(PtrOff),
6797 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6798 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6800 // Replace the old load's chain with the new load's chain.
6801 WorklistRemover DeadNodes(*this);
6802 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6804 // Shift the result left, if we've swallowed a left shift.
6805 SDValue Result = Load;
6806 if (ShLeftAmt != 0) {
6807 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6808 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6810 // If the shift amount is as large as the result size (but, presumably,
6811 // no larger than the source) then the useful bits of the result are
6812 // zero; we can't simply return the shortened shift, because the result
6813 // of that operation is undefined.
6815 if (ShLeftAmt >= VT.getSizeInBits())
6816 Result = DAG.getConstant(0, DL, VT);
6818 Result = DAG.getNode(ISD::SHL, DL, VT,
6819 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6822 // Return the new loaded value.
6826 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6827 SDValue N0 = N->getOperand(0);
6828 SDValue N1 = N->getOperand(1);
6829 EVT VT = N->getValueType(0);
6830 EVT EVT = cast<VTSDNode>(N1)->getVT();
6831 unsigned VTBits = VT.getScalarType().getSizeInBits();
6832 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6835 return DAG.getUNDEF(VT);
6837 // fold (sext_in_reg c1) -> c1
6838 if (isConstantIntBuildVectorOrConstantInt(N0))
6839 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6841 // If the input is already sign extended, just drop the extension.
6842 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6845 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6846 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6847 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6848 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6849 N0.getOperand(0), N1);
6851 // fold (sext_in_reg (sext x)) -> (sext x)
6852 // fold (sext_in_reg (aext x)) -> (sext x)
6853 // if x is small enough.
6854 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6855 SDValue N00 = N0.getOperand(0);
6856 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6857 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6858 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6861 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6862 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6863 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6865 // fold operands of sext_in_reg based on knowledge that the top bits are not
6867 if (SimplifyDemandedBits(SDValue(N, 0)))
6868 return SDValue(N, 0);
6870 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6871 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6872 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6875 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6876 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6877 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6878 if (N0.getOpcode() == ISD::SRL) {
6879 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6880 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6881 // We can turn this into an SRA iff the input to the SRL is already sign
6883 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6884 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6885 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6886 N0.getOperand(0), N0.getOperand(1));
6890 // fold (sext_inreg (extload x)) -> (sextload x)
6891 if (ISD::isEXTLoad(N0.getNode()) &&
6892 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6893 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6894 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6895 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6896 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6897 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6899 LN0->getBasePtr(), EVT,
6900 LN0->getMemOperand());
6901 CombineTo(N, ExtLoad);
6902 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6903 AddToWorklist(ExtLoad.getNode());
6904 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6906 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6907 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6909 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6910 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6911 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6912 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6913 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6915 LN0->getBasePtr(), EVT,
6916 LN0->getMemOperand());
6917 CombineTo(N, ExtLoad);
6918 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6919 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6922 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6923 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6924 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6925 N0.getOperand(1), false);
6926 if (BSwap.getNode())
6927 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6934 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6935 SDValue N0 = N->getOperand(0);
6936 EVT VT = N->getValueType(0);
6938 if (N0.getOpcode() == ISD::UNDEF)
6939 return DAG.getUNDEF(VT);
6941 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6943 return SDValue(Res, 0);
6948 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6949 SDValue N0 = N->getOperand(0);
6950 EVT VT = N->getValueType(0);
6951 bool isLE = DAG.getDataLayout().isLittleEndian();
6954 if (N0.getValueType() == N->getValueType(0))
6956 // fold (truncate c1) -> c1
6957 if (isConstantIntBuildVectorOrConstantInt(N0))
6958 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6959 // fold (truncate (truncate x)) -> (truncate x)
6960 if (N0.getOpcode() == ISD::TRUNCATE)
6961 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6962 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6963 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6964 N0.getOpcode() == ISD::SIGN_EXTEND ||
6965 N0.getOpcode() == ISD::ANY_EXTEND) {
6966 if (N0.getOperand(0).getValueType().bitsLT(VT))
6967 // if the source is smaller than the dest, we still need an extend
6968 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6970 if (N0.getOperand(0).getValueType().bitsGT(VT))
6971 // if the source is larger than the dest, than we just need the truncate
6972 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6973 // if the source and dest are the same type, we can drop both the extend
6974 // and the truncate.
6975 return N0.getOperand(0);
6978 // Fold extract-and-trunc into a narrow extract. For example:
6979 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6980 // i32 y = TRUNCATE(i64 x)
6982 // v16i8 b = BITCAST (v2i64 val)
6983 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6985 // Note: We only run this optimization after type legalization (which often
6986 // creates this pattern) and before operation legalization after which
6987 // we need to be more careful about the vector instructions that we generate.
6988 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6989 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6991 EVT VecTy = N0.getOperand(0).getValueType();
6992 EVT ExTy = N0.getValueType();
6993 EVT TrTy = N->getValueType(0);
6995 unsigned NumElem = VecTy.getVectorNumElements();
6996 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6998 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6999 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7001 SDValue EltNo = N0->getOperand(1);
7002 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7003 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7004 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7005 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7007 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7008 NVT, N0.getOperand(0));
7011 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7013 DAG.getConstant(Index, DL, IndexTy));
7017 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7018 if (N0.getOpcode() == ISD::SELECT) {
7019 EVT SrcVT = N0.getValueType();
7020 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7021 TLI.isTruncateFree(SrcVT, VT)) {
7023 SDValue Cond = N0.getOperand(0);
7024 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7025 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7026 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7030 // Fold a series of buildvector, bitcast, and truncate if possible.
7032 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7033 // (2xi32 (buildvector x, y)).
7034 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7035 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7036 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7037 N0.getOperand(0).hasOneUse()) {
7039 SDValue BuildVect = N0.getOperand(0);
7040 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7041 EVT TruncVecEltTy = VT.getVectorElementType();
7043 // Check that the element types match.
7044 if (BuildVectEltTy == TruncVecEltTy) {
7045 // Now we only need to compute the offset of the truncated elements.
7046 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7047 unsigned TruncVecNumElts = VT.getVectorNumElements();
7048 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7050 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7051 "Invalid number of elements");
7053 SmallVector<SDValue, 8> Opnds;
7054 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7055 Opnds.push_back(BuildVect.getOperand(i));
7057 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7061 // See if we can simplify the input to this truncate through knowledge that
7062 // only the low bits are being used.
7063 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7064 // Currently we only perform this optimization on scalars because vectors
7065 // may have different active low bits.
7066 if (!VT.isVector()) {
7068 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7069 VT.getSizeInBits()));
7070 if (Shorter.getNode())
7071 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7073 // fold (truncate (load x)) -> (smaller load x)
7074 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7075 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7076 if (SDValue Reduced = ReduceLoadWidth(N))
7079 // Handle the case where the load remains an extending load even
7080 // after truncation.
7081 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7082 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7083 if (!LN0->isVolatile() &&
7084 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7085 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7086 VT, LN0->getChain(), LN0->getBasePtr(),
7088 LN0->getMemOperand());
7089 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7094 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7095 // where ... are all 'undef'.
7096 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7097 SmallVector<EVT, 8> VTs;
7100 unsigned NumDefs = 0;
7102 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7103 SDValue X = N0.getOperand(i);
7104 if (X.getOpcode() != ISD::UNDEF) {
7109 // Stop if more than one members are non-undef.
7112 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7113 VT.getVectorElementType(),
7114 X.getValueType().getVectorNumElements()));
7118 return DAG.getUNDEF(VT);
7121 assert(V.getNode() && "The single defined operand is empty!");
7122 SmallVector<SDValue, 8> Opnds;
7123 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7125 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7128 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7129 AddToWorklist(NV.getNode());
7130 Opnds.push_back(NV);
7132 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7136 // Simplify the operands using demanded-bits information.
7137 if (!VT.isVector() &&
7138 SimplifyDemandedBits(SDValue(N, 0)))
7139 return SDValue(N, 0);
7144 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7145 SDValue Elt = N->getOperand(i);
7146 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7147 return Elt.getNode();
7148 return Elt.getOperand(Elt.getResNo()).getNode();
7151 /// build_pair (load, load) -> load
7152 /// if load locations are consecutive.
7153 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7154 assert(N->getOpcode() == ISD::BUILD_PAIR);
7156 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7157 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7158 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7159 LD1->getAddressSpace() != LD2->getAddressSpace())
7161 EVT LD1VT = LD1->getValueType(0);
7163 if (ISD::isNON_EXTLoad(LD2) &&
7165 // If both are volatile this would reduce the number of volatile loads.
7166 // If one is volatile it might be ok, but play conservative and bail out.
7167 !LD1->isVolatile() &&
7168 !LD2->isVolatile() &&
7169 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7170 unsigned Align = LD1->getAlignment();
7171 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7172 VT.getTypeForEVT(*DAG.getContext()));
7174 if (NewAlign <= Align &&
7175 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7176 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7177 LD1->getBasePtr(), LD1->getPointerInfo(),
7178 false, false, false, Align);
7184 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7185 SDValue N0 = N->getOperand(0);
7186 EVT VT = N->getValueType(0);
7188 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7189 // Only do this before legalize, since afterward the target may be depending
7190 // on the bitconvert.
7191 // First check to see if this is all constant.
7193 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7195 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7197 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7198 assert(!DestEltVT.isVector() &&
7199 "Element type of vector ValueType must not be vector!");
7201 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7204 // If the input is a constant, let getNode fold it.
7205 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7206 // If we can't allow illegal operations, we need to check that this is just
7207 // a fp -> int or int -> conversion and that the resulting operation will
7209 if (!LegalOperations ||
7210 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7211 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7212 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7213 TLI.isOperationLegal(ISD::Constant, VT)))
7214 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7217 // (conv (conv x, t1), t2) -> (conv x, t2)
7218 if (N0.getOpcode() == ISD::BITCAST)
7219 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7222 // fold (conv (load x)) -> (load (conv*)x)
7223 // If the resultant load doesn't need a higher alignment than the original!
7224 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7225 // Do not change the width of a volatile load.
7226 !cast<LoadSDNode>(N0)->isVolatile() &&
7227 // Do not remove the cast if the types differ in endian layout.
7228 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7229 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7230 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7231 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7232 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7233 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7234 VT.getTypeForEVT(*DAG.getContext()));
7235 unsigned OrigAlign = LN0->getAlignment();
7237 if (Align <= OrigAlign) {
7238 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7239 LN0->getBasePtr(), LN0->getPointerInfo(),
7240 LN0->isVolatile(), LN0->isNonTemporal(),
7241 LN0->isInvariant(), OrigAlign,
7243 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7248 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7249 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7250 // This often reduces constant pool loads.
7251 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7252 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7253 N0.getNode()->hasOneUse() && VT.isInteger() &&
7254 !VT.isVector() && !N0.getValueType().isVector()) {
7255 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7257 AddToWorklist(NewConv.getNode());
7260 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7261 if (N0.getOpcode() == ISD::FNEG)
7262 return DAG.getNode(ISD::XOR, DL, VT,
7263 NewConv, DAG.getConstant(SignBit, DL, VT));
7264 assert(N0.getOpcode() == ISD::FABS);
7265 return DAG.getNode(ISD::AND, DL, VT,
7266 NewConv, DAG.getConstant(~SignBit, DL, VT));
7269 // fold (bitconvert (fcopysign cst, x)) ->
7270 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7271 // Note that we don't handle (copysign x, cst) because this can always be
7272 // folded to an fneg or fabs.
7273 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7274 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7275 VT.isInteger() && !VT.isVector()) {
7276 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7277 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7278 if (isTypeLegal(IntXVT)) {
7279 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7280 IntXVT, N0.getOperand(1));
7281 AddToWorklist(X.getNode());
7283 // If X has a different width than the result/lhs, sext it or truncate it.
7284 unsigned VTWidth = VT.getSizeInBits();
7285 if (OrigXWidth < VTWidth) {
7286 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7287 AddToWorklist(X.getNode());
7288 } else if (OrigXWidth > VTWidth) {
7289 // To get the sign bit in the right place, we have to shift it right
7290 // before truncating.
7292 X = DAG.getNode(ISD::SRL, DL,
7293 X.getValueType(), X,
7294 DAG.getConstant(OrigXWidth-VTWidth, DL,
7296 AddToWorklist(X.getNode());
7297 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7298 AddToWorklist(X.getNode());
7301 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7302 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7303 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7304 AddToWorklist(X.getNode());
7306 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7307 VT, N0.getOperand(0));
7308 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7309 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7310 AddToWorklist(Cst.getNode());
7312 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7316 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7317 if (N0.getOpcode() == ISD::BUILD_PAIR)
7318 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7321 // Remove double bitcasts from shuffles - this is often a legacy of
7322 // XformToShuffleWithZero being used to combine bitmaskings (of
7323 // float vectors bitcast to integer vectors) into shuffles.
7324 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7325 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7326 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7327 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7328 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7329 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7331 // If operands are a bitcast, peek through if it casts the original VT.
7332 // If operands are a constant, just bitcast back to original VT.
7333 auto PeekThroughBitcast = [&](SDValue Op) {
7334 if (Op.getOpcode() == ISD::BITCAST &&
7335 Op.getOperand(0).getValueType() == VT)
7336 return SDValue(Op.getOperand(0));
7337 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7338 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7339 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7343 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7344 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7349 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7350 SmallVector<int, 8> NewMask;
7351 for (int M : SVN->getMask())
7352 for (int i = 0; i != MaskScale; ++i)
7353 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7355 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7357 std::swap(SV0, SV1);
7358 ShuffleVectorSDNode::commuteMask(NewMask);
7359 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7363 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7369 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7370 EVT VT = N->getValueType(0);
7371 return CombineConsecutiveLoads(N, VT);
7374 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7375 /// operands. DstEltVT indicates the destination element value type.
7376 SDValue DAGCombiner::
7377 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7378 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7380 // If this is already the right type, we're done.
7381 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7383 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7384 unsigned DstBitSize = DstEltVT.getSizeInBits();
7386 // If this is a conversion of N elements of one type to N elements of another
7387 // type, convert each element. This handles FP<->INT cases.
7388 if (SrcBitSize == DstBitSize) {
7389 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7390 BV->getValueType(0).getVectorNumElements());
7392 // Due to the FP element handling below calling this routine recursively,
7393 // we can end up with a scalar-to-vector node here.
7394 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7395 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7396 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7397 DstEltVT, BV->getOperand(0)));
7399 SmallVector<SDValue, 8> Ops;
7400 for (SDValue Op : BV->op_values()) {
7401 // If the vector element type is not legal, the BUILD_VECTOR operands
7402 // are promoted and implicitly truncated. Make that explicit here.
7403 if (Op.getValueType() != SrcEltVT)
7404 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7405 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7407 AddToWorklist(Ops.back().getNode());
7409 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7412 // Otherwise, we're growing or shrinking the elements. To avoid having to
7413 // handle annoying details of growing/shrinking FP values, we convert them to
7415 if (SrcEltVT.isFloatingPoint()) {
7416 // Convert the input float vector to a int vector where the elements are the
7418 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7419 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7423 // Now we know the input is an integer vector. If the output is a FP type,
7424 // convert to integer first, then to FP of the right size.
7425 if (DstEltVT.isFloatingPoint()) {
7426 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7427 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7429 // Next, convert to FP elements of the same size.
7430 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7435 // Okay, we know the src/dst types are both integers of differing types.
7436 // Handling growing first.
7437 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7438 if (SrcBitSize < DstBitSize) {
7439 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7441 SmallVector<SDValue, 8> Ops;
7442 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7443 i += NumInputsPerOutput) {
7444 bool isLE = DAG.getDataLayout().isLittleEndian();
7445 APInt NewBits = APInt(DstBitSize, 0);
7446 bool EltIsUndef = true;
7447 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7448 // Shift the previously computed bits over.
7449 NewBits <<= SrcBitSize;
7450 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7451 if (Op.getOpcode() == ISD::UNDEF) continue;
7454 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7455 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7459 Ops.push_back(DAG.getUNDEF(DstEltVT));
7461 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7464 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7465 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7468 // Finally, this must be the case where we are shrinking elements: each input
7469 // turns into multiple outputs.
7470 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7471 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7472 NumOutputsPerInput*BV->getNumOperands());
7473 SmallVector<SDValue, 8> Ops;
7475 for (const SDValue &Op : BV->op_values()) {
7476 if (Op.getOpcode() == ISD::UNDEF) {
7477 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7481 APInt OpVal = cast<ConstantSDNode>(Op)->
7482 getAPIntValue().zextOrTrunc(SrcBitSize);
7484 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7485 APInt ThisVal = OpVal.trunc(DstBitSize);
7486 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7487 OpVal = OpVal.lshr(DstBitSize);
7490 // For big endian targets, swap the order of the pieces of each element.
7491 if (DAG.getDataLayout().isBigEndian())
7492 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7495 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7498 /// Try to perform FMA combining on a given FADD node.
7499 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7500 SDValue N0 = N->getOperand(0);
7501 SDValue N1 = N->getOperand(1);
7502 EVT VT = N->getValueType(0);
7505 const TargetOptions &Options = DAG.getTarget().Options;
7507 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7509 // Floating-point multiply-add with intermediate rounding.
7510 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7512 // Floating-point multiply-add without intermediate rounding.
7514 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7515 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7517 // No valid opcode, do not combine.
7518 if (!HasFMAD && !HasFMA)
7521 // Always prefer FMAD to FMA for precision.
7522 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7523 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7524 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7526 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7527 // prefer to fold the multiply with fewer uses.
7528 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7529 N1.getOpcode() == ISD::FMUL) {
7530 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7534 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7535 if (N0.getOpcode() == ISD::FMUL &&
7536 (Aggressive || N0->hasOneUse())) {
7537 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7538 N0.getOperand(0), N0.getOperand(1), N1);
7541 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7542 // Note: Commutes FADD operands.
7543 if (N1.getOpcode() == ISD::FMUL &&
7544 (Aggressive || N1->hasOneUse())) {
7545 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7546 N1.getOperand(0), N1.getOperand(1), N0);
7549 // Look through FP_EXTEND nodes to do more combining.
7550 if (AllowFusion && LookThroughFPExt) {
7551 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7552 if (N0.getOpcode() == ISD::FP_EXTEND) {
7553 SDValue N00 = N0.getOperand(0);
7554 if (N00.getOpcode() == ISD::FMUL)
7555 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7556 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7558 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7559 N00.getOperand(1)), N1);
7562 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7563 // Note: Commutes FADD operands.
7564 if (N1.getOpcode() == ISD::FP_EXTEND) {
7565 SDValue N10 = N1.getOperand(0);
7566 if (N10.getOpcode() == ISD::FMUL)
7567 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7568 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7570 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7571 N10.getOperand(1)), N0);
7575 // More folding opportunities when target permits.
7576 if ((AllowFusion || HasFMAD) && Aggressive) {
7577 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7578 if (N0.getOpcode() == PreferredFusedOpcode &&
7579 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7580 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7581 N0.getOperand(0), N0.getOperand(1),
7582 DAG.getNode(PreferredFusedOpcode, SL, VT,
7583 N0.getOperand(2).getOperand(0),
7584 N0.getOperand(2).getOperand(1),
7588 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7589 if (N1->getOpcode() == PreferredFusedOpcode &&
7590 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7591 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7592 N1.getOperand(0), N1.getOperand(1),
7593 DAG.getNode(PreferredFusedOpcode, SL, VT,
7594 N1.getOperand(2).getOperand(0),
7595 N1.getOperand(2).getOperand(1),
7599 if (AllowFusion && LookThroughFPExt) {
7600 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7601 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7602 auto FoldFAddFMAFPExtFMul = [&] (
7603 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7604 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7605 DAG.getNode(PreferredFusedOpcode, SL, VT,
7606 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7607 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7610 if (N0.getOpcode() == PreferredFusedOpcode) {
7611 SDValue N02 = N0.getOperand(2);
7612 if (N02.getOpcode() == ISD::FP_EXTEND) {
7613 SDValue N020 = N02.getOperand(0);
7614 if (N020.getOpcode() == ISD::FMUL)
7615 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7616 N020.getOperand(0), N020.getOperand(1),
7621 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7622 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7623 // FIXME: This turns two single-precision and one double-precision
7624 // operation into two double-precision operations, which might not be
7625 // interesting for all targets, especially GPUs.
7626 auto FoldFAddFPExtFMAFMul = [&] (
7627 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7628 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7629 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7630 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7631 DAG.getNode(PreferredFusedOpcode, SL, VT,
7632 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7633 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7636 if (N0.getOpcode() == ISD::FP_EXTEND) {
7637 SDValue N00 = N0.getOperand(0);
7638 if (N00.getOpcode() == PreferredFusedOpcode) {
7639 SDValue N002 = N00.getOperand(2);
7640 if (N002.getOpcode() == ISD::FMUL)
7641 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7642 N002.getOperand(0), N002.getOperand(1),
7647 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7648 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7649 if (N1.getOpcode() == PreferredFusedOpcode) {
7650 SDValue N12 = N1.getOperand(2);
7651 if (N12.getOpcode() == ISD::FP_EXTEND) {
7652 SDValue N120 = N12.getOperand(0);
7653 if (N120.getOpcode() == ISD::FMUL)
7654 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7655 N120.getOperand(0), N120.getOperand(1),
7660 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7661 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7662 // FIXME: This turns two single-precision and one double-precision
7663 // operation into two double-precision operations, which might not be
7664 // interesting for all targets, especially GPUs.
7665 if (N1.getOpcode() == ISD::FP_EXTEND) {
7666 SDValue N10 = N1.getOperand(0);
7667 if (N10.getOpcode() == PreferredFusedOpcode) {
7668 SDValue N102 = N10.getOperand(2);
7669 if (N102.getOpcode() == ISD::FMUL)
7670 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7671 N102.getOperand(0), N102.getOperand(1),
7681 /// Try to perform FMA combining on a given FSUB node.
7682 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7683 SDValue N0 = N->getOperand(0);
7684 SDValue N1 = N->getOperand(1);
7685 EVT VT = N->getValueType(0);
7688 const TargetOptions &Options = DAG.getTarget().Options;
7690 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7692 // Floating-point multiply-add with intermediate rounding.
7693 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7695 // Floating-point multiply-add without intermediate rounding.
7697 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7698 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7700 // No valid opcode, do not combine.
7701 if (!HasFMAD && !HasFMA)
7704 // Always prefer FMAD to FMA for precision.
7705 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7706 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7707 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7709 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7710 if (N0.getOpcode() == ISD::FMUL &&
7711 (Aggressive || N0->hasOneUse())) {
7712 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7713 N0.getOperand(0), N0.getOperand(1),
7714 DAG.getNode(ISD::FNEG, SL, VT, N1));
7717 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7718 // Note: Commutes FSUB operands.
7719 if (N1.getOpcode() == ISD::FMUL &&
7720 (Aggressive || N1->hasOneUse()))
7721 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7722 DAG.getNode(ISD::FNEG, SL, VT,
7724 N1.getOperand(1), N0);
7726 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7727 if (N0.getOpcode() == ISD::FNEG &&
7728 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7729 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7730 SDValue N00 = N0.getOperand(0).getOperand(0);
7731 SDValue N01 = N0.getOperand(0).getOperand(1);
7732 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7733 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7734 DAG.getNode(ISD::FNEG, SL, VT, N1));
7737 // Look through FP_EXTEND nodes to do more combining.
7738 if (AllowFusion && LookThroughFPExt) {
7739 // fold (fsub (fpext (fmul x, y)), z)
7740 // -> (fma (fpext x), (fpext y), (fneg z))
7741 if (N0.getOpcode() == ISD::FP_EXTEND) {
7742 SDValue N00 = N0.getOperand(0);
7743 if (N00.getOpcode() == ISD::FMUL)
7744 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7745 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7747 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7749 DAG.getNode(ISD::FNEG, SL, VT, N1));
7752 // fold (fsub x, (fpext (fmul y, z)))
7753 // -> (fma (fneg (fpext y)), (fpext z), x)
7754 // Note: Commutes FSUB operands.
7755 if (N1.getOpcode() == ISD::FP_EXTEND) {
7756 SDValue N10 = N1.getOperand(0);
7757 if (N10.getOpcode() == ISD::FMUL)
7758 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7759 DAG.getNode(ISD::FNEG, SL, VT,
7760 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7761 N10.getOperand(0))),
7762 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7767 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7768 // -> (fneg (fma (fpext x), (fpext y), z))
7769 // Note: This could be removed with appropriate canonicalization of the
7770 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7771 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7772 // from implementing the canonicalization in visitFSUB.
7773 if (N0.getOpcode() == ISD::FP_EXTEND) {
7774 SDValue N00 = N0.getOperand(0);
7775 if (N00.getOpcode() == ISD::FNEG) {
7776 SDValue N000 = N00.getOperand(0);
7777 if (N000.getOpcode() == ISD::FMUL) {
7778 return DAG.getNode(ISD::FNEG, SL, VT,
7779 DAG.getNode(PreferredFusedOpcode, SL, VT,
7780 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7781 N000.getOperand(0)),
7782 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7783 N000.getOperand(1)),
7789 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7790 // -> (fneg (fma (fpext x)), (fpext y), z)
7791 // Note: This could be removed with appropriate canonicalization of the
7792 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7793 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7794 // from implementing the canonicalization in visitFSUB.
7795 if (N0.getOpcode() == ISD::FNEG) {
7796 SDValue N00 = N0.getOperand(0);
7797 if (N00.getOpcode() == ISD::FP_EXTEND) {
7798 SDValue N000 = N00.getOperand(0);
7799 if (N000.getOpcode() == ISD::FMUL) {
7800 return DAG.getNode(ISD::FNEG, SL, VT,
7801 DAG.getNode(PreferredFusedOpcode, SL, VT,
7802 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7803 N000.getOperand(0)),
7804 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7805 N000.getOperand(1)),
7813 // More folding opportunities when target permits.
7814 if ((AllowFusion || HasFMAD) && Aggressive) {
7815 // fold (fsub (fma x, y, (fmul u, v)), z)
7816 // -> (fma x, y (fma u, v, (fneg z)))
7817 if (N0.getOpcode() == PreferredFusedOpcode &&
7818 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7819 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7820 N0.getOperand(0), N0.getOperand(1),
7821 DAG.getNode(PreferredFusedOpcode, SL, VT,
7822 N0.getOperand(2).getOperand(0),
7823 N0.getOperand(2).getOperand(1),
7824 DAG.getNode(ISD::FNEG, SL, VT,
7828 // fold (fsub x, (fma y, z, (fmul u, v)))
7829 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7830 if (N1.getOpcode() == PreferredFusedOpcode &&
7831 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7832 SDValue N20 = N1.getOperand(2).getOperand(0);
7833 SDValue N21 = N1.getOperand(2).getOperand(1);
7834 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7835 DAG.getNode(ISD::FNEG, SL, VT,
7838 DAG.getNode(PreferredFusedOpcode, SL, VT,
7839 DAG.getNode(ISD::FNEG, SL, VT, N20),
7844 if (AllowFusion && LookThroughFPExt) {
7845 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7846 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7847 if (N0.getOpcode() == PreferredFusedOpcode) {
7848 SDValue N02 = N0.getOperand(2);
7849 if (N02.getOpcode() == ISD::FP_EXTEND) {
7850 SDValue N020 = N02.getOperand(0);
7851 if (N020.getOpcode() == ISD::FMUL)
7852 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7853 N0.getOperand(0), N0.getOperand(1),
7854 DAG.getNode(PreferredFusedOpcode, SL, VT,
7855 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7856 N020.getOperand(0)),
7857 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7858 N020.getOperand(1)),
7859 DAG.getNode(ISD::FNEG, SL, VT,
7864 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7865 // -> (fma (fpext x), (fpext y),
7866 // (fma (fpext u), (fpext v), (fneg z)))
7867 // FIXME: This turns two single-precision and one double-precision
7868 // operation into two double-precision operations, which might not be
7869 // interesting for all targets, especially GPUs.
7870 if (N0.getOpcode() == ISD::FP_EXTEND) {
7871 SDValue N00 = N0.getOperand(0);
7872 if (N00.getOpcode() == PreferredFusedOpcode) {
7873 SDValue N002 = N00.getOperand(2);
7874 if (N002.getOpcode() == ISD::FMUL)
7875 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7876 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7878 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7880 DAG.getNode(PreferredFusedOpcode, SL, VT,
7881 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7882 N002.getOperand(0)),
7883 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7884 N002.getOperand(1)),
7885 DAG.getNode(ISD::FNEG, SL, VT,
7890 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7891 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7892 if (N1.getOpcode() == PreferredFusedOpcode &&
7893 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7894 SDValue N120 = N1.getOperand(2).getOperand(0);
7895 if (N120.getOpcode() == ISD::FMUL) {
7896 SDValue N1200 = N120.getOperand(0);
7897 SDValue N1201 = N120.getOperand(1);
7898 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7899 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7901 DAG.getNode(PreferredFusedOpcode, SL, VT,
7902 DAG.getNode(ISD::FNEG, SL, VT,
7903 DAG.getNode(ISD::FP_EXTEND, SL,
7905 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7911 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7912 // -> (fma (fneg (fpext y)), (fpext z),
7913 // (fma (fneg (fpext u)), (fpext v), x))
7914 // FIXME: This turns two single-precision and one double-precision
7915 // operation into two double-precision operations, which might not be
7916 // interesting for all targets, especially GPUs.
7917 if (N1.getOpcode() == ISD::FP_EXTEND &&
7918 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7919 SDValue N100 = N1.getOperand(0).getOperand(0);
7920 SDValue N101 = N1.getOperand(0).getOperand(1);
7921 SDValue N102 = N1.getOperand(0).getOperand(2);
7922 if (N102.getOpcode() == ISD::FMUL) {
7923 SDValue N1020 = N102.getOperand(0);
7924 SDValue N1021 = N102.getOperand(1);
7925 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7926 DAG.getNode(ISD::FNEG, SL, VT,
7927 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7929 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7930 DAG.getNode(PreferredFusedOpcode, SL, VT,
7931 DAG.getNode(ISD::FNEG, SL, VT,
7932 DAG.getNode(ISD::FP_EXTEND, SL,
7934 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7945 /// Try to perform FMA combining on a given FMUL node.
7946 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7947 SDValue N0 = N->getOperand(0);
7948 SDValue N1 = N->getOperand(1);
7949 EVT VT = N->getValueType(0);
7952 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7954 const TargetOptions &Options = DAG.getTarget().Options;
7956 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7958 // Floating-point multiply-add with intermediate rounding.
7959 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7961 // Floating-point multiply-add without intermediate rounding.
7963 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7964 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7966 // No valid opcode, do not combine.
7967 if (!HasFMAD && !HasFMA)
7970 // Always prefer FMAD to FMA for precision.
7971 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7972 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7974 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7975 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7976 auto FuseFADD = [&](SDValue X, SDValue Y) {
7977 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7978 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7979 if (XC1 && XC1->isExactlyValue(+1.0))
7980 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7981 if (XC1 && XC1->isExactlyValue(-1.0))
7982 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7983 DAG.getNode(ISD::FNEG, SL, VT, Y));
7988 if (SDValue FMA = FuseFADD(N0, N1))
7990 if (SDValue FMA = FuseFADD(N1, N0))
7993 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
7994 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
7995 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
7996 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
7997 auto FuseFSUB = [&](SDValue X, SDValue Y) {
7998 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
7999 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8000 if (XC0 && XC0->isExactlyValue(+1.0))
8001 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8002 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8004 if (XC0 && XC0->isExactlyValue(-1.0))
8005 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8006 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8007 DAG.getNode(ISD::FNEG, SL, VT, Y));
8009 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8010 if (XC1 && XC1->isExactlyValue(+1.0))
8011 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8012 DAG.getNode(ISD::FNEG, SL, VT, Y));
8013 if (XC1 && XC1->isExactlyValue(-1.0))
8014 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8019 if (SDValue FMA = FuseFSUB(N0, N1))
8021 if (SDValue FMA = FuseFSUB(N1, N0))
8027 SDValue DAGCombiner::visitFADD(SDNode *N) {
8028 SDValue N0 = N->getOperand(0);
8029 SDValue N1 = N->getOperand(1);
8030 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8031 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8032 EVT VT = N->getValueType(0);
8034 const TargetOptions &Options = DAG.getTarget().Options;
8035 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8039 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8042 // fold (fadd c1, c2) -> c1 + c2
8044 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8046 // canonicalize constant to RHS
8047 if (N0CFP && !N1CFP)
8048 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8050 // fold (fadd A, (fneg B)) -> (fsub A, B)
8051 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8052 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8053 return DAG.getNode(ISD::FSUB, DL, VT, N0,
8054 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8056 // fold (fadd (fneg A), B) -> (fsub B, A)
8057 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8058 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8059 return DAG.getNode(ISD::FSUB, DL, VT, N1,
8060 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8062 // If 'unsafe math' is enabled, fold lots of things.
8063 if (Options.UnsafeFPMath) {
8064 // No FP constant should be created after legalization as Instruction
8065 // Selection pass has a hard time dealing with FP constants.
8066 bool AllowNewConst = (Level < AfterLegalizeDAG);
8068 // fold (fadd A, 0) -> A
8069 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8073 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8074 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8075 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8076 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8077 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8081 // If allowed, fold (fadd (fneg x), x) -> 0.0
8082 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8083 return DAG.getConstantFP(0.0, DL, VT);
8085 // If allowed, fold (fadd x, (fneg x)) -> 0.0
8086 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8087 return DAG.getConstantFP(0.0, DL, VT);
8089 // We can fold chains of FADD's of the same value into multiplications.
8090 // This transform is not safe in general because we are reducing the number
8091 // of rounding steps.
8092 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8093 if (N0.getOpcode() == ISD::FMUL) {
8094 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8095 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8097 // (fadd (fmul x, c), x) -> (fmul x, c+1)
8098 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8099 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8100 DAG.getConstantFP(1.0, DL, VT), Flags);
8101 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8104 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8105 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8106 N1.getOperand(0) == N1.getOperand(1) &&
8107 N0.getOperand(0) == N1.getOperand(0)) {
8108 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8109 DAG.getConstantFP(2.0, DL, VT), Flags);
8110 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8114 if (N1.getOpcode() == ISD::FMUL) {
8115 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8116 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8118 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8119 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8120 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8121 DAG.getConstantFP(1.0, DL, VT), Flags);
8122 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8125 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8126 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8127 N0.getOperand(0) == N0.getOperand(1) &&
8128 N1.getOperand(0) == N0.getOperand(0)) {
8129 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8130 DAG.getConstantFP(2.0, DL, VT), Flags);
8131 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8135 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8136 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8137 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8138 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8139 (N0.getOperand(0) == N1)) {
8140 return DAG.getNode(ISD::FMUL, DL, VT,
8141 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8145 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8146 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8147 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8148 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8149 N1.getOperand(0) == N0) {
8150 return DAG.getNode(ISD::FMUL, DL, VT,
8151 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8155 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8156 if (AllowNewConst &&
8157 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8158 N0.getOperand(0) == N0.getOperand(1) &&
8159 N1.getOperand(0) == N1.getOperand(1) &&
8160 N0.getOperand(0) == N1.getOperand(0)) {
8161 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8162 DAG.getConstantFP(4.0, DL, VT), Flags);
8165 } // enable-unsafe-fp-math
8167 // FADD -> FMA combines:
8168 if (SDValue Fused = visitFADDForFMACombine(N)) {
8169 AddToWorklist(Fused.getNode());
8176 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8177 SDValue N0 = N->getOperand(0);
8178 SDValue N1 = N->getOperand(1);
8179 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8180 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8181 EVT VT = N->getValueType(0);
8183 const TargetOptions &Options = DAG.getTarget().Options;
8184 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8188 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8191 // fold (fsub c1, c2) -> c1-c2
8193 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8195 // fold (fsub A, (fneg B)) -> (fadd A, B)
8196 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8197 return DAG.getNode(ISD::FADD, dl, VT, N0,
8198 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8200 // If 'unsafe math' is enabled, fold lots of things.
8201 if (Options.UnsafeFPMath) {
8203 if (N1CFP && N1CFP->isZero())
8206 // (fsub 0, B) -> -B
8207 if (N0CFP && N0CFP->isZero()) {
8208 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8209 return GetNegatedExpression(N1, DAG, LegalOperations);
8210 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8211 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8214 // (fsub x, x) -> 0.0
8216 return DAG.getConstantFP(0.0f, dl, VT);
8218 // (fsub x, (fadd x, y)) -> (fneg y)
8219 // (fsub x, (fadd y, x)) -> (fneg y)
8220 if (N1.getOpcode() == ISD::FADD) {
8221 SDValue N10 = N1->getOperand(0);
8222 SDValue N11 = N1->getOperand(1);
8224 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8225 return GetNegatedExpression(N11, DAG, LegalOperations);
8227 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8228 return GetNegatedExpression(N10, DAG, LegalOperations);
8232 // FSUB -> FMA combines:
8233 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8234 AddToWorklist(Fused.getNode());
8241 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8242 SDValue N0 = N->getOperand(0);
8243 SDValue N1 = N->getOperand(1);
8244 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8245 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8246 EVT VT = N->getValueType(0);
8248 const TargetOptions &Options = DAG.getTarget().Options;
8249 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8252 if (VT.isVector()) {
8253 // This just handles C1 * C2 for vectors. Other vector folds are below.
8254 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8258 // fold (fmul c1, c2) -> c1*c2
8260 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8262 // canonicalize constant to RHS
8263 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8264 !isConstantFPBuildVectorOrConstantFP(N1))
8265 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8267 // fold (fmul A, 1.0) -> A
8268 if (N1CFP && N1CFP->isExactlyValue(1.0))
8271 if (Options.UnsafeFPMath) {
8272 // fold (fmul A, 0) -> 0
8273 if (N1CFP && N1CFP->isZero())
8276 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8277 if (N0.getOpcode() == ISD::FMUL) {
8278 // Fold scalars or any vector constants (not just splats).
8279 // This fold is done in general by InstCombine, but extra fmul insts
8280 // may have been generated during lowering.
8281 SDValue N00 = N0.getOperand(0);
8282 SDValue N01 = N0.getOperand(1);
8283 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8284 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8285 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8287 // Check 1: Make sure that the first operand of the inner multiply is NOT
8288 // a constant. Otherwise, we may induce infinite looping.
8289 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8290 // Check 2: Make sure that the second operand of the inner multiply and
8291 // the second operand of the outer multiply are constants.
8292 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8293 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8294 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8295 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8300 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8301 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8302 // during an early run of DAGCombiner can prevent folding with fmuls
8303 // inserted during lowering.
8304 if (N0.getOpcode() == ISD::FADD &&
8305 (N0.getOperand(0) == N0.getOperand(1)) &&
8307 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8308 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8309 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8313 // fold (fmul X, 2.0) -> (fadd X, X)
8314 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8315 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8317 // fold (fmul X, -1.0) -> (fneg X)
8318 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8319 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8320 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8322 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8323 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8324 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8325 // Both can be negated for free, check to see if at least one is cheaper
8327 if (LHSNeg == 2 || RHSNeg == 2)
8328 return DAG.getNode(ISD::FMUL, DL, VT,
8329 GetNegatedExpression(N0, DAG, LegalOperations),
8330 GetNegatedExpression(N1, DAG, LegalOperations),
8335 // FMUL -> FMA combines:
8336 if (SDValue Fused = visitFMULForFMACombine(N)) {
8337 AddToWorklist(Fused.getNode());
8344 SDValue DAGCombiner::visitFMA(SDNode *N) {
8345 SDValue N0 = N->getOperand(0);
8346 SDValue N1 = N->getOperand(1);
8347 SDValue N2 = N->getOperand(2);
8348 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8349 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8350 EVT VT = N->getValueType(0);
8352 const TargetOptions &Options = DAG.getTarget().Options;
8354 // Constant fold FMA.
8355 if (isa<ConstantFPSDNode>(N0) &&
8356 isa<ConstantFPSDNode>(N1) &&
8357 isa<ConstantFPSDNode>(N2)) {
8358 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8361 if (Options.UnsafeFPMath) {
8362 if (N0CFP && N0CFP->isZero())
8364 if (N1CFP && N1CFP->isZero())
8367 // TODO: The FMA node should have flags that propagate to these nodes.
8368 if (N0CFP && N0CFP->isExactlyValue(1.0))
8369 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8370 if (N1CFP && N1CFP->isExactlyValue(1.0))
8371 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8373 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8374 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8375 !isConstantFPBuildVectorOrConstantFP(N1))
8376 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8378 // TODO: FMA nodes should have flags that propagate to the created nodes.
8379 // For now, create a Flags object for use with all unsafe math transforms.
8381 Flags.setUnsafeAlgebra(true);
8383 if (Options.UnsafeFPMath) {
8384 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8385 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8386 isConstantFPBuildVectorOrConstantFP(N1) &&
8387 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8388 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8389 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8393 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8394 if (N0.getOpcode() == ISD::FMUL &&
8395 isConstantFPBuildVectorOrConstantFP(N1) &&
8396 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8397 return DAG.getNode(ISD::FMA, dl, VT,
8399 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8405 // (fma x, 1, y) -> (fadd x, y)
8406 // (fma x, -1, y) -> (fadd (fneg x), y)
8408 if (N1CFP->isExactlyValue(1.0))
8409 // TODO: The FMA node should have flags that propagate to this node.
8410 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8412 if (N1CFP->isExactlyValue(-1.0) &&
8413 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8414 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8415 AddToWorklist(RHSNeg.getNode());
8416 // TODO: The FMA node should have flags that propagate to this node.
8417 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8421 if (Options.UnsafeFPMath) {
8422 // (fma x, c, x) -> (fmul x, (c+1))
8423 if (N1CFP && N0 == N2) {
8424 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8425 DAG.getNode(ISD::FADD, dl, VT,
8426 N1, DAG.getConstantFP(1.0, dl, VT),
8430 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8431 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8432 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8433 DAG.getNode(ISD::FADD, dl, VT,
8434 N1, DAG.getConstantFP(-1.0, dl, VT),
8442 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8444 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8445 // Notice that this is not always beneficial. One reason is different target
8446 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8447 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8448 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8449 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8450 if (!DAG.getTarget().Options.UnsafeFPMath)
8453 // Skip if current node is a reciprocal.
8454 SDValue N0 = N->getOperand(0);
8455 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8456 if (N0CFP && N0CFP->isExactlyValue(1.0))
8459 // Exit early if the target does not want this transform or if there can't
8460 // possibly be enough uses of the divisor to make the transform worthwhile.
8461 SDValue N1 = N->getOperand(1);
8462 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8463 if (!MinUses || N1->use_size() < MinUses)
8466 // Find all FDIV users of the same divisor.
8467 // Use a set because duplicates may be present in the user list.
8468 SetVector<SDNode *> Users;
8469 for (auto *U : N1->uses())
8470 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8473 // Now that we have the actual number of divisor uses, make sure it meets
8474 // the minimum threshold specified by the target.
8475 if (Users.size() < MinUses)
8478 EVT VT = N->getValueType(0);
8480 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8481 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8482 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8484 // Dividend / Divisor -> Dividend * Reciprocal
8485 for (auto *U : Users) {
8486 SDValue Dividend = U->getOperand(0);
8487 if (Dividend != FPOne) {
8488 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8490 CombineTo(U, NewNode);
8491 } else if (U != Reciprocal.getNode()) {
8492 // In the absence of fast-math-flags, this user node is always the
8493 // same node as Reciprocal, but with FMF they may be different nodes.
8494 CombineTo(U, Reciprocal);
8497 return SDValue(N, 0); // N was replaced.
8500 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8501 SDValue N0 = N->getOperand(0);
8502 SDValue N1 = N->getOperand(1);
8503 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8504 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8505 EVT VT = N->getValueType(0);
8507 const TargetOptions &Options = DAG.getTarget().Options;
8508 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8512 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8515 // fold (fdiv c1, c2) -> c1/c2
8517 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8519 if (Options.UnsafeFPMath) {
8520 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8522 // Compute the reciprocal 1.0 / c2.
8523 APFloat N1APF = N1CFP->getValueAPF();
8524 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8525 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8526 // Only do the transform if the reciprocal is a legal fp immediate that
8527 // isn't too nasty (eg NaN, denormal, ...).
8528 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8529 (!LegalOperations ||
8530 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8531 // backend)... we should handle this gracefully after Legalize.
8532 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8533 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8534 TLI.isFPImmLegal(Recip, VT)))
8535 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8536 DAG.getConstantFP(Recip, DL, VT), Flags);
8539 // If this FDIV is part of a reciprocal square root, it may be folded
8540 // into a target-specific square root estimate instruction.
8541 if (N1.getOpcode() == ISD::FSQRT) {
8542 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8543 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8545 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8546 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8547 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8549 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8550 AddToWorklist(RV.getNode());
8551 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8553 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8554 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8555 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8557 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8558 AddToWorklist(RV.getNode());
8559 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8561 } else if (N1.getOpcode() == ISD::FMUL) {
8562 // Look through an FMUL. Even though this won't remove the FDIV directly,
8563 // it's still worthwhile to get rid of the FSQRT if possible.
8566 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8567 SqrtOp = N1.getOperand(0);
8568 OtherOp = N1.getOperand(1);
8569 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8570 SqrtOp = N1.getOperand(1);
8571 OtherOp = N1.getOperand(0);
8573 if (SqrtOp.getNode()) {
8574 // We found a FSQRT, so try to make this fold:
8575 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8576 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8577 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8578 AddToWorklist(RV.getNode());
8579 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8584 // Fold into a reciprocal estimate and multiply instead of a real divide.
8585 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8586 AddToWorklist(RV.getNode());
8587 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8591 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8592 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8593 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8594 // Both can be negated for free, check to see if at least one is cheaper
8596 if (LHSNeg == 2 || RHSNeg == 2)
8597 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8598 GetNegatedExpression(N0, DAG, LegalOperations),
8599 GetNegatedExpression(N1, DAG, LegalOperations),
8604 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8605 return CombineRepeatedDivisors;
8610 SDValue DAGCombiner::visitFREM(SDNode *N) {
8611 SDValue N0 = N->getOperand(0);
8612 SDValue N1 = N->getOperand(1);
8613 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8614 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8615 EVT VT = N->getValueType(0);
8617 // fold (frem c1, c2) -> fmod(c1,c2)
8619 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8620 &cast<BinaryWithFlagsSDNode>(N)->Flags);
8625 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8626 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8629 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8630 // For now, create a Flags object for use with all unsafe math transforms.
8632 Flags.setUnsafeAlgebra(true);
8634 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8635 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8639 EVT VT = RV.getValueType();
8641 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8642 AddToWorklist(RV.getNode());
8644 // Unfortunately, RV is now NaN if the input was exactly 0.
8645 // Select out this case and force the answer to 0.
8646 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8647 EVT CCVT = getSetCCResultType(VT);
8648 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8649 AddToWorklist(ZeroCmp.getNode());
8650 AddToWorklist(RV.getNode());
8652 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8656 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8657 SDValue N0 = N->getOperand(0);
8658 SDValue N1 = N->getOperand(1);
8659 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8660 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8661 EVT VT = N->getValueType(0);
8663 if (N0CFP && N1CFP) // Constant fold
8664 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8667 const APFloat& V = N1CFP->getValueAPF();
8668 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8669 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8670 if (!V.isNegative()) {
8671 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8672 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8674 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8675 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8676 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8680 // copysign(fabs(x), y) -> copysign(x, y)
8681 // copysign(fneg(x), y) -> copysign(x, y)
8682 // copysign(copysign(x,z), y) -> copysign(x, y)
8683 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8684 N0.getOpcode() == ISD::FCOPYSIGN)
8685 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8686 N0.getOperand(0), N1);
8688 // copysign(x, abs(y)) -> abs(x)
8689 if (N1.getOpcode() == ISD::FABS)
8690 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8692 // copysign(x, copysign(y,z)) -> copysign(x, z)
8693 if (N1.getOpcode() == ISD::FCOPYSIGN)
8694 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8695 N0, N1.getOperand(1));
8697 // copysign(x, fp_extend(y)) -> copysign(x, y)
8698 // copysign(x, fp_round(y)) -> copysign(x, y)
8699 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8700 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8701 N0, N1.getOperand(0));
8706 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8707 SDValue N0 = N->getOperand(0);
8708 EVT VT = N->getValueType(0);
8709 EVT OpVT = N0.getValueType();
8711 // fold (sint_to_fp c1) -> c1fp
8712 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8713 // ...but only if the target supports immediate floating-point values
8714 (!LegalOperations ||
8715 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8716 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8718 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8719 // but UINT_TO_FP is legal on this target, try to convert.
8720 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8721 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8722 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8723 if (DAG.SignBitIsZero(N0))
8724 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8727 // The next optimizations are desirable only if SELECT_CC can be lowered.
8728 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8729 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8730 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8732 (!LegalOperations ||
8733 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8736 { N0.getOperand(0), N0.getOperand(1),
8737 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8739 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8742 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8743 // (select_cc x, y, 1.0, 0.0,, cc)
8744 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8745 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8746 (!LegalOperations ||
8747 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8750 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8751 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8752 N0.getOperand(0).getOperand(2) };
8753 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8760 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8761 SDValue N0 = N->getOperand(0);
8762 EVT VT = N->getValueType(0);
8763 EVT OpVT = N0.getValueType();
8765 // fold (uint_to_fp c1) -> c1fp
8766 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8767 // ...but only if the target supports immediate floating-point values
8768 (!LegalOperations ||
8769 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8770 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8772 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8773 // but SINT_TO_FP is legal on this target, try to convert.
8774 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8775 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8776 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8777 if (DAG.SignBitIsZero(N0))
8778 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8781 // The next optimizations are desirable only if SELECT_CC can be lowered.
8782 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8783 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8785 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8786 (!LegalOperations ||
8787 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8790 { N0.getOperand(0), N0.getOperand(1),
8791 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8793 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8800 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8801 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8802 SDValue N0 = N->getOperand(0);
8803 EVT VT = N->getValueType(0);
8805 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8808 SDValue Src = N0.getOperand(0);
8809 EVT SrcVT = Src.getValueType();
8810 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8811 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8813 // We can safely assume the conversion won't overflow the output range,
8814 // because (for example) (uint8_t)18293.f is undefined behavior.
8816 // Since we can assume the conversion won't overflow, our decision as to
8817 // whether the input will fit in the float should depend on the minimum
8818 // of the input range and output range.
8820 // This means this is also safe for a signed input and unsigned output, since
8821 // a negative input would lead to undefined behavior.
8822 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8823 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8824 unsigned ActualSize = std::min(InputSize, OutputSize);
8825 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8827 // We can only fold away the float conversion if the input range can be
8828 // represented exactly in the float range.
8829 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8830 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8831 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8833 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8835 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8836 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8839 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8844 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8845 SDValue N0 = N->getOperand(0);
8846 EVT VT = N->getValueType(0);
8848 // fold (fp_to_sint c1fp) -> c1
8849 if (isConstantFPBuildVectorOrConstantFP(N0))
8850 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8852 return FoldIntToFPToInt(N, DAG);
8855 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8856 SDValue N0 = N->getOperand(0);
8857 EVT VT = N->getValueType(0);
8859 // fold (fp_to_uint c1fp) -> c1
8860 if (isConstantFPBuildVectorOrConstantFP(N0))
8861 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8863 return FoldIntToFPToInt(N, DAG);
8866 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8867 SDValue N0 = N->getOperand(0);
8868 SDValue N1 = N->getOperand(1);
8869 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8870 EVT VT = N->getValueType(0);
8872 // fold (fp_round c1fp) -> c1fp
8874 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8876 // fold (fp_round (fp_extend x)) -> x
8877 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8878 return N0.getOperand(0);
8880 // fold (fp_round (fp_round x)) -> (fp_round x)
8881 if (N0.getOpcode() == ISD::FP_ROUND) {
8882 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8883 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8884 // If the first fp_round isn't a value preserving truncation, it might
8885 // introduce a tie in the second fp_round, that wouldn't occur in the
8886 // single-step fp_round we want to fold to.
8887 // In other words, double rounding isn't the same as rounding.
8888 // Also, this is a value preserving truncation iff both fp_round's are.
8889 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8891 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8892 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8896 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8897 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8898 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8899 N0.getOperand(0), N1);
8900 AddToWorklist(Tmp.getNode());
8901 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8902 Tmp, N0.getOperand(1));
8908 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8909 SDValue N0 = N->getOperand(0);
8910 EVT VT = N->getValueType(0);
8911 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8912 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8914 // fold (fp_round_inreg c1fp) -> c1fp
8915 if (N0CFP && isTypeLegal(EVT)) {
8917 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8918 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8924 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8925 SDValue N0 = N->getOperand(0);
8926 EVT VT = N->getValueType(0);
8928 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8929 if (N->hasOneUse() &&
8930 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8933 // fold (fp_extend c1fp) -> c1fp
8934 if (isConstantFPBuildVectorOrConstantFP(N0))
8935 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8937 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8938 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8939 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8940 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8942 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8944 if (N0.getOpcode() == ISD::FP_ROUND
8945 && N0.getNode()->getConstantOperandVal(1) == 1) {
8946 SDValue In = N0.getOperand(0);
8947 if (In.getValueType() == VT) return In;
8948 if (VT.bitsLT(In.getValueType()))
8949 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8950 In, N0.getOperand(1));
8951 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8954 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8955 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8956 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8957 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8958 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8960 LN0->getBasePtr(), N0.getValueType(),
8961 LN0->getMemOperand());
8962 CombineTo(N, ExtLoad);
8963 CombineTo(N0.getNode(),
8964 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8965 N0.getValueType(), ExtLoad,
8966 DAG.getIntPtrConstant(1, SDLoc(N0))),
8967 ExtLoad.getValue(1));
8968 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8974 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8975 SDValue N0 = N->getOperand(0);
8976 EVT VT = N->getValueType(0);
8978 // fold (fceil c1) -> fceil(c1)
8979 if (isConstantFPBuildVectorOrConstantFP(N0))
8980 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8985 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8986 SDValue N0 = N->getOperand(0);
8987 EVT VT = N->getValueType(0);
8989 // fold (ftrunc c1) -> ftrunc(c1)
8990 if (isConstantFPBuildVectorOrConstantFP(N0))
8991 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8996 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8997 SDValue N0 = N->getOperand(0);
8998 EVT VT = N->getValueType(0);
9000 // fold (ffloor c1) -> ffloor(c1)
9001 if (isConstantFPBuildVectorOrConstantFP(N0))
9002 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9007 // FIXME: FNEG and FABS have a lot in common; refactor.
9008 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9009 SDValue N0 = N->getOperand(0);
9010 EVT VT = N->getValueType(0);
9012 // Constant fold FNEG.
9013 if (isConstantFPBuildVectorOrConstantFP(N0))
9014 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9016 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9017 &DAG.getTarget().Options))
9018 return GetNegatedExpression(N0, DAG, LegalOperations);
9020 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9021 // constant pool values.
9022 if (!TLI.isFNegFree(VT) &&
9023 N0.getOpcode() == ISD::BITCAST &&
9024 N0.getNode()->hasOneUse()) {
9025 SDValue Int = N0.getOperand(0);
9026 EVT IntVT = Int.getValueType();
9027 if (IntVT.isInteger() && !IntVT.isVector()) {
9029 if (N0.getValueType().isVector()) {
9030 // For a vector, get a mask such as 0x80... per scalar element
9032 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9033 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9035 // For a scalar, just generate 0x80...
9036 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9039 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9040 DAG.getConstant(SignMask, DL0, IntVT));
9041 AddToWorklist(Int.getNode());
9042 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9046 // (fneg (fmul c, x)) -> (fmul -c, x)
9047 if (N0.getOpcode() == ISD::FMUL &&
9048 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9049 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9051 APFloat CVal = CFP1->getValueAPF();
9053 if (Level >= AfterLegalizeDAG &&
9054 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9055 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9056 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9057 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9059 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9066 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9067 SDValue N0 = N->getOperand(0);
9068 SDValue N1 = N->getOperand(1);
9069 EVT VT = N->getValueType(0);
9070 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9071 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9073 if (N0CFP && N1CFP) {
9074 const APFloat &C0 = N0CFP->getValueAPF();
9075 const APFloat &C1 = N1CFP->getValueAPF();
9076 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9079 // Canonicalize to constant on RHS.
9080 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9081 !isConstantFPBuildVectorOrConstantFP(N1))
9082 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9087 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9088 SDValue N0 = N->getOperand(0);
9089 SDValue N1 = N->getOperand(1);
9090 EVT VT = N->getValueType(0);
9091 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9092 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9094 if (N0CFP && N1CFP) {
9095 const APFloat &C0 = N0CFP->getValueAPF();
9096 const APFloat &C1 = N1CFP->getValueAPF();
9097 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9100 // Canonicalize to constant on RHS.
9101 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9102 !isConstantFPBuildVectorOrConstantFP(N1))
9103 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9108 SDValue DAGCombiner::visitFABS(SDNode *N) {
9109 SDValue N0 = N->getOperand(0);
9110 EVT VT = N->getValueType(0);
9112 // fold (fabs c1) -> fabs(c1)
9113 if (isConstantFPBuildVectorOrConstantFP(N0))
9114 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9116 // fold (fabs (fabs x)) -> (fabs x)
9117 if (N0.getOpcode() == ISD::FABS)
9118 return N->getOperand(0);
9120 // fold (fabs (fneg x)) -> (fabs x)
9121 // fold (fabs (fcopysign x, y)) -> (fabs x)
9122 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9123 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9125 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9126 // constant pool values.
9127 if (!TLI.isFAbsFree(VT) &&
9128 N0.getOpcode() == ISD::BITCAST &&
9129 N0.getNode()->hasOneUse()) {
9130 SDValue Int = N0.getOperand(0);
9131 EVT IntVT = Int.getValueType();
9132 if (IntVT.isInteger() && !IntVT.isVector()) {
9134 if (N0.getValueType().isVector()) {
9135 // For a vector, get a mask such as 0x7f... per scalar element
9137 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9138 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9140 // For a scalar, just generate 0x7f...
9141 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9144 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9145 DAG.getConstant(SignMask, DL, IntVT));
9146 AddToWorklist(Int.getNode());
9147 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9154 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9155 SDValue Chain = N->getOperand(0);
9156 SDValue N1 = N->getOperand(1);
9157 SDValue N2 = N->getOperand(2);
9159 // If N is a constant we could fold this into a fallthrough or unconditional
9160 // branch. However that doesn't happen very often in normal code, because
9161 // Instcombine/SimplifyCFG should have handled the available opportunities.
9162 // If we did this folding here, it would be necessary to update the
9163 // MachineBasicBlock CFG, which is awkward.
9165 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9167 if (N1.getOpcode() == ISD::SETCC &&
9168 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9169 N1.getOperand(0).getValueType())) {
9170 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9171 Chain, N1.getOperand(2),
9172 N1.getOperand(0), N1.getOperand(1), N2);
9175 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9176 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9177 (N1.getOperand(0).hasOneUse() &&
9178 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9179 SDNode *Trunc = nullptr;
9180 if (N1.getOpcode() == ISD::TRUNCATE) {
9181 // Look pass the truncate.
9182 Trunc = N1.getNode();
9183 N1 = N1.getOperand(0);
9186 // Match this pattern so that we can generate simpler code:
9189 // %b = and i32 %a, 2
9190 // %c = srl i32 %b, 1
9191 // brcond i32 %c ...
9196 // %b = and i32 %a, 2
9197 // %c = setcc eq %b, 0
9200 // This applies only when the AND constant value has one bit set and the
9201 // SRL constant is equal to the log2 of the AND constant. The back-end is
9202 // smart enough to convert the result into a TEST/JMP sequence.
9203 SDValue Op0 = N1.getOperand(0);
9204 SDValue Op1 = N1.getOperand(1);
9206 if (Op0.getOpcode() == ISD::AND &&
9207 Op1.getOpcode() == ISD::Constant) {
9208 SDValue AndOp1 = Op0.getOperand(1);
9210 if (AndOp1.getOpcode() == ISD::Constant) {
9211 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9213 if (AndConst.isPowerOf2() &&
9214 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9218 getSetCCResultType(Op0.getValueType()),
9219 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9222 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9223 MVT::Other, Chain, SetCC, N2);
9224 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9225 // will convert it back to (X & C1) >> C2.
9226 CombineTo(N, NewBRCond, false);
9227 // Truncate is dead.
9229 deleteAndRecombine(Trunc);
9230 // Replace the uses of SRL with SETCC
9231 WorklistRemover DeadNodes(*this);
9232 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9233 deleteAndRecombine(N1.getNode());
9234 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9240 // Restore N1 if the above transformation doesn't match.
9241 N1 = N->getOperand(1);
9244 // Transform br(xor(x, y)) -> br(x != y)
9245 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9246 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9247 SDNode *TheXor = N1.getNode();
9248 SDValue Op0 = TheXor->getOperand(0);
9249 SDValue Op1 = TheXor->getOperand(1);
9250 if (Op0.getOpcode() == Op1.getOpcode()) {
9251 // Avoid missing important xor optimizations.
9252 if (SDValue Tmp = visitXOR(TheXor)) {
9253 if (Tmp.getNode() != TheXor) {
9254 DEBUG(dbgs() << "\nReplacing.8 ";
9256 dbgs() << "\nWith: ";
9257 Tmp.getNode()->dump(&DAG);
9259 WorklistRemover DeadNodes(*this);
9260 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9261 deleteAndRecombine(TheXor);
9262 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9263 MVT::Other, Chain, Tmp, N2);
9266 // visitXOR has changed XOR's operands or replaced the XOR completely,
9268 return SDValue(N, 0);
9272 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9274 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9275 Op0.getOpcode() == ISD::XOR) {
9276 TheXor = Op0.getNode();
9280 EVT SetCCVT = N1.getValueType();
9282 SetCCVT = getSetCCResultType(SetCCVT);
9283 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9286 Equal ? ISD::SETEQ : ISD::SETNE);
9287 // Replace the uses of XOR with SETCC
9288 WorklistRemover DeadNodes(*this);
9289 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9290 deleteAndRecombine(N1.getNode());
9291 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9292 MVT::Other, Chain, SetCC, N2);
9299 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9301 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9302 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9303 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9305 // If N is a constant we could fold this into a fallthrough or unconditional
9306 // branch. However that doesn't happen very often in normal code, because
9307 // Instcombine/SimplifyCFG should have handled the available opportunities.
9308 // If we did this folding here, it would be necessary to update the
9309 // MachineBasicBlock CFG, which is awkward.
9311 // Use SimplifySetCC to simplify SETCC's.
9312 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9313 CondLHS, CondRHS, CC->get(), SDLoc(N),
9315 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9317 // fold to a simpler setcc
9318 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9319 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9320 N->getOperand(0), Simp.getOperand(2),
9321 Simp.getOperand(0), Simp.getOperand(1),
9327 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9328 /// and that N may be folded in the load / store addressing mode.
9329 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9331 const TargetLowering &TLI) {
9335 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9336 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9338 VT = LD->getMemoryVT();
9339 AS = LD->getAddressSpace();
9340 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9341 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9343 VT = ST->getMemoryVT();
9344 AS = ST->getAddressSpace();
9348 TargetLowering::AddrMode AM;
9349 if (N->getOpcode() == ISD::ADD) {
9350 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9353 AM.BaseOffs = Offset->getSExtValue();
9357 } else if (N->getOpcode() == ISD::SUB) {
9358 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9361 AM.BaseOffs = -Offset->getSExtValue();
9368 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9369 VT.getTypeForEVT(*DAG.getContext()), AS);
9372 /// Try turning a load/store into a pre-indexed load/store when the base
9373 /// pointer is an add or subtract and it has other uses besides the load/store.
9374 /// After the transformation, the new indexed load/store has effectively folded
9375 /// the add/subtract in and all of its other uses are redirected to the
9377 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9378 if (Level < AfterLegalizeDAG)
9384 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9385 if (LD->isIndexed())
9387 VT = LD->getMemoryVT();
9388 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9389 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9391 Ptr = LD->getBasePtr();
9392 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9393 if (ST->isIndexed())
9395 VT = ST->getMemoryVT();
9396 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9397 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9399 Ptr = ST->getBasePtr();
9405 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9406 // out. There is no reason to make this a preinc/predec.
9407 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9408 Ptr.getNode()->hasOneUse())
9411 // Ask the target to do addressing mode selection.
9414 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9415 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9418 // Backends without true r+i pre-indexed forms may need to pass a
9419 // constant base with a variable offset so that constant coercion
9420 // will work with the patterns in canonical form.
9421 bool Swapped = false;
9422 if (isa<ConstantSDNode>(BasePtr)) {
9423 std::swap(BasePtr, Offset);
9427 // Don't create a indexed load / store with zero offset.
9428 if (isNullConstant(Offset))
9431 // Try turning it into a pre-indexed load / store except when:
9432 // 1) The new base ptr is a frame index.
9433 // 2) If N is a store and the new base ptr is either the same as or is a
9434 // predecessor of the value being stored.
9435 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9436 // that would create a cycle.
9437 // 4) All uses are load / store ops that use it as old base ptr.
9439 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9440 // (plus the implicit offset) to a register to preinc anyway.
9441 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9446 SDValue Val = cast<StoreSDNode>(N)->getValue();
9447 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9451 // If the offset is a constant, there may be other adds of constants that
9452 // can be folded with this one. We should do this to avoid having to keep
9453 // a copy of the original base pointer.
9454 SmallVector<SDNode *, 16> OtherUses;
9455 if (isa<ConstantSDNode>(Offset))
9456 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9457 UE = BasePtr.getNode()->use_end();
9459 SDUse &Use = UI.getUse();
9460 // Skip the use that is Ptr and uses of other results from BasePtr's
9461 // node (important for nodes that return multiple results).
9462 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9465 if (Use.getUser()->isPredecessorOf(N))
9468 if (Use.getUser()->getOpcode() != ISD::ADD &&
9469 Use.getUser()->getOpcode() != ISD::SUB) {
9474 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9475 if (!isa<ConstantSDNode>(Op1)) {
9480 // FIXME: In some cases, we can be smarter about this.
9481 if (Op1.getValueType() != Offset.getValueType()) {
9486 OtherUses.push_back(Use.getUser());
9490 std::swap(BasePtr, Offset);
9492 // Now check for #3 and #4.
9493 bool RealUse = false;
9495 // Caches for hasPredecessorHelper
9496 SmallPtrSet<const SDNode *, 32> Visited;
9497 SmallVector<const SDNode *, 16> Worklist;
9499 for (SDNode *Use : Ptr.getNode()->uses()) {
9502 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9505 // If Ptr may be folded in addressing mode of other use, then it's
9506 // not profitable to do this transformation.
9507 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9516 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9517 BasePtr, Offset, AM);
9519 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9520 BasePtr, Offset, AM);
9523 DEBUG(dbgs() << "\nReplacing.4 ";
9525 dbgs() << "\nWith: ";
9526 Result.getNode()->dump(&DAG);
9528 WorklistRemover DeadNodes(*this);
9530 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9531 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9533 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9536 // Finally, since the node is now dead, remove it from the graph.
9537 deleteAndRecombine(N);
9540 std::swap(BasePtr, Offset);
9542 // Replace other uses of BasePtr that can be updated to use Ptr
9543 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9544 unsigned OffsetIdx = 1;
9545 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9547 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9548 BasePtr.getNode() && "Expected BasePtr operand");
9550 // We need to replace ptr0 in the following expression:
9551 // x0 * offset0 + y0 * ptr0 = t0
9553 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9555 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9556 // indexed load/store and the expresion that needs to be re-written.
9558 // Therefore, we have:
9559 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9561 ConstantSDNode *CN =
9562 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9564 APInt Offset0 = CN->getAPIntValue();
9565 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9567 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9568 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9569 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9570 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9572 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9574 APInt CNV = Offset0;
9575 if (X0 < 0) CNV = -CNV;
9576 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9577 else CNV = CNV - Offset1;
9579 SDLoc DL(OtherUses[i]);
9581 // We can now generate the new expression.
9582 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9583 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9585 SDValue NewUse = DAG.getNode(Opcode,
9587 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9588 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9589 deleteAndRecombine(OtherUses[i]);
9592 // Replace the uses of Ptr with uses of the updated base value.
9593 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9594 deleteAndRecombine(Ptr.getNode());
9599 /// Try to combine a load/store with a add/sub of the base pointer node into a
9600 /// post-indexed load/store. The transformation folded the add/subtract into the
9601 /// new indexed load/store effectively and all of its uses are redirected to the
9603 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9604 if (Level < AfterLegalizeDAG)
9610 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9611 if (LD->isIndexed())
9613 VT = LD->getMemoryVT();
9614 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9615 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9617 Ptr = LD->getBasePtr();
9618 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9619 if (ST->isIndexed())
9621 VT = ST->getMemoryVT();
9622 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9623 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9625 Ptr = ST->getBasePtr();
9631 if (Ptr.getNode()->hasOneUse())
9634 for (SDNode *Op : Ptr.getNode()->uses()) {
9636 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9641 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9642 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9643 // Don't create a indexed load / store with zero offset.
9644 if (isNullConstant(Offset))
9647 // Try turning it into a post-indexed load / store except when
9648 // 1) All uses are load / store ops that use it as base ptr (and
9649 // it may be folded as addressing mmode).
9650 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9651 // nor a successor of N. Otherwise, if Op is folded that would
9654 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9658 bool TryNext = false;
9659 for (SDNode *Use : BasePtr.getNode()->uses()) {
9660 if (Use == Ptr.getNode())
9663 // If all the uses are load / store addresses, then don't do the
9665 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9666 bool RealUse = false;
9667 for (SDNode *UseUse : Use->uses()) {
9668 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9683 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9684 SDValue Result = isLoad
9685 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9686 BasePtr, Offset, AM)
9687 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9688 BasePtr, Offset, AM);
9691 DEBUG(dbgs() << "\nReplacing.5 ";
9693 dbgs() << "\nWith: ";
9694 Result.getNode()->dump(&DAG);
9696 WorklistRemover DeadNodes(*this);
9698 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9699 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9701 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9704 // Finally, since the node is now dead, remove it from the graph.
9705 deleteAndRecombine(N);
9707 // Replace the uses of Use with uses of the updated base value.
9708 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9709 Result.getValue(isLoad ? 1 : 0));
9710 deleteAndRecombine(Op);
9719 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9720 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9721 ISD::MemIndexedMode AM = LD->getAddressingMode();
9722 assert(AM != ISD::UNINDEXED);
9723 SDValue BP = LD->getOperand(1);
9724 SDValue Inc = LD->getOperand(2);
9726 // Some backends use TargetConstants for load offsets, but don't expect
9727 // TargetConstants in general ADD nodes. We can convert these constants into
9728 // regular Constants (if the constant is not opaque).
9729 assert((Inc.getOpcode() != ISD::TargetConstant ||
9730 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9731 "Cannot split out indexing using opaque target constants");
9732 if (Inc.getOpcode() == ISD::TargetConstant) {
9733 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9734 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9735 ConstInc->getValueType(0));
9739 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9740 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9743 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9744 LoadSDNode *LD = cast<LoadSDNode>(N);
9745 SDValue Chain = LD->getChain();
9746 SDValue Ptr = LD->getBasePtr();
9748 // If load is not volatile and there are no uses of the loaded value (and
9749 // the updated indexed value in case of indexed loads), change uses of the
9750 // chain value into uses of the chain input (i.e. delete the dead load).
9751 if (!LD->isVolatile()) {
9752 if (N->getValueType(1) == MVT::Other) {
9754 if (!N->hasAnyUseOfValue(0)) {
9755 // It's not safe to use the two value CombineTo variant here. e.g.
9756 // v1, chain2 = load chain1, loc
9757 // v2, chain3 = load chain2, loc
9759 // Now we replace use of chain2 with chain1. This makes the second load
9760 // isomorphic to the one we are deleting, and thus makes this load live.
9761 DEBUG(dbgs() << "\nReplacing.6 ";
9763 dbgs() << "\nWith chain: ";
9764 Chain.getNode()->dump(&DAG);
9766 WorklistRemover DeadNodes(*this);
9767 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9770 deleteAndRecombine(N);
9772 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9776 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9778 // If this load has an opaque TargetConstant offset, then we cannot split
9779 // the indexing into an add/sub directly (that TargetConstant may not be
9780 // valid for a different type of node, and we cannot convert an opaque
9781 // target constant into a regular constant).
9782 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9783 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9785 if (!N->hasAnyUseOfValue(0) &&
9786 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9787 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9789 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9790 Index = SplitIndexingFromLoad(LD);
9791 // Try to fold the base pointer arithmetic into subsequent loads and
9793 AddUsersToWorklist(N);
9795 Index = DAG.getUNDEF(N->getValueType(1));
9796 DEBUG(dbgs() << "\nReplacing.7 ";
9798 dbgs() << "\nWith: ";
9799 Undef.getNode()->dump(&DAG);
9800 dbgs() << " and 2 other values\n");
9801 WorklistRemover DeadNodes(*this);
9802 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9803 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9804 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9805 deleteAndRecombine(N);
9806 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9811 // If this load is directly stored, replace the load value with the stored
9813 // TODO: Handle store large -> read small portion.
9814 // TODO: Handle TRUNCSTORE/LOADEXT
9815 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9816 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9817 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9818 if (PrevST->getBasePtr() == Ptr &&
9819 PrevST->getValue().getValueType() == N->getValueType(0))
9820 return CombineTo(N, Chain.getOperand(1), Chain);
9824 // Try to infer better alignment information than the load already has.
9825 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9826 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9827 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9829 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9830 LD->getValueType(0),
9831 Chain, Ptr, LD->getPointerInfo(),
9833 LD->isVolatile(), LD->isNonTemporal(),
9834 LD->isInvariant(), Align, LD->getAAInfo());
9835 if (NewLoad.getNode() != N)
9836 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9841 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9842 : DAG.getSubtarget().useAA();
9844 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9845 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9848 if (UseAA && LD->isUnindexed()) {
9849 // Walk up chain skipping non-aliasing memory nodes.
9850 SDValue BetterChain = FindBetterChain(N, Chain);
9852 // If there is a better chain.
9853 if (Chain != BetterChain) {
9856 // Replace the chain to void dependency.
9857 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9858 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9859 BetterChain, Ptr, LD->getMemOperand());
9861 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9862 LD->getValueType(0),
9863 BetterChain, Ptr, LD->getMemoryVT(),
9864 LD->getMemOperand());
9867 // Create token factor to keep old chain connected.
9868 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9869 MVT::Other, Chain, ReplLoad.getValue(1));
9871 // Make sure the new and old chains are cleaned up.
9872 AddToWorklist(Token.getNode());
9874 // Replace uses with load result and token factor. Don't add users
9876 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9880 // Try transforming N to an indexed load.
9881 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9882 return SDValue(N, 0);
9884 // Try to slice up N to more direct loads if the slices are mapped to
9885 // different register banks or pairing can take place.
9887 return SDValue(N, 0);
9893 /// \brief Helper structure used to slice a load in smaller loads.
9894 /// Basically a slice is obtained from the following sequence:
9895 /// Origin = load Ty1, Base
9896 /// Shift = srl Ty1 Origin, CstTy Amount
9897 /// Inst = trunc Shift to Ty2
9899 /// Then, it will be rewriten into:
9900 /// Slice = load SliceTy, Base + SliceOffset
9901 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9903 /// SliceTy is deduced from the number of bits that are actually used to
9905 struct LoadedSlice {
9906 /// \brief Helper structure used to compute the cost of a slice.
9908 /// Are we optimizing for code size.
9913 unsigned CrossRegisterBanksCopies;
9917 Cost(bool ForCodeSize = false)
9918 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9919 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9921 /// \brief Get the cost of one isolated slice.
9922 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9923 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9924 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9925 EVT TruncType = LS.Inst->getValueType(0);
9926 EVT LoadedType = LS.getLoadedType();
9927 if (TruncType != LoadedType &&
9928 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9932 /// \brief Account for slicing gain in the current cost.
9933 /// Slicing provide a few gains like removing a shift or a
9934 /// truncate. This method allows to grow the cost of the original
9935 /// load with the gain from this slice.
9936 void addSliceGain(const LoadedSlice &LS) {
9937 // Each slice saves a truncate.
9938 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9939 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9940 LS.Inst->getValueType(0)))
9942 // If there is a shift amount, this slice gets rid of it.
9945 // If this slice can merge a cross register bank copy, account for it.
9946 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9947 ++CrossRegisterBanksCopies;
9950 Cost &operator+=(const Cost &RHS) {
9952 Truncates += RHS.Truncates;
9953 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9959 bool operator==(const Cost &RHS) const {
9960 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9961 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9962 ZExts == RHS.ZExts && Shift == RHS.Shift;
9965 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9967 bool operator<(const Cost &RHS) const {
9968 // Assume cross register banks copies are as expensive as loads.
9969 // FIXME: Do we want some more target hooks?
9970 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9971 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9972 // Unless we are optimizing for code size, consider the
9973 // expensive operation first.
9974 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9975 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9976 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9977 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9980 bool operator>(const Cost &RHS) const { return RHS < *this; }
9982 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9984 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9986 // The last instruction that represent the slice. This should be a
9987 // truncate instruction.
9989 // The original load instruction.
9991 // The right shift amount in bits from the original load.
9993 // The DAG from which Origin came from.
9994 // This is used to get some contextual information about legal types, etc.
9997 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9998 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9999 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10001 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10002 /// \return Result is \p BitWidth and has used bits set to 1 and
10003 /// not used bits set to 0.
10004 APInt getUsedBits() const {
10005 // Reproduce the trunc(lshr) sequence:
10006 // - Start from the truncated value.
10007 // - Zero extend to the desired bit width.
10009 assert(Origin && "No original load to compare against.");
10010 unsigned BitWidth = Origin->getValueSizeInBits(0);
10011 assert(Inst && "This slice is not bound to an instruction");
10012 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10013 "Extracted slice is bigger than the whole type!");
10014 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10015 UsedBits.setAllBits();
10016 UsedBits = UsedBits.zext(BitWidth);
10017 UsedBits <<= Shift;
10021 /// \brief Get the size of the slice to be loaded in bytes.
10022 unsigned getLoadedSize() const {
10023 unsigned SliceSize = getUsedBits().countPopulation();
10024 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10025 return SliceSize / 8;
10028 /// \brief Get the type that will be loaded for this slice.
10029 /// Note: This may not be the final type for the slice.
10030 EVT getLoadedType() const {
10031 assert(DAG && "Missing context");
10032 LLVMContext &Ctxt = *DAG->getContext();
10033 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10036 /// \brief Get the alignment of the load used for this slice.
10037 unsigned getAlignment() const {
10038 unsigned Alignment = Origin->getAlignment();
10039 unsigned Offset = getOffsetFromBase();
10041 Alignment = MinAlign(Alignment, Alignment + Offset);
10045 /// \brief Check if this slice can be rewritten with legal operations.
10046 bool isLegal() const {
10047 // An invalid slice is not legal.
10048 if (!Origin || !Inst || !DAG)
10051 // Offsets are for indexed load only, we do not handle that.
10052 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10055 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10057 // Check that the type is legal.
10058 EVT SliceType = getLoadedType();
10059 if (!TLI.isTypeLegal(SliceType))
10062 // Check that the load is legal for this type.
10063 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10066 // Check that the offset can be computed.
10067 // 1. Check its type.
10068 EVT PtrType = Origin->getBasePtr().getValueType();
10069 if (PtrType == MVT::Untyped || PtrType.isExtended())
10072 // 2. Check that it fits in the immediate.
10073 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10076 // 3. Check that the computation is legal.
10077 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10080 // Check that the zext is legal if it needs one.
10081 EVT TruncateType = Inst->getValueType(0);
10082 if (TruncateType != SliceType &&
10083 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10089 /// \brief Get the offset in bytes of this slice in the original chunk of
10091 /// \pre DAG != nullptr.
10092 uint64_t getOffsetFromBase() const {
10093 assert(DAG && "Missing context.");
10094 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10095 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10096 uint64_t Offset = Shift / 8;
10097 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10098 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10099 "The size of the original loaded type is not a multiple of a"
10101 // If Offset is bigger than TySizeInBytes, it means we are loading all
10102 // zeros. This should have been optimized before in the process.
10103 assert(TySizeInBytes > Offset &&
10104 "Invalid shift amount for given loaded size");
10106 Offset = TySizeInBytes - Offset - getLoadedSize();
10110 /// \brief Generate the sequence of instructions to load the slice
10111 /// represented by this object and redirect the uses of this slice to
10112 /// this new sequence of instructions.
10113 /// \pre this->Inst && this->Origin are valid Instructions and this
10114 /// object passed the legal check: LoadedSlice::isLegal returned true.
10115 /// \return The last instruction of the sequence used to load the slice.
10116 SDValue loadSlice() const {
10117 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10118 const SDValue &OldBaseAddr = Origin->getBasePtr();
10119 SDValue BaseAddr = OldBaseAddr;
10120 // Get the offset in that chunk of bytes w.r.t. the endianess.
10121 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10122 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10124 // BaseAddr = BaseAddr + Offset.
10125 EVT ArithType = BaseAddr.getValueType();
10127 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10128 DAG->getConstant(Offset, DL, ArithType));
10131 // Create the type of the loaded slice according to its size.
10132 EVT SliceType = getLoadedType();
10134 // Create the load for the slice.
10135 SDValue LastInst = DAG->getLoad(
10136 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10137 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10138 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10139 // If the final type is not the same as the loaded type, this means that
10140 // we have to pad with zero. Create a zero extend for that.
10141 EVT FinalType = Inst->getValueType(0);
10142 if (SliceType != FinalType)
10144 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10148 /// \brief Check if this slice can be merged with an expensive cross register
10149 /// bank copy. E.g.,
10151 /// f = bitcast i32 i to float
10152 bool canMergeExpensiveCrossRegisterBankCopy() const {
10153 if (!Inst || !Inst->hasOneUse())
10155 SDNode *Use = *Inst->use_begin();
10156 if (Use->getOpcode() != ISD::BITCAST)
10158 assert(DAG && "Missing context");
10159 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10160 EVT ResVT = Use->getValueType(0);
10161 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10162 const TargetRegisterClass *ArgRC =
10163 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10164 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10167 // At this point, we know that we perform a cross-register-bank copy.
10168 // Check if it is expensive.
10169 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10170 // Assume bitcasts are cheap, unless both register classes do not
10171 // explicitly share a common sub class.
10172 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10175 // Check if it will be merged with the load.
10176 // 1. Check the alignment constraint.
10177 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10178 ResVT.getTypeForEVT(*DAG->getContext()));
10180 if (RequiredAlignment > getAlignment())
10183 // 2. Check that the load is a legal operation for that type.
10184 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10187 // 3. Check that we do not have a zext in the way.
10188 if (Inst->getValueType(0) != getLoadedType())
10196 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10197 /// \p UsedBits looks like 0..0 1..1 0..0.
10198 static bool areUsedBitsDense(const APInt &UsedBits) {
10199 // If all the bits are one, this is dense!
10200 if (UsedBits.isAllOnesValue())
10203 // Get rid of the unused bits on the right.
10204 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10205 // Get rid of the unused bits on the left.
10206 if (NarrowedUsedBits.countLeadingZeros())
10207 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10208 // Check that the chunk of bits is completely used.
10209 return NarrowedUsedBits.isAllOnesValue();
10212 /// \brief Check whether or not \p First and \p Second are next to each other
10213 /// in memory. This means that there is no hole between the bits loaded
10214 /// by \p First and the bits loaded by \p Second.
10215 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10216 const LoadedSlice &Second) {
10217 assert(First.Origin == Second.Origin && First.Origin &&
10218 "Unable to match different memory origins.");
10219 APInt UsedBits = First.getUsedBits();
10220 assert((UsedBits & Second.getUsedBits()) == 0 &&
10221 "Slices are not supposed to overlap.");
10222 UsedBits |= Second.getUsedBits();
10223 return areUsedBitsDense(UsedBits);
10226 /// \brief Adjust the \p GlobalLSCost according to the target
10227 /// paring capabilities and the layout of the slices.
10228 /// \pre \p GlobalLSCost should account for at least as many loads as
10229 /// there is in the slices in \p LoadedSlices.
10230 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10231 LoadedSlice::Cost &GlobalLSCost) {
10232 unsigned NumberOfSlices = LoadedSlices.size();
10233 // If there is less than 2 elements, no pairing is possible.
10234 if (NumberOfSlices < 2)
10237 // Sort the slices so that elements that are likely to be next to each
10238 // other in memory are next to each other in the list.
10239 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10240 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10241 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10242 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10244 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10245 // First (resp. Second) is the first (resp. Second) potentially candidate
10246 // to be placed in a paired load.
10247 const LoadedSlice *First = nullptr;
10248 const LoadedSlice *Second = nullptr;
10249 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10250 // Set the beginning of the pair.
10253 Second = &LoadedSlices[CurrSlice];
10255 // If First is NULL, it means we start a new pair.
10256 // Get to the next slice.
10260 EVT LoadedType = First->getLoadedType();
10262 // If the types of the slices are different, we cannot pair them.
10263 if (LoadedType != Second->getLoadedType())
10266 // Check if the target supplies paired loads for this type.
10267 unsigned RequiredAlignment = 0;
10268 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10269 // move to the next pair, this type is hopeless.
10273 // Check if we meet the alignment requirement.
10274 if (RequiredAlignment > First->getAlignment())
10277 // Check that both loads are next to each other in memory.
10278 if (!areSlicesNextToEachOther(*First, *Second))
10281 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10282 --GlobalLSCost.Loads;
10283 // Move to the next pair.
10288 /// \brief Check the profitability of all involved LoadedSlice.
10289 /// Currently, it is considered profitable if there is exactly two
10290 /// involved slices (1) which are (2) next to each other in memory, and
10291 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10293 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10294 /// the elements themselves.
10296 /// FIXME: When the cost model will be mature enough, we can relax
10297 /// constraints (1) and (2).
10298 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10299 const APInt &UsedBits, bool ForCodeSize) {
10300 unsigned NumberOfSlices = LoadedSlices.size();
10301 if (StressLoadSlicing)
10302 return NumberOfSlices > 1;
10305 if (NumberOfSlices != 2)
10309 if (!areUsedBitsDense(UsedBits))
10313 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10314 // The original code has one big load.
10315 OrigCost.Loads = 1;
10316 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10317 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10318 // Accumulate the cost of all the slices.
10319 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10320 GlobalSlicingCost += SliceCost;
10322 // Account as cost in the original configuration the gain obtained
10323 // with the current slices.
10324 OrigCost.addSliceGain(LS);
10327 // If the target supports paired load, adjust the cost accordingly.
10328 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10329 return OrigCost > GlobalSlicingCost;
10332 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10333 /// operations, split it in the various pieces being extracted.
10335 /// This sort of thing is introduced by SROA.
10336 /// This slicing takes care not to insert overlapping loads.
10337 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10338 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10339 if (Level < AfterLegalizeDAG)
10342 LoadSDNode *LD = cast<LoadSDNode>(N);
10343 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10344 !LD->getValueType(0).isInteger())
10347 // Keep track of already used bits to detect overlapping values.
10348 // In that case, we will just abort the transformation.
10349 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10351 SmallVector<LoadedSlice, 4> LoadedSlices;
10353 // Check if this load is used as several smaller chunks of bits.
10354 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10355 // of computation for each trunc.
10356 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10357 UI != UIEnd; ++UI) {
10358 // Skip the uses of the chain.
10359 if (UI.getUse().getResNo() != 0)
10362 SDNode *User = *UI;
10363 unsigned Shift = 0;
10365 // Check if this is a trunc(lshr).
10366 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10367 isa<ConstantSDNode>(User->getOperand(1))) {
10368 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10369 User = *User->use_begin();
10372 // At this point, User is a Truncate, iff we encountered, trunc or
10374 if (User->getOpcode() != ISD::TRUNCATE)
10377 // The width of the type must be a power of 2 and greater than 8-bits.
10378 // Otherwise the load cannot be represented in LLVM IR.
10379 // Moreover, if we shifted with a non-8-bits multiple, the slice
10380 // will be across several bytes. We do not support that.
10381 unsigned Width = User->getValueSizeInBits(0);
10382 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10385 // Build the slice for this chain of computations.
10386 LoadedSlice LS(User, LD, Shift, &DAG);
10387 APInt CurrentUsedBits = LS.getUsedBits();
10389 // Check if this slice overlaps with another.
10390 if ((CurrentUsedBits & UsedBits) != 0)
10392 // Update the bits used globally.
10393 UsedBits |= CurrentUsedBits;
10395 // Check if the new slice would be legal.
10399 // Record the slice.
10400 LoadedSlices.push_back(LS);
10403 // Abort slicing if it does not seem to be profitable.
10404 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10409 // Rewrite each chain to use an independent load.
10410 // By construction, each chain can be represented by a unique load.
10412 // Prepare the argument for the new token factor for all the slices.
10413 SmallVector<SDValue, 8> ArgChains;
10414 for (SmallVectorImpl<LoadedSlice>::const_iterator
10415 LSIt = LoadedSlices.begin(),
10416 LSItEnd = LoadedSlices.end();
10417 LSIt != LSItEnd; ++LSIt) {
10418 SDValue SliceInst = LSIt->loadSlice();
10419 CombineTo(LSIt->Inst, SliceInst, true);
10420 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10421 SliceInst = SliceInst.getOperand(0);
10422 assert(SliceInst->getOpcode() == ISD::LOAD &&
10423 "It takes more than a zext to get to the loaded slice!!");
10424 ArgChains.push_back(SliceInst.getValue(1));
10427 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10429 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10433 /// Check to see if V is (and load (ptr), imm), where the load is having
10434 /// specific bytes cleared out. If so, return the byte size being masked out
10435 /// and the shift amount.
10436 static std::pair<unsigned, unsigned>
10437 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10438 std::pair<unsigned, unsigned> Result(0, 0);
10440 // Check for the structure we're looking for.
10441 if (V->getOpcode() != ISD::AND ||
10442 !isa<ConstantSDNode>(V->getOperand(1)) ||
10443 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10446 // Check the chain and pointer.
10447 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10448 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10450 // The store should be chained directly to the load or be an operand of a
10452 if (LD == Chain.getNode())
10454 else if (Chain->getOpcode() != ISD::TokenFactor)
10455 return Result; // Fail.
10458 for (const SDValue &ChainOp : Chain->op_values())
10459 if (ChainOp.getNode() == LD) {
10463 if (!isOk) return Result;
10466 // This only handles simple types.
10467 if (V.getValueType() != MVT::i16 &&
10468 V.getValueType() != MVT::i32 &&
10469 V.getValueType() != MVT::i64)
10472 // Check the constant mask. Invert it so that the bits being masked out are
10473 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10474 // follow the sign bit for uniformity.
10475 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10476 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10477 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10478 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10479 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10480 if (NotMaskLZ == 64) return Result; // All zero mask.
10482 // See if we have a continuous run of bits. If so, we have 0*1+0*
10483 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10486 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10487 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10488 NotMaskLZ -= 64-V.getValueSizeInBits();
10490 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10491 switch (MaskedBytes) {
10495 default: return Result; // All one mask, or 5-byte mask.
10498 // Verify that the first bit starts at a multiple of mask so that the access
10499 // is aligned the same as the access width.
10500 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10502 Result.first = MaskedBytes;
10503 Result.second = NotMaskTZ/8;
10508 /// Check to see if IVal is something that provides a value as specified by
10509 /// MaskInfo. If so, replace the specified store with a narrower store of
10510 /// truncated IVal.
10512 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10513 SDValue IVal, StoreSDNode *St,
10515 unsigned NumBytes = MaskInfo.first;
10516 unsigned ByteShift = MaskInfo.second;
10517 SelectionDAG &DAG = DC->getDAG();
10519 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10520 // that uses this. If not, this is not a replacement.
10521 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10522 ByteShift*8, (ByteShift+NumBytes)*8);
10523 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10525 // Check that it is legal on the target to do this. It is legal if the new
10526 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10528 MVT VT = MVT::getIntegerVT(NumBytes*8);
10529 if (!DC->isTypeLegal(VT))
10532 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10533 // shifted by ByteShift and truncated down to NumBytes.
10536 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10537 DAG.getConstant(ByteShift*8, DL,
10538 DC->getShiftAmountTy(IVal.getValueType())));
10541 // Figure out the offset for the store and the alignment of the access.
10543 unsigned NewAlign = St->getAlignment();
10545 if (DAG.getDataLayout().isLittleEndian())
10546 StOffset = ByteShift;
10548 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10550 SDValue Ptr = St->getBasePtr();
10553 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10554 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10555 NewAlign = MinAlign(NewAlign, StOffset);
10558 // Truncate down to the new size.
10559 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10562 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10563 St->getPointerInfo().getWithOffset(StOffset),
10564 false, false, NewAlign).getNode();
10568 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10569 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10570 /// narrowing the load and store if it would end up being a win for performance
10572 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10573 StoreSDNode *ST = cast<StoreSDNode>(N);
10574 if (ST->isVolatile())
10577 SDValue Chain = ST->getChain();
10578 SDValue Value = ST->getValue();
10579 SDValue Ptr = ST->getBasePtr();
10580 EVT VT = Value.getValueType();
10582 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10585 unsigned Opc = Value.getOpcode();
10587 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10588 // is a byte mask indicating a consecutive number of bytes, check to see if
10589 // Y is known to provide just those bytes. If so, we try to replace the
10590 // load + replace + store sequence with a single (narrower) store, which makes
10592 if (Opc == ISD::OR) {
10593 std::pair<unsigned, unsigned> MaskedLoad;
10594 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10595 if (MaskedLoad.first)
10596 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10597 Value.getOperand(1), ST,this))
10598 return SDValue(NewST, 0);
10600 // Or is commutative, so try swapping X and Y.
10601 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10602 if (MaskedLoad.first)
10603 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10604 Value.getOperand(0), ST,this))
10605 return SDValue(NewST, 0);
10608 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10609 Value.getOperand(1).getOpcode() != ISD::Constant)
10612 SDValue N0 = Value.getOperand(0);
10613 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10614 Chain == SDValue(N0.getNode(), 1)) {
10615 LoadSDNode *LD = cast<LoadSDNode>(N0);
10616 if (LD->getBasePtr() != Ptr ||
10617 LD->getPointerInfo().getAddrSpace() !=
10618 ST->getPointerInfo().getAddrSpace())
10621 // Find the type to narrow it the load / op / store to.
10622 SDValue N1 = Value.getOperand(1);
10623 unsigned BitWidth = N1.getValueSizeInBits();
10624 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10625 if (Opc == ISD::AND)
10626 Imm ^= APInt::getAllOnesValue(BitWidth);
10627 if (Imm == 0 || Imm.isAllOnesValue())
10629 unsigned ShAmt = Imm.countTrailingZeros();
10630 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10631 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10632 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10633 // The narrowing should be profitable, the load/store operation should be
10634 // legal (or custom) and the store size should be equal to the NewVT width.
10635 while (NewBW < BitWidth &&
10636 (NewVT.getStoreSizeInBits() != NewBW ||
10637 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10638 !TLI.isNarrowingProfitable(VT, NewVT))) {
10639 NewBW = NextPowerOf2(NewBW);
10640 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10642 if (NewBW >= BitWidth)
10645 // If the lsb changed does not start at the type bitwidth boundary,
10646 // start at the previous one.
10648 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10649 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10650 std::min(BitWidth, ShAmt + NewBW));
10651 if ((Imm & Mask) == Imm) {
10652 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10653 if (Opc == ISD::AND)
10654 NewImm ^= APInt::getAllOnesValue(NewBW);
10655 uint64_t PtrOff = ShAmt / 8;
10656 // For big endian targets, we need to adjust the offset to the pointer to
10657 // load the correct bytes.
10658 if (DAG.getDataLayout().isBigEndian())
10659 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10661 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10662 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10663 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10666 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10667 Ptr.getValueType(), Ptr,
10668 DAG.getConstant(PtrOff, SDLoc(LD),
10669 Ptr.getValueType()));
10670 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10671 LD->getChain(), NewPtr,
10672 LD->getPointerInfo().getWithOffset(PtrOff),
10673 LD->isVolatile(), LD->isNonTemporal(),
10674 LD->isInvariant(), NewAlign,
10676 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10677 DAG.getConstant(NewImm, SDLoc(Value),
10679 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10681 ST->getPointerInfo().getWithOffset(PtrOff),
10682 false, false, NewAlign);
10684 AddToWorklist(NewPtr.getNode());
10685 AddToWorklist(NewLD.getNode());
10686 AddToWorklist(NewVal.getNode());
10687 WorklistRemover DeadNodes(*this);
10688 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10697 /// For a given floating point load / store pair, if the load value isn't used
10698 /// by any other operations, then consider transforming the pair to integer
10699 /// load / store operations if the target deems the transformation profitable.
10700 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10701 StoreSDNode *ST = cast<StoreSDNode>(N);
10702 SDValue Chain = ST->getChain();
10703 SDValue Value = ST->getValue();
10704 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10705 Value.hasOneUse() &&
10706 Chain == SDValue(Value.getNode(), 1)) {
10707 LoadSDNode *LD = cast<LoadSDNode>(Value);
10708 EVT VT = LD->getMemoryVT();
10709 if (!VT.isFloatingPoint() ||
10710 VT != ST->getMemoryVT() ||
10711 LD->isNonTemporal() ||
10712 ST->isNonTemporal() ||
10713 LD->getPointerInfo().getAddrSpace() != 0 ||
10714 ST->getPointerInfo().getAddrSpace() != 0)
10717 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10718 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10719 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10720 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10721 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10724 unsigned LDAlign = LD->getAlignment();
10725 unsigned STAlign = ST->getAlignment();
10726 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10727 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10728 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10731 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10732 LD->getChain(), LD->getBasePtr(),
10733 LD->getPointerInfo(),
10734 false, false, false, LDAlign);
10736 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10737 NewLD, ST->getBasePtr(),
10738 ST->getPointerInfo(),
10739 false, false, STAlign);
10741 AddToWorklist(NewLD.getNode());
10742 AddToWorklist(NewST.getNode());
10743 WorklistRemover DeadNodes(*this);
10744 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10753 /// Helper struct to parse and store a memory address as base + index + offset.
10754 /// We ignore sign extensions when it is safe to do so.
10755 /// The following two expressions are not equivalent. To differentiate we need
10756 /// to store whether there was a sign extension involved in the index
10758 /// (load (i64 add (i64 copyfromreg %c)
10759 /// (i64 signextend (add (i8 load %index)
10763 /// (load (i64 add (i64 copyfromreg %c)
10764 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10766 struct BaseIndexOffset {
10770 bool IsIndexSignExt;
10772 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10774 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10775 bool IsIndexSignExt) :
10776 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10778 bool equalBaseIndex(const BaseIndexOffset &Other) {
10779 return Other.Base == Base && Other.Index == Index &&
10780 Other.IsIndexSignExt == IsIndexSignExt;
10783 /// Parses tree in Ptr for base, index, offset addresses.
10784 static BaseIndexOffset match(SDValue Ptr) {
10785 bool IsIndexSignExt = false;
10787 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10788 // instruction, then it could be just the BASE or everything else we don't
10789 // know how to handle. Just use Ptr as BASE and give up.
10790 if (Ptr->getOpcode() != ISD::ADD)
10791 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10793 // We know that we have at least an ADD instruction. Try to pattern match
10794 // the simple case of BASE + OFFSET.
10795 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10796 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10797 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10801 // Inside a loop the current BASE pointer is calculated using an ADD and a
10802 // MUL instruction. In this case Ptr is the actual BASE pointer.
10803 // (i64 add (i64 %array_ptr)
10804 // (i64 mul (i64 %induction_var)
10805 // (i64 %element_size)))
10806 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10807 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10809 // Look at Base + Index + Offset cases.
10810 SDValue Base = Ptr->getOperand(0);
10811 SDValue IndexOffset = Ptr->getOperand(1);
10813 // Skip signextends.
10814 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10815 IndexOffset = IndexOffset->getOperand(0);
10816 IsIndexSignExt = true;
10819 // Either the case of Base + Index (no offset) or something else.
10820 if (IndexOffset->getOpcode() != ISD::ADD)
10821 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10823 // Now we have the case of Base + Index + offset.
10824 SDValue Index = IndexOffset->getOperand(0);
10825 SDValue Offset = IndexOffset->getOperand(1);
10827 if (!isa<ConstantSDNode>(Offset))
10828 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10830 // Ignore signextends.
10831 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10832 Index = Index->getOperand(0);
10833 IsIndexSignExt = true;
10834 } else IsIndexSignExt = false;
10836 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10837 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10842 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10844 ArrayRef<MemOpLink> Stores,
10845 SmallVectorImpl<SDValue> &Chains,
10847 SmallVector<SDValue, 8> BuildVector;
10849 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10850 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10851 Chains.push_back(St->getChain());
10852 BuildVector.push_back(St->getValue());
10855 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10858 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10859 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10860 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10861 // Make sure we have something to merge.
10865 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10866 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10867 unsigned LatestNodeUsed = 0;
10869 for (unsigned i=0; i < NumStores; ++i) {
10870 // Find a chain for the new wide-store operand. Notice that some
10871 // of the store nodes that we found may not be selected for inclusion
10872 // in the wide store. The chain we use needs to be the chain of the
10873 // latest store node which is *used* and replaced by the wide store.
10874 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10875 LatestNodeUsed = i;
10878 SmallVector<SDValue, 8> Chains;
10880 // The latest Node in the DAG.
10881 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10882 SDLoc DL(StoreNodes[0].MemNode);
10886 bool IsVec = MemVT.isVector();
10887 unsigned Elts = NumStores;
10889 // When merging vector stores, get the total number of elements.
10890 Elts *= MemVT.getVectorNumElements();
10892 // Get the type for the merged vector store.
10893 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10894 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10896 if (IsConstantSrc) {
10897 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10899 SmallVector<SDValue, 8> Ops;
10900 for (unsigned i = 0; i < NumStores; ++i) {
10901 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10902 SDValue Val = St->getValue();
10903 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10904 if (Val.getValueType() != MemVT)
10906 Ops.push_back(Val);
10907 Chains.push_back(St->getChain());
10910 // Build the extracted vector elements back into a vector.
10911 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10914 // We should always use a vector store when merging extracted vector
10915 // elements, so this path implies a store of constants.
10916 assert(IsConstantSrc && "Merged vector elements should use vector store");
10918 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10919 APInt StoreInt(SizeInBits, 0);
10921 // Construct a single integer constant which is made of the smaller
10922 // constant inputs.
10923 bool IsLE = DAG.getDataLayout().isLittleEndian();
10924 for (unsigned i = 0; i < NumStores; ++i) {
10925 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10926 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10927 Chains.push_back(St->getChain());
10929 SDValue Val = St->getValue();
10930 StoreInt <<= ElementSizeBytes * 8;
10931 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10932 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10933 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10934 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10936 llvm_unreachable("Invalid constant element type");
10940 // Create the new Load and Store operations.
10941 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10942 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10945 assert(!Chains.empty());
10947 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10948 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
10949 FirstInChain->getBasePtr(),
10950 FirstInChain->getPointerInfo(),
10952 FirstInChain->getAlignment());
10954 // Replace the last store with the new store
10955 CombineTo(LatestOp, NewStore);
10956 // Erase all other stores.
10957 for (unsigned i = 0; i < NumStores; ++i) {
10958 if (StoreNodes[i].MemNode == LatestOp)
10960 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10961 // ReplaceAllUsesWith will replace all uses that existed when it was
10962 // called, but graph optimizations may cause new ones to appear. For
10963 // example, the case in pr14333 looks like
10965 // St's chain -> St -> another store -> X
10967 // And the only difference from St to the other store is the chain.
10968 // When we change it's chain to be St's chain they become identical,
10969 // get CSEed and the net result is that X is now a use of St.
10970 // Since we know that St is redundant, just iterate.
10971 while (!St->use_empty())
10972 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10973 deleteAndRecombine(St);
10979 void DAGCombiner::getStoreMergeAndAliasCandidates(
10980 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10981 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10982 // This holds the base pointer, index, and the offset in bytes from the base
10984 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10986 // We must have a base and an offset.
10987 if (!BasePtr.Base.getNode())
10990 // Do not handle stores to undef base pointers.
10991 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10994 // Walk up the chain and look for nodes with offsets from the same
10995 // base pointer. Stop when reaching an instruction with a different kind
10996 // or instruction which has a different base pointer.
10997 EVT MemVT = St->getMemoryVT();
10999 StoreSDNode *Index = St;
11002 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11003 : DAG.getSubtarget().useAA();
11006 // Look at other users of the same chain. Stores on the same chain do not
11007 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11008 // to be on the same chain, so don't bother looking at adjacent chains.
11010 SDValue Chain = St->getChain();
11011 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11012 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11013 if (I.getOperandNo() != 0)
11016 if (OtherST->isVolatile() || OtherST->isIndexed())
11019 if (OtherST->getMemoryVT() != MemVT)
11022 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11024 if (Ptr.equalBaseIndex(BasePtr))
11025 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11033 // If the chain has more than one use, then we can't reorder the mem ops.
11034 if (Index != St && !SDValue(Index, 0)->hasOneUse())
11037 // Find the base pointer and offset for this memory node.
11038 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11040 // Check that the base pointer is the same as the original one.
11041 if (!Ptr.equalBaseIndex(BasePtr))
11044 // The memory operands must not be volatile.
11045 if (Index->isVolatile() || Index->isIndexed())
11049 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11050 if (St->isTruncatingStore())
11053 // The stored memory type must be the same.
11054 if (Index->getMemoryVT() != MemVT)
11057 // We found a potential memory operand to merge.
11058 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11060 // Find the next memory operand in the chain. If the next operand in the
11061 // chain is a store then move up and continue the scan with the next
11062 // memory operand. If the next operand is a load save it and use alias
11063 // information to check if it interferes with anything.
11064 SDNode *NextInChain = Index->getChain().getNode();
11066 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11067 // We found a store node. Use it for the next iteration.
11070 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11071 if (Ldn->isVolatile()) {
11076 // Save the load node for later. Continue the scan.
11077 AliasLoadNodes.push_back(Ldn);
11078 NextInChain = Ldn->getChain().getNode();
11088 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11089 if (OptLevel == CodeGenOpt::None)
11092 EVT MemVT = St->getMemoryVT();
11093 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11094 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11095 Attribute::NoImplicitFloat);
11097 // This function cannot currently deal with non-byte-sized memory sizes.
11098 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11101 if (!MemVT.isSimple())
11104 // Perform an early exit check. Do not bother looking at stored values that
11105 // are not constants, loads, or extracted vector elements.
11106 SDValue StoredVal = St->getValue();
11107 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11108 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11109 isa<ConstantFPSDNode>(StoredVal);
11110 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11111 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11113 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11116 // Don't merge vectors into wider vectors if the source data comes from loads.
11117 // TODO: This restriction can be lifted by using logic similar to the
11118 // ExtractVecSrc case.
11119 if (MemVT.isVector() && IsLoadSrc)
11122 // Only look at ends of store sequences.
11123 SDValue Chain = SDValue(St, 0);
11124 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11127 // Save the LoadSDNodes that we find in the chain.
11128 // We need to make sure that these nodes do not interfere with
11129 // any of the store nodes.
11130 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11132 // Save the StoreSDNodes that we find in the chain.
11133 SmallVector<MemOpLink, 8> StoreNodes;
11135 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11137 // Check if there is anything to merge.
11138 if (StoreNodes.size() < 2)
11141 // Sort the memory operands according to their distance from the base pointer.
11142 std::sort(StoreNodes.begin(), StoreNodes.end(),
11143 [](MemOpLink LHS, MemOpLink RHS) {
11144 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11145 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11146 LHS.SequenceNum > RHS.SequenceNum);
11149 // Scan the memory operations on the chain and find the first non-consecutive
11150 // store memory address.
11151 unsigned LastConsecutiveStore = 0;
11152 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11153 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11155 // Check that the addresses are consecutive starting from the second
11156 // element in the list of stores.
11158 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11159 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11163 bool Alias = false;
11164 // Check if this store interferes with any of the loads that we found.
11165 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11166 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11170 // We found a load that alias with this store. Stop the sequence.
11174 // Mark this node as useful.
11175 LastConsecutiveStore = i;
11178 // The node with the lowest store address.
11179 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11180 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11181 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11182 LLVMContext &Context = *DAG.getContext();
11183 const DataLayout &DL = DAG.getDataLayout();
11185 // Store the constants into memory as one consecutive store.
11186 if (IsConstantSrc) {
11187 unsigned LastLegalType = 0;
11188 unsigned LastLegalVectorType = 0;
11189 bool NonZero = false;
11190 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11191 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11192 SDValue StoredVal = St->getValue();
11194 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11195 NonZero |= !C->isNullValue();
11196 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11197 NonZero |= !C->getConstantFPValue()->isNullValue();
11203 // Find a legal type for the constant store.
11204 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11205 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11207 if (TLI.isTypeLegal(StoreTy) &&
11208 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11209 FirstStoreAlign, &IsFast) && IsFast) {
11210 LastLegalType = i+1;
11211 // Or check whether a truncstore is legal.
11212 } else if (TLI.getTypeAction(Context, StoreTy) ==
11213 TargetLowering::TypePromoteInteger) {
11214 EVT LegalizedStoredValueTy =
11215 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11216 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11217 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11218 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11220 LastLegalType = i + 1;
11224 // We only use vectors if the constant is known to be zero or the target
11225 // allows it and the function is not marked with the noimplicitfloat
11227 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11230 // Find a legal type for the vector store.
11231 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11232 if (TLI.isTypeLegal(Ty) &&
11233 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11234 FirstStoreAlign, &IsFast) && IsFast)
11235 LastLegalVectorType = i + 1;
11239 // Check if we found a legal integer type to store.
11240 if (LastLegalType == 0 && LastLegalVectorType == 0)
11243 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11244 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11246 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11250 // When extracting multiple vector elements, try to store them
11251 // in one vector store rather than a sequence of scalar stores.
11252 if (IsExtractVecSrc) {
11253 unsigned NumStoresToMerge = 0;
11254 bool IsVec = MemVT.isVector();
11255 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11256 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11257 unsigned StoreValOpcode = St->getValue().getOpcode();
11258 // This restriction could be loosened.
11259 // Bail out if any stored values are not elements extracted from a vector.
11260 // It should be possible to handle mixed sources, but load sources need
11261 // more careful handling (see the block of code below that handles
11262 // consecutive loads).
11263 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11264 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11267 // Find a legal type for the vector store.
11268 unsigned Elts = i + 1;
11270 // When merging vector stores, get the total number of elements.
11271 Elts *= MemVT.getVectorNumElements();
11273 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11275 if (TLI.isTypeLegal(Ty) &&
11276 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11277 FirstStoreAlign, &IsFast) && IsFast)
11278 NumStoresToMerge = i + 1;
11281 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11285 // Below we handle the case of multiple consecutive stores that
11286 // come from multiple consecutive loads. We merge them into a single
11287 // wide load and a single wide store.
11289 // Look for load nodes which are used by the stored values.
11290 SmallVector<MemOpLink, 8> LoadNodes;
11292 // Find acceptable loads. Loads need to have the same chain (token factor),
11293 // must not be zext, volatile, indexed, and they must be consecutive.
11294 BaseIndexOffset LdBasePtr;
11295 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11296 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11297 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11300 // Loads must only have one use.
11301 if (!Ld->hasNUsesOfValue(1, 0))
11304 // The memory operands must not be volatile.
11305 if (Ld->isVolatile() || Ld->isIndexed())
11308 // We do not accept ext loads.
11309 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11312 // The stored memory type must be the same.
11313 if (Ld->getMemoryVT() != MemVT)
11316 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11317 // If this is not the first ptr that we check.
11318 if (LdBasePtr.Base.getNode()) {
11319 // The base ptr must be the same.
11320 if (!LdPtr.equalBaseIndex(LdBasePtr))
11323 // Check that all other base pointers are the same as this one.
11327 // We found a potential memory operand to merge.
11328 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11331 if (LoadNodes.size() < 2)
11334 // If we have load/store pair instructions and we only have two values,
11336 unsigned RequiredAlignment;
11337 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11338 St->getAlignment() >= RequiredAlignment)
11341 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11342 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11343 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11345 // Scan the memory operations on the chain and find the first non-consecutive
11346 // load memory address. These variables hold the index in the store node
11348 unsigned LastConsecutiveLoad = 0;
11349 // This variable refers to the size and not index in the array.
11350 unsigned LastLegalVectorType = 0;
11351 unsigned LastLegalIntegerType = 0;
11352 StartAddress = LoadNodes[0].OffsetFromBase;
11353 SDValue FirstChain = FirstLoad->getChain();
11354 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11355 // All loads much share the same chain.
11356 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11359 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11360 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11362 LastConsecutiveLoad = i;
11363 // Find a legal type for the vector store.
11364 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11365 bool IsFastSt, IsFastLd;
11366 if (TLI.isTypeLegal(StoreTy) &&
11367 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11368 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11369 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11370 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11371 LastLegalVectorType = i + 1;
11374 // Find a legal type for the integer store.
11375 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11376 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11377 if (TLI.isTypeLegal(StoreTy) &&
11378 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11379 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11380 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11381 FirstLoadAlign, &IsFastLd) && IsFastLd)
11382 LastLegalIntegerType = i + 1;
11383 // Or check whether a truncstore and extload is legal.
11384 else if (TLI.getTypeAction(Context, StoreTy) ==
11385 TargetLowering::TypePromoteInteger) {
11386 EVT LegalizedStoredValueTy =
11387 TLI.getTypeToTransformTo(Context, StoreTy);
11388 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11389 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11390 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11391 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11392 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11393 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11395 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11396 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11398 LastLegalIntegerType = i+1;
11402 // Only use vector types if the vector type is larger than the integer type.
11403 // If they are the same, use integers.
11404 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11405 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11407 // We add +1 here because the LastXXX variables refer to location while
11408 // the NumElem refers to array/index size.
11409 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11410 NumElem = std::min(LastLegalType, NumElem);
11415 // Collect the chains from all merged stores.
11416 SmallVector<SDValue, 8> MergeStoreChains;
11417 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11419 // The latest Node in the DAG.
11420 unsigned LatestNodeUsed = 0;
11421 for (unsigned i=1; i<NumElem; ++i) {
11422 // Find a chain for the new wide-store operand. Notice that some
11423 // of the store nodes that we found may not be selected for inclusion
11424 // in the wide store. The chain we use needs to be the chain of the
11425 // latest store node which is *used* and replaced by the wide store.
11426 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11427 LatestNodeUsed = i;
11429 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11432 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11434 // Find if it is better to use vectors or integers to load and store
11438 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11440 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11441 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11444 SDLoc LoadDL(LoadNodes[0].MemNode);
11445 SDLoc StoreDL(StoreNodes[0].MemNode);
11447 // The merged loads are required to have the same chain, so using the first's
11448 // chain is acceptable.
11449 SDValue NewLoad = DAG.getLoad(
11450 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11451 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11453 SDValue NewStoreChain =
11454 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11456 SDValue NewStore = DAG.getStore(
11457 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11458 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11460 // Replace one of the loads with the new load.
11461 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11462 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11463 SDValue(NewLoad.getNode(), 1));
11465 // Remove the rest of the load chains.
11466 for (unsigned i = 1; i < NumElem ; ++i) {
11467 // Replace all chain users of the old load nodes with the chain of the new
11469 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11470 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11473 // Replace the last store with the new store.
11474 CombineTo(LatestOp, NewStore);
11475 // Erase all other stores.
11476 for (unsigned i = 0; i < NumElem ; ++i) {
11477 // Remove all Store nodes.
11478 if (StoreNodes[i].MemNode == LatestOp)
11480 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11481 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11482 deleteAndRecombine(St);
11488 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11492 // Replace the chain to avoid dependency.
11493 if (ST->isTruncatingStore()) {
11494 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11495 ST->getBasePtr(), ST->getMemoryVT(),
11496 ST->getMemOperand());
11498 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11499 ST->getMemOperand());
11502 // Create token to keep both nodes around.
11503 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11504 MVT::Other, ST->getChain(), ReplStore);
11506 // Make sure the new and old chains are cleaned up.
11507 AddToWorklist(Token.getNode());
11509 // Don't add users to work list.
11510 return CombineTo(ST, Token, false);
11513 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11514 SDValue Value = ST->getValue();
11515 if (Value.getOpcode() == ISD::TargetConstantFP)
11520 SDValue Chain = ST->getChain();
11521 SDValue Ptr = ST->getBasePtr();
11523 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11525 // NOTE: If the original store is volatile, this transform must not increase
11526 // the number of stores. For example, on x86-32 an f64 can be stored in one
11527 // processor operation but an i64 (which is not legal) requires two. So the
11528 // transform should not be done in this case.
11531 switch (CFP->getSimpleValueType(0).SimpleTy) {
11533 llvm_unreachable("Unknown FP type");
11534 case MVT::f16: // We don't do this for these yet.
11540 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11541 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11543 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11544 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11546 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11551 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11552 !ST->isVolatile()) ||
11553 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11555 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11556 getZExtValue(), SDLoc(CFP), MVT::i64);
11557 return DAG.getStore(Chain, DL, Tmp,
11558 Ptr, ST->getMemOperand());
11561 if (!ST->isVolatile() &&
11562 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11563 // Many FP stores are not made apparent until after legalize, e.g. for
11564 // argument passing. Since this is so common, custom legalize the
11565 // 64-bit integer store into two 32-bit stores.
11566 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11567 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11568 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11569 if (DAG.getDataLayout().isBigEndian())
11572 unsigned Alignment = ST->getAlignment();
11573 bool isVolatile = ST->isVolatile();
11574 bool isNonTemporal = ST->isNonTemporal();
11575 AAMDNodes AAInfo = ST->getAAInfo();
11577 SDValue St0 = DAG.getStore(Chain, DL, Lo,
11578 Ptr, ST->getPointerInfo(),
11579 isVolatile, isNonTemporal,
11580 ST->getAlignment(), AAInfo);
11581 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11582 DAG.getConstant(4, DL, Ptr.getValueType()));
11583 Alignment = MinAlign(Alignment, 4U);
11584 SDValue St1 = DAG.getStore(Chain, DL, Hi,
11585 Ptr, ST->getPointerInfo().getWithOffset(4),
11586 isVolatile, isNonTemporal,
11587 Alignment, AAInfo);
11588 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11596 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11597 StoreSDNode *ST = cast<StoreSDNode>(N);
11598 SDValue Chain = ST->getChain();
11599 SDValue Value = ST->getValue();
11600 SDValue Ptr = ST->getBasePtr();
11602 // If this is a store of a bit convert, store the input value if the
11603 // resultant store does not need a higher alignment than the original.
11604 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11605 ST->isUnindexed()) {
11606 unsigned OrigAlign = ST->getAlignment();
11607 EVT SVT = Value.getOperand(0).getValueType();
11608 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11609 SVT.getTypeForEVT(*DAG.getContext()));
11610 if (Align <= OrigAlign &&
11611 ((!LegalOperations && !ST->isVolatile()) ||
11612 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11613 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11614 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11615 ST->isNonTemporal(), OrigAlign,
11619 // Turn 'store undef, Ptr' -> nothing.
11620 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11623 // Try to infer better alignment information than the store already has.
11624 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11625 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11626 if (Align > ST->getAlignment()) {
11628 DAG.getTruncStore(Chain, SDLoc(N), Value,
11629 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11630 ST->isVolatile(), ST->isNonTemporal(), Align,
11632 if (NewStore.getNode() != N)
11633 return CombineTo(ST, NewStore, true);
11638 // Try transforming a pair floating point load / store ops to integer
11639 // load / store ops.
11640 if (SDValue NewST = TransformFPLoadStorePair(N))
11643 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11644 : DAG.getSubtarget().useAA();
11646 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11647 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11650 if (UseAA && ST->isUnindexed()) {
11651 // FIXME: We should do this even without AA enabled. AA will just allow
11652 // FindBetterChain to work in more situations. The problem with this is that
11653 // any combine that expects memory operations to be on consecutive chains
11654 // first needs to be updated to look for users of the same chain.
11656 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11657 // adjacent stores.
11658 if (findBetterNeighborChains(ST)) {
11659 // replaceStoreChain uses CombineTo, which handled all of the worklist
11660 // manipulation. Return the original node to not do anything else.
11661 return SDValue(ST, 0);
11665 // Try transforming N to an indexed store.
11666 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11667 return SDValue(N, 0);
11669 // FIXME: is there such a thing as a truncating indexed store?
11670 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11671 Value.getValueType().isInteger()) {
11672 // See if we can simplify the input to this truncstore with knowledge that
11673 // only the low bits are being used. For example:
11674 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11676 GetDemandedBits(Value,
11677 APInt::getLowBitsSet(
11678 Value.getValueType().getScalarType().getSizeInBits(),
11679 ST->getMemoryVT().getScalarType().getSizeInBits()));
11680 AddToWorklist(Value.getNode());
11681 if (Shorter.getNode())
11682 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11683 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11685 // Otherwise, see if we can simplify the operation with
11686 // SimplifyDemandedBits, which only works if the value has a single use.
11687 if (SimplifyDemandedBits(Value,
11688 APInt::getLowBitsSet(
11689 Value.getValueType().getScalarType().getSizeInBits(),
11690 ST->getMemoryVT().getScalarType().getSizeInBits())))
11691 return SDValue(N, 0);
11694 // If this is a load followed by a store to the same location, then the store
11696 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11697 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11698 ST->isUnindexed() && !ST->isVolatile() &&
11699 // There can't be any side effects between the load and store, such as
11700 // a call or store.
11701 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11702 // The store is dead, remove it.
11707 // If this is a store followed by a store with the same value to the same
11708 // location, then the store is dead/noop.
11709 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11710 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11711 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11712 ST1->isUnindexed() && !ST1->isVolatile()) {
11713 // The store is dead, remove it.
11718 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11719 // truncating store. We can do this even if this is already a truncstore.
11720 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11721 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11722 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11723 ST->getMemoryVT())) {
11724 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11725 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11728 // Only perform this optimization before the types are legal, because we
11729 // don't want to perform this optimization on every DAGCombine invocation.
11731 bool EverChanged = false;
11734 // There can be multiple store sequences on the same chain.
11735 // Keep trying to merge store sequences until we are unable to do so
11736 // or until we merge the last store on the chain.
11737 bool Changed = MergeConsecutiveStores(ST);
11738 EverChanged |= Changed;
11739 if (!Changed) break;
11740 } while (ST->getOpcode() != ISD::DELETED_NODE);
11743 return SDValue(N, 0);
11746 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11748 // Make sure to do this only after attempting to merge stores in order to
11749 // avoid changing the types of some subset of stores due to visit order,
11750 // preventing their merging.
11751 if (isa<ConstantFPSDNode>(Value)) {
11752 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11756 return ReduceLoadOpStoreWidth(N);
11759 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11760 SDValue InVec = N->getOperand(0);
11761 SDValue InVal = N->getOperand(1);
11762 SDValue EltNo = N->getOperand(2);
11765 // If the inserted element is an UNDEF, just use the input vector.
11766 if (InVal.getOpcode() == ISD::UNDEF)
11769 EVT VT = InVec.getValueType();
11771 // If we can't generate a legal BUILD_VECTOR, exit
11772 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11775 // Check that we know which element is being inserted
11776 if (!isa<ConstantSDNode>(EltNo))
11778 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11780 // Canonicalize insert_vector_elt dag nodes.
11782 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11783 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11785 // Do this only if the child insert_vector node has one use; also
11786 // do this only if indices are both constants and Idx1 < Idx0.
11787 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11788 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11789 unsigned OtherElt =
11790 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11791 if (Elt < OtherElt) {
11793 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11794 InVec.getOperand(0), InVal, EltNo);
11795 AddToWorklist(NewOp.getNode());
11796 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11797 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11801 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11802 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11803 // vector elements.
11804 SmallVector<SDValue, 8> Ops;
11805 // Do not combine these two vectors if the output vector will not replace
11806 // the input vector.
11807 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11808 Ops.append(InVec.getNode()->op_begin(),
11809 InVec.getNode()->op_end());
11810 } else if (InVec.getOpcode() == ISD::UNDEF) {
11811 unsigned NElts = VT.getVectorNumElements();
11812 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11817 // Insert the element
11818 if (Elt < Ops.size()) {
11819 // All the operands of BUILD_VECTOR must have the same type;
11820 // we enforce that here.
11821 EVT OpVT = Ops[0].getValueType();
11822 if (InVal.getValueType() != OpVT)
11823 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11824 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11825 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11829 // Return the new vector
11830 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11833 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11834 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11835 EVT ResultVT = EVE->getValueType(0);
11836 EVT VecEltVT = InVecVT.getVectorElementType();
11837 unsigned Align = OriginalLoad->getAlignment();
11838 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11839 VecEltVT.getTypeForEVT(*DAG.getContext()));
11841 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11846 SDValue NewPtr = OriginalLoad->getBasePtr();
11848 EVT PtrType = NewPtr.getValueType();
11849 MachinePointerInfo MPI;
11851 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11852 int Elt = ConstEltNo->getZExtValue();
11853 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11854 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11855 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11857 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11858 Offset = DAG.getNode(
11859 ISD::MUL, DL, PtrType, Offset,
11860 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11861 MPI = OriginalLoad->getPointerInfo();
11863 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11865 // The replacement we need to do here is a little tricky: we need to
11866 // replace an extractelement of a load with a load.
11867 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11868 // Note that this replacement assumes that the extractvalue is the only
11869 // use of the load; that's okay because we don't want to perform this
11870 // transformation in other cases anyway.
11873 if (ResultVT.bitsGT(VecEltVT)) {
11874 // If the result type of vextract is wider than the load, then issue an
11875 // extending load instead.
11876 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11880 Load = DAG.getExtLoad(
11881 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11882 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11883 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11884 Chain = Load.getValue(1);
11886 Load = DAG.getLoad(
11887 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11888 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11889 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11890 Chain = Load.getValue(1);
11891 if (ResultVT.bitsLT(VecEltVT))
11892 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11894 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11896 WorklistRemover DeadNodes(*this);
11897 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11898 SDValue To[] = { Load, Chain };
11899 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11900 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11901 // worklist explicitly as well.
11902 AddToWorklist(Load.getNode());
11903 AddUsersToWorklist(Load.getNode()); // Add users too
11904 // Make sure to revisit this node to clean it up; it will usually be dead.
11905 AddToWorklist(EVE);
11907 return SDValue(EVE, 0);
11910 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11911 // (vextract (scalar_to_vector val, 0) -> val
11912 SDValue InVec = N->getOperand(0);
11913 EVT VT = InVec.getValueType();
11914 EVT NVT = N->getValueType(0);
11916 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11917 // Check if the result type doesn't match the inserted element type. A
11918 // SCALAR_TO_VECTOR may truncate the inserted element and the
11919 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11920 SDValue InOp = InVec.getOperand(0);
11921 if (InOp.getValueType() != NVT) {
11922 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11923 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11928 SDValue EltNo = N->getOperand(1);
11929 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
11931 // extract_vector_elt (build_vector x, y), 1 -> y
11933 InVec.getOpcode() == ISD::BUILD_VECTOR &&
11934 TLI.isTypeLegal(VT) &&
11935 (InVec.hasOneUse() ||
11936 TLI.aggressivelyPreferBuildVectorSources(VT))) {
11937 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
11938 EVT InEltVT = Elt.getValueType();
11940 // Sometimes build_vector's scalar input types do not match result type.
11941 if (NVT == InEltVT)
11944 // TODO: It may be useful to truncate if free if the build_vector implicitly
11948 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11949 // We only perform this optimization before the op legalization phase because
11950 // we may introduce new vector instructions which are not backed by TD
11951 // patterns. For example on AVX, extracting elements from a wide vector
11952 // without using extract_subvector. However, if we can find an underlying
11953 // scalar value, then we can always use that.
11954 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
11955 int NumElem = VT.getVectorNumElements();
11956 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11957 // Find the new index to extract from.
11958 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
11960 // Extracting an undef index is undef.
11962 return DAG.getUNDEF(NVT);
11964 // Select the right vector half to extract from.
11966 if (OrigElt < NumElem) {
11967 SVInVec = InVec->getOperand(0);
11969 SVInVec = InVec->getOperand(1);
11970 OrigElt -= NumElem;
11973 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11974 SDValue InOp = SVInVec.getOperand(OrigElt);
11975 if (InOp.getValueType() != NVT) {
11976 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11977 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11983 // FIXME: We should handle recursing on other vector shuffles and
11984 // scalar_to_vector here as well.
11986 if (!LegalOperations) {
11987 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11988 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11989 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11993 bool BCNumEltsChanged = false;
11994 EVT ExtVT = VT.getVectorElementType();
11997 // If the result of load has to be truncated, then it's not necessarily
11999 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12002 if (InVec.getOpcode() == ISD::BITCAST) {
12003 // Don't duplicate a load with other uses.
12004 if (!InVec.hasOneUse())
12007 EVT BCVT = InVec.getOperand(0).getValueType();
12008 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12010 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12011 BCNumEltsChanged = true;
12012 InVec = InVec.getOperand(0);
12013 ExtVT = BCVT.getVectorElementType();
12016 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12017 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12018 ISD::isNormalLoad(InVec.getNode()) &&
12019 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12020 SDValue Index = N->getOperand(1);
12021 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12022 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12026 // Perform only after legalization to ensure build_vector / vector_shuffle
12027 // optimizations have already been done.
12028 if (!LegalOperations) return SDValue();
12030 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12031 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12032 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12035 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12037 LoadSDNode *LN0 = nullptr;
12038 const ShuffleVectorSDNode *SVN = nullptr;
12039 if (ISD::isNormalLoad(InVec.getNode())) {
12040 LN0 = cast<LoadSDNode>(InVec);
12041 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12042 InVec.getOperand(0).getValueType() == ExtVT &&
12043 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12044 // Don't duplicate a load with other uses.
12045 if (!InVec.hasOneUse())
12048 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12049 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12050 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12052 // (load $addr+1*size)
12054 // Don't duplicate a load with other uses.
12055 if (!InVec.hasOneUse())
12058 // If the bit convert changed the number of elements, it is unsafe
12059 // to examine the mask.
12060 if (BCNumEltsChanged)
12063 // Select the input vector, guarding against out of range extract vector.
12064 unsigned NumElems = VT.getVectorNumElements();
12065 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12066 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12068 if (InVec.getOpcode() == ISD::BITCAST) {
12069 // Don't duplicate a load with other uses.
12070 if (!InVec.hasOneUse())
12073 InVec = InVec.getOperand(0);
12075 if (ISD::isNormalLoad(InVec.getNode())) {
12076 LN0 = cast<LoadSDNode>(InVec);
12077 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12078 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12082 // Make sure we found a non-volatile load and the extractelement is
12084 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12087 // If Idx was -1 above, Elt is going to be -1, so just return undef.
12089 return DAG.getUNDEF(LVT);
12091 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12097 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12098 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12099 // We perform this optimization post type-legalization because
12100 // the type-legalizer often scalarizes integer-promoted vectors.
12101 // Performing this optimization before may create bit-casts which
12102 // will be type-legalized to complex code sequences.
12103 // We perform this optimization only before the operation legalizer because we
12104 // may introduce illegal operations.
12105 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12108 unsigned NumInScalars = N->getNumOperands();
12110 EVT VT = N->getValueType(0);
12112 // Check to see if this is a BUILD_VECTOR of a bunch of values
12113 // which come from any_extend or zero_extend nodes. If so, we can create
12114 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12115 // optimizations. We do not handle sign-extend because we can't fill the sign
12117 EVT SourceType = MVT::Other;
12118 bool AllAnyExt = true;
12120 for (unsigned i = 0; i != NumInScalars; ++i) {
12121 SDValue In = N->getOperand(i);
12122 // Ignore undef inputs.
12123 if (In.getOpcode() == ISD::UNDEF) continue;
12125 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
12126 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12128 // Abort if the element is not an extension.
12129 if (!ZeroExt && !AnyExt) {
12130 SourceType = MVT::Other;
12134 // The input is a ZeroExt or AnyExt. Check the original type.
12135 EVT InTy = In.getOperand(0).getValueType();
12137 // Check that all of the widened source types are the same.
12138 if (SourceType == MVT::Other)
12141 else if (InTy != SourceType) {
12142 // Multiple income types. Abort.
12143 SourceType = MVT::Other;
12147 // Check if all of the extends are ANY_EXTENDs.
12148 AllAnyExt &= AnyExt;
12151 // In order to have valid types, all of the inputs must be extended from the
12152 // same source type and all of the inputs must be any or zero extend.
12153 // Scalar sizes must be a power of two.
12154 EVT OutScalarTy = VT.getScalarType();
12155 bool ValidTypes = SourceType != MVT::Other &&
12156 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12157 isPowerOf2_32(SourceType.getSizeInBits());
12159 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12160 // turn into a single shuffle instruction.
12164 bool isLE = DAG.getDataLayout().isLittleEndian();
12165 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12166 assert(ElemRatio > 1 && "Invalid element size ratio");
12167 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12168 DAG.getConstant(0, SDLoc(N), SourceType);
12170 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12171 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12173 // Populate the new build_vector
12174 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12175 SDValue Cast = N->getOperand(i);
12176 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12177 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12178 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12180 if (Cast.getOpcode() == ISD::UNDEF)
12181 In = DAG.getUNDEF(SourceType);
12183 In = Cast->getOperand(0);
12184 unsigned Index = isLE ? (i * ElemRatio) :
12185 (i * ElemRatio + (ElemRatio - 1));
12187 assert(Index < Ops.size() && "Invalid index");
12191 // The type of the new BUILD_VECTOR node.
12192 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12193 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12194 "Invalid vector size");
12195 // Check if the new vector type is legal.
12196 if (!isTypeLegal(VecVT)) return SDValue();
12198 // Make the new BUILD_VECTOR.
12199 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12201 // The new BUILD_VECTOR node has the potential to be further optimized.
12202 AddToWorklist(BV.getNode());
12203 // Bitcast to the desired type.
12204 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12207 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12208 EVT VT = N->getValueType(0);
12210 unsigned NumInScalars = N->getNumOperands();
12213 EVT SrcVT = MVT::Other;
12214 unsigned Opcode = ISD::DELETED_NODE;
12215 unsigned NumDefs = 0;
12217 for (unsigned i = 0; i != NumInScalars; ++i) {
12218 SDValue In = N->getOperand(i);
12219 unsigned Opc = In.getOpcode();
12221 if (Opc == ISD::UNDEF)
12224 // If all scalar values are floats and converted from integers.
12225 if (Opcode == ISD::DELETED_NODE &&
12226 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12233 EVT InVT = In.getOperand(0).getValueType();
12235 // If all scalar values are typed differently, bail out. It's chosen to
12236 // simplify BUILD_VECTOR of integer types.
12237 if (SrcVT == MVT::Other)
12244 // If the vector has just one element defined, it's not worth to fold it into
12245 // a vectorized one.
12249 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12250 && "Should only handle conversion from integer to float.");
12251 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12253 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12255 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12258 // Just because the floating-point vector type is legal does not necessarily
12259 // mean that the corresponding integer vector type is.
12260 if (!isTypeLegal(NVT))
12263 SmallVector<SDValue, 8> Opnds;
12264 for (unsigned i = 0; i != NumInScalars; ++i) {
12265 SDValue In = N->getOperand(i);
12267 if (In.getOpcode() == ISD::UNDEF)
12268 Opnds.push_back(DAG.getUNDEF(SrcVT));
12270 Opnds.push_back(In.getOperand(0));
12272 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12273 AddToWorklist(BV.getNode());
12275 return DAG.getNode(Opcode, dl, VT, BV);
12278 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12279 unsigned NumInScalars = N->getNumOperands();
12281 EVT VT = N->getValueType(0);
12283 // A vector built entirely of undefs is undef.
12284 if (ISD::allOperandsUndef(N))
12285 return DAG.getUNDEF(VT);
12287 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12290 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12293 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12294 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12295 // at most two distinct vectors, turn this into a shuffle node.
12297 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12298 if (!isTypeLegal(VT))
12301 // May only combine to shuffle after legalize if shuffle is legal.
12302 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12305 SDValue VecIn1, VecIn2;
12306 bool UsesZeroVector = false;
12307 for (unsigned i = 0; i != NumInScalars; ++i) {
12308 SDValue Op = N->getOperand(i);
12309 // Ignore undef inputs.
12310 if (Op.getOpcode() == ISD::UNDEF) continue;
12312 // See if we can combine this build_vector into a blend with a zero vector.
12313 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12314 UsesZeroVector = true;
12318 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12319 // constant index, bail out.
12320 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12321 !isa<ConstantSDNode>(Op.getOperand(1))) {
12322 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12326 // We allow up to two distinct input vectors.
12327 SDValue ExtractedFromVec = Op.getOperand(0);
12328 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12331 if (!VecIn1.getNode()) {
12332 VecIn1 = ExtractedFromVec;
12333 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12334 VecIn2 = ExtractedFromVec;
12336 // Too many inputs.
12337 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12342 // If everything is good, we can make a shuffle operation.
12343 if (VecIn1.getNode()) {
12344 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12345 SmallVector<int, 8> Mask;
12346 for (unsigned i = 0; i != NumInScalars; ++i) {
12347 unsigned Opcode = N->getOperand(i).getOpcode();
12348 if (Opcode == ISD::UNDEF) {
12349 Mask.push_back(-1);
12353 // Operands can also be zero.
12354 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12355 assert(UsesZeroVector &&
12356 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12357 "Unexpected node found!");
12358 Mask.push_back(NumInScalars+i);
12362 // If extracting from the first vector, just use the index directly.
12363 SDValue Extract = N->getOperand(i);
12364 SDValue ExtVal = Extract.getOperand(1);
12365 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12366 if (Extract.getOperand(0) == VecIn1) {
12367 Mask.push_back(ExtIndex);
12371 // Otherwise, use InIdx + InputVecSize
12372 Mask.push_back(InNumElements + ExtIndex);
12375 // Avoid introducing illegal shuffles with zero.
12376 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12379 // We can't generate a shuffle node with mismatched input and output types.
12380 // Attempt to transform a single input vector to the correct type.
12381 if ((VT != VecIn1.getValueType())) {
12382 // If the input vector type has a different base type to the output
12383 // vector type, bail out.
12384 EVT VTElemType = VT.getVectorElementType();
12385 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12386 (VecIn2.getNode() &&
12387 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12390 // If the input vector is too small, widen it.
12391 // We only support widening of vectors which are half the size of the
12392 // output registers. For example XMM->YMM widening on X86 with AVX.
12393 EVT VecInT = VecIn1.getValueType();
12394 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12395 // If we only have one small input, widen it by adding undef values.
12396 if (!VecIn2.getNode())
12397 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12398 DAG.getUNDEF(VecIn1.getValueType()));
12399 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12400 // If we have two small inputs of the same type, try to concat them.
12401 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12402 VecIn2 = SDValue(nullptr, 0);
12405 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12406 // If the input vector is too large, try to split it.
12407 // We don't support having two input vectors that are too large.
12408 // If the zero vector was used, we can not split the vector,
12409 // since we'd need 3 inputs.
12410 if (UsesZeroVector || VecIn2.getNode())
12413 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12416 // Try to replace VecIn1 with two extract_subvectors
12417 // No need to update the masks, they should still be correct.
12418 VecIn2 = DAG.getNode(
12419 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12420 DAG.getConstant(VT.getVectorNumElements(), dl,
12421 TLI.getVectorIdxTy(DAG.getDataLayout())));
12422 VecIn1 = DAG.getNode(
12423 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12424 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12429 if (UsesZeroVector)
12430 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12431 DAG.getConstantFP(0.0, dl, VT);
12433 // If VecIn2 is unused then change it to undef.
12434 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12436 // Check that we were able to transform all incoming values to the same
12438 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12439 VecIn1.getValueType() != VT)
12442 // Return the new VECTOR_SHUFFLE node.
12446 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12452 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12453 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12454 EVT OpVT = N->getOperand(0).getValueType();
12456 // If the operands are legal vectors, leave them alone.
12457 if (TLI.isTypeLegal(OpVT))
12461 EVT VT = N->getValueType(0);
12462 SmallVector<SDValue, 8> Ops;
12464 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12465 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12467 // Keep track of what we encounter.
12468 bool AnyInteger = false;
12469 bool AnyFP = false;
12470 for (const SDValue &Op : N->ops()) {
12471 if (ISD::BITCAST == Op.getOpcode() &&
12472 !Op.getOperand(0).getValueType().isVector())
12473 Ops.push_back(Op.getOperand(0));
12474 else if (ISD::UNDEF == Op.getOpcode())
12475 Ops.push_back(ScalarUndef);
12479 // Note whether we encounter an integer or floating point scalar.
12480 // If it's neither, bail out, it could be something weird like x86mmx.
12481 EVT LastOpVT = Ops.back().getValueType();
12482 if (LastOpVT.isFloatingPoint())
12484 else if (LastOpVT.isInteger())
12490 // If any of the operands is a floating point scalar bitcast to a vector,
12491 // use floating point types throughout, and bitcast everything.
12492 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12494 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12495 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12497 for (SDValue &Op : Ops) {
12498 if (Op.getValueType() == SVT)
12500 if (Op.getOpcode() == ISD::UNDEF)
12503 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12508 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12509 VT.getSizeInBits() / SVT.getSizeInBits());
12510 return DAG.getNode(ISD::BITCAST, DL, VT,
12511 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12514 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12515 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12516 // most two distinct vectors the same size as the result, attempt to turn this
12517 // into a legal shuffle.
12518 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12519 EVT VT = N->getValueType(0);
12520 EVT OpVT = N->getOperand(0).getValueType();
12521 int NumElts = VT.getVectorNumElements();
12522 int NumOpElts = OpVT.getVectorNumElements();
12524 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12525 SmallVector<int, 8> Mask;
12527 for (SDValue Op : N->ops()) {
12528 // Peek through any bitcast.
12529 while (Op.getOpcode() == ISD::BITCAST)
12530 Op = Op.getOperand(0);
12532 // UNDEF nodes convert to UNDEF shuffle mask values.
12533 if (Op.getOpcode() == ISD::UNDEF) {
12534 Mask.append((unsigned)NumOpElts, -1);
12538 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12541 // What vector are we extracting the subvector from and at what index?
12542 SDValue ExtVec = Op.getOperand(0);
12544 // We want the EVT of the original extraction to correctly scale the
12545 // extraction index.
12546 EVT ExtVT = ExtVec.getValueType();
12548 // Peek through any bitcast.
12549 while (ExtVec.getOpcode() == ISD::BITCAST)
12550 ExtVec = ExtVec.getOperand(0);
12552 // UNDEF nodes convert to UNDEF shuffle mask values.
12553 if (ExtVec.getOpcode() == ISD::UNDEF) {
12554 Mask.append((unsigned)NumOpElts, -1);
12558 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12560 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12562 // Ensure that we are extracting a subvector from a vector the same
12563 // size as the result.
12564 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12567 // Scale the subvector index to account for any bitcast.
12568 int NumExtElts = ExtVT.getVectorNumElements();
12569 if (0 == (NumExtElts % NumElts))
12570 ExtIdx /= (NumExtElts / NumElts);
12571 else if (0 == (NumElts % NumExtElts))
12572 ExtIdx *= (NumElts / NumExtElts);
12576 // At most we can reference 2 inputs in the final shuffle.
12577 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12579 for (int i = 0; i != NumOpElts; ++i)
12580 Mask.push_back(i + ExtIdx);
12581 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12583 for (int i = 0; i != NumOpElts; ++i)
12584 Mask.push_back(i + ExtIdx + NumElts);
12590 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12593 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12594 DAG.getBitcast(VT, SV1), Mask);
12597 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12598 // If we only have one input vector, we don't need to do any concatenation.
12599 if (N->getNumOperands() == 1)
12600 return N->getOperand(0);
12602 // Check if all of the operands are undefs.
12603 EVT VT = N->getValueType(0);
12604 if (ISD::allOperandsUndef(N))
12605 return DAG.getUNDEF(VT);
12607 // Optimize concat_vectors where all but the first of the vectors are undef.
12608 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12609 return Op.getOpcode() == ISD::UNDEF;
12611 SDValue In = N->getOperand(0);
12612 assert(In.getValueType().isVector() && "Must concat vectors");
12614 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12615 if (In->getOpcode() == ISD::BITCAST &&
12616 !In->getOperand(0)->getValueType(0).isVector()) {
12617 SDValue Scalar = In->getOperand(0);
12619 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12620 // look through the trunc so we can still do the transform:
12621 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12622 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12623 !TLI.isTypeLegal(Scalar.getValueType()) &&
12624 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12625 Scalar = Scalar->getOperand(0);
12627 EVT SclTy = Scalar->getValueType(0);
12629 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12632 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12633 VT.getSizeInBits() / SclTy.getSizeInBits());
12634 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12637 SDLoc dl = SDLoc(N);
12638 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12639 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12643 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12644 // We have already tested above for an UNDEF only concatenation.
12645 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12646 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12647 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12648 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12650 bool AllBuildVectorsOrUndefs =
12651 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12652 if (AllBuildVectorsOrUndefs) {
12653 SmallVector<SDValue, 8> Opnds;
12654 EVT SVT = VT.getScalarType();
12657 if (!SVT.isFloatingPoint()) {
12658 // If BUILD_VECTOR are from built from integer, they may have different
12659 // operand types. Get the smallest type and truncate all operands to it.
12660 bool FoundMinVT = false;
12661 for (const SDValue &Op : N->ops())
12662 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12663 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12664 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12667 assert(FoundMinVT && "Concat vector type mismatch");
12670 for (const SDValue &Op : N->ops()) {
12671 EVT OpVT = Op.getValueType();
12672 unsigned NumElts = OpVT.getVectorNumElements();
12674 if (ISD::UNDEF == Op.getOpcode())
12675 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12677 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12678 if (SVT.isFloatingPoint()) {
12679 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12680 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12682 for (unsigned i = 0; i != NumElts; ++i)
12684 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12689 assert(VT.getVectorNumElements() == Opnds.size() &&
12690 "Concat vector type mismatch");
12691 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12694 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12695 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12698 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12699 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12700 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12703 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12704 // nodes often generate nop CONCAT_VECTOR nodes.
12705 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12706 // place the incoming vectors at the exact same location.
12707 SDValue SingleSource = SDValue();
12708 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12710 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12711 SDValue Op = N->getOperand(i);
12713 if (Op.getOpcode() == ISD::UNDEF)
12716 // Check if this is the identity extract:
12717 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12720 // Find the single incoming vector for the extract_subvector.
12721 if (SingleSource.getNode()) {
12722 if (Op.getOperand(0) != SingleSource)
12725 SingleSource = Op.getOperand(0);
12727 // Check the source type is the same as the type of the result.
12728 // If not, this concat may extend the vector, so we can not
12729 // optimize it away.
12730 if (SingleSource.getValueType() != N->getValueType(0))
12734 unsigned IdentityIndex = i * PartNumElem;
12735 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12736 // The extract index must be constant.
12740 // Check that we are reading from the identity index.
12741 if (CS->getZExtValue() != IdentityIndex)
12745 if (SingleSource.getNode())
12746 return SingleSource;
12751 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12752 EVT NVT = N->getValueType(0);
12753 SDValue V = N->getOperand(0);
12755 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12757 // (extract_subvec (concat V1, V2, ...), i)
12760 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12762 if (V->getOperand(0).getValueType() != NVT)
12764 unsigned Idx = N->getConstantOperandVal(1);
12765 unsigned NumElems = NVT.getVectorNumElements();
12766 assert((Idx % NumElems) == 0 &&
12767 "IDX in concat is not a multiple of the result vector length.");
12768 return V->getOperand(Idx / NumElems);
12772 if (V->getOpcode() == ISD::BITCAST)
12773 V = V.getOperand(0);
12775 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12777 // Handle only simple case where vector being inserted and vector
12778 // being extracted are of same type, and are half size of larger vectors.
12779 EVT BigVT = V->getOperand(0).getValueType();
12780 EVT SmallVT = V->getOperand(1).getValueType();
12781 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12784 // Only handle cases where both indexes are constants with the same type.
12785 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12786 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12788 if (InsIdx && ExtIdx &&
12789 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12790 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12792 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12794 // indices are equal or bit offsets are equal => V1
12795 // otherwise => (extract_subvec V1, ExtIdx)
12796 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12797 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12798 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12799 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12800 DAG.getNode(ISD::BITCAST, dl,
12801 N->getOperand(0).getValueType(),
12802 V->getOperand(0)), N->getOperand(1));
12809 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12810 SDValue V, SelectionDAG &DAG) {
12812 EVT VT = V.getValueType();
12814 switch (V.getOpcode()) {
12818 case ISD::CONCAT_VECTORS: {
12819 EVT OpVT = V->getOperand(0).getValueType();
12820 int OpSize = OpVT.getVectorNumElements();
12821 SmallBitVector OpUsedElements(OpSize, false);
12822 bool FoundSimplification = false;
12823 SmallVector<SDValue, 4> NewOps;
12824 NewOps.reserve(V->getNumOperands());
12825 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12826 SDValue Op = V->getOperand(i);
12827 bool OpUsed = false;
12828 for (int j = 0; j < OpSize; ++j)
12829 if (UsedElements[i * OpSize + j]) {
12830 OpUsedElements[j] = true;
12834 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12835 : DAG.getUNDEF(OpVT));
12836 FoundSimplification |= Op == NewOps.back();
12837 OpUsedElements.reset();
12839 if (FoundSimplification)
12840 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12844 case ISD::INSERT_SUBVECTOR: {
12845 SDValue BaseV = V->getOperand(0);
12846 SDValue SubV = V->getOperand(1);
12847 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12851 int SubSize = SubV.getValueType().getVectorNumElements();
12852 int Idx = IdxN->getZExtValue();
12853 bool SubVectorUsed = false;
12854 SmallBitVector SubUsedElements(SubSize, false);
12855 for (int i = 0; i < SubSize; ++i)
12856 if (UsedElements[i + Idx]) {
12857 SubVectorUsed = true;
12858 SubUsedElements[i] = true;
12859 UsedElements[i + Idx] = false;
12862 // Now recurse on both the base and sub vectors.
12863 SDValue SimplifiedSubV =
12865 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12866 : DAG.getUNDEF(SubV.getValueType());
12867 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12868 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12869 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12870 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12876 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12877 SDValue N1, SelectionDAG &DAG) {
12878 EVT VT = SVN->getValueType(0);
12879 int NumElts = VT.getVectorNumElements();
12880 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12881 for (int M : SVN->getMask())
12882 if (M >= 0 && M < NumElts)
12883 N0UsedElements[M] = true;
12884 else if (M >= NumElts)
12885 N1UsedElements[M - NumElts] = true;
12887 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12888 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12889 if (S0 == N0 && S1 == N1)
12892 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12895 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12896 // or turn a shuffle of a single concat into simpler shuffle then concat.
12897 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12898 EVT VT = N->getValueType(0);
12899 unsigned NumElts = VT.getVectorNumElements();
12901 SDValue N0 = N->getOperand(0);
12902 SDValue N1 = N->getOperand(1);
12903 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12905 SmallVector<SDValue, 4> Ops;
12906 EVT ConcatVT = N0.getOperand(0).getValueType();
12907 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12908 unsigned NumConcats = NumElts / NumElemsPerConcat;
12910 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12911 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12912 // half vector elements.
12913 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12914 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12915 SVN->getMask().end(), [](int i) { return i == -1; })) {
12916 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12917 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
12918 N1 = DAG.getUNDEF(ConcatVT);
12919 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12922 // Look at every vector that's inserted. We're looking for exact
12923 // subvector-sized copies from a concatenated vector
12924 for (unsigned I = 0; I != NumConcats; ++I) {
12925 // Make sure we're dealing with a copy.
12926 unsigned Begin = I * NumElemsPerConcat;
12927 bool AllUndef = true, NoUndef = true;
12928 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12929 if (SVN->getMaskElt(J) >= 0)
12936 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12939 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12940 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12943 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12944 if (FirstElt < N0.getNumOperands())
12945 Ops.push_back(N0.getOperand(FirstElt));
12947 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12949 } else if (AllUndef) {
12950 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12951 } else { // Mixed with general masks and undefs, can't do optimization.
12956 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12959 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12960 EVT VT = N->getValueType(0);
12961 unsigned NumElts = VT.getVectorNumElements();
12963 SDValue N0 = N->getOperand(0);
12964 SDValue N1 = N->getOperand(1);
12966 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12968 // Canonicalize shuffle undef, undef -> undef
12969 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12970 return DAG.getUNDEF(VT);
12972 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12974 // Canonicalize shuffle v, v -> v, undef
12976 SmallVector<int, 8> NewMask;
12977 for (unsigned i = 0; i != NumElts; ++i) {
12978 int Idx = SVN->getMaskElt(i);
12979 if (Idx >= (int)NumElts) Idx -= NumElts;
12980 NewMask.push_back(Idx);
12982 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12986 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12987 if (N0.getOpcode() == ISD::UNDEF) {
12988 SmallVector<int, 8> NewMask;
12989 for (unsigned i = 0; i != NumElts; ++i) {
12990 int Idx = SVN->getMaskElt(i);
12992 if (Idx >= (int)NumElts)
12995 Idx = -1; // remove reference to lhs
12997 NewMask.push_back(Idx);
12999 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13003 // Remove references to rhs if it is undef
13004 if (N1.getOpcode() == ISD::UNDEF) {
13005 bool Changed = false;
13006 SmallVector<int, 8> NewMask;
13007 for (unsigned i = 0; i != NumElts; ++i) {
13008 int Idx = SVN->getMaskElt(i);
13009 if (Idx >= (int)NumElts) {
13013 NewMask.push_back(Idx);
13016 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13019 // If it is a splat, check if the argument vector is another splat or a
13021 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13022 SDNode *V = N0.getNode();
13024 // If this is a bit convert that changes the element type of the vector but
13025 // not the number of vector elements, look through it. Be careful not to
13026 // look though conversions that change things like v4f32 to v2f64.
13027 if (V->getOpcode() == ISD::BITCAST) {
13028 SDValue ConvInput = V->getOperand(0);
13029 if (ConvInput.getValueType().isVector() &&
13030 ConvInput.getValueType().getVectorNumElements() == NumElts)
13031 V = ConvInput.getNode();
13034 if (V->getOpcode() == ISD::BUILD_VECTOR) {
13035 assert(V->getNumOperands() == NumElts &&
13036 "BUILD_VECTOR has wrong number of operands");
13038 bool AllSame = true;
13039 for (unsigned i = 0; i != NumElts; ++i) {
13040 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13041 Base = V->getOperand(i);
13045 // Splat of <u, u, u, u>, return <u, u, u, u>
13046 if (!Base.getNode())
13048 for (unsigned i = 0; i != NumElts; ++i) {
13049 if (V->getOperand(i) != Base) {
13054 // Splat of <x, x, x, x>, return <x, x, x, x>
13058 // Canonicalize any other splat as a build_vector.
13059 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13060 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13061 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13062 V->getValueType(0), Ops);
13064 // We may have jumped through bitcasts, so the type of the
13065 // BUILD_VECTOR may not match the type of the shuffle.
13066 if (V->getValueType(0) != VT)
13067 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13072 // There are various patterns used to build up a vector from smaller vectors,
13073 // subvectors, or elements. Scan chains of these and replace unused insertions
13074 // or components with undef.
13075 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13078 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13079 Level < AfterLegalizeVectorOps &&
13080 (N1.getOpcode() == ISD::UNDEF ||
13081 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13082 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13083 SDValue V = partitionShuffleOfConcats(N, DAG);
13089 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13090 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13091 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13092 SmallVector<SDValue, 8> Ops;
13093 for (int M : SVN->getMask()) {
13094 SDValue Op = DAG.getUNDEF(VT.getScalarType());
13096 int Idx = M % NumElts;
13097 SDValue &S = (M < (int)NumElts ? N0 : N1);
13098 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13099 Op = S.getOperand(Idx);
13100 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13102 Op = S.getOperand(0);
13104 // Operand can't be combined - bail out.
13110 if (Ops.size() == VT.getVectorNumElements()) {
13111 // BUILD_VECTOR requires all inputs to be of the same type, find the
13112 // maximum type and extend them all.
13113 EVT SVT = VT.getScalarType();
13114 if (SVT.isInteger())
13115 for (SDValue &Op : Ops)
13116 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13117 if (SVT != VT.getScalarType())
13118 for (SDValue &Op : Ops)
13119 Op = TLI.isZExtFree(Op.getValueType(), SVT)
13120 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13121 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13122 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13126 // If this shuffle only has a single input that is a bitcasted shuffle,
13127 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13128 // back to their original types.
13129 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13130 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13131 TLI.isTypeLegal(VT)) {
13133 // Peek through the bitcast only if there is one user.
13135 while (BC0.getOpcode() == ISD::BITCAST) {
13136 if (!BC0.hasOneUse())
13138 BC0 = BC0.getOperand(0);
13141 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13143 return SmallVector<int, 8>(Mask.begin(), Mask.end());
13145 SmallVector<int, 8> NewMask;
13147 for (int s = 0; s != Scale; ++s)
13148 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13152 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13153 EVT SVT = VT.getScalarType();
13154 EVT InnerVT = BC0->getValueType(0);
13155 EVT InnerSVT = InnerVT.getScalarType();
13157 // Determine which shuffle works with the smaller scalar type.
13158 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13159 EVT ScaleSVT = ScaleVT.getScalarType();
13161 if (TLI.isTypeLegal(ScaleVT) &&
13162 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13163 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13165 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13166 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13168 // Scale the shuffle masks to the smaller scalar type.
13169 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13170 SmallVector<int, 8> InnerMask =
13171 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13172 SmallVector<int, 8> OuterMask =
13173 ScaleShuffleMask(SVN->getMask(), OuterScale);
13175 // Merge the shuffle masks.
13176 SmallVector<int, 8> NewMask;
13177 for (int M : OuterMask)
13178 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13180 // Test for shuffle mask legality over both commutations.
13181 SDValue SV0 = BC0->getOperand(0);
13182 SDValue SV1 = BC0->getOperand(1);
13183 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13185 std::swap(SV0, SV1);
13186 ShuffleVectorSDNode::commuteMask(NewMask);
13187 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13191 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13192 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13193 return DAG.getNode(
13194 ISD::BITCAST, SDLoc(N), VT,
13195 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13201 // Canonicalize shuffles according to rules:
13202 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13203 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13204 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13205 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13206 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13207 TLI.isTypeLegal(VT)) {
13208 // The incoming shuffle must be of the same type as the result of the
13209 // current shuffle.
13210 assert(N1->getOperand(0).getValueType() == VT &&
13211 "Shuffle types don't match");
13213 SDValue SV0 = N1->getOperand(0);
13214 SDValue SV1 = N1->getOperand(1);
13215 bool HasSameOp0 = N0 == SV0;
13216 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13217 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13218 // Commute the operands of this shuffle so that next rule
13220 return DAG.getCommutedVectorShuffle(*SVN);
13223 // Try to fold according to rules:
13224 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13225 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13226 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13227 // Don't try to fold shuffles with illegal type.
13228 // Only fold if this shuffle is the only user of the other shuffle.
13229 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13230 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13231 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13233 // The incoming shuffle must be of the same type as the result of the
13234 // current shuffle.
13235 assert(OtherSV->getOperand(0).getValueType() == VT &&
13236 "Shuffle types don't match");
13239 SmallVector<int, 4> Mask;
13240 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13241 // operand, and SV1 as the second operand.
13242 for (unsigned i = 0; i != NumElts; ++i) {
13243 int Idx = SVN->getMaskElt(i);
13245 // Propagate Undef.
13246 Mask.push_back(Idx);
13250 SDValue CurrentVec;
13251 if (Idx < (int)NumElts) {
13252 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13253 // shuffle mask to identify which vector is actually referenced.
13254 Idx = OtherSV->getMaskElt(Idx);
13256 // Propagate Undef.
13257 Mask.push_back(Idx);
13261 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13262 : OtherSV->getOperand(1);
13264 // This shuffle index references an element within N1.
13268 // Simple case where 'CurrentVec' is UNDEF.
13269 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13270 Mask.push_back(-1);
13274 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13275 // will be the first or second operand of the combined shuffle.
13276 Idx = Idx % NumElts;
13277 if (!SV0.getNode() || SV0 == CurrentVec) {
13278 // Ok. CurrentVec is the left hand side.
13279 // Update the mask accordingly.
13281 Mask.push_back(Idx);
13285 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13286 if (SV1.getNode() && SV1 != CurrentVec)
13289 // Ok. CurrentVec is the right hand side.
13290 // Update the mask accordingly.
13292 Mask.push_back(Idx + NumElts);
13295 // Check if all indices in Mask are Undef. In case, propagate Undef.
13296 bool isUndefMask = true;
13297 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13298 isUndefMask &= Mask[i] < 0;
13301 return DAG.getUNDEF(VT);
13303 if (!SV0.getNode())
13304 SV0 = DAG.getUNDEF(VT);
13305 if (!SV1.getNode())
13306 SV1 = DAG.getUNDEF(VT);
13308 // Avoid introducing shuffles with illegal mask.
13309 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13310 ShuffleVectorSDNode::commuteMask(Mask);
13312 if (!TLI.isShuffleMaskLegal(Mask, VT))
13315 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13316 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13317 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13318 std::swap(SV0, SV1);
13321 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13322 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13323 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13324 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13330 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13331 SDValue InVal = N->getOperand(0);
13332 EVT VT = N->getValueType(0);
13334 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13335 // with a VECTOR_SHUFFLE.
13336 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13337 SDValue InVec = InVal->getOperand(0);
13338 SDValue EltNo = InVal->getOperand(1);
13340 // FIXME: We could support implicit truncation if the shuffle can be
13341 // scaled to a smaller vector scalar type.
13342 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13343 if (C0 && VT == InVec.getValueType() &&
13344 VT.getScalarType() == InVal.getValueType()) {
13345 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13346 int Elt = C0->getZExtValue();
13349 if (TLI.isShuffleMaskLegal(NewMask, VT))
13350 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13358 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13359 SDValue N0 = N->getOperand(0);
13360 SDValue N2 = N->getOperand(2);
13362 // If the input vector is a concatenation, and the insert replaces
13363 // one of the halves, we can optimize into a single concat_vectors.
13364 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13365 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13366 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13367 EVT VT = N->getValueType(0);
13369 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13370 // (concat_vectors Z, Y)
13372 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13373 N->getOperand(1), N0.getOperand(1));
13375 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13376 // (concat_vectors X, Z)
13377 if (InsIdx == VT.getVectorNumElements()/2)
13378 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13379 N0.getOperand(0), N->getOperand(1));
13385 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13386 SDValue N0 = N->getOperand(0);
13388 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13389 if (N0->getOpcode() == ISD::FP16_TO_FP)
13390 return N0->getOperand(0);
13395 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13396 SDValue N0 = N->getOperand(0);
13398 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13399 if (N0->getOpcode() == ISD::AND) {
13400 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13401 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13402 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13410 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13411 /// with the destination vector and a zero vector.
13412 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13413 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13414 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13415 EVT VT = N->getValueType(0);
13416 SDValue LHS = N->getOperand(0);
13417 SDValue RHS = N->getOperand(1);
13420 // Make sure we're not running after operation legalization where it
13421 // may have custom lowered the vector shuffles.
13422 if (LegalOperations)
13425 if (N->getOpcode() != ISD::AND)
13428 if (RHS.getOpcode() == ISD::BITCAST)
13429 RHS = RHS.getOperand(0);
13431 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13434 EVT RVT = RHS.getValueType();
13435 unsigned NumElts = RHS.getNumOperands();
13437 // Attempt to create a valid clear mask, splitting the mask into
13438 // sub elements and checking to see if each is
13439 // all zeros or all ones - suitable for shuffle masking.
13440 auto BuildClearMask = [&](int Split) {
13441 int NumSubElts = NumElts * Split;
13442 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13444 SmallVector<int, 8> Indices;
13445 for (int i = 0; i != NumSubElts; ++i) {
13446 int EltIdx = i / Split;
13447 int SubIdx = i % Split;
13448 SDValue Elt = RHS.getOperand(EltIdx);
13449 if (Elt.getOpcode() == ISD::UNDEF) {
13450 Indices.push_back(-1);
13455 if (isa<ConstantSDNode>(Elt))
13456 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13457 else if (isa<ConstantFPSDNode>(Elt))
13458 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13462 // Extract the sub element from the constant bit mask.
13463 if (DAG.getDataLayout().isBigEndian()) {
13464 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13466 Bits = Bits.lshr(SubIdx * NumSubBits);
13470 Bits = Bits.trunc(NumSubBits);
13472 if (Bits.isAllOnesValue())
13473 Indices.push_back(i);
13474 else if (Bits == 0)
13475 Indices.push_back(i + NumSubElts);
13480 // Let's see if the target supports this vector_shuffle.
13481 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13482 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13483 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13486 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13487 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13488 DAG.getBitcast(ClearVT, LHS),
13489 Zero, &Indices[0]));
13492 // Determine maximum split level (byte level masking).
13494 if (RVT.getScalarSizeInBits() % 8 == 0)
13495 MaxSplit = RVT.getScalarSizeInBits() / 8;
13497 for (int Split = 1; Split <= MaxSplit; ++Split)
13498 if (RVT.getScalarSizeInBits() % Split == 0)
13499 if (SDValue S = BuildClearMask(Split))
13505 /// Visit a binary vector operation, like ADD.
13506 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13507 assert(N->getValueType(0).isVector() &&
13508 "SimplifyVBinOp only works on vectors!");
13510 SDValue LHS = N->getOperand(0);
13511 SDValue RHS = N->getOperand(1);
13512 SDValue Ops[] = {LHS, RHS};
13514 // See if we can constant fold the vector operation.
13515 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13516 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13519 // Try to convert a constant mask AND into a shuffle clear mask.
13520 if (SDValue Shuffle = XformToShuffleWithZero(N))
13523 // Type legalization might introduce new shuffles in the DAG.
13524 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13525 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13526 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13527 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13528 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13529 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13530 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13531 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13533 if (SVN0->getMask().equals(SVN1->getMask())) {
13534 EVT VT = N->getValueType(0);
13535 SDValue UndefVector = LHS.getOperand(1);
13536 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13537 LHS.getOperand(0), RHS.getOperand(0),
13539 AddUsersToWorklist(N);
13540 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13541 &SVN0->getMask()[0]);
13548 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13549 SDValue N1, SDValue N2){
13550 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13552 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13553 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13555 // If we got a simplified select_cc node back from SimplifySelectCC, then
13556 // break it down into a new SETCC node, and a new SELECT node, and then return
13557 // the SELECT node, since we were called with a SELECT node.
13558 if (SCC.getNode()) {
13559 // Check to see if we got a select_cc back (to turn into setcc/select).
13560 // Otherwise, just return whatever node we got back, like fabs.
13561 if (SCC.getOpcode() == ISD::SELECT_CC) {
13562 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13564 SCC.getOperand(0), SCC.getOperand(1),
13565 SCC.getOperand(4));
13566 AddToWorklist(SETCC.getNode());
13567 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13568 SCC.getOperand(2), SCC.getOperand(3));
13576 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13577 /// being selected between, see if we can simplify the select. Callers of this
13578 /// should assume that TheSelect is deleted if this returns true. As such, they
13579 /// should return the appropriate thing (e.g. the node) back to the top-level of
13580 /// the DAG combiner loop to avoid it being looked at.
13581 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13584 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13585 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13586 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13587 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13588 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13589 SDValue Sqrt = RHS;
13592 const ConstantFPSDNode *NegZero = nullptr;
13594 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13595 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13596 CmpLHS = TheSelect->getOperand(0);
13597 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13599 // SELECT or VSELECT
13600 SDValue Cmp = TheSelect->getOperand(0);
13601 if (Cmp.getOpcode() == ISD::SETCC) {
13602 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13603 CmpLHS = Cmp.getOperand(0);
13604 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13607 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13608 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13609 CC == ISD::SETULT || CC == ISD::SETLT)) {
13610 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13611 CombineTo(TheSelect, Sqrt);
13616 // Cannot simplify select with vector condition
13617 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13619 // If this is a select from two identical things, try to pull the operation
13620 // through the select.
13621 if (LHS.getOpcode() != RHS.getOpcode() ||
13622 !LHS.hasOneUse() || !RHS.hasOneUse())
13625 // If this is a load and the token chain is identical, replace the select
13626 // of two loads with a load through a select of the address to load from.
13627 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13628 // constants have been dropped into the constant pool.
13629 if (LHS.getOpcode() == ISD::LOAD) {
13630 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13631 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13633 // Token chains must be identical.
13634 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13635 // Do not let this transformation reduce the number of volatile loads.
13636 LLD->isVolatile() || RLD->isVolatile() ||
13637 // FIXME: If either is a pre/post inc/dec load,
13638 // we'd need to split out the address adjustment.
13639 LLD->isIndexed() || RLD->isIndexed() ||
13640 // If this is an EXTLOAD, the VT's must match.
13641 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13642 // If this is an EXTLOAD, the kind of extension must match.
13643 (LLD->getExtensionType() != RLD->getExtensionType() &&
13644 // The only exception is if one of the extensions is anyext.
13645 LLD->getExtensionType() != ISD::EXTLOAD &&
13646 RLD->getExtensionType() != ISD::EXTLOAD) ||
13647 // FIXME: this discards src value information. This is
13648 // over-conservative. It would be beneficial to be able to remember
13649 // both potential memory locations. Since we are discarding
13650 // src value info, don't do the transformation if the memory
13651 // locations are not in the default address space.
13652 LLD->getPointerInfo().getAddrSpace() != 0 ||
13653 RLD->getPointerInfo().getAddrSpace() != 0 ||
13654 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13655 LLD->getBasePtr().getValueType()))
13658 // Check that the select condition doesn't reach either load. If so,
13659 // folding this will induce a cycle into the DAG. If not, this is safe to
13660 // xform, so create a select of the addresses.
13662 if (TheSelect->getOpcode() == ISD::SELECT) {
13663 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13664 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13665 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13667 // The loads must not depend on one another.
13668 if (LLD->isPredecessorOf(RLD) ||
13669 RLD->isPredecessorOf(LLD))
13671 Addr = DAG.getSelect(SDLoc(TheSelect),
13672 LLD->getBasePtr().getValueType(),
13673 TheSelect->getOperand(0), LLD->getBasePtr(),
13674 RLD->getBasePtr());
13675 } else { // Otherwise SELECT_CC
13676 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13677 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13679 if ((LLD->hasAnyUseOfValue(1) &&
13680 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13681 (RLD->hasAnyUseOfValue(1) &&
13682 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13685 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13686 LLD->getBasePtr().getValueType(),
13687 TheSelect->getOperand(0),
13688 TheSelect->getOperand(1),
13689 LLD->getBasePtr(), RLD->getBasePtr(),
13690 TheSelect->getOperand(4));
13694 // It is safe to replace the two loads if they have different alignments,
13695 // but the new load must be the minimum (most restrictive) alignment of the
13697 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13698 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13699 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13700 Load = DAG.getLoad(TheSelect->getValueType(0),
13702 // FIXME: Discards pointer and AA info.
13703 LLD->getChain(), Addr, MachinePointerInfo(),
13704 LLD->isVolatile(), LLD->isNonTemporal(),
13705 isInvariant, Alignment);
13707 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13708 RLD->getExtensionType() : LLD->getExtensionType(),
13710 TheSelect->getValueType(0),
13711 // FIXME: Discards pointer and AA info.
13712 LLD->getChain(), Addr, MachinePointerInfo(),
13713 LLD->getMemoryVT(), LLD->isVolatile(),
13714 LLD->isNonTemporal(), isInvariant, Alignment);
13717 // Users of the select now use the result of the load.
13718 CombineTo(TheSelect, Load);
13720 // Users of the old loads now use the new load's chain. We know the
13721 // old-load value is dead now.
13722 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13723 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13730 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13731 /// where 'cond' is the comparison specified by CC.
13732 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13733 SDValue N2, SDValue N3,
13734 ISD::CondCode CC, bool NotExtCompare) {
13735 // (x ? y : y) -> y.
13736 if (N2 == N3) return N2;
13738 EVT VT = N2.getValueType();
13739 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13740 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13742 // Determine if the condition we're dealing with is constant
13743 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13744 N0, N1, CC, DL, false);
13745 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13747 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13748 // fold select_cc true, x, y -> x
13749 // fold select_cc false, x, y -> y
13750 return !SCCC->isNullValue() ? N2 : N3;
13753 // Check to see if we can simplify the select into an fabs node
13754 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13755 // Allow either -0.0 or 0.0
13756 if (CFP->isZero()) {
13757 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13758 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13759 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13760 N2 == N3.getOperand(0))
13761 return DAG.getNode(ISD::FABS, DL, VT, N0);
13763 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13764 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13765 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13766 N2.getOperand(0) == N3)
13767 return DAG.getNode(ISD::FABS, DL, VT, N3);
13771 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13772 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13773 // in it. This is a win when the constant is not otherwise available because
13774 // it replaces two constant pool loads with one. We only do this if the FP
13775 // type is known to be legal, because if it isn't, then we are before legalize
13776 // types an we want the other legalization to happen first (e.g. to avoid
13777 // messing with soft float) and if the ConstantFP is not legal, because if
13778 // it is legal, we may not need to store the FP constant in a constant pool.
13779 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13780 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13781 if (TLI.isTypeLegal(N2.getValueType()) &&
13782 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13783 TargetLowering::Legal &&
13784 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13785 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13786 // If both constants have multiple uses, then we won't need to do an
13787 // extra load, they are likely around in registers for other users.
13788 (TV->hasOneUse() || FV->hasOneUse())) {
13789 Constant *Elts[] = {
13790 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13791 const_cast<ConstantFP*>(TV->getConstantFPValue())
13793 Type *FPTy = Elts[0]->getType();
13794 const DataLayout &TD = DAG.getDataLayout();
13796 // Create a ConstantArray of the two constants.
13797 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13799 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13800 TD.getPrefTypeAlignment(FPTy));
13801 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13803 // Get the offsets to the 0 and 1 element of the array so that we can
13804 // select between them.
13805 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13806 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13807 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13809 SDValue Cond = DAG.getSetCC(DL,
13810 getSetCCResultType(N0.getValueType()),
13812 AddToWorklist(Cond.getNode());
13813 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13815 AddToWorklist(CstOffset.getNode());
13816 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13818 AddToWorklist(CPIdx.getNode());
13819 return DAG.getLoad(
13820 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13821 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13822 false, false, false, Alignment);
13826 // Check to see if we can perform the "gzip trick", transforming
13827 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13828 if (isNullConstant(N3) && CC == ISD::SETLT &&
13829 (isNullConstant(N1) || // (a < 0) ? b : 0
13830 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13831 EVT XType = N0.getValueType();
13832 EVT AType = N2.getValueType();
13833 if (XType.bitsGE(AType)) {
13834 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13835 // single-bit constant.
13836 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13837 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13838 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13839 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13840 getShiftAmountTy(N0.getValueType()));
13841 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13843 AddToWorklist(Shift.getNode());
13845 if (XType.bitsGT(AType)) {
13846 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13847 AddToWorklist(Shift.getNode());
13850 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13853 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13855 DAG.getConstant(XType.getSizeInBits() - 1,
13857 getShiftAmountTy(N0.getValueType())));
13858 AddToWorklist(Shift.getNode());
13860 if (XType.bitsGT(AType)) {
13861 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13862 AddToWorklist(Shift.getNode());
13865 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13869 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13870 // where y is has a single bit set.
13871 // A plaintext description would be, we can turn the SELECT_CC into an AND
13872 // when the condition can be materialized as an all-ones register. Any
13873 // single bit-test can be materialized as an all-ones register with
13874 // shift-left and shift-right-arith.
13875 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13876 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13877 SDValue AndLHS = N0->getOperand(0);
13878 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13879 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13880 // Shift the tested bit over the sign bit.
13881 APInt AndMask = ConstAndRHS->getAPIntValue();
13883 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13884 getShiftAmountTy(AndLHS.getValueType()));
13885 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13887 // Now arithmetic right shift it all the way over, so the result is either
13888 // all-ones, or zero.
13890 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13891 getShiftAmountTy(Shl.getValueType()));
13892 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13894 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13898 // fold select C, 16, 0 -> shl C, 4
13899 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13900 TLI.getBooleanContents(N0.getValueType()) ==
13901 TargetLowering::ZeroOrOneBooleanContent) {
13903 // If the caller doesn't want us to simplify this into a zext of a compare,
13905 if (NotExtCompare && N2C->isOne())
13908 // Get a SetCC of the condition
13909 // NOTE: Don't create a SETCC if it's not legal on this target.
13910 if (!LegalOperations ||
13911 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13913 // cast from setcc result type to select result type
13915 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13917 if (N2.getValueType().bitsLT(SCC.getValueType()))
13918 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13919 N2.getValueType());
13921 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13922 N2.getValueType(), SCC);
13924 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13925 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13926 N2.getValueType(), SCC);
13929 AddToWorklist(SCC.getNode());
13930 AddToWorklist(Temp.getNode());
13935 // shl setcc result by log2 n2c
13936 return DAG.getNode(
13937 ISD::SHL, DL, N2.getValueType(), Temp,
13938 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13939 getShiftAmountTy(Temp.getValueType())));
13943 // Check to see if this is an integer abs.
13944 // select_cc setg[te] X, 0, X, -X ->
13945 // select_cc setgt X, -1, X, -X ->
13946 // select_cc setl[te] X, 0, -X, X ->
13947 // select_cc setlt X, 1, -X, X ->
13948 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13950 ConstantSDNode *SubC = nullptr;
13951 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13952 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13953 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13954 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13955 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13956 (N1C->isOne() && CC == ISD::SETLT)) &&
13957 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13958 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13960 EVT XType = N0.getValueType();
13961 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13963 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13965 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13966 getShiftAmountTy(N0.getValueType())));
13967 SDValue Add = DAG.getNode(ISD::ADD, DL,
13969 AddToWorklist(Shift.getNode());
13970 AddToWorklist(Add.getNode());
13971 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13978 /// This is a stub for TargetLowering::SimplifySetCC.
13979 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13980 SDValue N1, ISD::CondCode Cond,
13981 SDLoc DL, bool foldBooleans) {
13982 TargetLowering::DAGCombinerInfo
13983 DagCombineInfo(DAG, Level, false, this);
13984 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13987 /// Given an ISD::SDIV node expressing a divide by constant, return
13988 /// a DAG expression to select that will generate the same value by multiplying
13989 /// by a magic number.
13990 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13991 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13992 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13996 // Avoid division by zero.
13997 if (C->isNullValue())
14000 std::vector<SDNode*> Built;
14002 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14004 for (SDNode *N : Built)
14009 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14010 /// DAG expression that will generate the same value by right shifting.
14011 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14012 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14016 // Avoid division by zero.
14017 if (C->isNullValue())
14020 std::vector<SDNode *> Built;
14021 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14023 for (SDNode *N : Built)
14028 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14029 /// expression that will generate the same value by multiplying by a magic
14031 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14032 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14033 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14037 // Avoid division by zero.
14038 if (C->isNullValue())
14041 std::vector<SDNode*> Built;
14043 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14045 for (SDNode *N : Built)
14050 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14051 if (Level >= AfterLegalizeDAG)
14054 // Expose the DAG combiner to the target combiner implementations.
14055 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14057 unsigned Iterations = 0;
14058 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14060 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14061 // For the reciprocal, we need to find the zero of the function:
14062 // F(X) = A X - 1 [which has a zero at X = 1/A]
14064 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14065 // does not require additional intermediate precision]
14066 EVT VT = Op.getValueType();
14068 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14070 AddToWorklist(Est.getNode());
14072 // Newton iterations: Est = Est + Est (1 - Arg * Est)
14073 for (unsigned i = 0; i < Iterations; ++i) {
14074 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14075 AddToWorklist(NewEst.getNode());
14077 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14078 AddToWorklist(NewEst.getNode());
14080 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14081 AddToWorklist(NewEst.getNode());
14083 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14084 AddToWorklist(Est.getNode());
14093 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14094 /// For the reciprocal sqrt, we need to find the zero of the function:
14095 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14097 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14098 /// As a result, we precompute A/2 prior to the iteration loop.
14099 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14100 unsigned Iterations,
14101 SDNodeFlags *Flags) {
14102 EVT VT = Arg.getValueType();
14104 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14106 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14107 // this entire sequence requires only one FP constant.
14108 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14109 AddToWorklist(HalfArg.getNode());
14111 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14112 AddToWorklist(HalfArg.getNode());
14114 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14115 for (unsigned i = 0; i < Iterations; ++i) {
14116 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14117 AddToWorklist(NewEst.getNode());
14119 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14120 AddToWorklist(NewEst.getNode());
14122 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14123 AddToWorklist(NewEst.getNode());
14125 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14126 AddToWorklist(Est.getNode());
14131 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14132 /// For the reciprocal sqrt, we need to find the zero of the function:
14133 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14135 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14136 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14137 unsigned Iterations,
14138 SDNodeFlags *Flags) {
14139 EVT VT = Arg.getValueType();
14141 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14142 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14144 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14145 for (unsigned i = 0; i < Iterations; ++i) {
14146 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14147 AddToWorklist(HalfEst.getNode());
14149 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14150 AddToWorklist(Est.getNode());
14152 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14153 AddToWorklist(Est.getNode());
14155 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14156 AddToWorklist(Est.getNode());
14158 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14159 AddToWorklist(Est.getNode());
14164 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14165 if (Level >= AfterLegalizeDAG)
14168 // Expose the DAG combiner to the target combiner implementations.
14169 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14170 unsigned Iterations = 0;
14171 bool UseOneConstNR = false;
14172 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14173 AddToWorklist(Est.getNode());
14175 Est = UseOneConstNR ?
14176 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14177 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14185 /// Return true if base is a frame index, which is known not to alias with
14186 /// anything but itself. Provides base object and offset as results.
14187 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14188 const GlobalValue *&GV, const void *&CV) {
14189 // Assume it is a primitive operation.
14190 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14192 // If it's an adding a simple constant then integrate the offset.
14193 if (Base.getOpcode() == ISD::ADD) {
14194 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14195 Base = Base.getOperand(0);
14196 Offset += C->getZExtValue();
14200 // Return the underlying GlobalValue, and update the Offset. Return false
14201 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14202 // by multiple nodes with different offsets.
14203 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14204 GV = G->getGlobal();
14205 Offset += G->getOffset();
14209 // Return the underlying Constant value, and update the Offset. Return false
14210 // for ConstantSDNodes since the same constant pool entry may be represented
14211 // by multiple nodes with different offsets.
14212 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14213 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14214 : (const void *)C->getConstVal();
14215 Offset += C->getOffset();
14218 // If it's any of the following then it can't alias with anything but itself.
14219 return isa<FrameIndexSDNode>(Base);
14222 /// Return true if there is any possibility that the two addresses overlap.
14223 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14224 // If they are the same then they must be aliases.
14225 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14227 // If they are both volatile then they cannot be reordered.
14228 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14230 // If one operation reads from invariant memory, and the other may store, they
14231 // cannot alias. These should really be checking the equivalent of mayWrite,
14232 // but it only matters for memory nodes other than load /store.
14233 if (Op0->isInvariant() && Op1->writeMem())
14236 if (Op1->isInvariant() && Op0->writeMem())
14239 // Gather base node and offset information.
14240 SDValue Base1, Base2;
14241 int64_t Offset1, Offset2;
14242 const GlobalValue *GV1, *GV2;
14243 const void *CV1, *CV2;
14244 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14245 Base1, Offset1, GV1, CV1);
14246 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14247 Base2, Offset2, GV2, CV2);
14249 // If they have a same base address then check to see if they overlap.
14250 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14251 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14252 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14254 // It is possible for different frame indices to alias each other, mostly
14255 // when tail call optimization reuses return address slots for arguments.
14256 // To catch this case, look up the actual index of frame indices to compute
14257 // the real alias relationship.
14258 if (isFrameIndex1 && isFrameIndex2) {
14259 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14260 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14261 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14262 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14263 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14266 // Otherwise, if we know what the bases are, and they aren't identical, then
14267 // we know they cannot alias.
14268 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14271 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14272 // compared to the size and offset of the access, we may be able to prove they
14273 // do not alias. This check is conservative for now to catch cases created by
14274 // splitting vector types.
14275 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14276 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14277 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14278 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14279 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14280 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14281 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14283 // There is no overlap between these relatively aligned accesses of similar
14284 // size, return no alias.
14285 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14286 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14290 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14292 : DAG.getSubtarget().useAA();
14294 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14295 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14299 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14300 // Use alias analysis information.
14301 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14302 Op1->getSrcValueOffset());
14303 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14304 Op0->getSrcValueOffset() - MinOffset;
14305 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14306 Op1->getSrcValueOffset() - MinOffset;
14307 AliasResult AAResult =
14308 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14309 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14310 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14311 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14312 if (AAResult == NoAlias)
14316 // Otherwise we have to assume they alias.
14320 /// Walk up chain skipping non-aliasing memory nodes,
14321 /// looking for aliasing nodes and adding them to the Aliases vector.
14322 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14323 SmallVectorImpl<SDValue> &Aliases) {
14324 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14325 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14327 // Get alias information for node.
14328 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14331 Chains.push_back(OriginalChain);
14332 unsigned Depth = 0;
14334 // Look at each chain and determine if it is an alias. If so, add it to the
14335 // aliases list. If not, then continue up the chain looking for the next
14337 while (!Chains.empty()) {
14338 SDValue Chain = Chains.pop_back_val();
14340 // For TokenFactor nodes, look at each operand and only continue up the
14341 // chain until we reach the depth limit.
14343 // FIXME: The depth check could be made to return the last non-aliasing
14344 // chain we found before we hit a tokenfactor rather than the original
14348 Aliases.push_back(OriginalChain);
14352 // Don't bother if we've been before.
14353 if (!Visited.insert(Chain.getNode()).second)
14356 switch (Chain.getOpcode()) {
14357 case ISD::EntryToken:
14358 // Entry token is ideal chain operand, but handled in FindBetterChain.
14363 // Get alias information for Chain.
14364 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14365 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14367 // If chain is alias then stop here.
14368 if (!(IsLoad && IsOpLoad) &&
14369 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14370 Aliases.push_back(Chain);
14372 // Look further up the chain.
14373 Chains.push_back(Chain.getOperand(0));
14379 case ISD::TokenFactor:
14380 // We have to check each of the operands of the token factor for "small"
14381 // token factors, so we queue them up. Adding the operands to the queue
14382 // (stack) in reverse order maintains the original order and increases the
14383 // likelihood that getNode will find a matching token factor (CSE.)
14384 if (Chain.getNumOperands() > 16) {
14385 Aliases.push_back(Chain);
14388 for (unsigned n = Chain.getNumOperands(); n;)
14389 Chains.push_back(Chain.getOperand(--n));
14394 // For all other instructions we will just have to take what we can get.
14395 Aliases.push_back(Chain);
14400 // We need to be careful here to also search for aliases through the
14401 // value operand of a store, etc. Consider the following situation:
14403 // L1 = load Token1, %52
14404 // S1 = store Token1, L1, %51
14405 // L2 = load Token1, %52+8
14406 // S2 = store Token1, L2, %51+8
14407 // Token2 = Token(S1, S2)
14408 // L3 = load Token2, %53
14409 // S3 = store Token2, L3, %52
14410 // L4 = load Token2, %53+8
14411 // S4 = store Token2, L4, %52+8
14412 // If we search for aliases of S3 (which loads address %52), and we look
14413 // only through the chain, then we'll miss the trivial dependence on L1
14414 // (which also loads from %52). We then might change all loads and
14415 // stores to use Token1 as their chain operand, which could result in
14416 // copying %53 into %52 before copying %52 into %51 (which should
14419 // The problem is, however, that searching for such data dependencies
14420 // can become expensive, and the cost is not directly related to the
14421 // chain depth. Instead, we'll rule out such configurations here by
14422 // insisting that we've visited all chain users (except for users
14423 // of the original chain, which is not necessary). When doing this,
14424 // we need to look through nodes we don't care about (otherwise, things
14425 // like register copies will interfere with trivial cases).
14427 SmallVector<const SDNode *, 16> Worklist;
14428 for (const SDNode *N : Visited)
14429 if (N != OriginalChain.getNode())
14430 Worklist.push_back(N);
14432 while (!Worklist.empty()) {
14433 const SDNode *M = Worklist.pop_back_val();
14435 // We have already visited M, and want to make sure we've visited any uses
14436 // of M that we care about. For uses that we've not visisted, and don't
14437 // care about, queue them to the worklist.
14439 for (SDNode::use_iterator UI = M->use_begin(),
14440 UIE = M->use_end(); UI != UIE; ++UI)
14441 if (UI.getUse().getValueType() == MVT::Other &&
14442 Visited.insert(*UI).second) {
14443 if (isa<MemSDNode>(*UI)) {
14444 // We've not visited this use, and we care about it (it could have an
14445 // ordering dependency with the original node).
14447 Aliases.push_back(OriginalChain);
14451 // We've not visited this use, but we don't care about it. Mark it as
14452 // visited and enqueue it to the worklist.
14453 Worklist.push_back(*UI);
14458 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14459 /// (aliasing node.)
14460 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14461 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14463 // Accumulate all the aliases to this node.
14464 GatherAllAliases(N, OldChain, Aliases);
14466 // If no operands then chain to entry token.
14467 if (Aliases.size() == 0)
14468 return DAG.getEntryNode();
14470 // If a single operand then chain to it. We don't need to revisit it.
14471 if (Aliases.size() == 1)
14474 // Construct a custom tailored token factor.
14475 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14478 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14479 // This holds the base pointer, index, and the offset in bytes from the base
14481 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14483 // We must have a base and an offset.
14484 if (!BasePtr.Base.getNode())
14487 // Do not handle stores to undef base pointers.
14488 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14491 SmallVector<StoreSDNode *, 8> ChainedStores;
14492 ChainedStores.push_back(St);
14494 // Walk up the chain and look for nodes with offsets from the same
14495 // base pointer. Stop when reaching an instruction with a different kind
14496 // or instruction which has a different base pointer.
14497 StoreSDNode *Index = St;
14499 // If the chain has more than one use, then we can't reorder the mem ops.
14500 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14503 if (Index->isVolatile() || Index->isIndexed())
14506 // Find the base pointer and offset for this memory node.
14507 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14509 // Check that the base pointer is the same as the original one.
14510 if (!Ptr.equalBaseIndex(BasePtr))
14513 // Find the next memory operand in the chain. If the next operand in the
14514 // chain is a store then move up and continue the scan with the next
14515 // memory operand. If the next operand is a load save it and use alias
14516 // information to check if it interferes with anything.
14517 SDNode *NextInChain = Index->getChain().getNode();
14519 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14520 // We found a store node. Use it for the next iteration.
14521 ChainedStores.push_back(STn);
14524 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14525 NextInChain = Ldn->getChain().getNode();
14534 bool MadeChange = false;
14535 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14537 for (StoreSDNode *ChainedStore : ChainedStores) {
14538 SDValue Chain = ChainedStore->getChain();
14539 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14541 if (Chain != BetterChain) {
14543 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14547 // Do all replacements after finding the replacements to make to avoid making
14548 // the chains more complicated by introducing new TokenFactors.
14549 for (auto Replacement : BetterChains)
14550 replaceStoreChain(Replacement.first, Replacement.second);
14555 /// This is the entry point for the file.
14556 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14557 CodeGenOpt::Level OptLevel) {
14558 /// This is the main entry point to this class.
14559 DAGCombiner(*this, AA, OptLevel).Run(Level);