1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 /// Replaces all uses of the results of one DAG node with new values.
160 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
163 /// Replaces all uses of the results of one DAG node with new values.
164 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
165 return CombineTo(N, &Res, 1, AddTo);
168 /// Replaces all uses of the results of one DAG node with new values.
169 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
171 SDValue To[] = { Res0, Res1 };
172 return CombineTo(N, To, 2, AddTo);
175 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
179 /// Check the specified integer node value to see if it can be simplified or
180 /// if things it uses can be simplified by bit propagation.
181 /// If so, return true.
182 bool SimplifyDemandedBits(SDValue Op) {
183 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
184 APInt Demanded = APInt::getAllOnesValue(BitWidth);
185 return SimplifyDemandedBits(Op, Demanded);
188 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
190 bool CombineToPreIndexedLoadStore(SDNode *N);
191 bool CombineToPostIndexedLoadStore(SDNode *N);
192 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
193 bool SliceUpLoad(SDNode *N);
195 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
198 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
199 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
200 /// \param EltNo index of the vector element to load.
201 /// \param OriginalLoad load that EVE came from to be replaced.
202 /// \returns EVE on success SDValue() on failure.
203 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
204 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
205 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
206 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
207 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
208 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
209 SDValue PromoteIntBinOp(SDValue Op);
210 SDValue PromoteIntShiftOp(SDValue Op);
211 SDValue PromoteExtend(SDValue Op);
212 bool PromoteLoad(SDValue Op);
214 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
215 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
216 ISD::NodeType ExtType);
218 /// Call the node-specific routine that knows how to fold each
219 /// particular type of node. If that doesn't do anything, try the
220 /// target-specific DAG combines.
221 SDValue combine(SDNode *N);
223 // Visitation implementation - Implement dag node combining for different
224 // node types. The semantics are as follows:
226 // SDValue.getNode() == 0 - No change was made
227 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
228 // otherwise - N should be replaced by the returned Operand.
230 SDValue visitTokenFactor(SDNode *N);
231 SDValue visitMERGE_VALUES(SDNode *N);
232 SDValue visitADD(SDNode *N);
233 SDValue visitSUB(SDNode *N);
234 SDValue visitADDC(SDNode *N);
235 SDValue visitSUBC(SDNode *N);
236 SDValue visitADDE(SDNode *N);
237 SDValue visitSUBE(SDNode *N);
238 SDValue visitMUL(SDNode *N);
239 SDValue useDivRem(SDNode *N);
240 SDValue visitSDIV(SDNode *N);
241 SDValue visitUDIV(SDNode *N);
242 SDValue visitREM(SDNode *N);
243 SDValue visitMULHU(SDNode *N);
244 SDValue visitMULHS(SDNode *N);
245 SDValue visitSMUL_LOHI(SDNode *N);
246 SDValue visitUMUL_LOHI(SDNode *N);
247 SDValue visitSMULO(SDNode *N);
248 SDValue visitUMULO(SDNode *N);
249 SDValue visitIMINMAX(SDNode *N);
250 SDValue visitAND(SDNode *N);
251 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitOR(SDNode *N);
253 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
254 SDValue visitXOR(SDNode *N);
255 SDValue SimplifyVBinOp(SDNode *N);
256 SDValue visitSHL(SDNode *N);
257 SDValue visitSRA(SDNode *N);
258 SDValue visitSRL(SDNode *N);
259 SDValue visitRotate(SDNode *N);
260 SDValue visitBSWAP(SDNode *N);
261 SDValue visitCTLZ(SDNode *N);
262 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
263 SDValue visitCTTZ(SDNode *N);
264 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
265 SDValue visitCTPOP(SDNode *N);
266 SDValue visitSELECT(SDNode *N);
267 SDValue visitVSELECT(SDNode *N);
268 SDValue visitSELECT_CC(SDNode *N);
269 SDValue visitSETCC(SDNode *N);
270 SDValue visitSIGN_EXTEND(SDNode *N);
271 SDValue visitZERO_EXTEND(SDNode *N);
272 SDValue visitANY_EXTEND(SDNode *N);
273 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
274 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
275 SDValue visitTRUNCATE(SDNode *N);
276 SDValue visitBITCAST(SDNode *N);
277 SDValue visitBUILD_PAIR(SDNode *N);
278 SDValue visitFADD(SDNode *N);
279 SDValue visitFSUB(SDNode *N);
280 SDValue visitFMUL(SDNode *N);
281 SDValue visitFMA(SDNode *N);
282 SDValue visitFDIV(SDNode *N);
283 SDValue visitFREM(SDNode *N);
284 SDValue visitFSQRT(SDNode *N);
285 SDValue visitFCOPYSIGN(SDNode *N);
286 SDValue visitSINT_TO_FP(SDNode *N);
287 SDValue visitUINT_TO_FP(SDNode *N);
288 SDValue visitFP_TO_SINT(SDNode *N);
289 SDValue visitFP_TO_UINT(SDNode *N);
290 SDValue visitFP_ROUND(SDNode *N);
291 SDValue visitFP_ROUND_INREG(SDNode *N);
292 SDValue visitFP_EXTEND(SDNode *N);
293 SDValue visitFNEG(SDNode *N);
294 SDValue visitFABS(SDNode *N);
295 SDValue visitFCEIL(SDNode *N);
296 SDValue visitFTRUNC(SDNode *N);
297 SDValue visitFFLOOR(SDNode *N);
298 SDValue visitFMINNUM(SDNode *N);
299 SDValue visitFMAXNUM(SDNode *N);
300 SDValue visitBRCOND(SDNode *N);
301 SDValue visitBR_CC(SDNode *N);
302 SDValue visitLOAD(SDNode *N);
304 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
305 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
307 SDValue visitSTORE(SDNode *N);
308 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
309 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
310 SDValue visitBUILD_VECTOR(SDNode *N);
311 SDValue visitCONCAT_VECTORS(SDNode *N);
312 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
313 SDValue visitVECTOR_SHUFFLE(SDNode *N);
314 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
315 SDValue visitINSERT_SUBVECTOR(SDNode *N);
316 SDValue visitMLOAD(SDNode *N);
317 SDValue visitMSTORE(SDNode *N);
318 SDValue visitMGATHER(SDNode *N);
319 SDValue visitMSCATTER(SDNode *N);
320 SDValue visitFP_TO_FP16(SDNode *N);
321 SDValue visitFP16_TO_FP(SDNode *N);
323 SDValue visitFADDForFMACombine(SDNode *N);
324 SDValue visitFSUBForFMACombine(SDNode *N);
325 SDValue visitFMULForFMACombine(SDNode *N);
327 SDValue XformToShuffleWithZero(SDNode *N);
328 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
330 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
332 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
333 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
334 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
335 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
336 SDValue N3, ISD::CondCode CC,
337 bool NotExtCompare = false);
338 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
339 SDLoc DL, bool foldBooleans = true);
341 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
343 bool isOneUseSetCC(SDValue N) const;
345 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
347 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
348 SDValue CombineExtLoad(SDNode *N);
349 SDValue combineRepeatedFPDivisors(SDNode *N);
350 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
351 SDValue BuildSDIV(SDNode *N);
352 SDValue BuildSDIVPow2(SDNode *N);
353 SDValue BuildUDIV(SDNode *N);
354 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
355 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
356 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
358 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
360 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
361 bool DemandHighBits = true);
362 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
363 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
364 SDValue InnerPos, SDValue InnerNeg,
365 unsigned PosOpcode, unsigned NegOpcode,
367 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
368 SDValue ReduceLoadWidth(SDNode *N);
369 SDValue ReduceLoadOpStoreWidth(SDNode *N);
370 SDValue TransformFPLoadStorePair(SDNode *N);
371 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
372 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
374 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
376 /// Walk up chain skipping non-aliasing memory nodes,
377 /// looking for aliasing nodes and adding them to the Aliases vector.
378 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
379 SmallVectorImpl<SDValue> &Aliases);
381 /// Return true if there is any possibility that the two addresses overlap.
382 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
384 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
385 /// chain (aliasing node.)
386 SDValue FindBetterChain(SDNode *N, SDValue Chain);
388 /// Do FindBetterChain for a store and any possibly adjacent stores on
389 /// consecutive chains.
390 bool findBetterNeighborChains(StoreSDNode *St);
392 /// Holds a pointer to an LSBaseSDNode as well as information on where it
393 /// is located in a sequence of memory operations connected by a chain.
395 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
396 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
397 // Ptr to the mem node.
398 LSBaseSDNode *MemNode;
399 // Offset from the base ptr.
400 int64_t OffsetFromBase;
401 // What is the sequence number of this mem node.
402 // Lowest mem operand in the DAG starts at zero.
403 unsigned SequenceNum;
406 /// This is a helper function for visitMUL to check the profitability
407 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
408 /// MulNode is the original multiply, AddNode is (add x, c1),
409 /// and ConstNode is c2.
410 bool isMulAddWithConstProfitable(SDNode *MulNode,
414 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
415 /// constant build_vector of the stored constant values in Stores.
416 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
418 ArrayRef<MemOpLink> Stores,
419 SmallVectorImpl<SDValue> &Chains,
422 /// This is a helper function for MergeConsecutiveStores. When the source
423 /// elements of the consecutive stores are all constants or all extracted
424 /// vector elements, try to merge them into one larger store.
425 /// \return True if a merged store was created.
426 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
427 EVT MemVT, unsigned NumStores,
428 bool IsConstantSrc, bool UseVector);
430 /// This is a helper function for MergeConsecutiveStores.
431 /// Stores that may be merged are placed in StoreNodes.
432 /// Loads that may alias with those stores are placed in AliasLoadNodes.
433 void getStoreMergeAndAliasCandidates(
434 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
435 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
437 /// Merge consecutive store operations into a wide store.
438 /// This optimization uses wide integers or vectors when possible.
439 /// \return True if some memory operations were changed.
440 bool MergeConsecutiveStores(StoreSDNode *N);
442 /// \brief Try to transform a truncation where C is a constant:
443 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
445 /// \p N needs to be a truncation and its first operand an AND. Other
446 /// requirements are checked by the function (e.g. that trunc is
447 /// single-use) and if missed an empty SDValue is returned.
448 SDValue distributeTruncateThroughAnd(SDNode *N);
451 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
452 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
453 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
454 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
457 /// Runs the dag combiner on all nodes in the work list
458 void Run(CombineLevel AtLevel);
460 SelectionDAG &getDAG() const { return DAG; }
462 /// Returns a type large enough to hold any valid shift amount - before type
463 /// legalization these can be huge.
464 EVT getShiftAmountTy(EVT LHSTy) {
465 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
466 if (LHSTy.isVector())
468 auto &DL = DAG.getDataLayout();
469 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
470 : TLI.getPointerTy(DL);
473 /// This method returns true if we are running before type legalization or
474 /// if the specified VT is legal.
475 bool isTypeLegal(const EVT &VT) {
476 if (!LegalTypes) return true;
477 return TLI.isTypeLegal(VT);
480 /// Convenience wrapper around TargetLowering::getSetCCResultType
481 EVT getSetCCResultType(EVT VT) const {
482 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
489 /// This class is a DAGUpdateListener that removes any deleted
490 /// nodes from the worklist.
491 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
494 explicit WorklistRemover(DAGCombiner &dc)
495 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
497 void NodeDeleted(SDNode *N, SDNode *E) override {
498 DC.removeFromWorklist(N);
503 //===----------------------------------------------------------------------===//
504 // TargetLowering::DAGCombinerInfo implementation
505 //===----------------------------------------------------------------------===//
507 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
508 ((DAGCombiner*)DC)->AddToWorklist(N);
511 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
512 ((DAGCombiner*)DC)->removeFromWorklist(N);
515 SDValue TargetLowering::DAGCombinerInfo::
516 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
517 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
520 SDValue TargetLowering::DAGCombinerInfo::
521 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
522 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
526 SDValue TargetLowering::DAGCombinerInfo::
527 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
528 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
531 void TargetLowering::DAGCombinerInfo::
532 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
533 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
536 //===----------------------------------------------------------------------===//
538 //===----------------------------------------------------------------------===//
540 void DAGCombiner::deleteAndRecombine(SDNode *N) {
541 removeFromWorklist(N);
543 // If the operands of this node are only used by the node, they will now be
544 // dead. Make sure to re-visit them and recursively delete dead nodes.
545 for (const SDValue &Op : N->ops())
546 // For an operand generating multiple values, one of the values may
547 // become dead allowing further simplification (e.g. split index
548 // arithmetic from an indexed load).
549 if (Op->hasOneUse() || Op->getNumValues() > 1)
550 AddToWorklist(Op.getNode());
555 /// Return 1 if we can compute the negated form of the specified expression for
556 /// the same cost as the expression itself, or 2 if we can compute the negated
557 /// form more cheaply than the expression itself.
558 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
559 const TargetLowering &TLI,
560 const TargetOptions *Options,
561 unsigned Depth = 0) {
562 // fneg is removable even if it has multiple uses.
563 if (Op.getOpcode() == ISD::FNEG) return 2;
565 // Don't allow anything with multiple uses.
566 if (!Op.hasOneUse()) return 0;
568 // Don't recurse exponentially.
569 if (Depth > 6) return 0;
571 switch (Op.getOpcode()) {
572 default: return false;
573 case ISD::ConstantFP:
574 // Don't invert constant FP values after legalize. The negated constant
575 // isn't necessarily legal.
576 return LegalOperations ? 0 : 1;
578 // FIXME: determine better conditions for this xform.
579 if (!Options->UnsafeFPMath) return 0;
581 // After operation legalization, it might not be legal to create new FSUBs.
582 if (LegalOperations &&
583 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
586 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
587 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
590 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
591 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
594 // We can't turn -(A-B) into B-A when we honor signed zeros.
595 if (!Options->UnsafeFPMath) return 0;
597 // fold (fneg (fsub A, B)) -> (fsub B, A)
602 if (Options->HonorSignDependentRoundingFPMath()) return 0;
604 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
605 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
609 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
615 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
620 /// If isNegatibleForFree returns true, return the newly negated expression.
621 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
622 bool LegalOperations, unsigned Depth = 0) {
623 const TargetOptions &Options = DAG.getTarget().Options;
624 // fneg is removable even if it has multiple uses.
625 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
627 // Don't allow anything with multiple uses.
628 assert(Op.hasOneUse() && "Unknown reuse!");
630 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
632 const SDNodeFlags *Flags = Op.getNode()->getFlags();
634 switch (Op.getOpcode()) {
635 default: llvm_unreachable("Unknown code");
636 case ISD::ConstantFP: {
637 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
639 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
642 // FIXME: determine better conditions for this xform.
643 assert(Options.UnsafeFPMath);
645 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
646 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
647 DAG.getTargetLoweringInfo(), &Options, Depth+1))
648 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
649 GetNegatedExpression(Op.getOperand(0), DAG,
650 LegalOperations, Depth+1),
651 Op.getOperand(1), Flags);
652 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
653 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
654 GetNegatedExpression(Op.getOperand(1), DAG,
655 LegalOperations, Depth+1),
656 Op.getOperand(0), Flags);
658 // We can't turn -(A-B) into B-A when we honor signed zeros.
659 assert(Options.UnsafeFPMath);
661 // fold (fneg (fsub 0, B)) -> B
662 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
664 return Op.getOperand(1);
666 // fold (fneg (fsub A, B)) -> (fsub B, A)
667 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
668 Op.getOperand(1), Op.getOperand(0), Flags);
672 assert(!Options.HonorSignDependentRoundingFPMath());
674 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
675 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
676 DAG.getTargetLoweringInfo(), &Options, Depth+1))
677 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
678 GetNegatedExpression(Op.getOperand(0), DAG,
679 LegalOperations, Depth+1),
680 Op.getOperand(1), Flags);
682 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
683 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
685 GetNegatedExpression(Op.getOperand(1), DAG,
686 LegalOperations, Depth+1), Flags);
690 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
691 GetNegatedExpression(Op.getOperand(0), DAG,
692 LegalOperations, Depth+1));
694 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
695 GetNegatedExpression(Op.getOperand(0), DAG,
696 LegalOperations, Depth+1),
701 // Return true if this node is a setcc, or is a select_cc
702 // that selects between the target values used for true and false, making it
703 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
704 // the appropriate nodes based on the type of node we are checking. This
705 // simplifies life a bit for the callers.
706 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
708 if (N.getOpcode() == ISD::SETCC) {
709 LHS = N.getOperand(0);
710 RHS = N.getOperand(1);
711 CC = N.getOperand(2);
715 if (N.getOpcode() != ISD::SELECT_CC ||
716 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
717 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
720 if (TLI.getBooleanContents(N.getValueType()) ==
721 TargetLowering::UndefinedBooleanContent)
724 LHS = N.getOperand(0);
725 RHS = N.getOperand(1);
726 CC = N.getOperand(4);
730 /// Return true if this is a SetCC-equivalent operation with only one use.
731 /// If this is true, it allows the users to invert the operation for free when
732 /// it is profitable to do so.
733 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
735 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
740 /// Returns true if N is a BUILD_VECTOR node whose
741 /// elements are all the same constant or undefined.
742 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
743 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
748 unsigned SplatBitSize;
750 EVT EltVT = N->getValueType(0).getVectorElementType();
751 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
753 EltVT.getSizeInBits() >= SplatBitSize);
756 // \brief Returns the SDNode if it is a constant integer BuildVector
757 // or constant integer.
758 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
759 if (isa<ConstantSDNode>(N))
761 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
766 // \brief Returns the SDNode if it is a constant float BuildVector
767 // or constant float.
768 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
769 if (isa<ConstantFPSDNode>(N))
771 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
776 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
778 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
779 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
782 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
783 BitVector UndefElements;
784 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
786 // BuildVectors can truncate their operands. Ignore that case here.
787 // FIXME: We blindly ignore splats which include undef which is overly
789 if (CN && UndefElements.none() &&
790 CN->getValueType(0) == N.getValueType().getScalarType())
797 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
799 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
800 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
803 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
804 BitVector UndefElements;
805 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
807 if (CN && UndefElements.none())
814 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
815 SDValue N0, SDValue N1) {
816 EVT VT = N0.getValueType();
817 if (N0.getOpcode() == Opc) {
818 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
819 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
820 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
821 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
822 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
825 if (N0.hasOneUse()) {
826 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
828 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
829 if (!OpNode.getNode())
831 AddToWorklist(OpNode.getNode());
832 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
837 if (N1.getOpcode() == Opc) {
838 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
839 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
840 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
841 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
842 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
845 if (N1.hasOneUse()) {
846 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
848 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
849 if (!OpNode.getNode())
851 AddToWorklist(OpNode.getNode());
852 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
860 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
862 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
864 DEBUG(dbgs() << "\nReplacing.1 ";
866 dbgs() << "\nWith: ";
867 To[0].getNode()->dump(&DAG);
868 dbgs() << " and " << NumTo-1 << " other values\n");
869 for (unsigned i = 0, e = NumTo; i != e; ++i)
870 assert((!To[i].getNode() ||
871 N->getValueType(i) == To[i].getValueType()) &&
872 "Cannot combine value to value of different type!");
874 WorklistRemover DeadNodes(*this);
875 DAG.ReplaceAllUsesWith(N, To);
877 // Push the new nodes and any users onto the worklist
878 for (unsigned i = 0, e = NumTo; i != e; ++i) {
879 if (To[i].getNode()) {
880 AddToWorklist(To[i].getNode());
881 AddUsersToWorklist(To[i].getNode());
886 // Finally, if the node is now dead, remove it from the graph. The node
887 // may not be dead if the replacement process recursively simplified to
888 // something else needing this node.
890 deleteAndRecombine(N);
891 return SDValue(N, 0);
895 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
896 // Replace all uses. If any nodes become isomorphic to other nodes and
897 // are deleted, make sure to remove them from our worklist.
898 WorklistRemover DeadNodes(*this);
899 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
901 // Push the new node and any (possibly new) users onto the worklist.
902 AddToWorklist(TLO.New.getNode());
903 AddUsersToWorklist(TLO.New.getNode());
905 // Finally, if the node is now dead, remove it from the graph. The node
906 // may not be dead if the replacement process recursively simplified to
907 // something else needing this node.
908 if (TLO.Old.getNode()->use_empty())
909 deleteAndRecombine(TLO.Old.getNode());
912 /// Check the specified integer node value to see if it can be simplified or if
913 /// things it uses can be simplified by bit propagation. If so, return true.
914 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
915 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
916 APInt KnownZero, KnownOne;
917 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
921 AddToWorklist(Op.getNode());
923 // Replace the old value with the new one.
925 DEBUG(dbgs() << "\nReplacing.2 ";
926 TLO.Old.getNode()->dump(&DAG);
927 dbgs() << "\nWith: ";
928 TLO.New.getNode()->dump(&DAG);
931 CommitTargetLoweringOpt(TLO);
935 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
937 EVT VT = Load->getValueType(0);
938 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
940 DEBUG(dbgs() << "\nReplacing.9 ";
942 dbgs() << "\nWith: ";
943 Trunc.getNode()->dump(&DAG);
945 WorklistRemover DeadNodes(*this);
946 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
947 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
948 deleteAndRecombine(Load);
949 AddToWorklist(Trunc.getNode());
952 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
955 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
956 EVT MemVT = LD->getMemoryVT();
957 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
958 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
960 : LD->getExtensionType();
962 return DAG.getExtLoad(ExtType, dl, PVT,
963 LD->getChain(), LD->getBasePtr(),
964 MemVT, LD->getMemOperand());
967 unsigned Opc = Op.getOpcode();
970 case ISD::AssertSext:
971 return DAG.getNode(ISD::AssertSext, dl, PVT,
972 SExtPromoteOperand(Op.getOperand(0), PVT),
974 case ISD::AssertZext:
975 return DAG.getNode(ISD::AssertZext, dl, PVT,
976 ZExtPromoteOperand(Op.getOperand(0), PVT),
978 case ISD::Constant: {
980 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
981 return DAG.getNode(ExtOpc, dl, PVT, Op);
985 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
987 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
990 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
991 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
993 EVT OldVT = Op.getValueType();
995 bool Replace = false;
996 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
997 if (!NewOp.getNode())
999 AddToWorklist(NewOp.getNode());
1002 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1003 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1004 DAG.getValueType(OldVT));
1007 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1008 EVT OldVT = Op.getValueType();
1010 bool Replace = false;
1011 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1012 if (!NewOp.getNode())
1014 AddToWorklist(NewOp.getNode());
1017 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1018 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1021 /// Promote the specified integer binary operation if the target indicates it is
1022 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1023 /// i32 since i16 instructions are longer.
1024 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1025 if (!LegalOperations)
1028 EVT VT = Op.getValueType();
1029 if (VT.isVector() || !VT.isInteger())
1032 // If operation type is 'undesirable', e.g. i16 on x86, consider
1034 unsigned Opc = Op.getOpcode();
1035 if (TLI.isTypeDesirableForOp(Opc, VT))
1039 // Consult target whether it is a good idea to promote this operation and
1040 // what's the right type to promote it to.
1041 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1042 assert(PVT != VT && "Don't know what type to promote to!");
1044 bool Replace0 = false;
1045 SDValue N0 = Op.getOperand(0);
1046 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1050 bool Replace1 = false;
1051 SDValue N1 = Op.getOperand(1);
1056 NN1 = PromoteOperand(N1, PVT, Replace1);
1061 AddToWorklist(NN0.getNode());
1063 AddToWorklist(NN1.getNode());
1066 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1068 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1070 DEBUG(dbgs() << "\nPromoting ";
1071 Op.getNode()->dump(&DAG));
1073 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1074 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1079 /// Promote the specified integer shift operation if the target indicates it is
1080 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1081 /// i32 since i16 instructions are longer.
1082 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1083 if (!LegalOperations)
1086 EVT VT = Op.getValueType();
1087 if (VT.isVector() || !VT.isInteger())
1090 // If operation type is 'undesirable', e.g. i16 on x86, consider
1092 unsigned Opc = Op.getOpcode();
1093 if (TLI.isTypeDesirableForOp(Opc, VT))
1097 // Consult target whether it is a good idea to promote this operation and
1098 // what's the right type to promote it to.
1099 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100 assert(PVT != VT && "Don't know what type to promote to!");
1102 bool Replace = false;
1103 SDValue N0 = Op.getOperand(0);
1104 if (Opc == ISD::SRA)
1105 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1106 else if (Opc == ISD::SRL)
1107 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1109 N0 = PromoteOperand(N0, PVT, Replace);
1113 AddToWorklist(N0.getNode());
1115 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1117 DEBUG(dbgs() << "\nPromoting ";
1118 Op.getNode()->dump(&DAG));
1120 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1121 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1126 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1127 if (!LegalOperations)
1130 EVT VT = Op.getValueType();
1131 if (VT.isVector() || !VT.isInteger())
1134 // If operation type is 'undesirable', e.g. i16 on x86, consider
1136 unsigned Opc = Op.getOpcode();
1137 if (TLI.isTypeDesirableForOp(Opc, VT))
1141 // Consult target whether it is a good idea to promote this operation and
1142 // what's the right type to promote it to.
1143 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1144 assert(PVT != VT && "Don't know what type to promote to!");
1145 // fold (aext (aext x)) -> (aext x)
1146 // fold (aext (zext x)) -> (zext x)
1147 // fold (aext (sext x)) -> (sext x)
1148 DEBUG(dbgs() << "\nPromoting ";
1149 Op.getNode()->dump(&DAG));
1150 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1155 bool DAGCombiner::PromoteLoad(SDValue Op) {
1156 if (!LegalOperations)
1159 EVT VT = Op.getValueType();
1160 if (VT.isVector() || !VT.isInteger())
1163 // If operation type is 'undesirable', e.g. i16 on x86, consider
1165 unsigned Opc = Op.getOpcode();
1166 if (TLI.isTypeDesirableForOp(Opc, VT))
1170 // Consult target whether it is a good idea to promote this operation and
1171 // what's the right type to promote it to.
1172 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1173 assert(PVT != VT && "Don't know what type to promote to!");
1176 SDNode *N = Op.getNode();
1177 LoadSDNode *LD = cast<LoadSDNode>(N);
1178 EVT MemVT = LD->getMemoryVT();
1179 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1180 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1182 : LD->getExtensionType();
1183 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1184 LD->getChain(), LD->getBasePtr(),
1185 MemVT, LD->getMemOperand());
1186 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1188 DEBUG(dbgs() << "\nPromoting ";
1191 Result.getNode()->dump(&DAG);
1193 WorklistRemover DeadNodes(*this);
1194 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1195 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1196 deleteAndRecombine(N);
1197 AddToWorklist(Result.getNode());
1203 /// \brief Recursively delete a node which has no uses and any operands for
1204 /// which it is the only use.
1206 /// Note that this both deletes the nodes and removes them from the worklist.
1207 /// It also adds any nodes who have had a user deleted to the worklist as they
1208 /// may now have only one use and subject to other combines.
1209 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1210 if (!N->use_empty())
1213 SmallSetVector<SDNode *, 16> Nodes;
1216 N = Nodes.pop_back_val();
1220 if (N->use_empty()) {
1221 for (const SDValue &ChildN : N->op_values())
1222 Nodes.insert(ChildN.getNode());
1224 removeFromWorklist(N);
1229 } while (!Nodes.empty());
1233 //===----------------------------------------------------------------------===//
1234 // Main DAG Combiner implementation
1235 //===----------------------------------------------------------------------===//
1237 void DAGCombiner::Run(CombineLevel AtLevel) {
1238 // set the instance variables, so that the various visit routines may use it.
1240 LegalOperations = Level >= AfterLegalizeVectorOps;
1241 LegalTypes = Level >= AfterLegalizeTypes;
1243 // Add all the dag nodes to the worklist.
1244 for (SDNode &Node : DAG.allnodes())
1245 AddToWorklist(&Node);
1247 // Create a dummy node (which is not added to allnodes), that adds a reference
1248 // to the root node, preventing it from being deleted, and tracking any
1249 // changes of the root.
1250 HandleSDNode Dummy(DAG.getRoot());
1252 // while the worklist isn't empty, find a node and
1253 // try and combine it.
1254 while (!WorklistMap.empty()) {
1256 // The Worklist holds the SDNodes in order, but it may contain null entries.
1258 N = Worklist.pop_back_val();
1261 bool GoodWorklistEntry = WorklistMap.erase(N);
1262 (void)GoodWorklistEntry;
1263 assert(GoodWorklistEntry &&
1264 "Found a worklist entry without a corresponding map entry!");
1266 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1267 // N is deleted from the DAG, since they too may now be dead or may have a
1268 // reduced number of uses, allowing other xforms.
1269 if (recursivelyDeleteUnusedNodes(N))
1272 WorklistRemover DeadNodes(*this);
1274 // If this combine is running after legalizing the DAG, re-legalize any
1275 // nodes pulled off the worklist.
1276 if (Level == AfterLegalizeDAG) {
1277 SmallSetVector<SDNode *, 16> UpdatedNodes;
1278 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1280 for (SDNode *LN : UpdatedNodes) {
1282 AddUsersToWorklist(LN);
1288 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1290 // Add any operands of the new node which have not yet been combined to the
1291 // worklist as well. Because the worklist uniques things already, this
1292 // won't repeatedly process the same operand.
1293 CombinedNodes.insert(N);
1294 for (const SDValue &ChildN : N->op_values())
1295 if (!CombinedNodes.count(ChildN.getNode()))
1296 AddToWorklist(ChildN.getNode());
1298 SDValue RV = combine(N);
1305 // If we get back the same node we passed in, rather than a new node or
1306 // zero, we know that the node must have defined multiple values and
1307 // CombineTo was used. Since CombineTo takes care of the worklist
1308 // mechanics for us, we have no work to do in this case.
1309 if (RV.getNode() == N)
1312 assert(N->getOpcode() != ISD::DELETED_NODE &&
1313 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1314 "Node was deleted but visit returned new node!");
1316 DEBUG(dbgs() << " ... into: ";
1317 RV.getNode()->dump(&DAG));
1319 // Transfer debug value.
1320 DAG.TransferDbgValues(SDValue(N, 0), RV);
1321 if (N->getNumValues() == RV.getNode()->getNumValues())
1322 DAG.ReplaceAllUsesWith(N, RV.getNode());
1324 assert(N->getValueType(0) == RV.getValueType() &&
1325 N->getNumValues() == 1 && "Type mismatch");
1327 DAG.ReplaceAllUsesWith(N, &OpV);
1330 // Push the new node and any users onto the worklist
1331 AddToWorklist(RV.getNode());
1332 AddUsersToWorklist(RV.getNode());
1334 // Finally, if the node is now dead, remove it from the graph. The node
1335 // may not be dead if the replacement process recursively simplified to
1336 // something else needing this node. This will also take care of adding any
1337 // operands which have lost a user to the worklist.
1338 recursivelyDeleteUnusedNodes(N);
1341 // If the root changed (e.g. it was a dead load, update the root).
1342 DAG.setRoot(Dummy.getValue());
1343 DAG.RemoveDeadNodes();
1346 SDValue DAGCombiner::visit(SDNode *N) {
1347 switch (N->getOpcode()) {
1349 case ISD::TokenFactor: return visitTokenFactor(N);
1350 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1351 case ISD::ADD: return visitADD(N);
1352 case ISD::SUB: return visitSUB(N);
1353 case ISD::ADDC: return visitADDC(N);
1354 case ISD::SUBC: return visitSUBC(N);
1355 case ISD::ADDE: return visitADDE(N);
1356 case ISD::SUBE: return visitSUBE(N);
1357 case ISD::MUL: return visitMUL(N);
1358 case ISD::SDIV: return visitSDIV(N);
1359 case ISD::UDIV: return visitUDIV(N);
1361 case ISD::UREM: return visitREM(N);
1362 case ISD::MULHU: return visitMULHU(N);
1363 case ISD::MULHS: return visitMULHS(N);
1364 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1365 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1366 case ISD::SMULO: return visitSMULO(N);
1367 case ISD::UMULO: return visitUMULO(N);
1371 case ISD::UMAX: return visitIMINMAX(N);
1372 case ISD::AND: return visitAND(N);
1373 case ISD::OR: return visitOR(N);
1374 case ISD::XOR: return visitXOR(N);
1375 case ISD::SHL: return visitSHL(N);
1376 case ISD::SRA: return visitSRA(N);
1377 case ISD::SRL: return visitSRL(N);
1379 case ISD::ROTL: return visitRotate(N);
1380 case ISD::BSWAP: return visitBSWAP(N);
1381 case ISD::CTLZ: return visitCTLZ(N);
1382 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1383 case ISD::CTTZ: return visitCTTZ(N);
1384 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1385 case ISD::CTPOP: return visitCTPOP(N);
1386 case ISD::SELECT: return visitSELECT(N);
1387 case ISD::VSELECT: return visitVSELECT(N);
1388 case ISD::SELECT_CC: return visitSELECT_CC(N);
1389 case ISD::SETCC: return visitSETCC(N);
1390 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1391 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1392 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1393 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1394 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1395 case ISD::TRUNCATE: return visitTRUNCATE(N);
1396 case ISD::BITCAST: return visitBITCAST(N);
1397 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1398 case ISD::FADD: return visitFADD(N);
1399 case ISD::FSUB: return visitFSUB(N);
1400 case ISD::FMUL: return visitFMUL(N);
1401 case ISD::FMA: return visitFMA(N);
1402 case ISD::FDIV: return visitFDIV(N);
1403 case ISD::FREM: return visitFREM(N);
1404 case ISD::FSQRT: return visitFSQRT(N);
1405 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1406 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1407 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1408 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1409 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1410 case ISD::FP_ROUND: return visitFP_ROUND(N);
1411 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1412 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1413 case ISD::FNEG: return visitFNEG(N);
1414 case ISD::FABS: return visitFABS(N);
1415 case ISD::FFLOOR: return visitFFLOOR(N);
1416 case ISD::FMINNUM: return visitFMINNUM(N);
1417 case ISD::FMAXNUM: return visitFMAXNUM(N);
1418 case ISD::FCEIL: return visitFCEIL(N);
1419 case ISD::FTRUNC: return visitFTRUNC(N);
1420 case ISD::BRCOND: return visitBRCOND(N);
1421 case ISD::BR_CC: return visitBR_CC(N);
1422 case ISD::LOAD: return visitLOAD(N);
1423 case ISD::STORE: return visitSTORE(N);
1424 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1425 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1426 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1427 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1428 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1429 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1430 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1431 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1432 case ISD::MGATHER: return visitMGATHER(N);
1433 case ISD::MLOAD: return visitMLOAD(N);
1434 case ISD::MSCATTER: return visitMSCATTER(N);
1435 case ISD::MSTORE: return visitMSTORE(N);
1436 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1437 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1442 SDValue DAGCombiner::combine(SDNode *N) {
1443 SDValue RV = visit(N);
1445 // If nothing happened, try a target-specific DAG combine.
1446 if (!RV.getNode()) {
1447 assert(N->getOpcode() != ISD::DELETED_NODE &&
1448 "Node was deleted but visit returned NULL!");
1450 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1451 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1453 // Expose the DAG combiner to the target combiner impls.
1454 TargetLowering::DAGCombinerInfo
1455 DagCombineInfo(DAG, Level, false, this);
1457 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1461 // If nothing happened still, try promoting the operation.
1462 if (!RV.getNode()) {
1463 switch (N->getOpcode()) {
1471 RV = PromoteIntBinOp(SDValue(N, 0));
1476 RV = PromoteIntShiftOp(SDValue(N, 0));
1478 case ISD::SIGN_EXTEND:
1479 case ISD::ZERO_EXTEND:
1480 case ISD::ANY_EXTEND:
1481 RV = PromoteExtend(SDValue(N, 0));
1484 if (PromoteLoad(SDValue(N, 0)))
1490 // If N is a commutative binary node, try commuting it to enable more
1492 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1493 N->getNumValues() == 1) {
1494 SDValue N0 = N->getOperand(0);
1495 SDValue N1 = N->getOperand(1);
1497 // Constant operands are canonicalized to RHS.
1498 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1499 SDValue Ops[] = {N1, N0};
1500 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1503 return SDValue(CSENode, 0);
1510 /// Given a node, return its input chain if it has one, otherwise return a null
1512 static SDValue getInputChainForNode(SDNode *N) {
1513 if (unsigned NumOps = N->getNumOperands()) {
1514 if (N->getOperand(0).getValueType() == MVT::Other)
1515 return N->getOperand(0);
1516 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1517 return N->getOperand(NumOps-1);
1518 for (unsigned i = 1; i < NumOps-1; ++i)
1519 if (N->getOperand(i).getValueType() == MVT::Other)
1520 return N->getOperand(i);
1525 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1526 // If N has two operands, where one has an input chain equal to the other,
1527 // the 'other' chain is redundant.
1528 if (N->getNumOperands() == 2) {
1529 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1530 return N->getOperand(0);
1531 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1532 return N->getOperand(1);
1535 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1536 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1537 SmallPtrSet<SDNode*, 16> SeenOps;
1538 bool Changed = false; // If we should replace this token factor.
1540 // Start out with this token factor.
1543 // Iterate through token factors. The TFs grows when new token factors are
1545 for (unsigned i = 0; i < TFs.size(); ++i) {
1546 SDNode *TF = TFs[i];
1548 // Check each of the operands.
1549 for (const SDValue &Op : TF->op_values()) {
1551 switch (Op.getOpcode()) {
1552 case ISD::EntryToken:
1553 // Entry tokens don't need to be added to the list. They are
1558 case ISD::TokenFactor:
1559 if (Op.hasOneUse() &&
1560 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1561 // Queue up for processing.
1562 TFs.push_back(Op.getNode());
1563 // Clean up in case the token factor is removed.
1564 AddToWorklist(Op.getNode());
1571 // Only add if it isn't already in the list.
1572 if (SeenOps.insert(Op.getNode()).second)
1583 // If we've changed things around then replace token factor.
1586 // The entry token is the only possible outcome.
1587 Result = DAG.getEntryNode();
1589 // New and improved token factor.
1590 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1593 // Add users to worklist if AA is enabled, since it may introduce
1594 // a lot of new chained token factors while removing memory deps.
1595 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1596 : DAG.getSubtarget().useAA();
1597 return CombineTo(N, Result, UseAA /*add to worklist*/);
1603 /// MERGE_VALUES can always be eliminated.
1604 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1605 WorklistRemover DeadNodes(*this);
1606 // Replacing results may cause a different MERGE_VALUES to suddenly
1607 // be CSE'd with N, and carry its uses with it. Iterate until no
1608 // uses remain, to ensure that the node can be safely deleted.
1609 // First add the users of this node to the work list so that they
1610 // can be tried again once they have new operands.
1611 AddUsersToWorklist(N);
1613 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1614 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1615 } while (!N->use_empty());
1616 deleteAndRecombine(N);
1617 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1620 static bool isNullConstant(SDValue V) {
1621 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1622 return Const != nullptr && Const->isNullValue();
1625 static bool isNullFPConstant(SDValue V) {
1626 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1627 return Const != nullptr && Const->isZero() && !Const->isNegative();
1630 static bool isAllOnesConstant(SDValue V) {
1631 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1632 return Const != nullptr && Const->isAllOnesValue();
1635 static bool isOneConstant(SDValue V) {
1636 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1637 return Const != nullptr && Const->isOne();
1640 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1641 /// ContantSDNode pointer else nullptr.
1642 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1643 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1644 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1647 SDValue DAGCombiner::visitADD(SDNode *N) {
1648 SDValue N0 = N->getOperand(0);
1649 SDValue N1 = N->getOperand(1);
1650 EVT VT = N0.getValueType();
1653 if (VT.isVector()) {
1654 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1657 // fold (add x, 0) -> x, vector edition
1658 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1660 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1664 // fold (add x, undef) -> undef
1665 if (N0.getOpcode() == ISD::UNDEF)
1667 if (N1.getOpcode() == ISD::UNDEF)
1669 // fold (add c1, c2) -> c1+c2
1670 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1671 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1673 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1674 // canonicalize constant to RHS
1675 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1676 !isConstantIntBuildVectorOrConstantInt(N1))
1677 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1678 // fold (add x, 0) -> x
1679 if (isNullConstant(N1))
1681 // fold (add Sym, c) -> Sym+c
1682 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1683 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1684 GA->getOpcode() == ISD::GlobalAddress)
1685 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1687 (uint64_t)N1C->getSExtValue());
1688 // fold ((c1-A)+c2) -> (c1+c2)-A
1689 if (N1C && N0.getOpcode() == ISD::SUB)
1690 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1692 return DAG.getNode(ISD::SUB, DL, VT,
1693 DAG.getConstant(N1C->getAPIntValue()+
1694 N0C->getAPIntValue(), DL, VT),
1698 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1700 // fold ((0-A) + B) -> B-A
1701 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1702 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1703 // fold (A + (0-B)) -> A-B
1704 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1705 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1706 // fold (A+(B-A)) -> B
1707 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1708 return N1.getOperand(0);
1709 // fold ((B-A)+A) -> B
1710 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1711 return N0.getOperand(0);
1712 // fold (A+(B-(A+C))) to (B-C)
1713 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1714 N0 == N1.getOperand(1).getOperand(0))
1715 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1716 N1.getOperand(1).getOperand(1));
1717 // fold (A+(B-(C+A))) to (B-C)
1718 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1719 N0 == N1.getOperand(1).getOperand(1))
1720 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1721 N1.getOperand(1).getOperand(0));
1722 // fold (A+((B-A)+or-C)) to (B+or-C)
1723 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1724 N1.getOperand(0).getOpcode() == ISD::SUB &&
1725 N0 == N1.getOperand(0).getOperand(1))
1726 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1727 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1729 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1730 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1731 SDValue N00 = N0.getOperand(0);
1732 SDValue N01 = N0.getOperand(1);
1733 SDValue N10 = N1.getOperand(0);
1734 SDValue N11 = N1.getOperand(1);
1736 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1737 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1738 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1739 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1742 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1743 return SDValue(N, 0);
1745 // fold (a+b) -> (a|b) iff a and b share no bits.
1746 if (VT.isInteger() && !VT.isVector()) {
1747 APInt LHSZero, LHSOne;
1748 APInt RHSZero, RHSOne;
1749 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1751 if (LHSZero.getBoolValue()) {
1752 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1754 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1755 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1756 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1757 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1758 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1763 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1764 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1765 isNullConstant(N1.getOperand(0).getOperand(0)))
1766 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1767 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1768 N1.getOperand(0).getOperand(1),
1770 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1771 isNullConstant(N0.getOperand(0).getOperand(0)))
1772 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1773 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1774 N0.getOperand(0).getOperand(1),
1777 if (N1.getOpcode() == ISD::AND) {
1778 SDValue AndOp0 = N1.getOperand(0);
1779 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1780 unsigned DestBits = VT.getScalarType().getSizeInBits();
1782 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1783 // and similar xforms where the inner op is either ~0 or 0.
1784 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1786 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1790 // add (sext i1), X -> sub X, (zext i1)
1791 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1792 N0.getOperand(0).getValueType() == MVT::i1 &&
1793 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1795 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1796 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1799 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1800 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1801 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1802 if (TN->getVT() == MVT::i1) {
1804 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1805 DAG.getConstant(1, DL, VT));
1806 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1813 SDValue DAGCombiner::visitADDC(SDNode *N) {
1814 SDValue N0 = N->getOperand(0);
1815 SDValue N1 = N->getOperand(1);
1816 EVT VT = N0.getValueType();
1818 // If the flag result is dead, turn this into an ADD.
1819 if (!N->hasAnyUseOfValue(1))
1820 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1821 DAG.getNode(ISD::CARRY_FALSE,
1822 SDLoc(N), MVT::Glue));
1824 // canonicalize constant to RHS.
1825 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1826 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1828 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1830 // fold (addc x, 0) -> x + no carry out
1831 if (isNullConstant(N1))
1832 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1833 SDLoc(N), MVT::Glue));
1835 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1836 APInt LHSZero, LHSOne;
1837 APInt RHSZero, RHSOne;
1838 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1840 if (LHSZero.getBoolValue()) {
1841 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1843 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1844 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1845 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1846 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1847 DAG.getNode(ISD::CARRY_FALSE,
1848 SDLoc(N), MVT::Glue));
1854 SDValue DAGCombiner::visitADDE(SDNode *N) {
1855 SDValue N0 = N->getOperand(0);
1856 SDValue N1 = N->getOperand(1);
1857 SDValue CarryIn = N->getOperand(2);
1859 // canonicalize constant to RHS
1860 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1861 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1863 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1866 // fold (adde x, y, false) -> (addc x, y)
1867 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1868 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1873 // Since it may not be valid to emit a fold to zero for vector initializers
1874 // check if we can before folding.
1875 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1877 bool LegalOperations, bool LegalTypes) {
1879 return DAG.getConstant(0, DL, VT);
1880 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1881 return DAG.getConstant(0, DL, VT);
1885 SDValue DAGCombiner::visitSUB(SDNode *N) {
1886 SDValue N0 = N->getOperand(0);
1887 SDValue N1 = N->getOperand(1);
1888 EVT VT = N0.getValueType();
1891 if (VT.isVector()) {
1892 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1895 // fold (sub x, 0) -> x, vector edition
1896 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1900 // fold (sub x, x) -> 0
1901 // FIXME: Refactor this and xor and other similar operations together.
1903 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1904 // fold (sub c1, c2) -> c1-c2
1905 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1906 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1908 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1909 // fold (sub x, c) -> (add x, -c)
1912 return DAG.getNode(ISD::ADD, DL, VT, N0,
1913 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1915 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1916 if (isAllOnesConstant(N0))
1917 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1918 // fold A-(A-B) -> B
1919 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1920 return N1.getOperand(1);
1921 // fold (A+B)-A -> B
1922 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1923 return N0.getOperand(1);
1924 // fold (A+B)-B -> A
1925 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1926 return N0.getOperand(0);
1927 // fold C2-(A+C1) -> (C2-C1)-A
1928 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1929 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1930 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1932 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1934 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1937 // fold ((A+(B+or-C))-B) -> A+or-C
1938 if (N0.getOpcode() == ISD::ADD &&
1939 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1940 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1941 N0.getOperand(1).getOperand(0) == N1)
1942 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1943 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1944 // fold ((A+(C+B))-B) -> A+C
1945 if (N0.getOpcode() == ISD::ADD &&
1946 N0.getOperand(1).getOpcode() == ISD::ADD &&
1947 N0.getOperand(1).getOperand(1) == N1)
1948 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1949 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1950 // fold ((A-(B-C))-C) -> A-B
1951 if (N0.getOpcode() == ISD::SUB &&
1952 N0.getOperand(1).getOpcode() == ISD::SUB &&
1953 N0.getOperand(1).getOperand(1) == N1)
1954 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1955 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1957 // If either operand of a sub is undef, the result is undef
1958 if (N0.getOpcode() == ISD::UNDEF)
1960 if (N1.getOpcode() == ISD::UNDEF)
1963 // If the relocation model supports it, consider symbol offsets.
1964 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1965 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1966 // fold (sub Sym, c) -> Sym-c
1967 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1968 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1970 (uint64_t)N1C->getSExtValue());
1971 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1972 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1973 if (GA->getGlobal() == GB->getGlobal())
1974 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1978 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1979 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1980 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1981 if (TN->getVT() == MVT::i1) {
1983 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1984 DAG.getConstant(1, DL, VT));
1985 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1992 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1993 SDValue N0 = N->getOperand(0);
1994 SDValue N1 = N->getOperand(1);
1995 EVT VT = N0.getValueType();
1998 // If the flag result is dead, turn this into an SUB.
1999 if (!N->hasAnyUseOfValue(1))
2000 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2001 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2003 // fold (subc x, x) -> 0 + no borrow
2005 return CombineTo(N, DAG.getConstant(0, DL, VT),
2006 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2008 // fold (subc x, 0) -> x + no borrow
2009 if (isNullConstant(N1))
2010 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2012 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2013 if (isAllOnesConstant(N0))
2014 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2015 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2020 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2021 SDValue N0 = N->getOperand(0);
2022 SDValue N1 = N->getOperand(1);
2023 SDValue CarryIn = N->getOperand(2);
2025 // fold (sube x, y, false) -> (subc x, y)
2026 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2027 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2032 SDValue DAGCombiner::visitMUL(SDNode *N) {
2033 SDValue N0 = N->getOperand(0);
2034 SDValue N1 = N->getOperand(1);
2035 EVT VT = N0.getValueType();
2037 // fold (mul x, undef) -> 0
2038 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2039 return DAG.getConstant(0, SDLoc(N), VT);
2041 bool N0IsConst = false;
2042 bool N1IsConst = false;
2043 bool N1IsOpaqueConst = false;
2044 bool N0IsOpaqueConst = false;
2045 APInt ConstValue0, ConstValue1;
2047 if (VT.isVector()) {
2048 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2051 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2052 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2054 N0IsConst = isa<ConstantSDNode>(N0);
2056 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2057 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2059 N1IsConst = isa<ConstantSDNode>(N1);
2061 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2062 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2066 // fold (mul c1, c2) -> c1*c2
2067 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2068 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2069 N0.getNode(), N1.getNode());
2071 // canonicalize constant to RHS (vector doesn't have to splat)
2072 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2073 !isConstantIntBuildVectorOrConstantInt(N1))
2074 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2075 // fold (mul x, 0) -> 0
2076 if (N1IsConst && ConstValue1 == 0)
2078 // We require a splat of the entire scalar bit width for non-contiguous
2081 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2082 // fold (mul x, 1) -> x
2083 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2085 // fold (mul x, -1) -> 0-x
2086 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2088 return DAG.getNode(ISD::SUB, DL, VT,
2089 DAG.getConstant(0, DL, VT), N0);
2091 // fold (mul x, (1 << c)) -> x << c
2092 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2095 return DAG.getNode(ISD::SHL, DL, VT, N0,
2096 DAG.getConstant(ConstValue1.logBase2(), DL,
2097 getShiftAmountTy(N0.getValueType())));
2099 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2100 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2102 unsigned Log2Val = (-ConstValue1).logBase2();
2104 // FIXME: If the input is something that is easily negated (e.g. a
2105 // single-use add), we should put the negate there.
2106 return DAG.getNode(ISD::SUB, DL, VT,
2107 DAG.getConstant(0, DL, VT),
2108 DAG.getNode(ISD::SHL, DL, VT, N0,
2109 DAG.getConstant(Log2Val, DL,
2110 getShiftAmountTy(N0.getValueType()))));
2114 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2115 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2116 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2117 isa<ConstantSDNode>(N0.getOperand(1)))) {
2118 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2119 N1, N0.getOperand(1));
2120 AddToWorklist(C3.getNode());
2121 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2122 N0.getOperand(0), C3);
2125 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2128 SDValue Sh(nullptr,0), Y(nullptr,0);
2129 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2130 if (N0.getOpcode() == ISD::SHL &&
2131 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2132 isa<ConstantSDNode>(N0.getOperand(1))) &&
2133 N0.getNode()->hasOneUse()) {
2135 } else if (N1.getOpcode() == ISD::SHL &&
2136 isa<ConstantSDNode>(N1.getOperand(1)) &&
2137 N1.getNode()->hasOneUse()) {
2142 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2143 Sh.getOperand(0), Y);
2144 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2145 Mul, Sh.getOperand(1));
2149 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2150 if (isConstantIntBuildVectorOrConstantInt(N1) &&
2151 N0.getOpcode() == ISD::ADD &&
2152 isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2153 isMulAddWithConstProfitable(N, N0, N1))
2154 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2155 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2156 N0.getOperand(0), N1),
2157 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2158 N0.getOperand(1), N1));
2161 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2167 /// Return true if divmod libcall is available.
2168 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2169 const TargetLowering &TLI) {
2171 switch (Node->getSimpleValueType(0).SimpleTy) {
2172 default: return false; // No libcall for vector types.
2173 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2174 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2175 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2176 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2177 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2180 return TLI.getLibcallName(LC) != nullptr;
2183 /// Issue divrem if both quotient and remainder are needed.
2184 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2185 if (Node->use_empty())
2186 return SDValue(); // This is a dead node, leave it alone.
2188 EVT VT = Node->getValueType(0);
2189 if (!TLI.isTypeLegal(VT))
2192 unsigned Opcode = Node->getOpcode();
2193 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2195 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2196 // If DIVREM is going to get expanded into a libcall,
2197 // but there is no libcall available, then don't combine.
2198 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2199 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2202 // If div is legal, it's better to do the normal expansion
2203 unsigned OtherOpcode = 0;
2204 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2205 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2206 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2209 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2210 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2214 SDValue Op0 = Node->getOperand(0);
2215 SDValue Op1 = Node->getOperand(1);
2217 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2218 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2220 if (User == Node || User->use_empty())
2222 // Convert the other matching node(s), too;
2223 // otherwise, the DIVREM may get target-legalized into something
2224 // target-specific that we won't be able to recognize.
2225 unsigned UserOpc = User->getOpcode();
2226 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2227 User->getOperand(0) == Op0 &&
2228 User->getOperand(1) == Op1) {
2230 if (UserOpc == OtherOpcode) {
2231 SDVTList VTs = DAG.getVTList(VT, VT);
2232 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2233 } else if (UserOpc == DivRemOpc) {
2234 combined = SDValue(User, 0);
2236 assert(UserOpc == Opcode);
2240 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2241 CombineTo(User, combined);
2242 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2243 CombineTo(User, combined.getValue(1));
2249 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2250 SDValue N0 = N->getOperand(0);
2251 SDValue N1 = N->getOperand(1);
2252 EVT VT = N->getValueType(0);
2256 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2261 // fold (sdiv c1, c2) -> c1/c2
2262 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2263 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2264 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2265 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2266 // fold (sdiv X, 1) -> X
2267 if (N1C && N1C->isOne())
2269 // fold (sdiv X, -1) -> 0-X
2270 if (N1C && N1C->isAllOnesValue())
2271 return DAG.getNode(ISD::SUB, DL, VT,
2272 DAG.getConstant(0, DL, VT), N0);
2274 // If we know the sign bits of both operands are zero, strength reduce to a
2275 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2276 if (!VT.isVector()) {
2277 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2278 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2281 // fold (sdiv X, pow2) -> simple ops after legalize
2282 // FIXME: We check for the exact bit here because the generic lowering gives
2283 // better results in that case. The target-specific lowering should learn how
2284 // to handle exact sdivs efficiently.
2285 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2286 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2287 (N1C->getAPIntValue().isPowerOf2() ||
2288 (-N1C->getAPIntValue()).isPowerOf2())) {
2289 // Target-specific implementation of sdiv x, pow2.
2290 if (SDValue Res = BuildSDIVPow2(N))
2293 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2295 // Splat the sign bit into the register
2297 DAG.getNode(ISD::SRA, DL, VT, N0,
2298 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2299 getShiftAmountTy(N0.getValueType())));
2300 AddToWorklist(SGN.getNode());
2302 // Add (N0 < 0) ? abs2 - 1 : 0;
2304 DAG.getNode(ISD::SRL, DL, VT, SGN,
2305 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2306 getShiftAmountTy(SGN.getValueType())));
2307 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2308 AddToWorklist(SRL.getNode());
2309 AddToWorklist(ADD.getNode()); // Divide by pow2
2310 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2311 DAG.getConstant(lg2, DL,
2312 getShiftAmountTy(ADD.getValueType())));
2314 // If we're dividing by a positive value, we're done. Otherwise, we must
2315 // negate the result.
2316 if (N1C->getAPIntValue().isNonNegative())
2319 AddToWorklist(SRA.getNode());
2320 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2323 // If integer divide is expensive and we satisfy the requirements, emit an
2324 // alternate sequence. Targets may check function attributes for size/speed
2326 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2327 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2328 if (SDValue Op = BuildSDIV(N))
2331 // sdiv, srem -> sdivrem
2332 if (SDValue DivRem = useDivRem(N))
2336 if (N0.getOpcode() == ISD::UNDEF)
2337 return DAG.getConstant(0, DL, VT);
2338 // X / undef -> undef
2339 if (N1.getOpcode() == ISD::UNDEF)
2345 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2346 SDValue N0 = N->getOperand(0);
2347 SDValue N1 = N->getOperand(1);
2348 EVT VT = N->getValueType(0);
2352 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2357 // fold (udiv c1, c2) -> c1/c2
2358 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2359 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2361 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2364 // fold (udiv x, (1 << c)) -> x >>u c
2365 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2366 return DAG.getNode(ISD::SRL, DL, VT, N0,
2367 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2368 getShiftAmountTy(N0.getValueType())));
2370 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2371 if (N1.getOpcode() == ISD::SHL) {
2372 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2373 if (SHC->getAPIntValue().isPowerOf2()) {
2374 EVT ADDVT = N1.getOperand(1).getValueType();
2375 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2377 DAG.getConstant(SHC->getAPIntValue()
2380 AddToWorklist(Add.getNode());
2381 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2386 // fold (udiv x, c) -> alternate
2387 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2388 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2389 if (SDValue Op = BuildUDIV(N))
2392 // sdiv, srem -> sdivrem
2393 if (SDValue DivRem = useDivRem(N))
2397 if (N0.getOpcode() == ISD::UNDEF)
2398 return DAG.getConstant(0, DL, VT);
2399 // X / undef -> undef
2400 if (N1.getOpcode() == ISD::UNDEF)
2406 // handles ISD::SREM and ISD::UREM
2407 SDValue DAGCombiner::visitREM(SDNode *N) {
2408 unsigned Opcode = N->getOpcode();
2409 SDValue N0 = N->getOperand(0);
2410 SDValue N1 = N->getOperand(1);
2411 EVT VT = N->getValueType(0);
2412 bool isSigned = (Opcode == ISD::SREM);
2415 // fold (rem c1, c2) -> c1%c2
2416 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2417 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2419 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2423 // If we know the sign bits of both operands are zero, strength reduce to a
2424 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2425 if (!VT.isVector()) {
2426 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2427 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2430 // fold (urem x, pow2) -> (and x, pow2-1)
2431 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2432 N1C->getAPIntValue().isPowerOf2()) {
2433 return DAG.getNode(ISD::AND, DL, VT, N0,
2434 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2436 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2437 if (N1.getOpcode() == ISD::SHL) {
2438 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2439 if (SHC->getAPIntValue().isPowerOf2()) {
2441 DAG.getNode(ISD::ADD, DL, VT, N1,
2442 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2444 AddToWorklist(Add.getNode());
2445 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2451 // If X/C can be simplified by the division-by-constant logic, lower
2452 // X%C to the equivalent of X-X/C*C.
2453 if (N1C && !N1C->isNullValue()) {
2454 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2455 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2456 AddToWorklist(Div.getNode());
2457 SDValue OptimizedDiv = combine(Div.getNode());
2458 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2459 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2460 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2461 AddToWorklist(Mul.getNode());
2466 // sdiv, srem -> sdivrem
2467 if (SDValue DivRem = useDivRem(N))
2468 return DivRem.getValue(1);
2471 if (N0.getOpcode() == ISD::UNDEF)
2472 return DAG.getConstant(0, DL, VT);
2473 // X % undef -> undef
2474 if (N1.getOpcode() == ISD::UNDEF)
2480 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2481 SDValue N0 = N->getOperand(0);
2482 SDValue N1 = N->getOperand(1);
2483 EVT VT = N->getValueType(0);
2486 // fold (mulhs x, 0) -> 0
2487 if (isNullConstant(N1))
2489 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2490 if (isOneConstant(N1)) {
2492 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2493 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2495 getShiftAmountTy(N0.getValueType())));
2497 // fold (mulhs x, undef) -> 0
2498 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2499 return DAG.getConstant(0, SDLoc(N), VT);
2501 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2503 if (VT.isSimple() && !VT.isVector()) {
2504 MVT Simple = VT.getSimpleVT();
2505 unsigned SimpleSize = Simple.getSizeInBits();
2506 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2507 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2508 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2509 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2510 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2511 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2512 DAG.getConstant(SimpleSize, DL,
2513 getShiftAmountTy(N1.getValueType())));
2514 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2521 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2522 SDValue N0 = N->getOperand(0);
2523 SDValue N1 = N->getOperand(1);
2524 EVT VT = N->getValueType(0);
2527 // fold (mulhu x, 0) -> 0
2528 if (isNullConstant(N1))
2530 // fold (mulhu x, 1) -> 0
2531 if (isOneConstant(N1))
2532 return DAG.getConstant(0, DL, N0.getValueType());
2533 // fold (mulhu x, undef) -> 0
2534 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2535 return DAG.getConstant(0, DL, VT);
2537 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2539 if (VT.isSimple() && !VT.isVector()) {
2540 MVT Simple = VT.getSimpleVT();
2541 unsigned SimpleSize = Simple.getSizeInBits();
2542 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2543 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2544 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2545 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2546 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2547 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2548 DAG.getConstant(SimpleSize, DL,
2549 getShiftAmountTy(N1.getValueType())));
2550 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2557 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2558 /// give the opcodes for the two computations that are being performed. Return
2559 /// true if a simplification was made.
2560 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2562 // If the high half is not needed, just compute the low half.
2563 bool HiExists = N->hasAnyUseOfValue(1);
2565 (!LegalOperations ||
2566 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2567 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2568 return CombineTo(N, Res, Res);
2571 // If the low half is not needed, just compute the high half.
2572 bool LoExists = N->hasAnyUseOfValue(0);
2574 (!LegalOperations ||
2575 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2576 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2577 return CombineTo(N, Res, Res);
2580 // If both halves are used, return as it is.
2581 if (LoExists && HiExists)
2584 // If the two computed results can be simplified separately, separate them.
2586 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2587 AddToWorklist(Lo.getNode());
2588 SDValue LoOpt = combine(Lo.getNode());
2589 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2590 (!LegalOperations ||
2591 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2592 return CombineTo(N, LoOpt, LoOpt);
2596 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2597 AddToWorklist(Hi.getNode());
2598 SDValue HiOpt = combine(Hi.getNode());
2599 if (HiOpt.getNode() && HiOpt != Hi &&
2600 (!LegalOperations ||
2601 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2602 return CombineTo(N, HiOpt, HiOpt);
2608 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2609 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2612 EVT VT = N->getValueType(0);
2615 // If the type is twice as wide is legal, transform the mulhu to a wider
2616 // multiply plus a shift.
2617 if (VT.isSimple() && !VT.isVector()) {
2618 MVT Simple = VT.getSimpleVT();
2619 unsigned SimpleSize = Simple.getSizeInBits();
2620 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2621 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2622 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2623 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2624 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2625 // Compute the high part as N1.
2626 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2627 DAG.getConstant(SimpleSize, DL,
2628 getShiftAmountTy(Lo.getValueType())));
2629 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2630 // Compute the low part as N0.
2631 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2632 return CombineTo(N, Lo, Hi);
2639 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2640 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2643 EVT VT = N->getValueType(0);
2646 // If the type is twice as wide is legal, transform the mulhu to a wider
2647 // multiply plus a shift.
2648 if (VT.isSimple() && !VT.isVector()) {
2649 MVT Simple = VT.getSimpleVT();
2650 unsigned SimpleSize = Simple.getSizeInBits();
2651 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2652 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2653 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2654 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2655 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2656 // Compute the high part as N1.
2657 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2658 DAG.getConstant(SimpleSize, DL,
2659 getShiftAmountTy(Lo.getValueType())));
2660 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2661 // Compute the low part as N0.
2662 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2663 return CombineTo(N, Lo, Hi);
2670 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2671 // (smulo x, 2) -> (saddo x, x)
2672 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2673 if (C2->getAPIntValue() == 2)
2674 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2675 N->getOperand(0), N->getOperand(0));
2680 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2681 // (umulo x, 2) -> (uaddo x, x)
2682 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2683 if (C2->getAPIntValue() == 2)
2684 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2685 N->getOperand(0), N->getOperand(0));
2690 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2691 SDValue N0 = N->getOperand(0);
2692 SDValue N1 = N->getOperand(1);
2693 EVT VT = N0.getValueType();
2697 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2700 // fold (add c1, c2) -> c1+c2
2701 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2702 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2704 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2706 // canonicalize constant to RHS
2707 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2708 !isConstantIntBuildVectorOrConstantInt(N1))
2709 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2714 /// If this is a binary operator with two operands of the same opcode, try to
2716 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2717 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2718 EVT VT = N0.getValueType();
2719 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2721 // Bail early if none of these transforms apply.
2722 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2724 // For each of OP in AND/OR/XOR:
2725 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2726 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2727 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2728 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2729 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2731 // do not sink logical op inside of a vector extend, since it may combine
2733 EVT Op0VT = N0.getOperand(0).getValueType();
2734 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2735 N0.getOpcode() == ISD::SIGN_EXTEND ||
2736 N0.getOpcode() == ISD::BSWAP ||
2737 // Avoid infinite looping with PromoteIntBinOp.
2738 (N0.getOpcode() == ISD::ANY_EXTEND &&
2739 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2740 (N0.getOpcode() == ISD::TRUNCATE &&
2741 (!TLI.isZExtFree(VT, Op0VT) ||
2742 !TLI.isTruncateFree(Op0VT, VT)) &&
2743 TLI.isTypeLegal(Op0VT))) &&
2745 Op0VT == N1.getOperand(0).getValueType() &&
2746 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2747 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2748 N0.getOperand(0).getValueType(),
2749 N0.getOperand(0), N1.getOperand(0));
2750 AddToWorklist(ORNode.getNode());
2751 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2754 // For each of OP in SHL/SRL/SRA/AND...
2755 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2756 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2757 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2758 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2759 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2760 N0.getOperand(1) == N1.getOperand(1)) {
2761 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2762 N0.getOperand(0).getValueType(),
2763 N0.getOperand(0), N1.getOperand(0));
2764 AddToWorklist(ORNode.getNode());
2765 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2766 ORNode, N0.getOperand(1));
2769 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2770 // Only perform this optimization after type legalization and before
2771 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2772 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2773 // we don't want to undo this promotion.
2774 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2776 if ((N0.getOpcode() == ISD::BITCAST ||
2777 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2778 Level == AfterLegalizeTypes) {
2779 SDValue In0 = N0.getOperand(0);
2780 SDValue In1 = N1.getOperand(0);
2781 EVT In0Ty = In0.getValueType();
2782 EVT In1Ty = In1.getValueType();
2784 // If both incoming values are integers, and the original types are the
2786 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2787 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2788 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2789 AddToWorklist(Op.getNode());
2794 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2795 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2796 // If both shuffles use the same mask, and both shuffle within a single
2797 // vector, then it is worthwhile to move the swizzle after the operation.
2798 // The type-legalizer generates this pattern when loading illegal
2799 // vector types from memory. In many cases this allows additional shuffle
2801 // There are other cases where moving the shuffle after the xor/and/or
2802 // is profitable even if shuffles don't perform a swizzle.
2803 // If both shuffles use the same mask, and both shuffles have the same first
2804 // or second operand, then it might still be profitable to move the shuffle
2805 // after the xor/and/or operation.
2806 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2807 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2808 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2810 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2811 "Inputs to shuffles are not the same type");
2813 // Check that both shuffles use the same mask. The masks are known to be of
2814 // the same length because the result vector type is the same.
2815 // Check also that shuffles have only one use to avoid introducing extra
2817 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2818 SVN0->getMask().equals(SVN1->getMask())) {
2819 SDValue ShOp = N0->getOperand(1);
2821 // Don't try to fold this node if it requires introducing a
2822 // build vector of all zeros that might be illegal at this stage.
2823 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2825 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2830 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2831 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2832 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2833 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2834 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2835 N0->getOperand(0), N1->getOperand(0));
2836 AddToWorklist(NewNode.getNode());
2837 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2838 &SVN0->getMask()[0]);
2841 // Don't try to fold this node if it requires introducing a
2842 // build vector of all zeros that might be illegal at this stage.
2843 ShOp = N0->getOperand(0);
2844 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2846 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2851 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2852 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2853 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2854 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2855 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2856 N0->getOperand(1), N1->getOperand(1));
2857 AddToWorklist(NewNode.getNode());
2858 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2859 &SVN0->getMask()[0]);
2867 /// This contains all DAGCombine rules which reduce two values combined by
2868 /// an And operation to a single value. This makes them reusable in the context
2869 /// of visitSELECT(). Rules involving constants are not included as
2870 /// visitSELECT() already handles those cases.
2871 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2872 SDNode *LocReference) {
2873 EVT VT = N1.getValueType();
2875 // fold (and x, undef) -> 0
2876 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2877 return DAG.getConstant(0, SDLoc(LocReference), VT);
2878 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2879 SDValue LL, LR, RL, RR, CC0, CC1;
2880 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2881 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2882 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2884 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2885 LL.getValueType().isInteger()) {
2886 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2887 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2888 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2889 LR.getValueType(), LL, RL);
2890 AddToWorklist(ORNode.getNode());
2891 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2893 if (isAllOnesConstant(LR)) {
2894 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2895 if (Op1 == ISD::SETEQ) {
2896 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2897 LR.getValueType(), LL, RL);
2898 AddToWorklist(ANDNode.getNode());
2899 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2901 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2902 if (Op1 == ISD::SETGT) {
2903 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2904 LR.getValueType(), LL, RL);
2905 AddToWorklist(ORNode.getNode());
2906 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2910 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2911 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2912 Op0 == Op1 && LL.getValueType().isInteger() &&
2913 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2914 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2916 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2917 LL, DAG.getConstant(1, DL,
2918 LL.getValueType()));
2919 AddToWorklist(ADDNode.getNode());
2920 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2921 DAG.getConstant(2, DL, LL.getValueType()),
2924 // canonicalize equivalent to ll == rl
2925 if (LL == RR && LR == RL) {
2926 Op1 = ISD::getSetCCSwappedOperands(Op1);
2929 if (LL == RL && LR == RR) {
2930 bool isInteger = LL.getValueType().isInteger();
2931 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2932 if (Result != ISD::SETCC_INVALID &&
2933 (!LegalOperations ||
2934 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2935 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2936 EVT CCVT = getSetCCResultType(LL.getValueType());
2937 if (N0.getValueType() == CCVT ||
2938 (!LegalOperations && N0.getValueType() == MVT::i1))
2939 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2945 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2946 VT.getSizeInBits() <= 64) {
2947 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2948 APInt ADDC = ADDI->getAPIntValue();
2949 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2950 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2951 // immediate for an add, but it is legal if its top c2 bits are set,
2952 // transform the ADD so the immediate doesn't need to be materialized
2954 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2955 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2956 SRLI->getZExtValue());
2957 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2959 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2962 DAG.getNode(ISD::ADD, DL, VT,
2963 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2964 CombineTo(N0.getNode(), NewAdd);
2965 // Return N so it doesn't get rechecked!
2966 return SDValue(LocReference, 0);
2977 SDValue DAGCombiner::visitAND(SDNode *N) {
2978 SDValue N0 = N->getOperand(0);
2979 SDValue N1 = N->getOperand(1);
2980 EVT VT = N1.getValueType();
2983 if (VT.isVector()) {
2984 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2987 // fold (and x, 0) -> 0, vector edition
2988 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2989 // do not return N0, because undef node may exist in N0
2990 return DAG.getConstant(
2991 APInt::getNullValue(
2992 N0.getValueType().getScalarType().getSizeInBits()),
2993 SDLoc(N), N0.getValueType());
2994 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2995 // do not return N1, because undef node may exist in N1
2996 return DAG.getConstant(
2997 APInt::getNullValue(
2998 N1.getValueType().getScalarType().getSizeInBits()),
2999 SDLoc(N), N1.getValueType());
3001 // fold (and x, -1) -> x, vector edition
3002 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3004 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3008 // fold (and c1, c2) -> c1&c2
3009 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3010 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3011 if (N0C && N1C && !N1C->isOpaque())
3012 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3013 // canonicalize constant to RHS
3014 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3015 !isConstantIntBuildVectorOrConstantInt(N1))
3016 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3017 // fold (and x, -1) -> x
3018 if (isAllOnesConstant(N1))
3020 // if (and x, c) is known to be zero, return 0
3021 unsigned BitWidth = VT.getScalarType().getSizeInBits();
3022 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3023 APInt::getAllOnesValue(BitWidth)))
3024 return DAG.getConstant(0, SDLoc(N), VT);
3026 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3028 // fold (and (or x, C), D) -> D if (C & D) == D
3029 if (N1C && N0.getOpcode() == ISD::OR)
3030 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3031 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3033 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3034 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3035 SDValue N0Op0 = N0.getOperand(0);
3036 APInt Mask = ~N1C->getAPIntValue();
3037 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3038 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3039 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3040 N0.getValueType(), N0Op0);
3042 // Replace uses of the AND with uses of the Zero extend node.
3045 // We actually want to replace all uses of the any_extend with the
3046 // zero_extend, to avoid duplicating things. This will later cause this
3047 // AND to be folded.
3048 CombineTo(N0.getNode(), Zext);
3049 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3052 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3053 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3054 // already be zero by virtue of the width of the base type of the load.
3056 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3058 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3059 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3060 N0.getOpcode() == ISD::LOAD) {
3061 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3062 N0 : N0.getOperand(0) );
3064 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3065 // This can be a pure constant or a vector splat, in which case we treat the
3066 // vector as a scalar and use the splat value.
3067 APInt Constant = APInt::getNullValue(1);
3068 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3069 Constant = C->getAPIntValue();
3070 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3071 APInt SplatValue, SplatUndef;
3072 unsigned SplatBitSize;
3074 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3075 SplatBitSize, HasAnyUndefs);
3077 // Undef bits can contribute to a possible optimisation if set, so
3079 SplatValue |= SplatUndef;
3081 // The splat value may be something like "0x00FFFFFF", which means 0 for
3082 // the first vector value and FF for the rest, repeating. We need a mask
3083 // that will apply equally to all members of the vector, so AND all the
3084 // lanes of the constant together.
3085 EVT VT = Vector->getValueType(0);
3086 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3088 // If the splat value has been compressed to a bitlength lower
3089 // than the size of the vector lane, we need to re-expand it to
3091 if (BitWidth > SplatBitSize)
3092 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3093 SplatBitSize < BitWidth;
3094 SplatBitSize = SplatBitSize * 2)
3095 SplatValue |= SplatValue.shl(SplatBitSize);
3097 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3098 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3099 if (SplatBitSize % BitWidth == 0) {
3100 Constant = APInt::getAllOnesValue(BitWidth);
3101 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3102 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3107 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3108 // actually legal and isn't going to get expanded, else this is a false
3110 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3111 Load->getValueType(0),
3112 Load->getMemoryVT());
3114 // Resize the constant to the same size as the original memory access before
3115 // extension. If it is still the AllOnesValue then this AND is completely
3118 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3121 switch (Load->getExtensionType()) {
3122 default: B = false; break;
3123 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3125 case ISD::NON_EXTLOAD: B = true; break;
3128 if (B && Constant.isAllOnesValue()) {
3129 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3130 // preserve semantics once we get rid of the AND.
3131 SDValue NewLoad(Load, 0);
3132 if (Load->getExtensionType() == ISD::EXTLOAD) {
3133 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3134 Load->getValueType(0), SDLoc(Load),
3135 Load->getChain(), Load->getBasePtr(),
3136 Load->getOffset(), Load->getMemoryVT(),
3137 Load->getMemOperand());
3138 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3139 if (Load->getNumValues() == 3) {
3140 // PRE/POST_INC loads have 3 values.
3141 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3142 NewLoad.getValue(2) };
3143 CombineTo(Load, To, 3, true);
3145 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3149 // Fold the AND away, taking care not to fold to the old load node if we
3151 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3153 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3157 // fold (and (load x), 255) -> (zextload x, i8)
3158 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3159 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3160 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3161 (N0.getOpcode() == ISD::ANY_EXTEND &&
3162 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3163 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3164 LoadSDNode *LN0 = HasAnyExt
3165 ? cast<LoadSDNode>(N0.getOperand(0))
3166 : cast<LoadSDNode>(N0);
3167 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3168 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3169 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3170 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3171 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3172 EVT LoadedVT = LN0->getMemoryVT();
3173 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3175 if (ExtVT == LoadedVT &&
3176 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3180 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3181 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3182 LN0->getMemOperand());
3184 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3185 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3188 // Do not change the width of a volatile load.
3189 // Do not generate loads of non-round integer types since these can
3190 // be expensive (and would be wrong if the type is not byte sized).
3191 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3192 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3194 EVT PtrType = LN0->getOperand(1).getValueType();
3196 unsigned Alignment = LN0->getAlignment();
3197 SDValue NewPtr = LN0->getBasePtr();
3199 // For big endian targets, we need to add an offset to the pointer
3200 // to load the correct bytes. For little endian systems, we merely
3201 // need to read fewer bytes from the same pointer.
3202 if (DAG.getDataLayout().isBigEndian()) {
3203 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3204 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3205 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3207 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3208 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3209 Alignment = MinAlign(Alignment, PtrOff);
3212 AddToWorklist(NewPtr.getNode());
3215 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3216 LN0->getChain(), NewPtr,
3217 LN0->getPointerInfo(),
3218 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3219 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3221 CombineTo(LN0, Load, Load.getValue(1));
3222 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3228 if (SDValue Combined = visitANDLike(N0, N1, N))
3231 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3232 if (N0.getOpcode() == N1.getOpcode())
3233 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3236 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3237 // fold (and (sra)) -> (and (srl)) when possible.
3238 if (!VT.isVector() &&
3239 SimplifyDemandedBits(SDValue(N, 0)))
3240 return SDValue(N, 0);
3242 // fold (zext_inreg (extload x)) -> (zextload x)
3243 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3244 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3245 EVT MemVT = LN0->getMemoryVT();
3246 // If we zero all the possible extended bits, then we can turn this into
3247 // a zextload if we are running before legalize or the operation is legal.
3248 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3249 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3250 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3251 ((!LegalOperations && !LN0->isVolatile()) ||
3252 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3253 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3254 LN0->getChain(), LN0->getBasePtr(),
3255 MemVT, LN0->getMemOperand());
3257 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3258 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3261 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3262 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3264 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3265 EVT MemVT = LN0->getMemoryVT();
3266 // If we zero all the possible extended bits, then we can turn this into
3267 // a zextload if we are running before legalize or the operation is legal.
3268 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3269 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3270 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3271 ((!LegalOperations && !LN0->isVolatile()) ||
3272 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3273 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3274 LN0->getChain(), LN0->getBasePtr(),
3275 MemVT, LN0->getMemOperand());
3277 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3278 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3281 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3282 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3283 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3284 N0.getOperand(1), false);
3285 if (BSwap.getNode())
3292 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3293 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3294 bool DemandHighBits) {
3295 if (!LegalOperations)
3298 EVT VT = N->getValueType(0);
3299 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3301 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3304 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3305 bool LookPassAnd0 = false;
3306 bool LookPassAnd1 = false;
3307 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3309 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3311 if (N0.getOpcode() == ISD::AND) {
3312 if (!N0.getNode()->hasOneUse())
3314 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3315 if (!N01C || N01C->getZExtValue() != 0xFF00)
3317 N0 = N0.getOperand(0);
3318 LookPassAnd0 = true;
3321 if (N1.getOpcode() == ISD::AND) {
3322 if (!N1.getNode()->hasOneUse())
3324 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3325 if (!N11C || N11C->getZExtValue() != 0xFF)
3327 N1 = N1.getOperand(0);
3328 LookPassAnd1 = true;
3331 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3333 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3335 if (!N0.getNode()->hasOneUse() ||
3336 !N1.getNode()->hasOneUse())
3339 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3340 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3343 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3346 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3347 SDValue N00 = N0->getOperand(0);
3348 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3349 if (!N00.getNode()->hasOneUse())
3351 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3352 if (!N001C || N001C->getZExtValue() != 0xFF)
3354 N00 = N00.getOperand(0);
3355 LookPassAnd0 = true;
3358 SDValue N10 = N1->getOperand(0);
3359 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3360 if (!N10.getNode()->hasOneUse())
3362 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3363 if (!N101C || N101C->getZExtValue() != 0xFF00)
3365 N10 = N10.getOperand(0);
3366 LookPassAnd1 = true;
3372 // Make sure everything beyond the low halfword gets set to zero since the SRL
3373 // 16 will clear the top bits.
3374 unsigned OpSizeInBits = VT.getSizeInBits();
3375 if (DemandHighBits && OpSizeInBits > 16) {
3376 // If the left-shift isn't masked out then the only way this is a bswap is
3377 // if all bits beyond the low 8 are 0. In that case the entire pattern
3378 // reduces to a left shift anyway: leave it for other parts of the combiner.
3382 // However, if the right shift isn't masked out then it might be because
3383 // it's not needed. See if we can spot that too.
3384 if (!LookPassAnd1 &&
3385 !DAG.MaskedValueIsZero(
3386 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3390 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3391 if (OpSizeInBits > 16) {
3393 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3394 DAG.getConstant(OpSizeInBits - 16, DL,
3395 getShiftAmountTy(VT)));
3400 /// Return true if the specified node is an element that makes up a 32-bit
3401 /// packed halfword byteswap.
3402 /// ((x & 0x000000ff) << 8) |
3403 /// ((x & 0x0000ff00) >> 8) |
3404 /// ((x & 0x00ff0000) << 8) |
3405 /// ((x & 0xff000000) >> 8)
3406 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3407 if (!N.getNode()->hasOneUse())
3410 unsigned Opc = N.getOpcode();
3411 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3414 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3419 switch (N1C->getZExtValue()) {
3422 case 0xFF: Num = 0; break;
3423 case 0xFF00: Num = 1; break;
3424 case 0xFF0000: Num = 2; break;
3425 case 0xFF000000: Num = 3; break;
3428 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3429 SDValue N0 = N.getOperand(0);
3430 if (Opc == ISD::AND) {
3431 if (Num == 0 || Num == 2) {
3433 // (x >> 8) & 0xff0000
3434 if (N0.getOpcode() != ISD::SRL)
3436 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3437 if (!C || C->getZExtValue() != 8)
3440 // (x << 8) & 0xff00
3441 // (x << 8) & 0xff000000
3442 if (N0.getOpcode() != ISD::SHL)
3444 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3445 if (!C || C->getZExtValue() != 8)
3448 } else if (Opc == ISD::SHL) {
3450 // (x & 0xff0000) << 8
3451 if (Num != 0 && Num != 2)
3453 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3454 if (!C || C->getZExtValue() != 8)
3456 } else { // Opc == ISD::SRL
3457 // (x & 0xff00) >> 8
3458 // (x & 0xff000000) >> 8
3459 if (Num != 1 && Num != 3)
3461 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3462 if (!C || C->getZExtValue() != 8)
3469 Parts[Num] = N0.getOperand(0).getNode();
3473 /// Match a 32-bit packed halfword bswap. That is
3474 /// ((x & 0x000000ff) << 8) |
3475 /// ((x & 0x0000ff00) >> 8) |
3476 /// ((x & 0x00ff0000) << 8) |
3477 /// ((x & 0xff000000) >> 8)
3478 /// => (rotl (bswap x), 16)
3479 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3480 if (!LegalOperations)
3483 EVT VT = N->getValueType(0);
3486 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3490 // (or (or (and), (and)), (or (and), (and)))
3491 // (or (or (or (and), (and)), (and)), (and))
3492 if (N0.getOpcode() != ISD::OR)
3494 SDValue N00 = N0.getOperand(0);
3495 SDValue N01 = N0.getOperand(1);
3496 SDNode *Parts[4] = {};
3498 if (N1.getOpcode() == ISD::OR &&
3499 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3500 // (or (or (and), (and)), (or (and), (and)))
3501 SDValue N000 = N00.getOperand(0);
3502 if (!isBSwapHWordElement(N000, Parts))
3505 SDValue N001 = N00.getOperand(1);
3506 if (!isBSwapHWordElement(N001, Parts))
3508 SDValue N010 = N01.getOperand(0);
3509 if (!isBSwapHWordElement(N010, Parts))
3511 SDValue N011 = N01.getOperand(1);
3512 if (!isBSwapHWordElement(N011, Parts))
3515 // (or (or (or (and), (and)), (and)), (and))
3516 if (!isBSwapHWordElement(N1, Parts))
3518 if (!isBSwapHWordElement(N01, Parts))
3520 if (N00.getOpcode() != ISD::OR)
3522 SDValue N000 = N00.getOperand(0);
3523 if (!isBSwapHWordElement(N000, Parts))
3525 SDValue N001 = N00.getOperand(1);
3526 if (!isBSwapHWordElement(N001, Parts))
3530 // Make sure the parts are all coming from the same node.
3531 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3535 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3536 SDValue(Parts[0], 0));
3538 // Result of the bswap should be rotated by 16. If it's not legal, then
3539 // do (x << 16) | (x >> 16).
3540 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3541 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3542 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3543 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3544 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3545 return DAG.getNode(ISD::OR, DL, VT,
3546 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3547 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3550 /// This contains all DAGCombine rules which reduce two values combined by
3551 /// an Or operation to a single value \see visitANDLike().
3552 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3553 EVT VT = N1.getValueType();
3554 // fold (or x, undef) -> -1
3555 if (!LegalOperations &&
3556 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3557 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3558 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3559 SDLoc(LocReference), VT);
3561 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3562 SDValue LL, LR, RL, RR, CC0, CC1;
3563 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3564 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3565 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3567 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3568 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3569 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3570 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3571 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3572 LR.getValueType(), LL, RL);
3573 AddToWorklist(ORNode.getNode());
3574 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3576 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3577 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3578 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3579 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3580 LR.getValueType(), LL, RL);
3581 AddToWorklist(ANDNode.getNode());
3582 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3585 // canonicalize equivalent to ll == rl
3586 if (LL == RR && LR == RL) {
3587 Op1 = ISD::getSetCCSwappedOperands(Op1);
3590 if (LL == RL && LR == RR) {
3591 bool isInteger = LL.getValueType().isInteger();
3592 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3593 if (Result != ISD::SETCC_INVALID &&
3594 (!LegalOperations ||
3595 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3596 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3597 EVT CCVT = getSetCCResultType(LL.getValueType());
3598 if (N0.getValueType() == CCVT ||
3599 (!LegalOperations && N0.getValueType() == MVT::i1))
3600 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3606 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3607 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3608 // Don't increase # computations.
3609 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3610 // We can only do this xform if we know that bits from X that are set in C2
3611 // but not in C1 are already zero. Likewise for Y.
3612 if (const ConstantSDNode *N0O1C =
3613 getAsNonOpaqueConstant(N0.getOperand(1))) {
3614 if (const ConstantSDNode *N1O1C =
3615 getAsNonOpaqueConstant(N1.getOperand(1))) {
3616 // We can only do this xform if we know that bits from X that are set in
3617 // C2 but not in C1 are already zero. Likewise for Y.
3618 const APInt &LHSMask = N0O1C->getAPIntValue();
3619 const APInt &RHSMask = N1O1C->getAPIntValue();
3621 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3622 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3623 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3624 N0.getOperand(0), N1.getOperand(0));
3625 SDLoc DL(LocReference);
3626 return DAG.getNode(ISD::AND, DL, VT, X,
3627 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3633 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3634 if (N0.getOpcode() == ISD::AND &&
3635 N1.getOpcode() == ISD::AND &&
3636 N0.getOperand(0) == N1.getOperand(0) &&
3637 // Don't increase # computations.
3638 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3639 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3640 N0.getOperand(1), N1.getOperand(1));
3641 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3647 SDValue DAGCombiner::visitOR(SDNode *N) {
3648 SDValue N0 = N->getOperand(0);
3649 SDValue N1 = N->getOperand(1);
3650 EVT VT = N1.getValueType();
3653 if (VT.isVector()) {
3654 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3657 // fold (or x, 0) -> x, vector edition
3658 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3660 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3663 // fold (or x, -1) -> -1, vector edition
3664 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3665 // do not return N0, because undef node may exist in N0
3666 return DAG.getConstant(
3667 APInt::getAllOnesValue(
3668 N0.getValueType().getScalarType().getSizeInBits()),
3669 SDLoc(N), N0.getValueType());
3670 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3671 // do not return N1, because undef node may exist in N1
3672 return DAG.getConstant(
3673 APInt::getAllOnesValue(
3674 N1.getValueType().getScalarType().getSizeInBits()),
3675 SDLoc(N), N1.getValueType());
3677 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3678 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3679 // Do this only if the resulting shuffle is legal.
3680 if (isa<ShuffleVectorSDNode>(N0) &&
3681 isa<ShuffleVectorSDNode>(N1) &&
3682 // Avoid folding a node with illegal type.
3683 TLI.isTypeLegal(VT) &&
3684 N0->getOperand(1) == N1->getOperand(1) &&
3685 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3686 bool CanFold = true;
3687 unsigned NumElts = VT.getVectorNumElements();
3688 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3689 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3690 // We construct two shuffle masks:
3691 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3692 // and N1 as the second operand.
3693 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3694 // and N0 as the second operand.
3695 // We do this because OR is commutable and therefore there might be
3696 // two ways to fold this node into a shuffle.
3697 SmallVector<int,4> Mask1;
3698 SmallVector<int,4> Mask2;
3700 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3701 int M0 = SV0->getMaskElt(i);
3702 int M1 = SV1->getMaskElt(i);
3704 // Both shuffle indexes are undef. Propagate Undef.
3705 if (M0 < 0 && M1 < 0) {
3706 Mask1.push_back(M0);
3707 Mask2.push_back(M0);
3711 if (M0 < 0 || M1 < 0 ||
3712 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3713 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3718 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3719 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3723 // Fold this sequence only if the resulting shuffle is 'legal'.
3724 if (TLI.isShuffleMaskLegal(Mask1, VT))
3725 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3726 N1->getOperand(0), &Mask1[0]);
3727 if (TLI.isShuffleMaskLegal(Mask2, VT))
3728 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3729 N0->getOperand(0), &Mask2[0]);
3734 // fold (or c1, c2) -> c1|c2
3735 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3736 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3737 if (N0C && N1C && !N1C->isOpaque())
3738 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3739 // canonicalize constant to RHS
3740 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3741 !isConstantIntBuildVectorOrConstantInt(N1))
3742 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3743 // fold (or x, 0) -> x
3744 if (isNullConstant(N1))
3746 // fold (or x, -1) -> -1
3747 if (isAllOnesConstant(N1))
3749 // fold (or x, c) -> c iff (x & ~c) == 0
3750 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3753 if (SDValue Combined = visitORLike(N0, N1, N))
3756 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3757 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3759 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3763 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3765 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3766 // iff (c1 & c2) == 0.
3767 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3768 isa<ConstantSDNode>(N0.getOperand(1))) {
3769 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3770 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3771 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3774 ISD::AND, SDLoc(N), VT,
3775 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3779 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3780 if (N0.getOpcode() == N1.getOpcode())
3781 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3784 // See if this is some rotate idiom.
3785 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3786 return SDValue(Rot, 0);
3788 // Simplify the operands using demanded-bits information.
3789 if (!VT.isVector() &&
3790 SimplifyDemandedBits(SDValue(N, 0)))
3791 return SDValue(N, 0);
3796 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3797 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3798 if (Op.getOpcode() == ISD::AND) {
3799 if (isConstOrConstSplat(Op.getOperand(1))) {
3800 Mask = Op.getOperand(1);
3801 Op = Op.getOperand(0);
3807 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3815 // Return true if we can prove that, whenever Neg and Pos are both in the
3816 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
3817 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3819 // (or (shift1 X, Neg), (shift2 X, Pos))
3821 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3822 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
3823 // to consider shift amounts with defined behavior.
3824 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3825 // If EltSize is a power of 2 then:
3827 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3828 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3830 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3831 // for the stronger condition:
3833 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
3835 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3836 // we can just replace Neg with Neg' for the rest of the function.
3838 // In other cases we check for the even stronger condition:
3840 // Neg == EltSize - Pos [B]
3842 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3843 // behavior if Pos == 0 (and consequently Neg == EltSize).
3845 // We could actually use [A] whenever EltSize is a power of 2, but the
3846 // only extra cases that it would match are those uninteresting ones
3847 // where Neg and Pos are never in range at the same time. E.g. for
3848 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3849 // as well as (sub 32, Pos), but:
3851 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3853 // always invokes undefined behavior for 32-bit X.
3855 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3856 unsigned MaskLoBits = 0;
3857 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3858 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3859 if (NegC->getAPIntValue() == EltSize - 1) {
3860 Neg = Neg.getOperand(0);
3861 MaskLoBits = Log2_64(EltSize);
3866 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3867 if (Neg.getOpcode() != ISD::SUB)
3869 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3872 SDValue NegOp1 = Neg.getOperand(1);
3874 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3875 // Pos'. The truncation is redundant for the purpose of the equality.
3876 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3877 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3878 if (PosC->getAPIntValue() == EltSize - 1)
3879 Pos = Pos.getOperand(0);
3881 // The condition we need is now:
3883 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3885 // If NegOp1 == Pos then we need:
3887 // EltSize & Mask == NegC & Mask
3889 // (because "x & Mask" is a truncation and distributes through subtraction).
3892 Width = NegC->getAPIntValue();
3894 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3895 // Then the condition we want to prove becomes:
3897 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3899 // which, again because "x & Mask" is a truncation, becomes:
3901 // NegC & Mask == (EltSize - PosC) & Mask
3902 // EltSize & Mask == (NegC + PosC) & Mask
3903 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3904 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3905 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3911 // Now we just need to check that EltSize & Mask == Width & Mask.
3913 // EltSize & Mask is 0 since Mask is EltSize - 1.
3914 return Width.getLoBits(MaskLoBits) == 0;
3915 return Width == EltSize;
3918 // A subroutine of MatchRotate used once we have found an OR of two opposite
3919 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3920 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3921 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3922 // Neg with outer conversions stripped away.
3923 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3924 SDValue Neg, SDValue InnerPos,
3925 SDValue InnerNeg, unsigned PosOpcode,
3926 unsigned NegOpcode, SDLoc DL) {
3927 // fold (or (shl x, (*ext y)),
3928 // (srl x, (*ext (sub 32, y)))) ->
3929 // (rotl x, y) or (rotr x, (sub 32, y))
3931 // fold (or (shl x, (*ext (sub 32, y))),
3932 // (srl x, (*ext y))) ->
3933 // (rotr x, y) or (rotl x, (sub 32, y))
3934 EVT VT = Shifted.getValueType();
3935 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
3936 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3937 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3938 HasPos ? Pos : Neg).getNode();
3944 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3945 // idioms for rotate, and if the target supports rotation instructions, generate
3947 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3948 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3949 EVT VT = LHS.getValueType();
3950 if (!TLI.isTypeLegal(VT)) return nullptr;
3952 // The target must have at least one rotate flavor.
3953 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3954 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3955 if (!HasROTL && !HasROTR) return nullptr;
3957 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3958 SDValue LHSShift; // The shift.
3959 SDValue LHSMask; // AND value if any.
3960 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3961 return nullptr; // Not part of a rotate.
3963 SDValue RHSShift; // The shift.
3964 SDValue RHSMask; // AND value if any.
3965 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3966 return nullptr; // Not part of a rotate.
3968 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3969 return nullptr; // Not shifting the same value.
3971 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3972 return nullptr; // Shifts must disagree.
3974 // Canonicalize shl to left side in a shl/srl pair.
3975 if (RHSShift.getOpcode() == ISD::SHL) {
3976 std::swap(LHS, RHS);
3977 std::swap(LHSShift, RHSShift);
3978 std::swap(LHSMask, RHSMask);
3981 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3982 SDValue LHSShiftArg = LHSShift.getOperand(0);
3983 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3984 SDValue RHSShiftArg = RHSShift.getOperand(0);
3985 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3987 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3988 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3989 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
3990 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
3991 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
3992 if ((LShVal + RShVal) != EltSizeInBits)
3995 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3996 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3998 // If there is an AND of either shifted operand, apply it to the result.
3999 if (LHSMask.getNode() || RHSMask.getNode()) {
4000 APInt Mask = APInt::getAllOnesValue(EltSizeInBits);
4002 if (LHSMask.getNode()) {
4003 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4004 Mask &= isConstOrConstSplat(LHSMask)->getAPIntValue() | RHSBits;
4006 if (RHSMask.getNode()) {
4007 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4008 Mask &= isConstOrConstSplat(RHSMask)->getAPIntValue() | LHSBits;
4011 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
4014 return Rot.getNode();
4017 // If there is a mask here, and we have a variable shift, we can't be sure
4018 // that we're masking out the right stuff.
4019 if (LHSMask.getNode() || RHSMask.getNode())
4022 // If the shift amount is sign/zext/any-extended just peel it off.
4023 SDValue LExtOp0 = LHSShiftAmt;
4024 SDValue RExtOp0 = RHSShiftAmt;
4025 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4026 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4027 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4028 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4029 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4030 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4031 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4032 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4033 LExtOp0 = LHSShiftAmt.getOperand(0);
4034 RExtOp0 = RHSShiftAmt.getOperand(0);
4037 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4038 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4042 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4043 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4050 SDValue DAGCombiner::visitXOR(SDNode *N) {
4051 SDValue N0 = N->getOperand(0);
4052 SDValue N1 = N->getOperand(1);
4053 EVT VT = N0.getValueType();
4056 if (VT.isVector()) {
4057 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4060 // fold (xor x, 0) -> x, vector edition
4061 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4063 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4067 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4068 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4069 return DAG.getConstant(0, SDLoc(N), VT);
4070 // fold (xor x, undef) -> undef
4071 if (N0.getOpcode() == ISD::UNDEF)
4073 if (N1.getOpcode() == ISD::UNDEF)
4075 // fold (xor c1, c2) -> c1^c2
4076 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4077 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4079 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4080 // canonicalize constant to RHS
4081 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4082 !isConstantIntBuildVectorOrConstantInt(N1))
4083 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4084 // fold (xor x, 0) -> x
4085 if (isNullConstant(N1))
4088 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4091 // fold !(x cc y) -> (x !cc y)
4092 SDValue LHS, RHS, CC;
4093 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4094 bool isInt = LHS.getValueType().isInteger();
4095 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4098 if (!LegalOperations ||
4099 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4100 switch (N0.getOpcode()) {
4102 llvm_unreachable("Unhandled SetCC Equivalent!");
4104 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4105 case ISD::SELECT_CC:
4106 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4107 N0.getOperand(3), NotCC);
4112 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4113 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4114 N0.getNode()->hasOneUse() &&
4115 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4116 SDValue V = N0.getOperand(0);
4118 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4119 DAG.getConstant(1, DL, V.getValueType()));
4120 AddToWorklist(V.getNode());
4121 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4124 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4125 if (isOneConstant(N1) && VT == MVT::i1 &&
4126 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4127 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4128 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4129 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4130 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4131 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4132 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4133 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4136 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4137 if (isAllOnesConstant(N1) &&
4138 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4139 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4140 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4141 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4142 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4143 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4144 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4145 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4148 // fold (xor (and x, y), y) -> (and (not x), y)
4149 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4150 N0->getOperand(1) == N1) {
4151 SDValue X = N0->getOperand(0);
4152 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4153 AddToWorklist(NotX.getNode());
4154 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4156 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4157 if (N1C && N0.getOpcode() == ISD::XOR) {
4158 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4160 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4161 DAG.getConstant(N1C->getAPIntValue() ^
4162 N00C->getAPIntValue(), DL, VT));
4164 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4166 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4167 DAG.getConstant(N1C->getAPIntValue() ^
4168 N01C->getAPIntValue(), DL, VT));
4171 // fold (xor x, x) -> 0
4173 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4175 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4176 // Here is a concrete example of this equivalence:
4178 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4179 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4183 // i16 ~1 == 0b1111111111111110
4184 // i16 rol(~1, 14) == 0b1011111111111111
4186 // Some additional tips to help conceptualize this transform:
4187 // - Try to see the operation as placing a single zero in a value of all ones.
4188 // - There exists no value for x which would allow the result to contain zero.
4189 // - Values of x larger than the bitwidth are undefined and do not require a
4190 // consistent result.
4191 // - Pushing the zero left requires shifting one bits in from the right.
4192 // A rotate left of ~1 is a nice way of achieving the desired result.
4193 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4194 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4196 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4200 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4201 if (N0.getOpcode() == N1.getOpcode())
4202 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4205 // Simplify the expression using non-local knowledge.
4206 if (!VT.isVector() &&
4207 SimplifyDemandedBits(SDValue(N, 0)))
4208 return SDValue(N, 0);
4213 /// Handle transforms common to the three shifts, when the shift amount is a
4215 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4216 SDNode *LHS = N->getOperand(0).getNode();
4217 if (!LHS->hasOneUse()) return SDValue();
4219 // We want to pull some binops through shifts, so that we have (and (shift))
4220 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4221 // thing happens with address calculations, so it's important to canonicalize
4223 bool HighBitSet = false; // Can we transform this if the high bit is set?
4225 switch (LHS->getOpcode()) {
4226 default: return SDValue();
4229 HighBitSet = false; // We can only transform sra if the high bit is clear.
4232 HighBitSet = true; // We can only transform sra if the high bit is set.
4235 if (N->getOpcode() != ISD::SHL)
4236 return SDValue(); // only shl(add) not sr[al](add).
4237 HighBitSet = false; // We can only transform sra if the high bit is clear.
4241 // We require the RHS of the binop to be a constant and not opaque as well.
4242 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4243 if (!BinOpCst) return SDValue();
4245 // FIXME: disable this unless the input to the binop is a shift by a constant.
4246 // If it is not a shift, it pessimizes some common cases like:
4248 // void foo(int *X, int i) { X[i & 1235] = 1; }
4249 // int bar(int *X, int i) { return X[i & 255]; }
4250 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4251 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4252 BinOpLHSVal->getOpcode() != ISD::SRA &&
4253 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4254 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4257 EVT VT = N->getValueType(0);
4259 // If this is a signed shift right, and the high bit is modified by the
4260 // logical operation, do not perform the transformation. The highBitSet
4261 // boolean indicates the value of the high bit of the constant which would
4262 // cause it to be modified for this operation.
4263 if (N->getOpcode() == ISD::SRA) {
4264 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4265 if (BinOpRHSSignSet != HighBitSet)
4269 if (!TLI.isDesirableToCommuteWithShift(LHS))
4272 // Fold the constants, shifting the binop RHS by the shift amount.
4273 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4275 LHS->getOperand(1), N->getOperand(1));
4276 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4278 // Create the new shift.
4279 SDValue NewShift = DAG.getNode(N->getOpcode(),
4280 SDLoc(LHS->getOperand(0)),
4281 VT, LHS->getOperand(0), N->getOperand(1));
4283 // Create the new binop.
4284 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4287 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4288 assert(N->getOpcode() == ISD::TRUNCATE);
4289 assert(N->getOperand(0).getOpcode() == ISD::AND);
4291 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4292 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4293 SDValue N01 = N->getOperand(0).getOperand(1);
4295 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4296 if (!N01C->isOpaque()) {
4297 EVT TruncVT = N->getValueType(0);
4298 SDValue N00 = N->getOperand(0).getOperand(0);
4299 APInt TruncC = N01C->getAPIntValue();
4300 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4303 return DAG.getNode(ISD::AND, DL, TruncVT,
4304 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4305 DAG.getConstant(TruncC, DL, TruncVT));
4313 SDValue DAGCombiner::visitRotate(SDNode *N) {
4314 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4315 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4316 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4317 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4318 if (NewOp1.getNode())
4319 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4320 N->getOperand(0), NewOp1);
4325 SDValue DAGCombiner::visitSHL(SDNode *N) {
4326 SDValue N0 = N->getOperand(0);
4327 SDValue N1 = N->getOperand(1);
4328 EVT VT = N0.getValueType();
4329 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4332 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4333 if (VT.isVector()) {
4334 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4337 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4338 // If setcc produces all-one true value then:
4339 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4340 if (N1CV && N1CV->isConstant()) {
4341 if (N0.getOpcode() == ISD::AND) {
4342 SDValue N00 = N0->getOperand(0);
4343 SDValue N01 = N0->getOperand(1);
4344 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4346 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4347 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4348 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4349 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4351 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4354 N1C = isConstOrConstSplat(N1);
4359 // fold (shl c1, c2) -> c1<<c2
4360 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4361 if (N0C && N1C && !N1C->isOpaque())
4362 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4363 // fold (shl 0, x) -> 0
4364 if (isNullConstant(N0))
4366 // fold (shl x, c >= size(x)) -> undef
4367 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4368 return DAG.getUNDEF(VT);
4369 // fold (shl x, 0) -> x
4370 if (N1C && N1C->isNullValue())
4372 // fold (shl undef, x) -> 0
4373 if (N0.getOpcode() == ISD::UNDEF)
4374 return DAG.getConstant(0, SDLoc(N), VT);
4375 // if (shl x, c) is known to be zero, return 0
4376 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4377 APInt::getAllOnesValue(OpSizeInBits)))
4378 return DAG.getConstant(0, SDLoc(N), VT);
4379 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4380 if (N1.getOpcode() == ISD::TRUNCATE &&
4381 N1.getOperand(0).getOpcode() == ISD::AND) {
4382 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4383 if (NewOp1.getNode())
4384 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4387 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4388 return SDValue(N, 0);
4390 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4391 if (N1C && N0.getOpcode() == ISD::SHL) {
4392 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4393 uint64_t c1 = N0C1->getZExtValue();
4394 uint64_t c2 = N1C->getZExtValue();
4396 if (c1 + c2 >= OpSizeInBits)
4397 return DAG.getConstant(0, DL, VT);
4398 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4399 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4403 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4404 // For this to be valid, the second form must not preserve any of the bits
4405 // that are shifted out by the inner shift in the first form. This means
4406 // the outer shift size must be >= the number of bits added by the ext.
4407 // As a corollary, we don't care what kind of ext it is.
4408 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4409 N0.getOpcode() == ISD::ANY_EXTEND ||
4410 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4411 N0.getOperand(0).getOpcode() == ISD::SHL) {
4412 SDValue N0Op0 = N0.getOperand(0);
4413 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4414 uint64_t c1 = N0Op0C1->getZExtValue();
4415 uint64_t c2 = N1C->getZExtValue();
4416 EVT InnerShiftVT = N0Op0.getValueType();
4417 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4418 if (c2 >= OpSizeInBits - InnerShiftSize) {
4420 if (c1 + c2 >= OpSizeInBits)
4421 return DAG.getConstant(0, DL, VT);
4422 return DAG.getNode(ISD::SHL, DL, VT,
4423 DAG.getNode(N0.getOpcode(), DL, VT,
4424 N0Op0->getOperand(0)),
4425 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4430 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4431 // Only fold this if the inner zext has no other uses to avoid increasing
4432 // the total number of instructions.
4433 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4434 N0.getOperand(0).getOpcode() == ISD::SRL) {
4435 SDValue N0Op0 = N0.getOperand(0);
4436 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4437 uint64_t c1 = N0Op0C1->getZExtValue();
4438 if (c1 < VT.getScalarSizeInBits()) {
4439 uint64_t c2 = N1C->getZExtValue();
4441 SDValue NewOp0 = N0.getOperand(0);
4442 EVT CountVT = NewOp0.getOperand(1).getValueType();
4444 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4446 DAG.getConstant(c2, DL, CountVT));
4447 AddToWorklist(NewSHL.getNode());
4448 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4454 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4455 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4456 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4457 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4458 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4459 uint64_t C1 = N0C1->getZExtValue();
4460 uint64_t C2 = N1C->getZExtValue();
4463 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4464 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4465 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4466 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4470 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4471 // (and (srl x, (sub c1, c2), MASK)
4472 // Only fold this if the inner shift has no other uses -- if it does, folding
4473 // this will increase the total number of instructions.
4474 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4475 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4476 uint64_t c1 = N0C1->getZExtValue();
4477 if (c1 < OpSizeInBits) {
4478 uint64_t c2 = N1C->getZExtValue();
4479 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4482 Mask = Mask.shl(c2 - c1);
4484 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4485 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4487 Mask = Mask.lshr(c1 - c2);
4489 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4490 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4493 return DAG.getNode(ISD::AND, DL, VT, Shift,
4494 DAG.getConstant(Mask, DL, VT));
4498 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4499 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4500 unsigned BitSize = VT.getScalarSizeInBits();
4502 SDValue HiBitsMask =
4503 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4504 BitSize - N1C->getZExtValue()),
4506 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4510 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4511 // Variant of version done on multiply, except mul by a power of 2 is turned
4514 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4515 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4516 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4517 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4518 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4519 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4522 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4523 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4524 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4525 if (SDValue Folded =
4526 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4527 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4531 if (N1C && !N1C->isOpaque())
4532 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4538 SDValue DAGCombiner::visitSRA(SDNode *N) {
4539 SDValue N0 = N->getOperand(0);
4540 SDValue N1 = N->getOperand(1);
4541 EVT VT = N0.getValueType();
4542 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4545 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4546 if (VT.isVector()) {
4547 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4550 N1C = isConstOrConstSplat(N1);
4553 // fold (sra c1, c2) -> (sra c1, c2)
4554 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4555 if (N0C && N1C && !N1C->isOpaque())
4556 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4557 // fold (sra 0, x) -> 0
4558 if (isNullConstant(N0))
4560 // fold (sra -1, x) -> -1
4561 if (isAllOnesConstant(N0))
4563 // fold (sra x, (setge c, size(x))) -> undef
4564 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4565 return DAG.getUNDEF(VT);
4566 // fold (sra x, 0) -> x
4567 if (N1C && N1C->isNullValue())
4569 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4571 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4572 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4573 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4575 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4576 ExtVT, VT.getVectorNumElements());
4577 if ((!LegalOperations ||
4578 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4579 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4580 N0.getOperand(0), DAG.getValueType(ExtVT));
4583 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4584 if (N1C && N0.getOpcode() == ISD::SRA) {
4585 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4586 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4587 if (Sum >= OpSizeInBits)
4588 Sum = OpSizeInBits - 1;
4590 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4591 DAG.getConstant(Sum, DL, N1.getValueType()));
4595 // fold (sra (shl X, m), (sub result_size, n))
4596 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4597 // result_size - n != m.
4598 // If truncate is free for the target sext(shl) is likely to result in better
4600 if (N0.getOpcode() == ISD::SHL && N1C) {
4601 // Get the two constanst of the shifts, CN0 = m, CN = n.
4602 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4604 LLVMContext &Ctx = *DAG.getContext();
4605 // Determine what the truncate's result bitsize and type would be.
4606 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4609 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4611 // Determine the residual right-shift amount.
4612 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4614 // If the shift is not a no-op (in which case this should be just a sign
4615 // extend already), the truncated to type is legal, sign_extend is legal
4616 // on that type, and the truncate to that type is both legal and free,
4617 // perform the transform.
4618 if ((ShiftAmt > 0) &&
4619 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4620 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4621 TLI.isTruncateFree(VT, TruncVT)) {
4624 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4625 getShiftAmountTy(N0.getOperand(0).getValueType()));
4626 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4627 N0.getOperand(0), Amt);
4628 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4630 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4631 N->getValueType(0), Trunc);
4636 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4637 if (N1.getOpcode() == ISD::TRUNCATE &&
4638 N1.getOperand(0).getOpcode() == ISD::AND) {
4639 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4640 if (NewOp1.getNode())
4641 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4644 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4645 // if c1 is equal to the number of bits the trunc removes
4646 if (N0.getOpcode() == ISD::TRUNCATE &&
4647 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4648 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4649 N0.getOperand(0).hasOneUse() &&
4650 N0.getOperand(0).getOperand(1).hasOneUse() &&
4652 SDValue N0Op0 = N0.getOperand(0);
4653 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4654 unsigned LargeShiftVal = LargeShift->getZExtValue();
4655 EVT LargeVT = N0Op0.getValueType();
4657 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4660 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4661 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4662 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4663 N0Op0.getOperand(0), Amt);
4664 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4669 // Simplify, based on bits shifted out of the LHS.
4670 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4671 return SDValue(N, 0);
4674 // If the sign bit is known to be zero, switch this to a SRL.
4675 if (DAG.SignBitIsZero(N0))
4676 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4678 if (N1C && !N1C->isOpaque())
4679 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4685 SDValue DAGCombiner::visitSRL(SDNode *N) {
4686 SDValue N0 = N->getOperand(0);
4687 SDValue N1 = N->getOperand(1);
4688 EVT VT = N0.getValueType();
4689 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4692 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4693 if (VT.isVector()) {
4694 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4697 N1C = isConstOrConstSplat(N1);
4700 // fold (srl c1, c2) -> c1 >>u c2
4701 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4702 if (N0C && N1C && !N1C->isOpaque())
4703 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4704 // fold (srl 0, x) -> 0
4705 if (isNullConstant(N0))
4707 // fold (srl x, c >= size(x)) -> undef
4708 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4709 return DAG.getUNDEF(VT);
4710 // fold (srl x, 0) -> x
4711 if (N1C && N1C->isNullValue())
4713 // if (srl x, c) is known to be zero, return 0
4714 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4715 APInt::getAllOnesValue(OpSizeInBits)))
4716 return DAG.getConstant(0, SDLoc(N), VT);
4718 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4719 if (N1C && N0.getOpcode() == ISD::SRL) {
4720 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4721 uint64_t c1 = N01C->getZExtValue();
4722 uint64_t c2 = N1C->getZExtValue();
4724 if (c1 + c2 >= OpSizeInBits)
4725 return DAG.getConstant(0, DL, VT);
4726 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4727 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4731 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4732 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4733 N0.getOperand(0).getOpcode() == ISD::SRL &&
4734 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4736 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4737 uint64_t c2 = N1C->getZExtValue();
4738 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4739 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4740 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4741 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4742 if (c1 + OpSizeInBits == InnerShiftSize) {
4744 if (c1 + c2 >= InnerShiftSize)
4745 return DAG.getConstant(0, DL, VT);
4746 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4747 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4748 N0.getOperand(0)->getOperand(0),
4749 DAG.getConstant(c1 + c2, DL,
4754 // fold (srl (shl x, c), c) -> (and x, cst2)
4755 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4756 unsigned BitSize = N0.getScalarValueSizeInBits();
4757 if (BitSize <= 64) {
4758 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4760 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4761 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4765 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4766 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4767 // Shifting in all undef bits?
4768 EVT SmallVT = N0.getOperand(0).getValueType();
4769 unsigned BitSize = SmallVT.getScalarSizeInBits();
4770 if (N1C->getZExtValue() >= BitSize)
4771 return DAG.getUNDEF(VT);
4773 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4774 uint64_t ShiftAmt = N1C->getZExtValue();
4776 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4778 DAG.getConstant(ShiftAmt, DL0,
4779 getShiftAmountTy(SmallVT)));
4780 AddToWorklist(SmallShift.getNode());
4781 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4783 return DAG.getNode(ISD::AND, DL, VT,
4784 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4785 DAG.getConstant(Mask, DL, VT));
4789 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4790 // bit, which is unmodified by sra.
4791 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4792 if (N0.getOpcode() == ISD::SRA)
4793 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4796 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4797 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4798 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4799 APInt KnownZero, KnownOne;
4800 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4802 // If any of the input bits are KnownOne, then the input couldn't be all
4803 // zeros, thus the result of the srl will always be zero.
4804 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4806 // If all of the bits input the to ctlz node are known to be zero, then
4807 // the result of the ctlz is "32" and the result of the shift is one.
4808 APInt UnknownBits = ~KnownZero;
4809 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4811 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4812 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4813 // Okay, we know that only that the single bit specified by UnknownBits
4814 // could be set on input to the CTLZ node. If this bit is set, the SRL
4815 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4816 // to an SRL/XOR pair, which is likely to simplify more.
4817 unsigned ShAmt = UnknownBits.countTrailingZeros();
4818 SDValue Op = N0.getOperand(0);
4822 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4823 DAG.getConstant(ShAmt, DL,
4824 getShiftAmountTy(Op.getValueType())));
4825 AddToWorklist(Op.getNode());
4829 return DAG.getNode(ISD::XOR, DL, VT,
4830 Op, DAG.getConstant(1, DL, VT));
4834 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4835 if (N1.getOpcode() == ISD::TRUNCATE &&
4836 N1.getOperand(0).getOpcode() == ISD::AND) {
4837 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4838 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4841 // fold operands of srl based on knowledge that the low bits are not
4843 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4844 return SDValue(N, 0);
4846 if (N1C && !N1C->isOpaque())
4847 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4850 // Attempt to convert a srl of a load into a narrower zero-extending load.
4851 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4854 // Here is a common situation. We want to optimize:
4857 // %b = and i32 %a, 2
4858 // %c = srl i32 %b, 1
4859 // brcond i32 %c ...
4865 // %c = setcc eq %b, 0
4868 // However when after the source operand of SRL is optimized into AND, the SRL
4869 // itself may not be optimized further. Look for it and add the BRCOND into
4871 if (N->hasOneUse()) {
4872 SDNode *Use = *N->use_begin();
4873 if (Use->getOpcode() == ISD::BRCOND)
4875 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4876 // Also look pass the truncate.
4877 Use = *Use->use_begin();
4878 if (Use->getOpcode() == ISD::BRCOND)
4886 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4887 SDValue N0 = N->getOperand(0);
4888 EVT VT = N->getValueType(0);
4890 // fold (bswap c1) -> c2
4891 if (isConstantIntBuildVectorOrConstantInt(N0))
4892 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4893 // fold (bswap (bswap x)) -> x
4894 if (N0.getOpcode() == ISD::BSWAP)
4895 return N0->getOperand(0);
4899 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4900 SDValue N0 = N->getOperand(0);
4901 EVT VT = N->getValueType(0);
4903 // fold (ctlz c1) -> c2
4904 if (isConstantIntBuildVectorOrConstantInt(N0))
4905 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4909 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4910 SDValue N0 = N->getOperand(0);
4911 EVT VT = N->getValueType(0);
4913 // fold (ctlz_zero_undef c1) -> c2
4914 if (isConstantIntBuildVectorOrConstantInt(N0))
4915 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4919 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4920 SDValue N0 = N->getOperand(0);
4921 EVT VT = N->getValueType(0);
4923 // fold (cttz c1) -> c2
4924 if (isConstantIntBuildVectorOrConstantInt(N0))
4925 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4929 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4930 SDValue N0 = N->getOperand(0);
4931 EVT VT = N->getValueType(0);
4933 // fold (cttz_zero_undef c1) -> c2
4934 if (isConstantIntBuildVectorOrConstantInt(N0))
4935 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4939 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4940 SDValue N0 = N->getOperand(0);
4941 EVT VT = N->getValueType(0);
4943 // fold (ctpop c1) -> c2
4944 if (isConstantIntBuildVectorOrConstantInt(N0))
4945 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4950 /// \brief Generate Min/Max node
4951 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4952 SDValue True, SDValue False,
4953 ISD::CondCode CC, const TargetLowering &TLI,
4954 SelectionDAG &DAG) {
4955 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4965 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4966 if (TLI.isOperationLegal(Opcode, VT))
4967 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4976 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4977 if (TLI.isOperationLegal(Opcode, VT))
4978 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4986 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4987 SDValue N0 = N->getOperand(0);
4988 SDValue N1 = N->getOperand(1);
4989 SDValue N2 = N->getOperand(2);
4990 EVT VT = N->getValueType(0);
4991 EVT VT0 = N0.getValueType();
4993 // fold (select C, X, X) -> X
4996 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4997 // fold (select true, X, Y) -> X
4998 // fold (select false, X, Y) -> Y
4999 return !N0C->isNullValue() ? N1 : N2;
5001 // fold (select C, 1, X) -> (or C, X)
5002 if (VT == MVT::i1 && isOneConstant(N1))
5003 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5004 // fold (select C, 0, 1) -> (xor C, 1)
5005 // We can't do this reliably if integer based booleans have different contents
5006 // to floating point based booleans. This is because we can't tell whether we
5007 // have an integer-based boolean or a floating-point-based boolean unless we
5008 // can find the SETCC that produced it and inspect its operands. This is
5009 // fairly easy if C is the SETCC node, but it can potentially be
5010 // undiscoverable (or not reasonably discoverable). For example, it could be
5011 // in another basic block or it could require searching a complicated
5013 if (VT.isInteger() &&
5014 (VT0 == MVT::i1 || (VT0.isInteger() &&
5015 TLI.getBooleanContents(false, false) ==
5016 TLI.getBooleanContents(false, true) &&
5017 TLI.getBooleanContents(false, false) ==
5018 TargetLowering::ZeroOrOneBooleanContent)) &&
5019 isNullConstant(N1) && isOneConstant(N2)) {
5023 return DAG.getNode(ISD::XOR, DL, VT0,
5024 N0, DAG.getConstant(1, DL, VT0));
5027 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5028 N0, DAG.getConstant(1, DL0, VT0));
5029 AddToWorklist(XORNode.getNode());
5031 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5032 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5034 // fold (select C, 0, X) -> (and (not C), X)
5035 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5036 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5037 AddToWorklist(NOTNode.getNode());
5038 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5040 // fold (select C, X, 1) -> (or (not C), X)
5041 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5042 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5043 AddToWorklist(NOTNode.getNode());
5044 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5046 // fold (select C, X, 0) -> (and C, X)
5047 if (VT == MVT::i1 && isNullConstant(N2))
5048 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5049 // fold (select X, X, Y) -> (or X, Y)
5050 // fold (select X, 1, Y) -> (or X, Y)
5051 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5052 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5053 // fold (select X, Y, X) -> (and X, Y)
5054 // fold (select X, Y, 0) -> (and X, Y)
5055 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5056 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5058 // If we can fold this based on the true/false value, do so.
5059 if (SimplifySelectOps(N, N1, N2))
5060 return SDValue(N, 0); // Don't revisit N.
5062 if (VT0 == MVT::i1) {
5063 // The code in this block deals with the following 2 equivalences:
5064 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5065 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5066 // The target can specify its prefered form with the
5067 // shouldNormalizeToSelectSequence() callback. However we always transform
5068 // to the right anyway if we find the inner select exists in the DAG anyway
5069 // and we always transform to the left side if we know that we can further
5070 // optimize the combination of the conditions.
5071 bool normalizeToSequence
5072 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5073 // select (and Cond0, Cond1), X, Y
5074 // -> select Cond0, (select Cond1, X, Y), Y
5075 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5076 SDValue Cond0 = N0->getOperand(0);
5077 SDValue Cond1 = N0->getOperand(1);
5078 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5079 N1.getValueType(), Cond1, N1, N2);
5080 if (normalizeToSequence || !InnerSelect.use_empty())
5081 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5084 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5085 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5086 SDValue Cond0 = N0->getOperand(0);
5087 SDValue Cond1 = N0->getOperand(1);
5088 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5089 N1.getValueType(), Cond1, N1, N2);
5090 if (normalizeToSequence || !InnerSelect.use_empty())
5091 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5095 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5096 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5097 SDValue N1_0 = N1->getOperand(0);
5098 SDValue N1_1 = N1->getOperand(1);
5099 SDValue N1_2 = N1->getOperand(2);
5100 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5101 // Create the actual and node if we can generate good code for it.
5102 if (!normalizeToSequence) {
5103 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5105 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5108 // Otherwise see if we can optimize the "and" to a better pattern.
5109 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5110 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5114 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5115 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5116 SDValue N2_0 = N2->getOperand(0);
5117 SDValue N2_1 = N2->getOperand(1);
5118 SDValue N2_2 = N2->getOperand(2);
5119 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5120 // Create the actual or node if we can generate good code for it.
5121 if (!normalizeToSequence) {
5122 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5124 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5127 // Otherwise see if we can optimize to a better pattern.
5128 if (SDValue Combined = visitORLike(N0, N2_0, N))
5129 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5135 // fold selects based on a setcc into other things, such as min/max/abs
5136 if (N0.getOpcode() == ISD::SETCC) {
5137 // select x, y (fcmp lt x, y) -> fminnum x, y
5138 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5140 // This is OK if we don't care about what happens if either operand is a
5144 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5145 // no signed zeros as well as no nans.
5146 const TargetOptions &Options = DAG.getTarget().Options;
5147 if (Options.UnsafeFPMath &&
5148 VT.isFloatingPoint() && N0.hasOneUse() &&
5149 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5150 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5152 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5153 N0.getOperand(1), N1, N2, CC,
5158 if ((!LegalOperations &&
5159 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5160 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5161 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5162 N0.getOperand(0), N0.getOperand(1),
5163 N1, N2, N0.getOperand(2));
5164 return SimplifySelect(SDLoc(N), N0, N1, N2);
5171 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5174 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5176 // Split the inputs.
5177 SDValue Lo, Hi, LL, LH, RL, RH;
5178 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5179 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5181 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5182 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5184 return std::make_pair(Lo, Hi);
5187 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5188 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5189 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5191 SDValue Cond = N->getOperand(0);
5192 SDValue LHS = N->getOperand(1);
5193 SDValue RHS = N->getOperand(2);
5194 EVT VT = N->getValueType(0);
5195 int NumElems = VT.getVectorNumElements();
5196 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5197 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5198 Cond.getOpcode() == ISD::BUILD_VECTOR);
5200 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5201 // binary ones here.
5202 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5205 // We're sure we have an even number of elements due to the
5206 // concat_vectors we have as arguments to vselect.
5207 // Skip BV elements until we find one that's not an UNDEF
5208 // After we find an UNDEF element, keep looping until we get to half the
5209 // length of the BV and see if all the non-undef nodes are the same.
5210 ConstantSDNode *BottomHalf = nullptr;
5211 for (int i = 0; i < NumElems / 2; ++i) {
5212 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5215 if (BottomHalf == nullptr)
5216 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5217 else if (Cond->getOperand(i).getNode() != BottomHalf)
5221 // Do the same for the second half of the BuildVector
5222 ConstantSDNode *TopHalf = nullptr;
5223 for (int i = NumElems / 2; i < NumElems; ++i) {
5224 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5227 if (TopHalf == nullptr)
5228 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5229 else if (Cond->getOperand(i).getNode() != TopHalf)
5233 assert(TopHalf && BottomHalf &&
5234 "One half of the selector was all UNDEFs and the other was all the "
5235 "same value. This should have been addressed before this function.");
5237 ISD::CONCAT_VECTORS, dl, VT,
5238 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5239 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5242 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5244 if (Level >= AfterLegalizeTypes)
5247 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5248 SDValue Mask = MSC->getMask();
5249 SDValue Data = MSC->getValue();
5252 // If the MSCATTER data type requires splitting and the mask is provided by a
5253 // SETCC, then split both nodes and its operands before legalization. This
5254 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5255 // and enables future optimizations (e.g. min/max pattern matching on X86).
5256 if (Mask.getOpcode() != ISD::SETCC)
5259 // Check if any splitting is required.
5260 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5261 TargetLowering::TypeSplitVector)
5263 SDValue MaskLo, MaskHi, Lo, Hi;
5264 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5267 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5269 SDValue Chain = MSC->getChain();
5271 EVT MemoryVT = MSC->getMemoryVT();
5272 unsigned Alignment = MSC->getOriginalAlignment();
5274 EVT LoMemVT, HiMemVT;
5275 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5277 SDValue DataLo, DataHi;
5278 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5280 SDValue BasePtr = MSC->getBasePtr();
5281 SDValue IndexLo, IndexHi;
5282 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5284 MachineMemOperand *MMO = DAG.getMachineFunction().
5285 getMachineMemOperand(MSC->getPointerInfo(),
5286 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5287 Alignment, MSC->getAAInfo(), MSC->getRanges());
5289 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5290 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5293 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5294 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5297 AddToWorklist(Lo.getNode());
5298 AddToWorklist(Hi.getNode());
5300 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5303 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5305 if (Level >= AfterLegalizeTypes)
5308 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5309 SDValue Mask = MST->getMask();
5310 SDValue Data = MST->getValue();
5313 // If the MSTORE data type requires splitting and the mask is provided by a
5314 // SETCC, then split both nodes and its operands before legalization. This
5315 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5316 // and enables future optimizations (e.g. min/max pattern matching on X86).
5317 if (Mask.getOpcode() == ISD::SETCC) {
5319 // Check if any splitting is required.
5320 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5321 TargetLowering::TypeSplitVector)
5324 SDValue MaskLo, MaskHi, Lo, Hi;
5325 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5328 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5330 SDValue Chain = MST->getChain();
5331 SDValue Ptr = MST->getBasePtr();
5333 EVT MemoryVT = MST->getMemoryVT();
5334 unsigned Alignment = MST->getOriginalAlignment();
5336 // if Alignment is equal to the vector size,
5337 // take the half of it for the second part
5338 unsigned SecondHalfAlignment =
5339 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5340 Alignment/2 : Alignment;
5342 EVT LoMemVT, HiMemVT;
5343 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5345 SDValue DataLo, DataHi;
5346 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5348 MachineMemOperand *MMO = DAG.getMachineFunction().
5349 getMachineMemOperand(MST->getPointerInfo(),
5350 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5351 Alignment, MST->getAAInfo(), MST->getRanges());
5353 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5354 MST->isTruncatingStore());
5356 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5357 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5358 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5360 MMO = DAG.getMachineFunction().
5361 getMachineMemOperand(MST->getPointerInfo(),
5362 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5363 SecondHalfAlignment, MST->getAAInfo(),
5366 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5367 MST->isTruncatingStore());
5369 AddToWorklist(Lo.getNode());
5370 AddToWorklist(Hi.getNode());
5372 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5377 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5379 if (Level >= AfterLegalizeTypes)
5382 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5383 SDValue Mask = MGT->getMask();
5386 // If the MGATHER result requires splitting and the mask is provided by a
5387 // SETCC, then split both nodes and its operands before legalization. This
5388 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5389 // and enables future optimizations (e.g. min/max pattern matching on X86).
5391 if (Mask.getOpcode() != ISD::SETCC)
5394 EVT VT = N->getValueType(0);
5396 // Check if any splitting is required.
5397 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5398 TargetLowering::TypeSplitVector)
5401 SDValue MaskLo, MaskHi, Lo, Hi;
5402 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5404 SDValue Src0 = MGT->getValue();
5405 SDValue Src0Lo, Src0Hi;
5406 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5409 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5411 SDValue Chain = MGT->getChain();
5412 EVT MemoryVT = MGT->getMemoryVT();
5413 unsigned Alignment = MGT->getOriginalAlignment();
5415 EVT LoMemVT, HiMemVT;
5416 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5418 SDValue BasePtr = MGT->getBasePtr();
5419 SDValue Index = MGT->getIndex();
5420 SDValue IndexLo, IndexHi;
5421 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5423 MachineMemOperand *MMO = DAG.getMachineFunction().
5424 getMachineMemOperand(MGT->getPointerInfo(),
5425 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5426 Alignment, MGT->getAAInfo(), MGT->getRanges());
5428 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5429 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5432 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5433 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5436 AddToWorklist(Lo.getNode());
5437 AddToWorklist(Hi.getNode());
5439 // Build a factor node to remember that this load is independent of the
5441 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5444 // Legalized the chain result - switch anything that used the old chain to
5446 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5448 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5450 SDValue RetOps[] = { GatherRes, Chain };
5451 return DAG.getMergeValues(RetOps, DL);
5454 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5456 if (Level >= AfterLegalizeTypes)
5459 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5460 SDValue Mask = MLD->getMask();
5463 // If the MLOAD result requires splitting and the mask is provided by a
5464 // SETCC, then split both nodes and its operands before legalization. This
5465 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5466 // and enables future optimizations (e.g. min/max pattern matching on X86).
5468 if (Mask.getOpcode() == ISD::SETCC) {
5469 EVT VT = N->getValueType(0);
5471 // Check if any splitting is required.
5472 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5473 TargetLowering::TypeSplitVector)
5476 SDValue MaskLo, MaskHi, Lo, Hi;
5477 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5479 SDValue Src0 = MLD->getSrc0();
5480 SDValue Src0Lo, Src0Hi;
5481 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5484 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5486 SDValue Chain = MLD->getChain();
5487 SDValue Ptr = MLD->getBasePtr();
5488 EVT MemoryVT = MLD->getMemoryVT();
5489 unsigned Alignment = MLD->getOriginalAlignment();
5491 // if Alignment is equal to the vector size,
5492 // take the half of it for the second part
5493 unsigned SecondHalfAlignment =
5494 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5495 Alignment/2 : Alignment;
5497 EVT LoMemVT, HiMemVT;
5498 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5500 MachineMemOperand *MMO = DAG.getMachineFunction().
5501 getMachineMemOperand(MLD->getPointerInfo(),
5502 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5503 Alignment, MLD->getAAInfo(), MLD->getRanges());
5505 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5508 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5509 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5510 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5512 MMO = DAG.getMachineFunction().
5513 getMachineMemOperand(MLD->getPointerInfo(),
5514 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5515 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5517 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5520 AddToWorklist(Lo.getNode());
5521 AddToWorklist(Hi.getNode());
5523 // Build a factor node to remember that this load is independent of the
5525 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5528 // Legalized the chain result - switch anything that used the old chain to
5530 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5532 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5534 SDValue RetOps[] = { LoadRes, Chain };
5535 return DAG.getMergeValues(RetOps, DL);
5540 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5541 SDValue N0 = N->getOperand(0);
5542 SDValue N1 = N->getOperand(1);
5543 SDValue N2 = N->getOperand(2);
5546 // Canonicalize integer abs.
5547 // vselect (setg[te] X, 0), X, -X ->
5548 // vselect (setgt X, -1), X, -X ->
5549 // vselect (setl[te] X, 0), -X, X ->
5550 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5551 if (N0.getOpcode() == ISD::SETCC) {
5552 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5553 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5555 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5557 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5558 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5559 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5560 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5561 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5562 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5563 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5566 EVT VT = LHS.getValueType();
5567 SDValue Shift = DAG.getNode(
5568 ISD::SRA, DL, VT, LHS,
5569 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5570 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5571 AddToWorklist(Shift.getNode());
5572 AddToWorklist(Add.getNode());
5573 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5577 if (SimplifySelectOps(N, N1, N2))
5578 return SDValue(N, 0); // Don't revisit N.
5580 // If the VSELECT result requires splitting and the mask is provided by a
5581 // SETCC, then split both nodes and its operands before legalization. This
5582 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5583 // and enables future optimizations (e.g. min/max pattern matching on X86).
5584 if (N0.getOpcode() == ISD::SETCC) {
5585 EVT VT = N->getValueType(0);
5587 // Check if any splitting is required.
5588 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5589 TargetLowering::TypeSplitVector)
5592 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5593 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5594 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5595 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5597 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5598 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5600 // Add the new VSELECT nodes to the work list in case they need to be split
5602 AddToWorklist(Lo.getNode());
5603 AddToWorklist(Hi.getNode());
5605 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5608 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5609 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5611 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5612 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5615 // The ConvertSelectToConcatVector function is assuming both the above
5616 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5618 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5619 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5620 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5621 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5628 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5629 SDValue N0 = N->getOperand(0);
5630 SDValue N1 = N->getOperand(1);
5631 SDValue N2 = N->getOperand(2);
5632 SDValue N3 = N->getOperand(3);
5633 SDValue N4 = N->getOperand(4);
5634 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5636 // fold select_cc lhs, rhs, x, x, cc -> x
5640 // Determine if the condition we're dealing with is constant
5641 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5642 N0, N1, CC, SDLoc(N), false);
5643 if (SCC.getNode()) {
5644 AddToWorklist(SCC.getNode());
5646 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5647 if (!SCCC->isNullValue())
5648 return N2; // cond always true -> true val
5650 return N3; // cond always false -> false val
5651 } else if (SCC->getOpcode() == ISD::UNDEF) {
5652 // When the condition is UNDEF, just return the first operand. This is
5653 // coherent the DAG creation, no setcc node is created in this case
5655 } else if (SCC.getOpcode() == ISD::SETCC) {
5656 // Fold to a simpler select_cc
5657 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5658 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5663 // If we can fold this based on the true/false value, do so.
5664 if (SimplifySelectOps(N, N2, N3))
5665 return SDValue(N, 0); // Don't revisit N.
5667 // fold select_cc into other things, such as min/max/abs
5668 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5671 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5672 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5673 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5677 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5678 /// a build_vector of constants.
5679 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5680 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5681 /// Vector extends are not folded if operations are legal; this is to
5682 /// avoid introducing illegal build_vector dag nodes.
5683 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5684 SelectionDAG &DAG, bool LegalTypes,
5685 bool LegalOperations) {
5686 unsigned Opcode = N->getOpcode();
5687 SDValue N0 = N->getOperand(0);
5688 EVT VT = N->getValueType(0);
5690 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5691 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5692 && "Expected EXTEND dag node in input!");
5694 // fold (sext c1) -> c1
5695 // fold (zext c1) -> c1
5696 // fold (aext c1) -> c1
5697 if (isa<ConstantSDNode>(N0))
5698 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5700 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5701 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5702 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5703 EVT SVT = VT.getScalarType();
5704 if (!(VT.isVector() &&
5705 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5706 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5709 // We can fold this node into a build_vector.
5710 unsigned VTBits = SVT.getSizeInBits();
5711 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5712 SmallVector<SDValue, 8> Elts;
5713 unsigned NumElts = VT.getVectorNumElements();
5716 for (unsigned i=0; i != NumElts; ++i) {
5717 SDValue Op = N0->getOperand(i);
5718 if (Op->getOpcode() == ISD::UNDEF) {
5719 Elts.push_back(DAG.getUNDEF(SVT));
5724 // Get the constant value and if needed trunc it to the size of the type.
5725 // Nodes like build_vector might have constants wider than the scalar type.
5726 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5727 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5728 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5730 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5733 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5736 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5737 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5738 // transformation. Returns true if extension are possible and the above
5739 // mentioned transformation is profitable.
5740 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5742 SmallVectorImpl<SDNode *> &ExtendNodes,
5743 const TargetLowering &TLI) {
5744 bool HasCopyToRegUses = false;
5745 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5746 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5747 UE = N0.getNode()->use_end();
5752 if (UI.getUse().getResNo() != N0.getResNo())
5754 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5755 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5756 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5757 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5758 // Sign bits will be lost after a zext.
5761 for (unsigned i = 0; i != 2; ++i) {
5762 SDValue UseOp = User->getOperand(i);
5765 if (!isa<ConstantSDNode>(UseOp))
5770 ExtendNodes.push_back(User);
5773 // If truncates aren't free and there are users we can't
5774 // extend, it isn't worthwhile.
5777 // Remember if this value is live-out.
5778 if (User->getOpcode() == ISD::CopyToReg)
5779 HasCopyToRegUses = true;
5782 if (HasCopyToRegUses) {
5783 bool BothLiveOut = false;
5784 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5786 SDUse &Use = UI.getUse();
5787 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5793 // Both unextended and extended values are live out. There had better be
5794 // a good reason for the transformation.
5795 return ExtendNodes.size();
5800 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5801 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5802 ISD::NodeType ExtType) {
5803 // Extend SetCC uses if necessary.
5804 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5805 SDNode *SetCC = SetCCs[i];
5806 SmallVector<SDValue, 4> Ops;
5808 for (unsigned j = 0; j != 2; ++j) {
5809 SDValue SOp = SetCC->getOperand(j);
5811 Ops.push_back(ExtLoad);
5813 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5816 Ops.push_back(SetCC->getOperand(2));
5817 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5821 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5822 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5823 SDValue N0 = N->getOperand(0);
5824 EVT DstVT = N->getValueType(0);
5825 EVT SrcVT = N0.getValueType();
5827 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5828 N->getOpcode() == ISD::ZERO_EXTEND) &&
5829 "Unexpected node type (not an extend)!");
5831 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5832 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5833 // (v8i32 (sext (v8i16 (load x))))
5835 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5836 // (v4i32 (sextload (x + 16)))))
5837 // Where uses of the original load, i.e.:
5839 // are replaced with:
5841 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5842 // (v4i32 (sextload (x + 16)))))))
5844 // This combine is only applicable to illegal, but splittable, vectors.
5845 // All legal types, and illegal non-vector types, are handled elsewhere.
5846 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5848 if (N0->getOpcode() != ISD::LOAD)
5851 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5853 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5854 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5855 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5858 SmallVector<SDNode *, 4> SetCCs;
5859 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5862 ISD::LoadExtType ExtType =
5863 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5865 // Try to split the vector types to get down to legal types.
5866 EVT SplitSrcVT = SrcVT;
5867 EVT SplitDstVT = DstVT;
5868 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5869 SplitSrcVT.getVectorNumElements() > 1) {
5870 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5871 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5874 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5878 const unsigned NumSplits =
5879 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5880 const unsigned Stride = SplitSrcVT.getStoreSize();
5881 SmallVector<SDValue, 4> Loads;
5882 SmallVector<SDValue, 4> Chains;
5884 SDValue BasePtr = LN0->getBasePtr();
5885 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5886 const unsigned Offset = Idx * Stride;
5887 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5889 SDValue SplitLoad = DAG.getExtLoad(
5890 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5891 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5892 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5893 Align, LN0->getAAInfo());
5895 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5896 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5898 Loads.push_back(SplitLoad.getValue(0));
5899 Chains.push_back(SplitLoad.getValue(1));
5902 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5903 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5905 CombineTo(N, NewValue);
5907 // Replace uses of the original load (before extension)
5908 // with a truncate of the concatenated sextloaded vectors.
5910 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5911 CombineTo(N0.getNode(), Trunc, NewChain);
5912 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5913 (ISD::NodeType)N->getOpcode());
5914 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5917 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5918 SDValue N0 = N->getOperand(0);
5919 EVT VT = N->getValueType(0);
5921 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5923 return SDValue(Res, 0);
5925 // fold (sext (sext x)) -> (sext x)
5926 // fold (sext (aext x)) -> (sext x)
5927 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5928 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5931 if (N0.getOpcode() == ISD::TRUNCATE) {
5932 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5933 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5934 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5935 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5936 if (NarrowLoad.getNode() != N0.getNode()) {
5937 CombineTo(N0.getNode(), NarrowLoad);
5938 // CombineTo deleted the truncate, if needed, but not what's under it.
5941 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5944 // See if the value being truncated is already sign extended. If so, just
5945 // eliminate the trunc/sext pair.
5946 SDValue Op = N0.getOperand(0);
5947 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5948 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5949 unsigned DestBits = VT.getScalarType().getSizeInBits();
5950 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5952 if (OpBits == DestBits) {
5953 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5954 // bits, it is already ready.
5955 if (NumSignBits > DestBits-MidBits)
5957 } else if (OpBits < DestBits) {
5958 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5959 // bits, just sext from i32.
5960 if (NumSignBits > OpBits-MidBits)
5961 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5963 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5964 // bits, just truncate to i32.
5965 if (NumSignBits > OpBits-MidBits)
5966 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5969 // fold (sext (truncate x)) -> (sextinreg x).
5970 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5971 N0.getValueType())) {
5972 if (OpBits < DestBits)
5973 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5974 else if (OpBits > DestBits)
5975 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5976 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5977 DAG.getValueType(N0.getValueType()));
5981 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5982 // Only generate vector extloads when 1) they're legal, and 2) they are
5983 // deemed desirable by the target.
5984 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5985 ((!LegalOperations && !VT.isVector() &&
5986 !cast<LoadSDNode>(N0)->isVolatile()) ||
5987 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5988 bool DoXform = true;
5989 SmallVector<SDNode*, 4> SetCCs;
5990 if (!N0.hasOneUse())
5991 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5993 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5995 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5996 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5998 LN0->getBasePtr(), N0.getValueType(),
5999 LN0->getMemOperand());
6000 CombineTo(N, ExtLoad);
6001 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6002 N0.getValueType(), ExtLoad);
6003 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6004 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6006 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6010 // fold (sext (load x)) to multiple smaller sextloads.
6011 // Only on illegal but splittable vectors.
6012 if (SDValue ExtLoad = CombineExtLoad(N))
6015 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6016 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6017 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6018 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6019 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6020 EVT MemVT = LN0->getMemoryVT();
6021 if ((!LegalOperations && !LN0->isVolatile()) ||
6022 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6023 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6025 LN0->getBasePtr(), MemVT,
6026 LN0->getMemOperand());
6027 CombineTo(N, ExtLoad);
6028 CombineTo(N0.getNode(),
6029 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6030 N0.getValueType(), ExtLoad),
6031 ExtLoad.getValue(1));
6032 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6036 // fold (sext (and/or/xor (load x), cst)) ->
6037 // (and/or/xor (sextload x), (sext cst))
6038 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6039 N0.getOpcode() == ISD::XOR) &&
6040 isa<LoadSDNode>(N0.getOperand(0)) &&
6041 N0.getOperand(1).getOpcode() == ISD::Constant &&
6042 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6043 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6044 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6045 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6046 bool DoXform = true;
6047 SmallVector<SDNode*, 4> SetCCs;
6048 if (!N0.hasOneUse())
6049 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6052 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6053 LN0->getChain(), LN0->getBasePtr(),
6055 LN0->getMemOperand());
6056 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6057 Mask = Mask.sext(VT.getSizeInBits());
6059 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6060 ExtLoad, DAG.getConstant(Mask, DL, VT));
6061 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6062 SDLoc(N0.getOperand(0)),
6063 N0.getOperand(0).getValueType(), ExtLoad);
6065 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6066 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6068 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6073 if (N0.getOpcode() == ISD::SETCC) {
6074 EVT N0VT = N0.getOperand(0).getValueType();
6075 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6076 // Only do this before legalize for now.
6077 if (VT.isVector() && !LegalOperations &&
6078 TLI.getBooleanContents(N0VT) ==
6079 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6080 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6081 // of the same size as the compared operands. Only optimize sext(setcc())
6082 // if this is the case.
6083 EVT SVT = getSetCCResultType(N0VT);
6085 // We know that the # elements of the results is the same as the
6086 // # elements of the compare (and the # elements of the compare result
6087 // for that matter). Check to see that they are the same size. If so,
6088 // we know that the element size of the sext'd result matches the
6089 // element size of the compare operands.
6090 if (VT.getSizeInBits() == SVT.getSizeInBits())
6091 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6093 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6095 // If the desired elements are smaller or larger than the source
6096 // elements we can use a matching integer vector type and then
6097 // truncate/sign extend
6098 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6099 if (SVT == MatchingVectorType) {
6100 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6101 N0.getOperand(0), N0.getOperand(1),
6102 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6103 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6107 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6108 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6111 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6113 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6114 NegOne, DAG.getConstant(0, DL, VT),
6115 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6116 if (SCC.getNode()) return SCC;
6118 if (!VT.isVector()) {
6119 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6120 if (!LegalOperations ||
6121 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6123 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6124 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6125 N0.getOperand(0), N0.getOperand(1), CC);
6126 return DAG.getSelect(DL, VT, SetCC,
6127 NegOne, DAG.getConstant(0, DL, VT));
6132 // fold (sext x) -> (zext x) if the sign bit is known zero.
6133 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6134 DAG.SignBitIsZero(N0))
6135 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6140 // isTruncateOf - If N is a truncate of some other value, return true, record
6141 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6142 // This function computes KnownZero to avoid a duplicated call to
6143 // computeKnownBits in the caller.
6144 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6147 if (N->getOpcode() == ISD::TRUNCATE) {
6148 Op = N->getOperand(0);
6149 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6153 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6154 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6157 SDValue Op0 = N->getOperand(0);
6158 SDValue Op1 = N->getOperand(1);
6159 assert(Op0.getValueType() == Op1.getValueType());
6161 if (isNullConstant(Op0))
6163 else if (isNullConstant(Op1))
6168 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6170 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6176 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6177 SDValue N0 = N->getOperand(0);
6178 EVT VT = N->getValueType(0);
6180 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6182 return SDValue(Res, 0);
6184 // fold (zext (zext x)) -> (zext x)
6185 // fold (zext (aext x)) -> (zext x)
6186 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6187 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6190 // fold (zext (truncate x)) -> (zext x) or
6191 // (zext (truncate x)) -> (truncate x)
6192 // This is valid when the truncated bits of x are already zero.
6193 // FIXME: We should extend this to work for vectors too.
6196 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6197 APInt TruncatedBits =
6198 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6199 APInt(Op.getValueSizeInBits(), 0) :
6200 APInt::getBitsSet(Op.getValueSizeInBits(),
6201 N0.getValueSizeInBits(),
6202 std::min(Op.getValueSizeInBits(),
6203 VT.getSizeInBits()));
6204 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6205 if (VT.bitsGT(Op.getValueType()))
6206 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6207 if (VT.bitsLT(Op.getValueType()))
6208 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6214 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6215 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6216 if (N0.getOpcode() == ISD::TRUNCATE) {
6217 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6218 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6219 if (NarrowLoad.getNode() != N0.getNode()) {
6220 CombineTo(N0.getNode(), NarrowLoad);
6221 // CombineTo deleted the truncate, if needed, but not what's under it.
6224 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6228 // fold (zext (truncate x)) -> (and x, mask)
6229 if (N0.getOpcode() == ISD::TRUNCATE) {
6230 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6231 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6232 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6233 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6234 if (NarrowLoad.getNode() != N0.getNode()) {
6235 CombineTo(N0.getNode(), NarrowLoad);
6236 // CombineTo deleted the truncate, if needed, but not what's under it.
6239 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6242 EVT SrcVT = N0.getOperand(0).getValueType();
6243 EVT MinVT = N0.getValueType();
6245 // Try to mask before the extension to avoid having to generate a larger mask,
6246 // possibly over several sub-vectors.
6247 if (SrcVT.bitsLT(VT)) {
6248 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6249 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6250 SDValue Op = N0.getOperand(0);
6251 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6252 AddToWorklist(Op.getNode());
6253 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6257 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6258 SDValue Op = N0.getOperand(0);
6259 if (SrcVT.bitsLT(VT)) {
6260 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6261 AddToWorklist(Op.getNode());
6262 } else if (SrcVT.bitsGT(VT)) {
6263 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6264 AddToWorklist(Op.getNode());
6266 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6270 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6271 // if either of the casts is not free.
6272 if (N0.getOpcode() == ISD::AND &&
6273 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6274 N0.getOperand(1).getOpcode() == ISD::Constant &&
6275 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6276 N0.getValueType()) ||
6277 !TLI.isZExtFree(N0.getValueType(), VT))) {
6278 SDValue X = N0.getOperand(0).getOperand(0);
6279 if (X.getValueType().bitsLT(VT)) {
6280 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6281 } else if (X.getValueType().bitsGT(VT)) {
6282 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6284 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6285 Mask = Mask.zext(VT.getSizeInBits());
6287 return DAG.getNode(ISD::AND, DL, VT,
6288 X, DAG.getConstant(Mask, DL, VT));
6291 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6292 // Only generate vector extloads when 1) they're legal, and 2) they are
6293 // deemed desirable by the target.
6294 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6295 ((!LegalOperations && !VT.isVector() &&
6296 !cast<LoadSDNode>(N0)->isVolatile()) ||
6297 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6298 bool DoXform = true;
6299 SmallVector<SDNode*, 4> SetCCs;
6300 if (!N0.hasOneUse())
6301 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6303 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6305 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6306 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6308 LN0->getBasePtr(), N0.getValueType(),
6309 LN0->getMemOperand());
6310 CombineTo(N, ExtLoad);
6311 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6312 N0.getValueType(), ExtLoad);
6313 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6315 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6317 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6321 // fold (zext (load x)) to multiple smaller zextloads.
6322 // Only on illegal but splittable vectors.
6323 if (SDValue ExtLoad = CombineExtLoad(N))
6326 // fold (zext (and/or/xor (load x), cst)) ->
6327 // (and/or/xor (zextload x), (zext cst))
6328 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6329 N0.getOpcode() == ISD::XOR) &&
6330 isa<LoadSDNode>(N0.getOperand(0)) &&
6331 N0.getOperand(1).getOpcode() == ISD::Constant &&
6332 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6333 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6334 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6335 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6336 bool DoXform = true;
6337 SmallVector<SDNode*, 4> SetCCs;
6338 if (!N0.hasOneUse())
6339 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6342 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6343 LN0->getChain(), LN0->getBasePtr(),
6345 LN0->getMemOperand());
6346 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6347 Mask = Mask.zext(VT.getSizeInBits());
6349 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6350 ExtLoad, DAG.getConstant(Mask, DL, VT));
6351 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6352 SDLoc(N0.getOperand(0)),
6353 N0.getOperand(0).getValueType(), ExtLoad);
6355 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6356 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6358 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6363 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6364 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6365 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6366 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6367 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6368 EVT MemVT = LN0->getMemoryVT();
6369 if ((!LegalOperations && !LN0->isVolatile()) ||
6370 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6371 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6373 LN0->getBasePtr(), MemVT,
6374 LN0->getMemOperand());
6375 CombineTo(N, ExtLoad);
6376 CombineTo(N0.getNode(),
6377 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6379 ExtLoad.getValue(1));
6380 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6384 if (N0.getOpcode() == ISD::SETCC) {
6385 if (!LegalOperations && VT.isVector() &&
6386 N0.getValueType().getVectorElementType() == MVT::i1) {
6387 EVT N0VT = N0.getOperand(0).getValueType();
6388 if (getSetCCResultType(N0VT) == N0.getValueType())
6391 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6392 // Only do this before legalize for now.
6393 EVT EltVT = VT.getVectorElementType();
6395 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6396 DAG.getConstant(1, DL, EltVT));
6397 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6398 // We know that the # elements of the results is the same as the
6399 // # elements of the compare (and the # elements of the compare result
6400 // for that matter). Check to see that they are the same size. If so,
6401 // we know that the element size of the sext'd result matches the
6402 // element size of the compare operands.
6403 return DAG.getNode(ISD::AND, DL, VT,
6404 DAG.getSetCC(DL, VT, N0.getOperand(0),
6406 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6407 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6410 // If the desired elements are smaller or larger than the source
6411 // elements we can use a matching integer vector type and then
6412 // truncate/sign extend
6413 EVT MatchingElementType =
6414 EVT::getIntegerVT(*DAG.getContext(),
6415 N0VT.getScalarType().getSizeInBits());
6416 EVT MatchingVectorType =
6417 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6418 N0VT.getVectorNumElements());
6420 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6422 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6423 return DAG.getNode(ISD::AND, DL, VT,
6424 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6425 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6428 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6431 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6432 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6433 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6434 if (SCC.getNode()) return SCC;
6437 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6438 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6439 isa<ConstantSDNode>(N0.getOperand(1)) &&
6440 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6442 SDValue ShAmt = N0.getOperand(1);
6443 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6444 if (N0.getOpcode() == ISD::SHL) {
6445 SDValue InnerZExt = N0.getOperand(0);
6446 // If the original shl may be shifting out bits, do not perform this
6448 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6449 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6450 if (ShAmtVal > KnownZeroBits)
6456 // Ensure that the shift amount is wide enough for the shifted value.
6457 if (VT.getSizeInBits() >= 256)
6458 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6460 return DAG.getNode(N0.getOpcode(), DL, VT,
6461 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6468 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6469 SDValue N0 = N->getOperand(0);
6470 EVT VT = N->getValueType(0);
6472 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6474 return SDValue(Res, 0);
6476 // fold (aext (aext x)) -> (aext x)
6477 // fold (aext (zext x)) -> (zext x)
6478 // fold (aext (sext x)) -> (sext x)
6479 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6480 N0.getOpcode() == ISD::ZERO_EXTEND ||
6481 N0.getOpcode() == ISD::SIGN_EXTEND)
6482 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6484 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6485 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6486 if (N0.getOpcode() == ISD::TRUNCATE) {
6487 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6488 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6489 if (NarrowLoad.getNode() != N0.getNode()) {
6490 CombineTo(N0.getNode(), NarrowLoad);
6491 // CombineTo deleted the truncate, if needed, but not what's under it.
6494 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6498 // fold (aext (truncate x))
6499 if (N0.getOpcode() == ISD::TRUNCATE) {
6500 SDValue TruncOp = N0.getOperand(0);
6501 if (TruncOp.getValueType() == VT)
6502 return TruncOp; // x iff x size == zext size.
6503 if (TruncOp.getValueType().bitsGT(VT))
6504 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6505 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6508 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6509 // if the trunc is not free.
6510 if (N0.getOpcode() == ISD::AND &&
6511 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6512 N0.getOperand(1).getOpcode() == ISD::Constant &&
6513 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6514 N0.getValueType())) {
6515 SDValue X = N0.getOperand(0).getOperand(0);
6516 if (X.getValueType().bitsLT(VT)) {
6517 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6518 } else if (X.getValueType().bitsGT(VT)) {
6519 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6521 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6522 Mask = Mask.zext(VT.getSizeInBits());
6524 return DAG.getNode(ISD::AND, DL, VT,
6525 X, DAG.getConstant(Mask, DL, VT));
6528 // fold (aext (load x)) -> (aext (truncate (extload x)))
6529 // None of the supported targets knows how to perform load and any_ext
6530 // on vectors in one instruction. We only perform this transformation on
6532 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6533 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6534 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6535 bool DoXform = true;
6536 SmallVector<SDNode*, 4> SetCCs;
6537 if (!N0.hasOneUse())
6538 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6540 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6541 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6543 LN0->getBasePtr(), N0.getValueType(),
6544 LN0->getMemOperand());
6545 CombineTo(N, ExtLoad);
6546 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6547 N0.getValueType(), ExtLoad);
6548 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6549 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6551 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6555 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6556 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6557 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6558 if (N0.getOpcode() == ISD::LOAD &&
6559 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6561 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6562 ISD::LoadExtType ExtType = LN0->getExtensionType();
6563 EVT MemVT = LN0->getMemoryVT();
6564 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6565 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6566 VT, LN0->getChain(), LN0->getBasePtr(),
6567 MemVT, LN0->getMemOperand());
6568 CombineTo(N, ExtLoad);
6569 CombineTo(N0.getNode(),
6570 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6571 N0.getValueType(), ExtLoad),
6572 ExtLoad.getValue(1));
6573 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6577 if (N0.getOpcode() == ISD::SETCC) {
6579 // aext(setcc) -> vsetcc
6580 // aext(setcc) -> truncate(vsetcc)
6581 // aext(setcc) -> aext(vsetcc)
6582 // Only do this before legalize for now.
6583 if (VT.isVector() && !LegalOperations) {
6584 EVT N0VT = N0.getOperand(0).getValueType();
6585 // We know that the # elements of the results is the same as the
6586 // # elements of the compare (and the # elements of the compare result
6587 // for that matter). Check to see that they are the same size. If so,
6588 // we know that the element size of the sext'd result matches the
6589 // element size of the compare operands.
6590 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6591 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6593 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6594 // If the desired elements are smaller or larger than the source
6595 // elements we can use a matching integer vector type and then
6596 // truncate/any extend
6598 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6600 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6602 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6603 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6607 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6610 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6611 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6612 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6620 /// See if the specified operand can be simplified with the knowledge that only
6621 /// the bits specified by Mask are used. If so, return the simpler operand,
6622 /// otherwise return a null SDValue.
6623 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6624 switch (V.getOpcode()) {
6626 case ISD::Constant: {
6627 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6628 assert(CV && "Const value should be ConstSDNode.");
6629 const APInt &CVal = CV->getAPIntValue();
6630 APInt NewVal = CVal & Mask;
6632 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6637 // If the LHS or RHS don't contribute bits to the or, drop them.
6638 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6639 return V.getOperand(1);
6640 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6641 return V.getOperand(0);
6644 // Only look at single-use SRLs.
6645 if (!V.getNode()->hasOneUse())
6647 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6648 // See if we can recursively simplify the LHS.
6649 unsigned Amt = RHSC->getZExtValue();
6651 // Watch out for shift count overflow though.
6652 if (Amt >= Mask.getBitWidth()) break;
6653 APInt NewMask = Mask << Amt;
6654 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6655 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6656 SimplifyLHS, V.getOperand(1));
6662 /// If the result of a wider load is shifted to right of N bits and then
6663 /// truncated to a narrower type and where N is a multiple of number of bits of
6664 /// the narrower type, transform it to a narrower load from address + N / num of
6665 /// bits of new type. If the result is to be extended, also fold the extension
6666 /// to form a extending load.
6667 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6668 unsigned Opc = N->getOpcode();
6670 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6671 SDValue N0 = N->getOperand(0);
6672 EVT VT = N->getValueType(0);
6675 // This transformation isn't valid for vector loads.
6679 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6681 if (Opc == ISD::SIGN_EXTEND_INREG) {
6682 ExtType = ISD::SEXTLOAD;
6683 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6684 } else if (Opc == ISD::SRL) {
6685 // Another special-case: SRL is basically zero-extending a narrower value.
6686 ExtType = ISD::ZEXTLOAD;
6688 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6689 if (!N01) return SDValue();
6690 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6691 VT.getSizeInBits() - N01->getZExtValue());
6693 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6696 unsigned EVTBits = ExtVT.getSizeInBits();
6698 // Do not generate loads of non-round integer types since these can
6699 // be expensive (and would be wrong if the type is not byte sized).
6700 if (!ExtVT.isRound())
6704 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6705 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6706 ShAmt = N01->getZExtValue();
6707 // Is the shift amount a multiple of size of VT?
6708 if ((ShAmt & (EVTBits-1)) == 0) {
6709 N0 = N0.getOperand(0);
6710 // Is the load width a multiple of size of VT?
6711 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6715 // At this point, we must have a load or else we can't do the transform.
6716 if (!isa<LoadSDNode>(N0)) return SDValue();
6718 // Because a SRL must be assumed to *need* to zero-extend the high bits
6719 // (as opposed to anyext the high bits), we can't combine the zextload
6720 // lowering of SRL and an sextload.
6721 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6724 // If the shift amount is larger than the input type then we're not
6725 // accessing any of the loaded bytes. If the load was a zextload/extload
6726 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6727 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6732 // If the load is shifted left (and the result isn't shifted back right),
6733 // we can fold the truncate through the shift.
6734 unsigned ShLeftAmt = 0;
6735 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6736 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6737 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6738 ShLeftAmt = N01->getZExtValue();
6739 N0 = N0.getOperand(0);
6743 // If we haven't found a load, we can't narrow it. Don't transform one with
6744 // multiple uses, this would require adding a new load.
6745 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6748 // Don't change the width of a volatile load.
6749 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6750 if (LN0->isVolatile())
6753 // Verify that we are actually reducing a load width here.
6754 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6757 // For the transform to be legal, the load must produce only two values
6758 // (the value loaded and the chain). Don't transform a pre-increment
6759 // load, for example, which produces an extra value. Otherwise the
6760 // transformation is not equivalent, and the downstream logic to replace
6761 // uses gets things wrong.
6762 if (LN0->getNumValues() > 2)
6765 // If the load that we're shrinking is an extload and we're not just
6766 // discarding the extension we can't simply shrink the load. Bail.
6767 // TODO: It would be possible to merge the extensions in some cases.
6768 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6769 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6772 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6775 EVT PtrType = N0.getOperand(1).getValueType();
6777 if (PtrType == MVT::Untyped || PtrType.isExtended())
6778 // It's not possible to generate a constant of extended or untyped type.
6781 // For big endian targets, we need to adjust the offset to the pointer to
6782 // load the correct bytes.
6783 if (DAG.getDataLayout().isBigEndian()) {
6784 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6785 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6786 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6789 uint64_t PtrOff = ShAmt / 8;
6790 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6792 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6793 PtrType, LN0->getBasePtr(),
6794 DAG.getConstant(PtrOff, DL, PtrType));
6795 AddToWorklist(NewPtr.getNode());
6798 if (ExtType == ISD::NON_EXTLOAD)
6799 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6800 LN0->getPointerInfo().getWithOffset(PtrOff),
6801 LN0->isVolatile(), LN0->isNonTemporal(),
6802 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6804 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6805 LN0->getPointerInfo().getWithOffset(PtrOff),
6806 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6807 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6809 // Replace the old load's chain with the new load's chain.
6810 WorklistRemover DeadNodes(*this);
6811 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6813 // Shift the result left, if we've swallowed a left shift.
6814 SDValue Result = Load;
6815 if (ShLeftAmt != 0) {
6816 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6817 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6819 // If the shift amount is as large as the result size (but, presumably,
6820 // no larger than the source) then the useful bits of the result are
6821 // zero; we can't simply return the shortened shift, because the result
6822 // of that operation is undefined.
6824 if (ShLeftAmt >= VT.getSizeInBits())
6825 Result = DAG.getConstant(0, DL, VT);
6827 Result = DAG.getNode(ISD::SHL, DL, VT,
6828 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6831 // Return the new loaded value.
6835 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6836 SDValue N0 = N->getOperand(0);
6837 SDValue N1 = N->getOperand(1);
6838 EVT VT = N->getValueType(0);
6839 EVT EVT = cast<VTSDNode>(N1)->getVT();
6840 unsigned VTBits = VT.getScalarType().getSizeInBits();
6841 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6844 return DAG.getUNDEF(VT);
6846 // fold (sext_in_reg c1) -> c1
6847 if (isConstantIntBuildVectorOrConstantInt(N0))
6848 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6850 // If the input is already sign extended, just drop the extension.
6851 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6854 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6855 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6856 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6857 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6858 N0.getOperand(0), N1);
6860 // fold (sext_in_reg (sext x)) -> (sext x)
6861 // fold (sext_in_reg (aext x)) -> (sext x)
6862 // if x is small enough.
6863 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6864 SDValue N00 = N0.getOperand(0);
6865 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6866 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6867 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6870 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6871 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6872 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6874 // fold operands of sext_in_reg based on knowledge that the top bits are not
6876 if (SimplifyDemandedBits(SDValue(N, 0)))
6877 return SDValue(N, 0);
6879 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6880 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6881 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6884 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6885 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6886 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6887 if (N0.getOpcode() == ISD::SRL) {
6888 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6889 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6890 // We can turn this into an SRA iff the input to the SRL is already sign
6892 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6893 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6894 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6895 N0.getOperand(0), N0.getOperand(1));
6899 // fold (sext_inreg (extload x)) -> (sextload x)
6900 if (ISD::isEXTLoad(N0.getNode()) &&
6901 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6902 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6903 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6904 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6905 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6906 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6908 LN0->getBasePtr(), EVT,
6909 LN0->getMemOperand());
6910 CombineTo(N, ExtLoad);
6911 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6912 AddToWorklist(ExtLoad.getNode());
6913 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6915 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6916 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6918 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6919 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6920 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6921 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6922 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6924 LN0->getBasePtr(), EVT,
6925 LN0->getMemOperand());
6926 CombineTo(N, ExtLoad);
6927 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6928 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6931 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6932 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6933 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6934 N0.getOperand(1), false);
6935 if (BSwap.getNode())
6936 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6943 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6944 SDValue N0 = N->getOperand(0);
6945 EVT VT = N->getValueType(0);
6947 if (N0.getOpcode() == ISD::UNDEF)
6948 return DAG.getUNDEF(VT);
6950 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6952 return SDValue(Res, 0);
6957 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6958 SDValue N0 = N->getOperand(0);
6959 EVT VT = N->getValueType(0);
6960 bool isLE = DAG.getDataLayout().isLittleEndian();
6963 if (N0.getValueType() == N->getValueType(0))
6965 // fold (truncate c1) -> c1
6966 if (isConstantIntBuildVectorOrConstantInt(N0))
6967 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6968 // fold (truncate (truncate x)) -> (truncate x)
6969 if (N0.getOpcode() == ISD::TRUNCATE)
6970 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6971 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6972 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6973 N0.getOpcode() == ISD::SIGN_EXTEND ||
6974 N0.getOpcode() == ISD::ANY_EXTEND) {
6975 if (N0.getOperand(0).getValueType().bitsLT(VT))
6976 // if the source is smaller than the dest, we still need an extend
6977 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6979 if (N0.getOperand(0).getValueType().bitsGT(VT))
6980 // if the source is larger than the dest, than we just need the truncate
6981 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6982 // if the source and dest are the same type, we can drop both the extend
6983 // and the truncate.
6984 return N0.getOperand(0);
6987 // Fold extract-and-trunc into a narrow extract. For example:
6988 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6989 // i32 y = TRUNCATE(i64 x)
6991 // v16i8 b = BITCAST (v2i64 val)
6992 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6994 // Note: We only run this optimization after type legalization (which often
6995 // creates this pattern) and before operation legalization after which
6996 // we need to be more careful about the vector instructions that we generate.
6997 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6998 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7000 EVT VecTy = N0.getOperand(0).getValueType();
7001 EVT ExTy = N0.getValueType();
7002 EVT TrTy = N->getValueType(0);
7004 unsigned NumElem = VecTy.getVectorNumElements();
7005 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7007 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7008 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7010 SDValue EltNo = N0->getOperand(1);
7011 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7012 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7013 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7014 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7016 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7017 NVT, N0.getOperand(0));
7020 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7022 DAG.getConstant(Index, DL, IndexTy));
7026 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7027 if (N0.getOpcode() == ISD::SELECT) {
7028 EVT SrcVT = N0.getValueType();
7029 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7030 TLI.isTruncateFree(SrcVT, VT)) {
7032 SDValue Cond = N0.getOperand(0);
7033 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7034 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7035 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7039 // Fold a series of buildvector, bitcast, and truncate if possible.
7041 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7042 // (2xi32 (buildvector x, y)).
7043 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7044 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7045 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7046 N0.getOperand(0).hasOneUse()) {
7048 SDValue BuildVect = N0.getOperand(0);
7049 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7050 EVT TruncVecEltTy = VT.getVectorElementType();
7052 // Check that the element types match.
7053 if (BuildVectEltTy == TruncVecEltTy) {
7054 // Now we only need to compute the offset of the truncated elements.
7055 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7056 unsigned TruncVecNumElts = VT.getVectorNumElements();
7057 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7059 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7060 "Invalid number of elements");
7062 SmallVector<SDValue, 8> Opnds;
7063 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7064 Opnds.push_back(BuildVect.getOperand(i));
7066 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7070 // See if we can simplify the input to this truncate through knowledge that
7071 // only the low bits are being used.
7072 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7073 // Currently we only perform this optimization on scalars because vectors
7074 // may have different active low bits.
7075 if (!VT.isVector()) {
7077 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7078 VT.getSizeInBits()));
7079 if (Shorter.getNode())
7080 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7082 // fold (truncate (load x)) -> (smaller load x)
7083 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7084 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7085 if (SDValue Reduced = ReduceLoadWidth(N))
7088 // Handle the case where the load remains an extending load even
7089 // after truncation.
7090 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7091 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7092 if (!LN0->isVolatile() &&
7093 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7094 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7095 VT, LN0->getChain(), LN0->getBasePtr(),
7097 LN0->getMemOperand());
7098 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7103 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7104 // where ... are all 'undef'.
7105 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7106 SmallVector<EVT, 8> VTs;
7109 unsigned NumDefs = 0;
7111 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7112 SDValue X = N0.getOperand(i);
7113 if (X.getOpcode() != ISD::UNDEF) {
7118 // Stop if more than one members are non-undef.
7121 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7122 VT.getVectorElementType(),
7123 X.getValueType().getVectorNumElements()));
7127 return DAG.getUNDEF(VT);
7130 assert(V.getNode() && "The single defined operand is empty!");
7131 SmallVector<SDValue, 8> Opnds;
7132 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7134 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7137 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7138 AddToWorklist(NV.getNode());
7139 Opnds.push_back(NV);
7141 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7145 // Simplify the operands using demanded-bits information.
7146 if (!VT.isVector() &&
7147 SimplifyDemandedBits(SDValue(N, 0)))
7148 return SDValue(N, 0);
7153 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7154 SDValue Elt = N->getOperand(i);
7155 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7156 return Elt.getNode();
7157 return Elt.getOperand(Elt.getResNo()).getNode();
7160 /// build_pair (load, load) -> load
7161 /// if load locations are consecutive.
7162 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7163 assert(N->getOpcode() == ISD::BUILD_PAIR);
7165 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7166 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7167 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7168 LD1->getAddressSpace() != LD2->getAddressSpace())
7170 EVT LD1VT = LD1->getValueType(0);
7172 if (ISD::isNON_EXTLoad(LD2) &&
7174 // If both are volatile this would reduce the number of volatile loads.
7175 // If one is volatile it might be ok, but play conservative and bail out.
7176 !LD1->isVolatile() &&
7177 !LD2->isVolatile() &&
7178 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7179 unsigned Align = LD1->getAlignment();
7180 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7181 VT.getTypeForEVT(*DAG.getContext()));
7183 if (NewAlign <= Align &&
7184 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7185 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7186 LD1->getBasePtr(), LD1->getPointerInfo(),
7187 false, false, false, Align);
7193 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7194 SDValue N0 = N->getOperand(0);
7195 EVT VT = N->getValueType(0);
7197 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7198 // Only do this before legalize, since afterward the target may be depending
7199 // on the bitconvert.
7200 // First check to see if this is all constant.
7202 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7204 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7206 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7207 assert(!DestEltVT.isVector() &&
7208 "Element type of vector ValueType must not be vector!");
7210 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7213 // If the input is a constant, let getNode fold it.
7214 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7215 // If we can't allow illegal operations, we need to check that this is just
7216 // a fp -> int or int -> conversion and that the resulting operation will
7218 if (!LegalOperations ||
7219 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7220 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7221 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7222 TLI.isOperationLegal(ISD::Constant, VT)))
7223 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7226 // (conv (conv x, t1), t2) -> (conv x, t2)
7227 if (N0.getOpcode() == ISD::BITCAST)
7228 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7231 // fold (conv (load x)) -> (load (conv*)x)
7232 // If the resultant load doesn't need a higher alignment than the original!
7233 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7234 // Do not change the width of a volatile load.
7235 !cast<LoadSDNode>(N0)->isVolatile() &&
7236 // Do not remove the cast if the types differ in endian layout.
7237 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7238 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7239 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7240 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7241 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7242 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7243 VT.getTypeForEVT(*DAG.getContext()));
7244 unsigned OrigAlign = LN0->getAlignment();
7246 if (Align <= OrigAlign) {
7247 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7248 LN0->getBasePtr(), LN0->getPointerInfo(),
7249 LN0->isVolatile(), LN0->isNonTemporal(),
7250 LN0->isInvariant(), OrigAlign,
7252 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7257 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7258 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7259 // This often reduces constant pool loads.
7260 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7261 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7262 N0.getNode()->hasOneUse() && VT.isInteger() &&
7263 !VT.isVector() && !N0.getValueType().isVector()) {
7264 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7266 AddToWorklist(NewConv.getNode());
7269 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7270 if (N0.getOpcode() == ISD::FNEG)
7271 return DAG.getNode(ISD::XOR, DL, VT,
7272 NewConv, DAG.getConstant(SignBit, DL, VT));
7273 assert(N0.getOpcode() == ISD::FABS);
7274 return DAG.getNode(ISD::AND, DL, VT,
7275 NewConv, DAG.getConstant(~SignBit, DL, VT));
7278 // fold (bitconvert (fcopysign cst, x)) ->
7279 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7280 // Note that we don't handle (copysign x, cst) because this can always be
7281 // folded to an fneg or fabs.
7282 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7283 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7284 VT.isInteger() && !VT.isVector()) {
7285 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7286 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7287 if (isTypeLegal(IntXVT)) {
7288 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7289 IntXVT, N0.getOperand(1));
7290 AddToWorklist(X.getNode());
7292 // If X has a different width than the result/lhs, sext it or truncate it.
7293 unsigned VTWidth = VT.getSizeInBits();
7294 if (OrigXWidth < VTWidth) {
7295 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7296 AddToWorklist(X.getNode());
7297 } else if (OrigXWidth > VTWidth) {
7298 // To get the sign bit in the right place, we have to shift it right
7299 // before truncating.
7301 X = DAG.getNode(ISD::SRL, DL,
7302 X.getValueType(), X,
7303 DAG.getConstant(OrigXWidth-VTWidth, DL,
7305 AddToWorklist(X.getNode());
7306 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7307 AddToWorklist(X.getNode());
7310 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7311 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7312 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7313 AddToWorklist(X.getNode());
7315 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7316 VT, N0.getOperand(0));
7317 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7318 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7319 AddToWorklist(Cst.getNode());
7321 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7325 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7326 if (N0.getOpcode() == ISD::BUILD_PAIR)
7327 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7330 // Remove double bitcasts from shuffles - this is often a legacy of
7331 // XformToShuffleWithZero being used to combine bitmaskings (of
7332 // float vectors bitcast to integer vectors) into shuffles.
7333 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7334 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7335 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7336 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7337 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7338 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7340 // If operands are a bitcast, peek through if it casts the original VT.
7341 // If operands are a constant, just bitcast back to original VT.
7342 auto PeekThroughBitcast = [&](SDValue Op) {
7343 if (Op.getOpcode() == ISD::BITCAST &&
7344 Op.getOperand(0).getValueType() == VT)
7345 return SDValue(Op.getOperand(0));
7346 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7347 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7348 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7352 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7353 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7358 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7359 SmallVector<int, 8> NewMask;
7360 for (int M : SVN->getMask())
7361 for (int i = 0; i != MaskScale; ++i)
7362 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7364 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7366 std::swap(SV0, SV1);
7367 ShuffleVectorSDNode::commuteMask(NewMask);
7368 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7372 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7378 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7379 EVT VT = N->getValueType(0);
7380 return CombineConsecutiveLoads(N, VT);
7383 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7384 /// operands. DstEltVT indicates the destination element value type.
7385 SDValue DAGCombiner::
7386 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7387 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7389 // If this is already the right type, we're done.
7390 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7392 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7393 unsigned DstBitSize = DstEltVT.getSizeInBits();
7395 // If this is a conversion of N elements of one type to N elements of another
7396 // type, convert each element. This handles FP<->INT cases.
7397 if (SrcBitSize == DstBitSize) {
7398 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7399 BV->getValueType(0).getVectorNumElements());
7401 // Due to the FP element handling below calling this routine recursively,
7402 // we can end up with a scalar-to-vector node here.
7403 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7404 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7405 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7406 DstEltVT, BV->getOperand(0)));
7408 SmallVector<SDValue, 8> Ops;
7409 for (SDValue Op : BV->op_values()) {
7410 // If the vector element type is not legal, the BUILD_VECTOR operands
7411 // are promoted and implicitly truncated. Make that explicit here.
7412 if (Op.getValueType() != SrcEltVT)
7413 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7414 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7416 AddToWorklist(Ops.back().getNode());
7418 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7421 // Otherwise, we're growing or shrinking the elements. To avoid having to
7422 // handle annoying details of growing/shrinking FP values, we convert them to
7424 if (SrcEltVT.isFloatingPoint()) {
7425 // Convert the input float vector to a int vector where the elements are the
7427 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7428 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7432 // Now we know the input is an integer vector. If the output is a FP type,
7433 // convert to integer first, then to FP of the right size.
7434 if (DstEltVT.isFloatingPoint()) {
7435 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7436 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7438 // Next, convert to FP elements of the same size.
7439 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7444 // Okay, we know the src/dst types are both integers of differing types.
7445 // Handling growing first.
7446 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7447 if (SrcBitSize < DstBitSize) {
7448 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7450 SmallVector<SDValue, 8> Ops;
7451 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7452 i += NumInputsPerOutput) {
7453 bool isLE = DAG.getDataLayout().isLittleEndian();
7454 APInt NewBits = APInt(DstBitSize, 0);
7455 bool EltIsUndef = true;
7456 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7457 // Shift the previously computed bits over.
7458 NewBits <<= SrcBitSize;
7459 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7460 if (Op.getOpcode() == ISD::UNDEF) continue;
7463 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7464 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7468 Ops.push_back(DAG.getUNDEF(DstEltVT));
7470 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7473 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7474 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7477 // Finally, this must be the case where we are shrinking elements: each input
7478 // turns into multiple outputs.
7479 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7480 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7481 NumOutputsPerInput*BV->getNumOperands());
7482 SmallVector<SDValue, 8> Ops;
7484 for (const SDValue &Op : BV->op_values()) {
7485 if (Op.getOpcode() == ISD::UNDEF) {
7486 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7490 APInt OpVal = cast<ConstantSDNode>(Op)->
7491 getAPIntValue().zextOrTrunc(SrcBitSize);
7493 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7494 APInt ThisVal = OpVal.trunc(DstBitSize);
7495 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7496 OpVal = OpVal.lshr(DstBitSize);
7499 // For big endian targets, swap the order of the pieces of each element.
7500 if (DAG.getDataLayout().isBigEndian())
7501 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7504 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7507 /// Try to perform FMA combining on a given FADD node.
7508 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7509 SDValue N0 = N->getOperand(0);
7510 SDValue N1 = N->getOperand(1);
7511 EVT VT = N->getValueType(0);
7514 const TargetOptions &Options = DAG.getTarget().Options;
7516 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7518 // Floating-point multiply-add with intermediate rounding.
7519 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7521 // Floating-point multiply-add without intermediate rounding.
7523 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7524 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7526 // No valid opcode, do not combine.
7527 if (!HasFMAD && !HasFMA)
7530 // Always prefer FMAD to FMA for precision.
7531 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7532 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7533 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7535 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7536 // prefer to fold the multiply with fewer uses.
7537 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7538 N1.getOpcode() == ISD::FMUL) {
7539 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7543 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7544 if (N0.getOpcode() == ISD::FMUL &&
7545 (Aggressive || N0->hasOneUse())) {
7546 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7547 N0.getOperand(0), N0.getOperand(1), N1);
7550 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7551 // Note: Commutes FADD operands.
7552 if (N1.getOpcode() == ISD::FMUL &&
7553 (Aggressive || N1->hasOneUse())) {
7554 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7555 N1.getOperand(0), N1.getOperand(1), N0);
7558 // Look through FP_EXTEND nodes to do more combining.
7559 if (AllowFusion && LookThroughFPExt) {
7560 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7561 if (N0.getOpcode() == ISD::FP_EXTEND) {
7562 SDValue N00 = N0.getOperand(0);
7563 if (N00.getOpcode() == ISD::FMUL)
7564 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7565 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7567 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7568 N00.getOperand(1)), N1);
7571 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7572 // Note: Commutes FADD operands.
7573 if (N1.getOpcode() == ISD::FP_EXTEND) {
7574 SDValue N10 = N1.getOperand(0);
7575 if (N10.getOpcode() == ISD::FMUL)
7576 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7577 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7579 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7580 N10.getOperand(1)), N0);
7584 // More folding opportunities when target permits.
7585 if ((AllowFusion || HasFMAD) && Aggressive) {
7586 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7587 if (N0.getOpcode() == PreferredFusedOpcode &&
7588 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7589 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7590 N0.getOperand(0), N0.getOperand(1),
7591 DAG.getNode(PreferredFusedOpcode, SL, VT,
7592 N0.getOperand(2).getOperand(0),
7593 N0.getOperand(2).getOperand(1),
7597 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7598 if (N1->getOpcode() == PreferredFusedOpcode &&
7599 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7600 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7601 N1.getOperand(0), N1.getOperand(1),
7602 DAG.getNode(PreferredFusedOpcode, SL, VT,
7603 N1.getOperand(2).getOperand(0),
7604 N1.getOperand(2).getOperand(1),
7608 if (AllowFusion && LookThroughFPExt) {
7609 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7610 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7611 auto FoldFAddFMAFPExtFMul = [&] (
7612 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7613 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7614 DAG.getNode(PreferredFusedOpcode, SL, VT,
7615 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7616 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7619 if (N0.getOpcode() == PreferredFusedOpcode) {
7620 SDValue N02 = N0.getOperand(2);
7621 if (N02.getOpcode() == ISD::FP_EXTEND) {
7622 SDValue N020 = N02.getOperand(0);
7623 if (N020.getOpcode() == ISD::FMUL)
7624 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7625 N020.getOperand(0), N020.getOperand(1),
7630 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7631 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7632 // FIXME: This turns two single-precision and one double-precision
7633 // operation into two double-precision operations, which might not be
7634 // interesting for all targets, especially GPUs.
7635 auto FoldFAddFPExtFMAFMul = [&] (
7636 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7637 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7638 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7639 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7640 DAG.getNode(PreferredFusedOpcode, SL, VT,
7641 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7642 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7645 if (N0.getOpcode() == ISD::FP_EXTEND) {
7646 SDValue N00 = N0.getOperand(0);
7647 if (N00.getOpcode() == PreferredFusedOpcode) {
7648 SDValue N002 = N00.getOperand(2);
7649 if (N002.getOpcode() == ISD::FMUL)
7650 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7651 N002.getOperand(0), N002.getOperand(1),
7656 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7657 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7658 if (N1.getOpcode() == PreferredFusedOpcode) {
7659 SDValue N12 = N1.getOperand(2);
7660 if (N12.getOpcode() == ISD::FP_EXTEND) {
7661 SDValue N120 = N12.getOperand(0);
7662 if (N120.getOpcode() == ISD::FMUL)
7663 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7664 N120.getOperand(0), N120.getOperand(1),
7669 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7670 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7671 // FIXME: This turns two single-precision and one double-precision
7672 // operation into two double-precision operations, which might not be
7673 // interesting for all targets, especially GPUs.
7674 if (N1.getOpcode() == ISD::FP_EXTEND) {
7675 SDValue N10 = N1.getOperand(0);
7676 if (N10.getOpcode() == PreferredFusedOpcode) {
7677 SDValue N102 = N10.getOperand(2);
7678 if (N102.getOpcode() == ISD::FMUL)
7679 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7680 N102.getOperand(0), N102.getOperand(1),
7690 /// Try to perform FMA combining on a given FSUB node.
7691 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7692 SDValue N0 = N->getOperand(0);
7693 SDValue N1 = N->getOperand(1);
7694 EVT VT = N->getValueType(0);
7697 const TargetOptions &Options = DAG.getTarget().Options;
7699 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7701 // Floating-point multiply-add with intermediate rounding.
7702 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7704 // Floating-point multiply-add without intermediate rounding.
7706 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7707 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7709 // No valid opcode, do not combine.
7710 if (!HasFMAD && !HasFMA)
7713 // Always prefer FMAD to FMA for precision.
7714 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7715 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7716 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7718 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7719 if (N0.getOpcode() == ISD::FMUL &&
7720 (Aggressive || N0->hasOneUse())) {
7721 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7722 N0.getOperand(0), N0.getOperand(1),
7723 DAG.getNode(ISD::FNEG, SL, VT, N1));
7726 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7727 // Note: Commutes FSUB operands.
7728 if (N1.getOpcode() == ISD::FMUL &&
7729 (Aggressive || N1->hasOneUse()))
7730 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7731 DAG.getNode(ISD::FNEG, SL, VT,
7733 N1.getOperand(1), N0);
7735 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7736 if (N0.getOpcode() == ISD::FNEG &&
7737 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7738 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7739 SDValue N00 = N0.getOperand(0).getOperand(0);
7740 SDValue N01 = N0.getOperand(0).getOperand(1);
7741 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7742 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7743 DAG.getNode(ISD::FNEG, SL, VT, N1));
7746 // Look through FP_EXTEND nodes to do more combining.
7747 if (AllowFusion && LookThroughFPExt) {
7748 // fold (fsub (fpext (fmul x, y)), z)
7749 // -> (fma (fpext x), (fpext y), (fneg z))
7750 if (N0.getOpcode() == ISD::FP_EXTEND) {
7751 SDValue N00 = N0.getOperand(0);
7752 if (N00.getOpcode() == ISD::FMUL)
7753 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7754 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7756 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7758 DAG.getNode(ISD::FNEG, SL, VT, N1));
7761 // fold (fsub x, (fpext (fmul y, z)))
7762 // -> (fma (fneg (fpext y)), (fpext z), x)
7763 // Note: Commutes FSUB operands.
7764 if (N1.getOpcode() == ISD::FP_EXTEND) {
7765 SDValue N10 = N1.getOperand(0);
7766 if (N10.getOpcode() == ISD::FMUL)
7767 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7768 DAG.getNode(ISD::FNEG, SL, VT,
7769 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7770 N10.getOperand(0))),
7771 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7776 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7777 // -> (fneg (fma (fpext x), (fpext y), z))
7778 // Note: This could be removed with appropriate canonicalization of the
7779 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7780 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7781 // from implementing the canonicalization in visitFSUB.
7782 if (N0.getOpcode() == ISD::FP_EXTEND) {
7783 SDValue N00 = N0.getOperand(0);
7784 if (N00.getOpcode() == ISD::FNEG) {
7785 SDValue N000 = N00.getOperand(0);
7786 if (N000.getOpcode() == ISD::FMUL) {
7787 return DAG.getNode(ISD::FNEG, SL, VT,
7788 DAG.getNode(PreferredFusedOpcode, SL, VT,
7789 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7790 N000.getOperand(0)),
7791 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7792 N000.getOperand(1)),
7798 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7799 // -> (fneg (fma (fpext x)), (fpext y), z)
7800 // Note: This could be removed with appropriate canonicalization of the
7801 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7802 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7803 // from implementing the canonicalization in visitFSUB.
7804 if (N0.getOpcode() == ISD::FNEG) {
7805 SDValue N00 = N0.getOperand(0);
7806 if (N00.getOpcode() == ISD::FP_EXTEND) {
7807 SDValue N000 = N00.getOperand(0);
7808 if (N000.getOpcode() == ISD::FMUL) {
7809 return DAG.getNode(ISD::FNEG, SL, VT,
7810 DAG.getNode(PreferredFusedOpcode, SL, VT,
7811 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7812 N000.getOperand(0)),
7813 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7814 N000.getOperand(1)),
7822 // More folding opportunities when target permits.
7823 if ((AllowFusion || HasFMAD) && Aggressive) {
7824 // fold (fsub (fma x, y, (fmul u, v)), z)
7825 // -> (fma x, y (fma u, v, (fneg z)))
7826 if (N0.getOpcode() == PreferredFusedOpcode &&
7827 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7828 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7829 N0.getOperand(0), N0.getOperand(1),
7830 DAG.getNode(PreferredFusedOpcode, SL, VT,
7831 N0.getOperand(2).getOperand(0),
7832 N0.getOperand(2).getOperand(1),
7833 DAG.getNode(ISD::FNEG, SL, VT,
7837 // fold (fsub x, (fma y, z, (fmul u, v)))
7838 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7839 if (N1.getOpcode() == PreferredFusedOpcode &&
7840 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7841 SDValue N20 = N1.getOperand(2).getOperand(0);
7842 SDValue N21 = N1.getOperand(2).getOperand(1);
7843 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7844 DAG.getNode(ISD::FNEG, SL, VT,
7847 DAG.getNode(PreferredFusedOpcode, SL, VT,
7848 DAG.getNode(ISD::FNEG, SL, VT, N20),
7853 if (AllowFusion && LookThroughFPExt) {
7854 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7855 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7856 if (N0.getOpcode() == PreferredFusedOpcode) {
7857 SDValue N02 = N0.getOperand(2);
7858 if (N02.getOpcode() == ISD::FP_EXTEND) {
7859 SDValue N020 = N02.getOperand(0);
7860 if (N020.getOpcode() == ISD::FMUL)
7861 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7862 N0.getOperand(0), N0.getOperand(1),
7863 DAG.getNode(PreferredFusedOpcode, SL, VT,
7864 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7865 N020.getOperand(0)),
7866 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7867 N020.getOperand(1)),
7868 DAG.getNode(ISD::FNEG, SL, VT,
7873 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7874 // -> (fma (fpext x), (fpext y),
7875 // (fma (fpext u), (fpext v), (fneg z)))
7876 // FIXME: This turns two single-precision and one double-precision
7877 // operation into two double-precision operations, which might not be
7878 // interesting for all targets, especially GPUs.
7879 if (N0.getOpcode() == ISD::FP_EXTEND) {
7880 SDValue N00 = N0.getOperand(0);
7881 if (N00.getOpcode() == PreferredFusedOpcode) {
7882 SDValue N002 = N00.getOperand(2);
7883 if (N002.getOpcode() == ISD::FMUL)
7884 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7885 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7887 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7889 DAG.getNode(PreferredFusedOpcode, SL, VT,
7890 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7891 N002.getOperand(0)),
7892 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7893 N002.getOperand(1)),
7894 DAG.getNode(ISD::FNEG, SL, VT,
7899 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7900 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7901 if (N1.getOpcode() == PreferredFusedOpcode &&
7902 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7903 SDValue N120 = N1.getOperand(2).getOperand(0);
7904 if (N120.getOpcode() == ISD::FMUL) {
7905 SDValue N1200 = N120.getOperand(0);
7906 SDValue N1201 = N120.getOperand(1);
7907 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7908 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7910 DAG.getNode(PreferredFusedOpcode, SL, VT,
7911 DAG.getNode(ISD::FNEG, SL, VT,
7912 DAG.getNode(ISD::FP_EXTEND, SL,
7914 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7920 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7921 // -> (fma (fneg (fpext y)), (fpext z),
7922 // (fma (fneg (fpext u)), (fpext v), x))
7923 // FIXME: This turns two single-precision and one double-precision
7924 // operation into two double-precision operations, which might not be
7925 // interesting for all targets, especially GPUs.
7926 if (N1.getOpcode() == ISD::FP_EXTEND &&
7927 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7928 SDValue N100 = N1.getOperand(0).getOperand(0);
7929 SDValue N101 = N1.getOperand(0).getOperand(1);
7930 SDValue N102 = N1.getOperand(0).getOperand(2);
7931 if (N102.getOpcode() == ISD::FMUL) {
7932 SDValue N1020 = N102.getOperand(0);
7933 SDValue N1021 = N102.getOperand(1);
7934 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7935 DAG.getNode(ISD::FNEG, SL, VT,
7936 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7938 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7939 DAG.getNode(PreferredFusedOpcode, SL, VT,
7940 DAG.getNode(ISD::FNEG, SL, VT,
7941 DAG.getNode(ISD::FP_EXTEND, SL,
7943 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7954 /// Try to perform FMA combining on a given FMUL node.
7955 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7956 SDValue N0 = N->getOperand(0);
7957 SDValue N1 = N->getOperand(1);
7958 EVT VT = N->getValueType(0);
7961 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7963 const TargetOptions &Options = DAG.getTarget().Options;
7965 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7967 // Floating-point multiply-add with intermediate rounding.
7968 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7970 // Floating-point multiply-add without intermediate rounding.
7972 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7973 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7975 // No valid opcode, do not combine.
7976 if (!HasFMAD && !HasFMA)
7979 // Always prefer FMAD to FMA for precision.
7980 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7981 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7983 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7984 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7985 auto FuseFADD = [&](SDValue X, SDValue Y) {
7986 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7987 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7988 if (XC1 && XC1->isExactlyValue(+1.0))
7989 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7990 if (XC1 && XC1->isExactlyValue(-1.0))
7991 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7992 DAG.getNode(ISD::FNEG, SL, VT, Y));
7997 if (SDValue FMA = FuseFADD(N0, N1))
7999 if (SDValue FMA = FuseFADD(N1, N0))
8002 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8003 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8004 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8005 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8006 auto FuseFSUB = [&](SDValue X, SDValue Y) {
8007 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8008 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8009 if (XC0 && XC0->isExactlyValue(+1.0))
8010 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8011 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8013 if (XC0 && XC0->isExactlyValue(-1.0))
8014 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8015 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8016 DAG.getNode(ISD::FNEG, SL, VT, Y));
8018 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8019 if (XC1 && XC1->isExactlyValue(+1.0))
8020 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8021 DAG.getNode(ISD::FNEG, SL, VT, Y));
8022 if (XC1 && XC1->isExactlyValue(-1.0))
8023 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8028 if (SDValue FMA = FuseFSUB(N0, N1))
8030 if (SDValue FMA = FuseFSUB(N1, N0))
8036 SDValue DAGCombiner::visitFADD(SDNode *N) {
8037 SDValue N0 = N->getOperand(0);
8038 SDValue N1 = N->getOperand(1);
8039 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8040 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8041 EVT VT = N->getValueType(0);
8043 const TargetOptions &Options = DAG.getTarget().Options;
8044 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8048 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8051 // fold (fadd c1, c2) -> c1 + c2
8053 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8055 // canonicalize constant to RHS
8056 if (N0CFP && !N1CFP)
8057 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8059 // fold (fadd A, (fneg B)) -> (fsub A, B)
8060 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8061 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8062 return DAG.getNode(ISD::FSUB, DL, VT, N0,
8063 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8065 // fold (fadd (fneg A), B) -> (fsub B, A)
8066 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8067 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8068 return DAG.getNode(ISD::FSUB, DL, VT, N1,
8069 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8071 // If 'unsafe math' is enabled, fold lots of things.
8072 if (Options.UnsafeFPMath) {
8073 // No FP constant should be created after legalization as Instruction
8074 // Selection pass has a hard time dealing with FP constants.
8075 bool AllowNewConst = (Level < AfterLegalizeDAG);
8077 // fold (fadd A, 0) -> A
8078 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8082 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8083 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8084 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8085 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8086 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8090 // If allowed, fold (fadd (fneg x), x) -> 0.0
8091 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8092 return DAG.getConstantFP(0.0, DL, VT);
8094 // If allowed, fold (fadd x, (fneg x)) -> 0.0
8095 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8096 return DAG.getConstantFP(0.0, DL, VT);
8098 // We can fold chains of FADD's of the same value into multiplications.
8099 // This transform is not safe in general because we are reducing the number
8100 // of rounding steps.
8101 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8102 if (N0.getOpcode() == ISD::FMUL) {
8103 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8104 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8106 // (fadd (fmul x, c), x) -> (fmul x, c+1)
8107 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8108 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8109 DAG.getConstantFP(1.0, DL, VT), Flags);
8110 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8113 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8114 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8115 N1.getOperand(0) == N1.getOperand(1) &&
8116 N0.getOperand(0) == N1.getOperand(0)) {
8117 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8118 DAG.getConstantFP(2.0, DL, VT), Flags);
8119 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8123 if (N1.getOpcode() == ISD::FMUL) {
8124 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8125 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8127 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8128 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8129 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8130 DAG.getConstantFP(1.0, DL, VT), Flags);
8131 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8134 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8135 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8136 N0.getOperand(0) == N0.getOperand(1) &&
8137 N1.getOperand(0) == N0.getOperand(0)) {
8138 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8139 DAG.getConstantFP(2.0, DL, VT), Flags);
8140 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8144 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8145 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8146 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8147 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8148 (N0.getOperand(0) == N1)) {
8149 return DAG.getNode(ISD::FMUL, DL, VT,
8150 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8154 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8155 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8156 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8157 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8158 N1.getOperand(0) == N0) {
8159 return DAG.getNode(ISD::FMUL, DL, VT,
8160 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8164 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8165 if (AllowNewConst &&
8166 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8167 N0.getOperand(0) == N0.getOperand(1) &&
8168 N1.getOperand(0) == N1.getOperand(1) &&
8169 N0.getOperand(0) == N1.getOperand(0)) {
8170 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8171 DAG.getConstantFP(4.0, DL, VT), Flags);
8174 } // enable-unsafe-fp-math
8176 // FADD -> FMA combines:
8177 if (SDValue Fused = visitFADDForFMACombine(N)) {
8178 AddToWorklist(Fused.getNode());
8185 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8186 SDValue N0 = N->getOperand(0);
8187 SDValue N1 = N->getOperand(1);
8188 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8189 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8190 EVT VT = N->getValueType(0);
8192 const TargetOptions &Options = DAG.getTarget().Options;
8193 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8197 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8200 // fold (fsub c1, c2) -> c1-c2
8202 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8204 // fold (fsub A, (fneg B)) -> (fadd A, B)
8205 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8206 return DAG.getNode(ISD::FADD, dl, VT, N0,
8207 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8209 // If 'unsafe math' is enabled, fold lots of things.
8210 if (Options.UnsafeFPMath) {
8212 if (N1CFP && N1CFP->isZero())
8215 // (fsub 0, B) -> -B
8216 if (N0CFP && N0CFP->isZero()) {
8217 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8218 return GetNegatedExpression(N1, DAG, LegalOperations);
8219 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8220 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8223 // (fsub x, x) -> 0.0
8225 return DAG.getConstantFP(0.0f, dl, VT);
8227 // (fsub x, (fadd x, y)) -> (fneg y)
8228 // (fsub x, (fadd y, x)) -> (fneg y)
8229 if (N1.getOpcode() == ISD::FADD) {
8230 SDValue N10 = N1->getOperand(0);
8231 SDValue N11 = N1->getOperand(1);
8233 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8234 return GetNegatedExpression(N11, DAG, LegalOperations);
8236 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8237 return GetNegatedExpression(N10, DAG, LegalOperations);
8241 // FSUB -> FMA combines:
8242 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8243 AddToWorklist(Fused.getNode());
8250 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8251 SDValue N0 = N->getOperand(0);
8252 SDValue N1 = N->getOperand(1);
8253 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8254 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8255 EVT VT = N->getValueType(0);
8257 const TargetOptions &Options = DAG.getTarget().Options;
8258 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8261 if (VT.isVector()) {
8262 // This just handles C1 * C2 for vectors. Other vector folds are below.
8263 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8267 // fold (fmul c1, c2) -> c1*c2
8269 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8271 // canonicalize constant to RHS
8272 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8273 !isConstantFPBuildVectorOrConstantFP(N1))
8274 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8276 // fold (fmul A, 1.0) -> A
8277 if (N1CFP && N1CFP->isExactlyValue(1.0))
8280 if (Options.UnsafeFPMath) {
8281 // fold (fmul A, 0) -> 0
8282 if (N1CFP && N1CFP->isZero())
8285 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8286 if (N0.getOpcode() == ISD::FMUL) {
8287 // Fold scalars or any vector constants (not just splats).
8288 // This fold is done in general by InstCombine, but extra fmul insts
8289 // may have been generated during lowering.
8290 SDValue N00 = N0.getOperand(0);
8291 SDValue N01 = N0.getOperand(1);
8292 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8293 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8294 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8296 // Check 1: Make sure that the first operand of the inner multiply is NOT
8297 // a constant. Otherwise, we may induce infinite looping.
8298 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8299 // Check 2: Make sure that the second operand of the inner multiply and
8300 // the second operand of the outer multiply are constants.
8301 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8302 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8303 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8304 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8309 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8310 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8311 // during an early run of DAGCombiner can prevent folding with fmuls
8312 // inserted during lowering.
8313 if (N0.getOpcode() == ISD::FADD &&
8314 (N0.getOperand(0) == N0.getOperand(1)) &&
8316 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8317 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8318 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8322 // fold (fmul X, 2.0) -> (fadd X, X)
8323 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8324 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8326 // fold (fmul X, -1.0) -> (fneg X)
8327 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8328 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8329 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8331 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8332 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8333 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8334 // Both can be negated for free, check to see if at least one is cheaper
8336 if (LHSNeg == 2 || RHSNeg == 2)
8337 return DAG.getNode(ISD::FMUL, DL, VT,
8338 GetNegatedExpression(N0, DAG, LegalOperations),
8339 GetNegatedExpression(N1, DAG, LegalOperations),
8344 // FMUL -> FMA combines:
8345 if (SDValue Fused = visitFMULForFMACombine(N)) {
8346 AddToWorklist(Fused.getNode());
8353 SDValue DAGCombiner::visitFMA(SDNode *N) {
8354 SDValue N0 = N->getOperand(0);
8355 SDValue N1 = N->getOperand(1);
8356 SDValue N2 = N->getOperand(2);
8357 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8358 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8359 EVT VT = N->getValueType(0);
8361 const TargetOptions &Options = DAG.getTarget().Options;
8363 // Constant fold FMA.
8364 if (isa<ConstantFPSDNode>(N0) &&
8365 isa<ConstantFPSDNode>(N1) &&
8366 isa<ConstantFPSDNode>(N2)) {
8367 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8370 if (Options.UnsafeFPMath) {
8371 if (N0CFP && N0CFP->isZero())
8373 if (N1CFP && N1CFP->isZero())
8376 // TODO: The FMA node should have flags that propagate to these nodes.
8377 if (N0CFP && N0CFP->isExactlyValue(1.0))
8378 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8379 if (N1CFP && N1CFP->isExactlyValue(1.0))
8380 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8382 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8383 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8384 !isConstantFPBuildVectorOrConstantFP(N1))
8385 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8387 // TODO: FMA nodes should have flags that propagate to the created nodes.
8388 // For now, create a Flags object for use with all unsafe math transforms.
8390 Flags.setUnsafeAlgebra(true);
8392 if (Options.UnsafeFPMath) {
8393 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8394 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8395 isConstantFPBuildVectorOrConstantFP(N1) &&
8396 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8397 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8398 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8402 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8403 if (N0.getOpcode() == ISD::FMUL &&
8404 isConstantFPBuildVectorOrConstantFP(N1) &&
8405 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8406 return DAG.getNode(ISD::FMA, dl, VT,
8408 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8414 // (fma x, 1, y) -> (fadd x, y)
8415 // (fma x, -1, y) -> (fadd (fneg x), y)
8417 if (N1CFP->isExactlyValue(1.0))
8418 // TODO: The FMA node should have flags that propagate to this node.
8419 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8421 if (N1CFP->isExactlyValue(-1.0) &&
8422 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8423 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8424 AddToWorklist(RHSNeg.getNode());
8425 // TODO: The FMA node should have flags that propagate to this node.
8426 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8430 if (Options.UnsafeFPMath) {
8431 // (fma x, c, x) -> (fmul x, (c+1))
8432 if (N1CFP && N0 == N2) {
8433 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8434 DAG.getNode(ISD::FADD, dl, VT,
8435 N1, DAG.getConstantFP(1.0, dl, VT),
8439 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8440 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8441 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8442 DAG.getNode(ISD::FADD, dl, VT,
8443 N1, DAG.getConstantFP(-1.0, dl, VT),
8451 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8453 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8454 // Notice that this is not always beneficial. One reason is different target
8455 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8456 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8457 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8458 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8459 if (!DAG.getTarget().Options.UnsafeFPMath)
8462 // Skip if current node is a reciprocal.
8463 SDValue N0 = N->getOperand(0);
8464 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8465 if (N0CFP && N0CFP->isExactlyValue(1.0))
8468 // Exit early if the target does not want this transform or if there can't
8469 // possibly be enough uses of the divisor to make the transform worthwhile.
8470 SDValue N1 = N->getOperand(1);
8471 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8472 if (!MinUses || N1->use_size() < MinUses)
8475 // Find all FDIV users of the same divisor.
8476 // Use a set because duplicates may be present in the user list.
8477 SetVector<SDNode *> Users;
8478 for (auto *U : N1->uses())
8479 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8482 // Now that we have the actual number of divisor uses, make sure it meets
8483 // the minimum threshold specified by the target.
8484 if (Users.size() < MinUses)
8487 EVT VT = N->getValueType(0);
8489 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8490 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8491 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8493 // Dividend / Divisor -> Dividend * Reciprocal
8494 for (auto *U : Users) {
8495 SDValue Dividend = U->getOperand(0);
8496 if (Dividend != FPOne) {
8497 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8499 CombineTo(U, NewNode);
8500 } else if (U != Reciprocal.getNode()) {
8501 // In the absence of fast-math-flags, this user node is always the
8502 // same node as Reciprocal, but with FMF they may be different nodes.
8503 CombineTo(U, Reciprocal);
8506 return SDValue(N, 0); // N was replaced.
8509 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8510 SDValue N0 = N->getOperand(0);
8511 SDValue N1 = N->getOperand(1);
8512 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8513 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8514 EVT VT = N->getValueType(0);
8516 const TargetOptions &Options = DAG.getTarget().Options;
8517 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8521 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8524 // fold (fdiv c1, c2) -> c1/c2
8526 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8528 if (Options.UnsafeFPMath) {
8529 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8531 // Compute the reciprocal 1.0 / c2.
8532 APFloat N1APF = N1CFP->getValueAPF();
8533 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8534 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8535 // Only do the transform if the reciprocal is a legal fp immediate that
8536 // isn't too nasty (eg NaN, denormal, ...).
8537 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8538 (!LegalOperations ||
8539 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8540 // backend)... we should handle this gracefully after Legalize.
8541 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8542 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8543 TLI.isFPImmLegal(Recip, VT)))
8544 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8545 DAG.getConstantFP(Recip, DL, VT), Flags);
8548 // If this FDIV is part of a reciprocal square root, it may be folded
8549 // into a target-specific square root estimate instruction.
8550 if (N1.getOpcode() == ISD::FSQRT) {
8551 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8552 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8554 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8555 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8556 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8558 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8559 AddToWorklist(RV.getNode());
8560 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8562 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8563 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8564 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8566 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8567 AddToWorklist(RV.getNode());
8568 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8570 } else if (N1.getOpcode() == ISD::FMUL) {
8571 // Look through an FMUL. Even though this won't remove the FDIV directly,
8572 // it's still worthwhile to get rid of the FSQRT if possible.
8575 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8576 SqrtOp = N1.getOperand(0);
8577 OtherOp = N1.getOperand(1);
8578 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8579 SqrtOp = N1.getOperand(1);
8580 OtherOp = N1.getOperand(0);
8582 if (SqrtOp.getNode()) {
8583 // We found a FSQRT, so try to make this fold:
8584 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8585 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8586 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8587 AddToWorklist(RV.getNode());
8588 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8593 // Fold into a reciprocal estimate and multiply instead of a real divide.
8594 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8595 AddToWorklist(RV.getNode());
8596 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8600 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8601 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8602 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8603 // Both can be negated for free, check to see if at least one is cheaper
8605 if (LHSNeg == 2 || RHSNeg == 2)
8606 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8607 GetNegatedExpression(N0, DAG, LegalOperations),
8608 GetNegatedExpression(N1, DAG, LegalOperations),
8613 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8614 return CombineRepeatedDivisors;
8619 SDValue DAGCombiner::visitFREM(SDNode *N) {
8620 SDValue N0 = N->getOperand(0);
8621 SDValue N1 = N->getOperand(1);
8622 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8623 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8624 EVT VT = N->getValueType(0);
8626 // fold (frem c1, c2) -> fmod(c1,c2)
8628 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8629 &cast<BinaryWithFlagsSDNode>(N)->Flags);
8634 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8635 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8638 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8639 // For now, create a Flags object for use with all unsafe math transforms.
8641 Flags.setUnsafeAlgebra(true);
8643 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8644 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8648 EVT VT = RV.getValueType();
8650 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8651 AddToWorklist(RV.getNode());
8653 // Unfortunately, RV is now NaN if the input was exactly 0.
8654 // Select out this case and force the answer to 0.
8655 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8656 EVT CCVT = getSetCCResultType(VT);
8657 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8658 AddToWorklist(ZeroCmp.getNode());
8659 AddToWorklist(RV.getNode());
8661 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8665 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8666 SDValue N0 = N->getOperand(0);
8667 SDValue N1 = N->getOperand(1);
8668 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8669 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8670 EVT VT = N->getValueType(0);
8672 if (N0CFP && N1CFP) // Constant fold
8673 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8676 const APFloat& V = N1CFP->getValueAPF();
8677 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8678 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8679 if (!V.isNegative()) {
8680 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8681 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8683 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8684 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8685 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8689 // copysign(fabs(x), y) -> copysign(x, y)
8690 // copysign(fneg(x), y) -> copysign(x, y)
8691 // copysign(copysign(x,z), y) -> copysign(x, y)
8692 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8693 N0.getOpcode() == ISD::FCOPYSIGN)
8694 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8695 N0.getOperand(0), N1);
8697 // copysign(x, abs(y)) -> abs(x)
8698 if (N1.getOpcode() == ISD::FABS)
8699 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8701 // copysign(x, copysign(y,z)) -> copysign(x, z)
8702 if (N1.getOpcode() == ISD::FCOPYSIGN)
8703 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8704 N0, N1.getOperand(1));
8706 // copysign(x, fp_extend(y)) -> copysign(x, y)
8707 // copysign(x, fp_round(y)) -> copysign(x, y)
8708 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8709 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8710 N0, N1.getOperand(0));
8715 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8716 SDValue N0 = N->getOperand(0);
8717 EVT VT = N->getValueType(0);
8718 EVT OpVT = N0.getValueType();
8720 // fold (sint_to_fp c1) -> c1fp
8721 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8722 // ...but only if the target supports immediate floating-point values
8723 (!LegalOperations ||
8724 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8725 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8727 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8728 // but UINT_TO_FP is legal on this target, try to convert.
8729 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8730 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8731 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8732 if (DAG.SignBitIsZero(N0))
8733 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8736 // The next optimizations are desirable only if SELECT_CC can be lowered.
8737 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8738 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8739 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8741 (!LegalOperations ||
8742 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8745 { N0.getOperand(0), N0.getOperand(1),
8746 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8748 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8751 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8752 // (select_cc x, y, 1.0, 0.0,, cc)
8753 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8754 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8755 (!LegalOperations ||
8756 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8759 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8760 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8761 N0.getOperand(0).getOperand(2) };
8762 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8769 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8770 SDValue N0 = N->getOperand(0);
8771 EVT VT = N->getValueType(0);
8772 EVT OpVT = N0.getValueType();
8774 // fold (uint_to_fp c1) -> c1fp
8775 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8776 // ...but only if the target supports immediate floating-point values
8777 (!LegalOperations ||
8778 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8779 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8781 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8782 // but SINT_TO_FP is legal on this target, try to convert.
8783 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8784 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8785 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8786 if (DAG.SignBitIsZero(N0))
8787 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8790 // The next optimizations are desirable only if SELECT_CC can be lowered.
8791 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8792 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8794 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8795 (!LegalOperations ||
8796 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8799 { N0.getOperand(0), N0.getOperand(1),
8800 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8802 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8809 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8810 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8811 SDValue N0 = N->getOperand(0);
8812 EVT VT = N->getValueType(0);
8814 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8817 SDValue Src = N0.getOperand(0);
8818 EVT SrcVT = Src.getValueType();
8819 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8820 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8822 // We can safely assume the conversion won't overflow the output range,
8823 // because (for example) (uint8_t)18293.f is undefined behavior.
8825 // Since we can assume the conversion won't overflow, our decision as to
8826 // whether the input will fit in the float should depend on the minimum
8827 // of the input range and output range.
8829 // This means this is also safe for a signed input and unsigned output, since
8830 // a negative input would lead to undefined behavior.
8831 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8832 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8833 unsigned ActualSize = std::min(InputSize, OutputSize);
8834 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8836 // We can only fold away the float conversion if the input range can be
8837 // represented exactly in the float range.
8838 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8839 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8840 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8842 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8844 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8845 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8848 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8853 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8854 SDValue N0 = N->getOperand(0);
8855 EVT VT = N->getValueType(0);
8857 // fold (fp_to_sint c1fp) -> c1
8858 if (isConstantFPBuildVectorOrConstantFP(N0))
8859 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8861 return FoldIntToFPToInt(N, DAG);
8864 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8865 SDValue N0 = N->getOperand(0);
8866 EVT VT = N->getValueType(0);
8868 // fold (fp_to_uint c1fp) -> c1
8869 if (isConstantFPBuildVectorOrConstantFP(N0))
8870 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8872 return FoldIntToFPToInt(N, DAG);
8875 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8876 SDValue N0 = N->getOperand(0);
8877 SDValue N1 = N->getOperand(1);
8878 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8879 EVT VT = N->getValueType(0);
8881 // fold (fp_round c1fp) -> c1fp
8883 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8885 // fold (fp_round (fp_extend x)) -> x
8886 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8887 return N0.getOperand(0);
8889 // fold (fp_round (fp_round x)) -> (fp_round x)
8890 if (N0.getOpcode() == ISD::FP_ROUND) {
8891 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8892 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8893 // If the first fp_round isn't a value preserving truncation, it might
8894 // introduce a tie in the second fp_round, that wouldn't occur in the
8895 // single-step fp_round we want to fold to.
8896 // In other words, double rounding isn't the same as rounding.
8897 // Also, this is a value preserving truncation iff both fp_round's are.
8898 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8900 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8901 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8905 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8906 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8907 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8908 N0.getOperand(0), N1);
8909 AddToWorklist(Tmp.getNode());
8910 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8911 Tmp, N0.getOperand(1));
8917 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8918 SDValue N0 = N->getOperand(0);
8919 EVT VT = N->getValueType(0);
8920 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8921 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8923 // fold (fp_round_inreg c1fp) -> c1fp
8924 if (N0CFP && isTypeLegal(EVT)) {
8926 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8927 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8933 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8934 SDValue N0 = N->getOperand(0);
8935 EVT VT = N->getValueType(0);
8937 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8938 if (N->hasOneUse() &&
8939 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8942 // fold (fp_extend c1fp) -> c1fp
8943 if (isConstantFPBuildVectorOrConstantFP(N0))
8944 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8946 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8947 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8948 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8949 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8951 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8953 if (N0.getOpcode() == ISD::FP_ROUND
8954 && N0.getNode()->getConstantOperandVal(1) == 1) {
8955 SDValue In = N0.getOperand(0);
8956 if (In.getValueType() == VT) return In;
8957 if (VT.bitsLT(In.getValueType()))
8958 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8959 In, N0.getOperand(1));
8960 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8963 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8964 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8965 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8966 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8967 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8969 LN0->getBasePtr(), N0.getValueType(),
8970 LN0->getMemOperand());
8971 CombineTo(N, ExtLoad);
8972 CombineTo(N0.getNode(),
8973 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8974 N0.getValueType(), ExtLoad,
8975 DAG.getIntPtrConstant(1, SDLoc(N0))),
8976 ExtLoad.getValue(1));
8977 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8983 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8984 SDValue N0 = N->getOperand(0);
8985 EVT VT = N->getValueType(0);
8987 // fold (fceil c1) -> fceil(c1)
8988 if (isConstantFPBuildVectorOrConstantFP(N0))
8989 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8994 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8995 SDValue N0 = N->getOperand(0);
8996 EVT VT = N->getValueType(0);
8998 // fold (ftrunc c1) -> ftrunc(c1)
8999 if (isConstantFPBuildVectorOrConstantFP(N0))
9000 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9005 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9006 SDValue N0 = N->getOperand(0);
9007 EVT VT = N->getValueType(0);
9009 // fold (ffloor c1) -> ffloor(c1)
9010 if (isConstantFPBuildVectorOrConstantFP(N0))
9011 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9016 // FIXME: FNEG and FABS have a lot in common; refactor.
9017 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9018 SDValue N0 = N->getOperand(0);
9019 EVT VT = N->getValueType(0);
9021 // Constant fold FNEG.
9022 if (isConstantFPBuildVectorOrConstantFP(N0))
9023 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9025 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9026 &DAG.getTarget().Options))
9027 return GetNegatedExpression(N0, DAG, LegalOperations);
9029 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9030 // constant pool values.
9031 if (!TLI.isFNegFree(VT) &&
9032 N0.getOpcode() == ISD::BITCAST &&
9033 N0.getNode()->hasOneUse()) {
9034 SDValue Int = N0.getOperand(0);
9035 EVT IntVT = Int.getValueType();
9036 if (IntVT.isInteger() && !IntVT.isVector()) {
9038 if (N0.getValueType().isVector()) {
9039 // For a vector, get a mask such as 0x80... per scalar element
9041 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9042 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9044 // For a scalar, just generate 0x80...
9045 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9048 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9049 DAG.getConstant(SignMask, DL0, IntVT));
9050 AddToWorklist(Int.getNode());
9051 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9055 // (fneg (fmul c, x)) -> (fmul -c, x)
9056 if (N0.getOpcode() == ISD::FMUL &&
9057 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9058 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9060 APFloat CVal = CFP1->getValueAPF();
9062 if (Level >= AfterLegalizeDAG &&
9063 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9064 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9065 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9066 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9068 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9075 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9076 SDValue N0 = N->getOperand(0);
9077 SDValue N1 = N->getOperand(1);
9078 EVT VT = N->getValueType(0);
9079 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9080 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9082 if (N0CFP && N1CFP) {
9083 const APFloat &C0 = N0CFP->getValueAPF();
9084 const APFloat &C1 = N1CFP->getValueAPF();
9085 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9088 // Canonicalize to constant on RHS.
9089 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9090 !isConstantFPBuildVectorOrConstantFP(N1))
9091 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9096 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9097 SDValue N0 = N->getOperand(0);
9098 SDValue N1 = N->getOperand(1);
9099 EVT VT = N->getValueType(0);
9100 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9101 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9103 if (N0CFP && N1CFP) {
9104 const APFloat &C0 = N0CFP->getValueAPF();
9105 const APFloat &C1 = N1CFP->getValueAPF();
9106 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9109 // Canonicalize to constant on RHS.
9110 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9111 !isConstantFPBuildVectorOrConstantFP(N1))
9112 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9117 SDValue DAGCombiner::visitFABS(SDNode *N) {
9118 SDValue N0 = N->getOperand(0);
9119 EVT VT = N->getValueType(0);
9121 // fold (fabs c1) -> fabs(c1)
9122 if (isConstantFPBuildVectorOrConstantFP(N0))
9123 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9125 // fold (fabs (fabs x)) -> (fabs x)
9126 if (N0.getOpcode() == ISD::FABS)
9127 return N->getOperand(0);
9129 // fold (fabs (fneg x)) -> (fabs x)
9130 // fold (fabs (fcopysign x, y)) -> (fabs x)
9131 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9132 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9134 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9135 // constant pool values.
9136 if (!TLI.isFAbsFree(VT) &&
9137 N0.getOpcode() == ISD::BITCAST &&
9138 N0.getNode()->hasOneUse()) {
9139 SDValue Int = N0.getOperand(0);
9140 EVT IntVT = Int.getValueType();
9141 if (IntVT.isInteger() && !IntVT.isVector()) {
9143 if (N0.getValueType().isVector()) {
9144 // For a vector, get a mask such as 0x7f... per scalar element
9146 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9147 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9149 // For a scalar, just generate 0x7f...
9150 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9153 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9154 DAG.getConstant(SignMask, DL, IntVT));
9155 AddToWorklist(Int.getNode());
9156 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9163 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9164 SDValue Chain = N->getOperand(0);
9165 SDValue N1 = N->getOperand(1);
9166 SDValue N2 = N->getOperand(2);
9168 // If N is a constant we could fold this into a fallthrough or unconditional
9169 // branch. However that doesn't happen very often in normal code, because
9170 // Instcombine/SimplifyCFG should have handled the available opportunities.
9171 // If we did this folding here, it would be necessary to update the
9172 // MachineBasicBlock CFG, which is awkward.
9174 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9176 if (N1.getOpcode() == ISD::SETCC &&
9177 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9178 N1.getOperand(0).getValueType())) {
9179 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9180 Chain, N1.getOperand(2),
9181 N1.getOperand(0), N1.getOperand(1), N2);
9184 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9185 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9186 (N1.getOperand(0).hasOneUse() &&
9187 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9188 SDNode *Trunc = nullptr;
9189 if (N1.getOpcode() == ISD::TRUNCATE) {
9190 // Look pass the truncate.
9191 Trunc = N1.getNode();
9192 N1 = N1.getOperand(0);
9195 // Match this pattern so that we can generate simpler code:
9198 // %b = and i32 %a, 2
9199 // %c = srl i32 %b, 1
9200 // brcond i32 %c ...
9205 // %b = and i32 %a, 2
9206 // %c = setcc eq %b, 0
9209 // This applies only when the AND constant value has one bit set and the
9210 // SRL constant is equal to the log2 of the AND constant. The back-end is
9211 // smart enough to convert the result into a TEST/JMP sequence.
9212 SDValue Op0 = N1.getOperand(0);
9213 SDValue Op1 = N1.getOperand(1);
9215 if (Op0.getOpcode() == ISD::AND &&
9216 Op1.getOpcode() == ISD::Constant) {
9217 SDValue AndOp1 = Op0.getOperand(1);
9219 if (AndOp1.getOpcode() == ISD::Constant) {
9220 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9222 if (AndConst.isPowerOf2() &&
9223 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9227 getSetCCResultType(Op0.getValueType()),
9228 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9231 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9232 MVT::Other, Chain, SetCC, N2);
9233 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9234 // will convert it back to (X & C1) >> C2.
9235 CombineTo(N, NewBRCond, false);
9236 // Truncate is dead.
9238 deleteAndRecombine(Trunc);
9239 // Replace the uses of SRL with SETCC
9240 WorklistRemover DeadNodes(*this);
9241 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9242 deleteAndRecombine(N1.getNode());
9243 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9249 // Restore N1 if the above transformation doesn't match.
9250 N1 = N->getOperand(1);
9253 // Transform br(xor(x, y)) -> br(x != y)
9254 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9255 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9256 SDNode *TheXor = N1.getNode();
9257 SDValue Op0 = TheXor->getOperand(0);
9258 SDValue Op1 = TheXor->getOperand(1);
9259 if (Op0.getOpcode() == Op1.getOpcode()) {
9260 // Avoid missing important xor optimizations.
9261 if (SDValue Tmp = visitXOR(TheXor)) {
9262 if (Tmp.getNode() != TheXor) {
9263 DEBUG(dbgs() << "\nReplacing.8 ";
9265 dbgs() << "\nWith: ";
9266 Tmp.getNode()->dump(&DAG);
9268 WorklistRemover DeadNodes(*this);
9269 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9270 deleteAndRecombine(TheXor);
9271 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9272 MVT::Other, Chain, Tmp, N2);
9275 // visitXOR has changed XOR's operands or replaced the XOR completely,
9277 return SDValue(N, 0);
9281 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9283 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9284 Op0.getOpcode() == ISD::XOR) {
9285 TheXor = Op0.getNode();
9289 EVT SetCCVT = N1.getValueType();
9291 SetCCVT = getSetCCResultType(SetCCVT);
9292 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9295 Equal ? ISD::SETEQ : ISD::SETNE);
9296 // Replace the uses of XOR with SETCC
9297 WorklistRemover DeadNodes(*this);
9298 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9299 deleteAndRecombine(N1.getNode());
9300 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9301 MVT::Other, Chain, SetCC, N2);
9308 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9310 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9311 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9312 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9314 // If N is a constant we could fold this into a fallthrough or unconditional
9315 // branch. However that doesn't happen very often in normal code, because
9316 // Instcombine/SimplifyCFG should have handled the available opportunities.
9317 // If we did this folding here, it would be necessary to update the
9318 // MachineBasicBlock CFG, which is awkward.
9320 // Use SimplifySetCC to simplify SETCC's.
9321 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9322 CondLHS, CondRHS, CC->get(), SDLoc(N),
9324 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9326 // fold to a simpler setcc
9327 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9328 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9329 N->getOperand(0), Simp.getOperand(2),
9330 Simp.getOperand(0), Simp.getOperand(1),
9336 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9337 /// and that N may be folded in the load / store addressing mode.
9338 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9340 const TargetLowering &TLI) {
9344 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9345 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9347 VT = LD->getMemoryVT();
9348 AS = LD->getAddressSpace();
9349 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9350 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9352 VT = ST->getMemoryVT();
9353 AS = ST->getAddressSpace();
9357 TargetLowering::AddrMode AM;
9358 if (N->getOpcode() == ISD::ADD) {
9359 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9362 AM.BaseOffs = Offset->getSExtValue();
9366 } else if (N->getOpcode() == ISD::SUB) {
9367 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9370 AM.BaseOffs = -Offset->getSExtValue();
9377 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9378 VT.getTypeForEVT(*DAG.getContext()), AS);
9381 /// Try turning a load/store into a pre-indexed load/store when the base
9382 /// pointer is an add or subtract and it has other uses besides the load/store.
9383 /// After the transformation, the new indexed load/store has effectively folded
9384 /// the add/subtract in and all of its other uses are redirected to the
9386 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9387 if (Level < AfterLegalizeDAG)
9393 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9394 if (LD->isIndexed())
9396 VT = LD->getMemoryVT();
9397 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9398 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9400 Ptr = LD->getBasePtr();
9401 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9402 if (ST->isIndexed())
9404 VT = ST->getMemoryVT();
9405 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9406 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9408 Ptr = ST->getBasePtr();
9414 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9415 // out. There is no reason to make this a preinc/predec.
9416 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9417 Ptr.getNode()->hasOneUse())
9420 // Ask the target to do addressing mode selection.
9423 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9424 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9427 // Backends without true r+i pre-indexed forms may need to pass a
9428 // constant base with a variable offset so that constant coercion
9429 // will work with the patterns in canonical form.
9430 bool Swapped = false;
9431 if (isa<ConstantSDNode>(BasePtr)) {
9432 std::swap(BasePtr, Offset);
9436 // Don't create a indexed load / store with zero offset.
9437 if (isNullConstant(Offset))
9440 // Try turning it into a pre-indexed load / store except when:
9441 // 1) The new base ptr is a frame index.
9442 // 2) If N is a store and the new base ptr is either the same as or is a
9443 // predecessor of the value being stored.
9444 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9445 // that would create a cycle.
9446 // 4) All uses are load / store ops that use it as old base ptr.
9448 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9449 // (plus the implicit offset) to a register to preinc anyway.
9450 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9455 SDValue Val = cast<StoreSDNode>(N)->getValue();
9456 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9460 // If the offset is a constant, there may be other adds of constants that
9461 // can be folded with this one. We should do this to avoid having to keep
9462 // a copy of the original base pointer.
9463 SmallVector<SDNode *, 16> OtherUses;
9464 if (isa<ConstantSDNode>(Offset))
9465 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9466 UE = BasePtr.getNode()->use_end();
9468 SDUse &Use = UI.getUse();
9469 // Skip the use that is Ptr and uses of other results from BasePtr's
9470 // node (important for nodes that return multiple results).
9471 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9474 if (Use.getUser()->isPredecessorOf(N))
9477 if (Use.getUser()->getOpcode() != ISD::ADD &&
9478 Use.getUser()->getOpcode() != ISD::SUB) {
9483 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9484 if (!isa<ConstantSDNode>(Op1)) {
9489 // FIXME: In some cases, we can be smarter about this.
9490 if (Op1.getValueType() != Offset.getValueType()) {
9495 OtherUses.push_back(Use.getUser());
9499 std::swap(BasePtr, Offset);
9501 // Now check for #3 and #4.
9502 bool RealUse = false;
9504 // Caches for hasPredecessorHelper
9505 SmallPtrSet<const SDNode *, 32> Visited;
9506 SmallVector<const SDNode *, 16> Worklist;
9508 for (SDNode *Use : Ptr.getNode()->uses()) {
9511 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9514 // If Ptr may be folded in addressing mode of other use, then it's
9515 // not profitable to do this transformation.
9516 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9525 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9526 BasePtr, Offset, AM);
9528 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9529 BasePtr, Offset, AM);
9532 DEBUG(dbgs() << "\nReplacing.4 ";
9534 dbgs() << "\nWith: ";
9535 Result.getNode()->dump(&DAG);
9537 WorklistRemover DeadNodes(*this);
9539 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9540 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9542 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9545 // Finally, since the node is now dead, remove it from the graph.
9546 deleteAndRecombine(N);
9549 std::swap(BasePtr, Offset);
9551 // Replace other uses of BasePtr that can be updated to use Ptr
9552 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9553 unsigned OffsetIdx = 1;
9554 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9556 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9557 BasePtr.getNode() && "Expected BasePtr operand");
9559 // We need to replace ptr0 in the following expression:
9560 // x0 * offset0 + y0 * ptr0 = t0
9562 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9564 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9565 // indexed load/store and the expresion that needs to be re-written.
9567 // Therefore, we have:
9568 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9570 ConstantSDNode *CN =
9571 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9573 APInt Offset0 = CN->getAPIntValue();
9574 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9576 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9577 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9578 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9579 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9581 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9583 APInt CNV = Offset0;
9584 if (X0 < 0) CNV = -CNV;
9585 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9586 else CNV = CNV - Offset1;
9588 SDLoc DL(OtherUses[i]);
9590 // We can now generate the new expression.
9591 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9592 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9594 SDValue NewUse = DAG.getNode(Opcode,
9596 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9597 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9598 deleteAndRecombine(OtherUses[i]);
9601 // Replace the uses of Ptr with uses of the updated base value.
9602 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9603 deleteAndRecombine(Ptr.getNode());
9608 /// Try to combine a load/store with a add/sub of the base pointer node into a
9609 /// post-indexed load/store. The transformation folded the add/subtract into the
9610 /// new indexed load/store effectively and all of its uses are redirected to the
9612 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9613 if (Level < AfterLegalizeDAG)
9619 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9620 if (LD->isIndexed())
9622 VT = LD->getMemoryVT();
9623 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9624 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9626 Ptr = LD->getBasePtr();
9627 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9628 if (ST->isIndexed())
9630 VT = ST->getMemoryVT();
9631 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9632 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9634 Ptr = ST->getBasePtr();
9640 if (Ptr.getNode()->hasOneUse())
9643 for (SDNode *Op : Ptr.getNode()->uses()) {
9645 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9650 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9651 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9652 // Don't create a indexed load / store with zero offset.
9653 if (isNullConstant(Offset))
9656 // Try turning it into a post-indexed load / store except when
9657 // 1) All uses are load / store ops that use it as base ptr (and
9658 // it may be folded as addressing mmode).
9659 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9660 // nor a successor of N. Otherwise, if Op is folded that would
9663 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9667 bool TryNext = false;
9668 for (SDNode *Use : BasePtr.getNode()->uses()) {
9669 if (Use == Ptr.getNode())
9672 // If all the uses are load / store addresses, then don't do the
9674 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9675 bool RealUse = false;
9676 for (SDNode *UseUse : Use->uses()) {
9677 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9692 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9693 SDValue Result = isLoad
9694 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9695 BasePtr, Offset, AM)
9696 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9697 BasePtr, Offset, AM);
9700 DEBUG(dbgs() << "\nReplacing.5 ";
9702 dbgs() << "\nWith: ";
9703 Result.getNode()->dump(&DAG);
9705 WorklistRemover DeadNodes(*this);
9707 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9708 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9710 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9713 // Finally, since the node is now dead, remove it from the graph.
9714 deleteAndRecombine(N);
9716 // Replace the uses of Use with uses of the updated base value.
9717 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9718 Result.getValue(isLoad ? 1 : 0));
9719 deleteAndRecombine(Op);
9728 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9729 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9730 ISD::MemIndexedMode AM = LD->getAddressingMode();
9731 assert(AM != ISD::UNINDEXED);
9732 SDValue BP = LD->getOperand(1);
9733 SDValue Inc = LD->getOperand(2);
9735 // Some backends use TargetConstants for load offsets, but don't expect
9736 // TargetConstants in general ADD nodes. We can convert these constants into
9737 // regular Constants (if the constant is not opaque).
9738 assert((Inc.getOpcode() != ISD::TargetConstant ||
9739 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9740 "Cannot split out indexing using opaque target constants");
9741 if (Inc.getOpcode() == ISD::TargetConstant) {
9742 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9743 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9744 ConstInc->getValueType(0));
9748 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9749 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9752 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9753 LoadSDNode *LD = cast<LoadSDNode>(N);
9754 SDValue Chain = LD->getChain();
9755 SDValue Ptr = LD->getBasePtr();
9757 // If load is not volatile and there are no uses of the loaded value (and
9758 // the updated indexed value in case of indexed loads), change uses of the
9759 // chain value into uses of the chain input (i.e. delete the dead load).
9760 if (!LD->isVolatile()) {
9761 if (N->getValueType(1) == MVT::Other) {
9763 if (!N->hasAnyUseOfValue(0)) {
9764 // It's not safe to use the two value CombineTo variant here. e.g.
9765 // v1, chain2 = load chain1, loc
9766 // v2, chain3 = load chain2, loc
9768 // Now we replace use of chain2 with chain1. This makes the second load
9769 // isomorphic to the one we are deleting, and thus makes this load live.
9770 DEBUG(dbgs() << "\nReplacing.6 ";
9772 dbgs() << "\nWith chain: ";
9773 Chain.getNode()->dump(&DAG);
9775 WorklistRemover DeadNodes(*this);
9776 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9779 deleteAndRecombine(N);
9781 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9785 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9787 // If this load has an opaque TargetConstant offset, then we cannot split
9788 // the indexing into an add/sub directly (that TargetConstant may not be
9789 // valid for a different type of node, and we cannot convert an opaque
9790 // target constant into a regular constant).
9791 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9792 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9794 if (!N->hasAnyUseOfValue(0) &&
9795 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9796 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9798 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9799 Index = SplitIndexingFromLoad(LD);
9800 // Try to fold the base pointer arithmetic into subsequent loads and
9802 AddUsersToWorklist(N);
9804 Index = DAG.getUNDEF(N->getValueType(1));
9805 DEBUG(dbgs() << "\nReplacing.7 ";
9807 dbgs() << "\nWith: ";
9808 Undef.getNode()->dump(&DAG);
9809 dbgs() << " and 2 other values\n");
9810 WorklistRemover DeadNodes(*this);
9811 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9812 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9813 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9814 deleteAndRecombine(N);
9815 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9820 // If this load is directly stored, replace the load value with the stored
9822 // TODO: Handle store large -> read small portion.
9823 // TODO: Handle TRUNCSTORE/LOADEXT
9824 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9825 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9826 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9827 if (PrevST->getBasePtr() == Ptr &&
9828 PrevST->getValue().getValueType() == N->getValueType(0))
9829 return CombineTo(N, Chain.getOperand(1), Chain);
9833 // Try to infer better alignment information than the load already has.
9834 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9835 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9836 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9838 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9839 LD->getValueType(0),
9840 Chain, Ptr, LD->getPointerInfo(),
9842 LD->isVolatile(), LD->isNonTemporal(),
9843 LD->isInvariant(), Align, LD->getAAInfo());
9844 if (NewLoad.getNode() != N)
9845 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9850 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9851 : DAG.getSubtarget().useAA();
9853 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9854 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9857 if (UseAA && LD->isUnindexed()) {
9858 // Walk up chain skipping non-aliasing memory nodes.
9859 SDValue BetterChain = FindBetterChain(N, Chain);
9861 // If there is a better chain.
9862 if (Chain != BetterChain) {
9865 // Replace the chain to void dependency.
9866 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9867 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9868 BetterChain, Ptr, LD->getMemOperand());
9870 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9871 LD->getValueType(0),
9872 BetterChain, Ptr, LD->getMemoryVT(),
9873 LD->getMemOperand());
9876 // Create token factor to keep old chain connected.
9877 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9878 MVT::Other, Chain, ReplLoad.getValue(1));
9880 // Make sure the new and old chains are cleaned up.
9881 AddToWorklist(Token.getNode());
9883 // Replace uses with load result and token factor. Don't add users
9885 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9889 // Try transforming N to an indexed load.
9890 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9891 return SDValue(N, 0);
9893 // Try to slice up N to more direct loads if the slices are mapped to
9894 // different register banks or pairing can take place.
9896 return SDValue(N, 0);
9902 /// \brief Helper structure used to slice a load in smaller loads.
9903 /// Basically a slice is obtained from the following sequence:
9904 /// Origin = load Ty1, Base
9905 /// Shift = srl Ty1 Origin, CstTy Amount
9906 /// Inst = trunc Shift to Ty2
9908 /// Then, it will be rewriten into:
9909 /// Slice = load SliceTy, Base + SliceOffset
9910 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9912 /// SliceTy is deduced from the number of bits that are actually used to
9914 struct LoadedSlice {
9915 /// \brief Helper structure used to compute the cost of a slice.
9917 /// Are we optimizing for code size.
9922 unsigned CrossRegisterBanksCopies;
9926 Cost(bool ForCodeSize = false)
9927 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9928 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9930 /// \brief Get the cost of one isolated slice.
9931 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9932 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9933 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9934 EVT TruncType = LS.Inst->getValueType(0);
9935 EVT LoadedType = LS.getLoadedType();
9936 if (TruncType != LoadedType &&
9937 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9941 /// \brief Account for slicing gain in the current cost.
9942 /// Slicing provide a few gains like removing a shift or a
9943 /// truncate. This method allows to grow the cost of the original
9944 /// load with the gain from this slice.
9945 void addSliceGain(const LoadedSlice &LS) {
9946 // Each slice saves a truncate.
9947 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9948 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9949 LS.Inst->getValueType(0)))
9951 // If there is a shift amount, this slice gets rid of it.
9954 // If this slice can merge a cross register bank copy, account for it.
9955 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9956 ++CrossRegisterBanksCopies;
9959 Cost &operator+=(const Cost &RHS) {
9961 Truncates += RHS.Truncates;
9962 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9968 bool operator==(const Cost &RHS) const {
9969 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9970 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9971 ZExts == RHS.ZExts && Shift == RHS.Shift;
9974 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9976 bool operator<(const Cost &RHS) const {
9977 // Assume cross register banks copies are as expensive as loads.
9978 // FIXME: Do we want some more target hooks?
9979 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9980 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9981 // Unless we are optimizing for code size, consider the
9982 // expensive operation first.
9983 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9984 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9985 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9986 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9989 bool operator>(const Cost &RHS) const { return RHS < *this; }
9991 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9993 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9995 // The last instruction that represent the slice. This should be a
9996 // truncate instruction.
9998 // The original load instruction.
10000 // The right shift amount in bits from the original load.
10002 // The DAG from which Origin came from.
10003 // This is used to get some contextual information about legal types, etc.
10006 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10007 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10008 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10010 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10011 /// \return Result is \p BitWidth and has used bits set to 1 and
10012 /// not used bits set to 0.
10013 APInt getUsedBits() const {
10014 // Reproduce the trunc(lshr) sequence:
10015 // - Start from the truncated value.
10016 // - Zero extend to the desired bit width.
10018 assert(Origin && "No original load to compare against.");
10019 unsigned BitWidth = Origin->getValueSizeInBits(0);
10020 assert(Inst && "This slice is not bound to an instruction");
10021 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10022 "Extracted slice is bigger than the whole type!");
10023 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10024 UsedBits.setAllBits();
10025 UsedBits = UsedBits.zext(BitWidth);
10026 UsedBits <<= Shift;
10030 /// \brief Get the size of the slice to be loaded in bytes.
10031 unsigned getLoadedSize() const {
10032 unsigned SliceSize = getUsedBits().countPopulation();
10033 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10034 return SliceSize / 8;
10037 /// \brief Get the type that will be loaded for this slice.
10038 /// Note: This may not be the final type for the slice.
10039 EVT getLoadedType() const {
10040 assert(DAG && "Missing context");
10041 LLVMContext &Ctxt = *DAG->getContext();
10042 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10045 /// \brief Get the alignment of the load used for this slice.
10046 unsigned getAlignment() const {
10047 unsigned Alignment = Origin->getAlignment();
10048 unsigned Offset = getOffsetFromBase();
10050 Alignment = MinAlign(Alignment, Alignment + Offset);
10054 /// \brief Check if this slice can be rewritten with legal operations.
10055 bool isLegal() const {
10056 // An invalid slice is not legal.
10057 if (!Origin || !Inst || !DAG)
10060 // Offsets are for indexed load only, we do not handle that.
10061 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10064 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10066 // Check that the type is legal.
10067 EVT SliceType = getLoadedType();
10068 if (!TLI.isTypeLegal(SliceType))
10071 // Check that the load is legal for this type.
10072 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10075 // Check that the offset can be computed.
10076 // 1. Check its type.
10077 EVT PtrType = Origin->getBasePtr().getValueType();
10078 if (PtrType == MVT::Untyped || PtrType.isExtended())
10081 // 2. Check that it fits in the immediate.
10082 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10085 // 3. Check that the computation is legal.
10086 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10089 // Check that the zext is legal if it needs one.
10090 EVT TruncateType = Inst->getValueType(0);
10091 if (TruncateType != SliceType &&
10092 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10098 /// \brief Get the offset in bytes of this slice in the original chunk of
10100 /// \pre DAG != nullptr.
10101 uint64_t getOffsetFromBase() const {
10102 assert(DAG && "Missing context.");
10103 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10104 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10105 uint64_t Offset = Shift / 8;
10106 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10107 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10108 "The size of the original loaded type is not a multiple of a"
10110 // If Offset is bigger than TySizeInBytes, it means we are loading all
10111 // zeros. This should have been optimized before in the process.
10112 assert(TySizeInBytes > Offset &&
10113 "Invalid shift amount for given loaded size");
10115 Offset = TySizeInBytes - Offset - getLoadedSize();
10119 /// \brief Generate the sequence of instructions to load the slice
10120 /// represented by this object and redirect the uses of this slice to
10121 /// this new sequence of instructions.
10122 /// \pre this->Inst && this->Origin are valid Instructions and this
10123 /// object passed the legal check: LoadedSlice::isLegal returned true.
10124 /// \return The last instruction of the sequence used to load the slice.
10125 SDValue loadSlice() const {
10126 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10127 const SDValue &OldBaseAddr = Origin->getBasePtr();
10128 SDValue BaseAddr = OldBaseAddr;
10129 // Get the offset in that chunk of bytes w.r.t. the endianess.
10130 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10131 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10133 // BaseAddr = BaseAddr + Offset.
10134 EVT ArithType = BaseAddr.getValueType();
10136 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10137 DAG->getConstant(Offset, DL, ArithType));
10140 // Create the type of the loaded slice according to its size.
10141 EVT SliceType = getLoadedType();
10143 // Create the load for the slice.
10144 SDValue LastInst = DAG->getLoad(
10145 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10146 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10147 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10148 // If the final type is not the same as the loaded type, this means that
10149 // we have to pad with zero. Create a zero extend for that.
10150 EVT FinalType = Inst->getValueType(0);
10151 if (SliceType != FinalType)
10153 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10157 /// \brief Check if this slice can be merged with an expensive cross register
10158 /// bank copy. E.g.,
10160 /// f = bitcast i32 i to float
10161 bool canMergeExpensiveCrossRegisterBankCopy() const {
10162 if (!Inst || !Inst->hasOneUse())
10164 SDNode *Use = *Inst->use_begin();
10165 if (Use->getOpcode() != ISD::BITCAST)
10167 assert(DAG && "Missing context");
10168 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10169 EVT ResVT = Use->getValueType(0);
10170 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10171 const TargetRegisterClass *ArgRC =
10172 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10173 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10176 // At this point, we know that we perform a cross-register-bank copy.
10177 // Check if it is expensive.
10178 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10179 // Assume bitcasts are cheap, unless both register classes do not
10180 // explicitly share a common sub class.
10181 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10184 // Check if it will be merged with the load.
10185 // 1. Check the alignment constraint.
10186 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10187 ResVT.getTypeForEVT(*DAG->getContext()));
10189 if (RequiredAlignment > getAlignment())
10192 // 2. Check that the load is a legal operation for that type.
10193 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10196 // 3. Check that we do not have a zext in the way.
10197 if (Inst->getValueType(0) != getLoadedType())
10205 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10206 /// \p UsedBits looks like 0..0 1..1 0..0.
10207 static bool areUsedBitsDense(const APInt &UsedBits) {
10208 // If all the bits are one, this is dense!
10209 if (UsedBits.isAllOnesValue())
10212 // Get rid of the unused bits on the right.
10213 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10214 // Get rid of the unused bits on the left.
10215 if (NarrowedUsedBits.countLeadingZeros())
10216 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10217 // Check that the chunk of bits is completely used.
10218 return NarrowedUsedBits.isAllOnesValue();
10221 /// \brief Check whether or not \p First and \p Second are next to each other
10222 /// in memory. This means that there is no hole between the bits loaded
10223 /// by \p First and the bits loaded by \p Second.
10224 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10225 const LoadedSlice &Second) {
10226 assert(First.Origin == Second.Origin && First.Origin &&
10227 "Unable to match different memory origins.");
10228 APInt UsedBits = First.getUsedBits();
10229 assert((UsedBits & Second.getUsedBits()) == 0 &&
10230 "Slices are not supposed to overlap.");
10231 UsedBits |= Second.getUsedBits();
10232 return areUsedBitsDense(UsedBits);
10235 /// \brief Adjust the \p GlobalLSCost according to the target
10236 /// paring capabilities and the layout of the slices.
10237 /// \pre \p GlobalLSCost should account for at least as many loads as
10238 /// there is in the slices in \p LoadedSlices.
10239 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10240 LoadedSlice::Cost &GlobalLSCost) {
10241 unsigned NumberOfSlices = LoadedSlices.size();
10242 // If there is less than 2 elements, no pairing is possible.
10243 if (NumberOfSlices < 2)
10246 // Sort the slices so that elements that are likely to be next to each
10247 // other in memory are next to each other in the list.
10248 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10249 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10250 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10251 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10253 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10254 // First (resp. Second) is the first (resp. Second) potentially candidate
10255 // to be placed in a paired load.
10256 const LoadedSlice *First = nullptr;
10257 const LoadedSlice *Second = nullptr;
10258 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10259 // Set the beginning of the pair.
10262 Second = &LoadedSlices[CurrSlice];
10264 // If First is NULL, it means we start a new pair.
10265 // Get to the next slice.
10269 EVT LoadedType = First->getLoadedType();
10271 // If the types of the slices are different, we cannot pair them.
10272 if (LoadedType != Second->getLoadedType())
10275 // Check if the target supplies paired loads for this type.
10276 unsigned RequiredAlignment = 0;
10277 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10278 // move to the next pair, this type is hopeless.
10282 // Check if we meet the alignment requirement.
10283 if (RequiredAlignment > First->getAlignment())
10286 // Check that both loads are next to each other in memory.
10287 if (!areSlicesNextToEachOther(*First, *Second))
10290 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10291 --GlobalLSCost.Loads;
10292 // Move to the next pair.
10297 /// \brief Check the profitability of all involved LoadedSlice.
10298 /// Currently, it is considered profitable if there is exactly two
10299 /// involved slices (1) which are (2) next to each other in memory, and
10300 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10302 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10303 /// the elements themselves.
10305 /// FIXME: When the cost model will be mature enough, we can relax
10306 /// constraints (1) and (2).
10307 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10308 const APInt &UsedBits, bool ForCodeSize) {
10309 unsigned NumberOfSlices = LoadedSlices.size();
10310 if (StressLoadSlicing)
10311 return NumberOfSlices > 1;
10314 if (NumberOfSlices != 2)
10318 if (!areUsedBitsDense(UsedBits))
10322 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10323 // The original code has one big load.
10324 OrigCost.Loads = 1;
10325 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10326 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10327 // Accumulate the cost of all the slices.
10328 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10329 GlobalSlicingCost += SliceCost;
10331 // Account as cost in the original configuration the gain obtained
10332 // with the current slices.
10333 OrigCost.addSliceGain(LS);
10336 // If the target supports paired load, adjust the cost accordingly.
10337 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10338 return OrigCost > GlobalSlicingCost;
10341 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10342 /// operations, split it in the various pieces being extracted.
10344 /// This sort of thing is introduced by SROA.
10345 /// This slicing takes care not to insert overlapping loads.
10346 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10347 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10348 if (Level < AfterLegalizeDAG)
10351 LoadSDNode *LD = cast<LoadSDNode>(N);
10352 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10353 !LD->getValueType(0).isInteger())
10356 // Keep track of already used bits to detect overlapping values.
10357 // In that case, we will just abort the transformation.
10358 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10360 SmallVector<LoadedSlice, 4> LoadedSlices;
10362 // Check if this load is used as several smaller chunks of bits.
10363 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10364 // of computation for each trunc.
10365 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10366 UI != UIEnd; ++UI) {
10367 // Skip the uses of the chain.
10368 if (UI.getUse().getResNo() != 0)
10371 SDNode *User = *UI;
10372 unsigned Shift = 0;
10374 // Check if this is a trunc(lshr).
10375 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10376 isa<ConstantSDNode>(User->getOperand(1))) {
10377 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10378 User = *User->use_begin();
10381 // At this point, User is a Truncate, iff we encountered, trunc or
10383 if (User->getOpcode() != ISD::TRUNCATE)
10386 // The width of the type must be a power of 2 and greater than 8-bits.
10387 // Otherwise the load cannot be represented in LLVM IR.
10388 // Moreover, if we shifted with a non-8-bits multiple, the slice
10389 // will be across several bytes. We do not support that.
10390 unsigned Width = User->getValueSizeInBits(0);
10391 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10394 // Build the slice for this chain of computations.
10395 LoadedSlice LS(User, LD, Shift, &DAG);
10396 APInt CurrentUsedBits = LS.getUsedBits();
10398 // Check if this slice overlaps with another.
10399 if ((CurrentUsedBits & UsedBits) != 0)
10401 // Update the bits used globally.
10402 UsedBits |= CurrentUsedBits;
10404 // Check if the new slice would be legal.
10408 // Record the slice.
10409 LoadedSlices.push_back(LS);
10412 // Abort slicing if it does not seem to be profitable.
10413 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10418 // Rewrite each chain to use an independent load.
10419 // By construction, each chain can be represented by a unique load.
10421 // Prepare the argument for the new token factor for all the slices.
10422 SmallVector<SDValue, 8> ArgChains;
10423 for (SmallVectorImpl<LoadedSlice>::const_iterator
10424 LSIt = LoadedSlices.begin(),
10425 LSItEnd = LoadedSlices.end();
10426 LSIt != LSItEnd; ++LSIt) {
10427 SDValue SliceInst = LSIt->loadSlice();
10428 CombineTo(LSIt->Inst, SliceInst, true);
10429 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10430 SliceInst = SliceInst.getOperand(0);
10431 assert(SliceInst->getOpcode() == ISD::LOAD &&
10432 "It takes more than a zext to get to the loaded slice!!");
10433 ArgChains.push_back(SliceInst.getValue(1));
10436 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10438 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10442 /// Check to see if V is (and load (ptr), imm), where the load is having
10443 /// specific bytes cleared out. If so, return the byte size being masked out
10444 /// and the shift amount.
10445 static std::pair<unsigned, unsigned>
10446 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10447 std::pair<unsigned, unsigned> Result(0, 0);
10449 // Check for the structure we're looking for.
10450 if (V->getOpcode() != ISD::AND ||
10451 !isa<ConstantSDNode>(V->getOperand(1)) ||
10452 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10455 // Check the chain and pointer.
10456 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10457 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10459 // The store should be chained directly to the load or be an operand of a
10461 if (LD == Chain.getNode())
10463 else if (Chain->getOpcode() != ISD::TokenFactor)
10464 return Result; // Fail.
10467 for (const SDValue &ChainOp : Chain->op_values())
10468 if (ChainOp.getNode() == LD) {
10472 if (!isOk) return Result;
10475 // This only handles simple types.
10476 if (V.getValueType() != MVT::i16 &&
10477 V.getValueType() != MVT::i32 &&
10478 V.getValueType() != MVT::i64)
10481 // Check the constant mask. Invert it so that the bits being masked out are
10482 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10483 // follow the sign bit for uniformity.
10484 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10485 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10486 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10487 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10488 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10489 if (NotMaskLZ == 64) return Result; // All zero mask.
10491 // See if we have a continuous run of bits. If so, we have 0*1+0*
10492 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10495 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10496 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10497 NotMaskLZ -= 64-V.getValueSizeInBits();
10499 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10500 switch (MaskedBytes) {
10504 default: return Result; // All one mask, or 5-byte mask.
10507 // Verify that the first bit starts at a multiple of mask so that the access
10508 // is aligned the same as the access width.
10509 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10511 Result.first = MaskedBytes;
10512 Result.second = NotMaskTZ/8;
10517 /// Check to see if IVal is something that provides a value as specified by
10518 /// MaskInfo. If so, replace the specified store with a narrower store of
10519 /// truncated IVal.
10521 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10522 SDValue IVal, StoreSDNode *St,
10524 unsigned NumBytes = MaskInfo.first;
10525 unsigned ByteShift = MaskInfo.second;
10526 SelectionDAG &DAG = DC->getDAG();
10528 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10529 // that uses this. If not, this is not a replacement.
10530 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10531 ByteShift*8, (ByteShift+NumBytes)*8);
10532 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10534 // Check that it is legal on the target to do this. It is legal if the new
10535 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10537 MVT VT = MVT::getIntegerVT(NumBytes*8);
10538 if (!DC->isTypeLegal(VT))
10541 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10542 // shifted by ByteShift and truncated down to NumBytes.
10545 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10546 DAG.getConstant(ByteShift*8, DL,
10547 DC->getShiftAmountTy(IVal.getValueType())));
10550 // Figure out the offset for the store and the alignment of the access.
10552 unsigned NewAlign = St->getAlignment();
10554 if (DAG.getDataLayout().isLittleEndian())
10555 StOffset = ByteShift;
10557 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10559 SDValue Ptr = St->getBasePtr();
10562 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10563 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10564 NewAlign = MinAlign(NewAlign, StOffset);
10567 // Truncate down to the new size.
10568 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10571 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10572 St->getPointerInfo().getWithOffset(StOffset),
10573 false, false, NewAlign).getNode();
10577 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10578 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10579 /// narrowing the load and store if it would end up being a win for performance
10581 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10582 StoreSDNode *ST = cast<StoreSDNode>(N);
10583 if (ST->isVolatile())
10586 SDValue Chain = ST->getChain();
10587 SDValue Value = ST->getValue();
10588 SDValue Ptr = ST->getBasePtr();
10589 EVT VT = Value.getValueType();
10591 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10594 unsigned Opc = Value.getOpcode();
10596 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10597 // is a byte mask indicating a consecutive number of bytes, check to see if
10598 // Y is known to provide just those bytes. If so, we try to replace the
10599 // load + replace + store sequence with a single (narrower) store, which makes
10601 if (Opc == ISD::OR) {
10602 std::pair<unsigned, unsigned> MaskedLoad;
10603 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10604 if (MaskedLoad.first)
10605 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10606 Value.getOperand(1), ST,this))
10607 return SDValue(NewST, 0);
10609 // Or is commutative, so try swapping X and Y.
10610 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10611 if (MaskedLoad.first)
10612 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10613 Value.getOperand(0), ST,this))
10614 return SDValue(NewST, 0);
10617 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10618 Value.getOperand(1).getOpcode() != ISD::Constant)
10621 SDValue N0 = Value.getOperand(0);
10622 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10623 Chain == SDValue(N0.getNode(), 1)) {
10624 LoadSDNode *LD = cast<LoadSDNode>(N0);
10625 if (LD->getBasePtr() != Ptr ||
10626 LD->getPointerInfo().getAddrSpace() !=
10627 ST->getPointerInfo().getAddrSpace())
10630 // Find the type to narrow it the load / op / store to.
10631 SDValue N1 = Value.getOperand(1);
10632 unsigned BitWidth = N1.getValueSizeInBits();
10633 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10634 if (Opc == ISD::AND)
10635 Imm ^= APInt::getAllOnesValue(BitWidth);
10636 if (Imm == 0 || Imm.isAllOnesValue())
10638 unsigned ShAmt = Imm.countTrailingZeros();
10639 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10640 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10641 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10642 // The narrowing should be profitable, the load/store operation should be
10643 // legal (or custom) and the store size should be equal to the NewVT width.
10644 while (NewBW < BitWidth &&
10645 (NewVT.getStoreSizeInBits() != NewBW ||
10646 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10647 !TLI.isNarrowingProfitable(VT, NewVT))) {
10648 NewBW = NextPowerOf2(NewBW);
10649 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10651 if (NewBW >= BitWidth)
10654 // If the lsb changed does not start at the type bitwidth boundary,
10655 // start at the previous one.
10657 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10658 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10659 std::min(BitWidth, ShAmt + NewBW));
10660 if ((Imm & Mask) == Imm) {
10661 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10662 if (Opc == ISD::AND)
10663 NewImm ^= APInt::getAllOnesValue(NewBW);
10664 uint64_t PtrOff = ShAmt / 8;
10665 // For big endian targets, we need to adjust the offset to the pointer to
10666 // load the correct bytes.
10667 if (DAG.getDataLayout().isBigEndian())
10668 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10670 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10671 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10672 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10675 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10676 Ptr.getValueType(), Ptr,
10677 DAG.getConstant(PtrOff, SDLoc(LD),
10678 Ptr.getValueType()));
10679 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10680 LD->getChain(), NewPtr,
10681 LD->getPointerInfo().getWithOffset(PtrOff),
10682 LD->isVolatile(), LD->isNonTemporal(),
10683 LD->isInvariant(), NewAlign,
10685 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10686 DAG.getConstant(NewImm, SDLoc(Value),
10688 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10690 ST->getPointerInfo().getWithOffset(PtrOff),
10691 false, false, NewAlign);
10693 AddToWorklist(NewPtr.getNode());
10694 AddToWorklist(NewLD.getNode());
10695 AddToWorklist(NewVal.getNode());
10696 WorklistRemover DeadNodes(*this);
10697 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10706 /// For a given floating point load / store pair, if the load value isn't used
10707 /// by any other operations, then consider transforming the pair to integer
10708 /// load / store operations if the target deems the transformation profitable.
10709 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10710 StoreSDNode *ST = cast<StoreSDNode>(N);
10711 SDValue Chain = ST->getChain();
10712 SDValue Value = ST->getValue();
10713 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10714 Value.hasOneUse() &&
10715 Chain == SDValue(Value.getNode(), 1)) {
10716 LoadSDNode *LD = cast<LoadSDNode>(Value);
10717 EVT VT = LD->getMemoryVT();
10718 if (!VT.isFloatingPoint() ||
10719 VT != ST->getMemoryVT() ||
10720 LD->isNonTemporal() ||
10721 ST->isNonTemporal() ||
10722 LD->getPointerInfo().getAddrSpace() != 0 ||
10723 ST->getPointerInfo().getAddrSpace() != 0)
10726 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10727 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10728 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10729 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10730 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10733 unsigned LDAlign = LD->getAlignment();
10734 unsigned STAlign = ST->getAlignment();
10735 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10736 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10737 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10740 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10741 LD->getChain(), LD->getBasePtr(),
10742 LD->getPointerInfo(),
10743 false, false, false, LDAlign);
10745 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10746 NewLD, ST->getBasePtr(),
10747 ST->getPointerInfo(),
10748 false, false, STAlign);
10750 AddToWorklist(NewLD.getNode());
10751 AddToWorklist(NewST.getNode());
10752 WorklistRemover DeadNodes(*this);
10753 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10762 /// Helper struct to parse and store a memory address as base + index + offset.
10763 /// We ignore sign extensions when it is safe to do so.
10764 /// The following two expressions are not equivalent. To differentiate we need
10765 /// to store whether there was a sign extension involved in the index
10767 /// (load (i64 add (i64 copyfromreg %c)
10768 /// (i64 signextend (add (i8 load %index)
10772 /// (load (i64 add (i64 copyfromreg %c)
10773 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10775 struct BaseIndexOffset {
10779 bool IsIndexSignExt;
10781 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10783 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10784 bool IsIndexSignExt) :
10785 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10787 bool equalBaseIndex(const BaseIndexOffset &Other) {
10788 return Other.Base == Base && Other.Index == Index &&
10789 Other.IsIndexSignExt == IsIndexSignExt;
10792 /// Parses tree in Ptr for base, index, offset addresses.
10793 static BaseIndexOffset match(SDValue Ptr) {
10794 bool IsIndexSignExt = false;
10796 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10797 // instruction, then it could be just the BASE or everything else we don't
10798 // know how to handle. Just use Ptr as BASE and give up.
10799 if (Ptr->getOpcode() != ISD::ADD)
10800 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10802 // We know that we have at least an ADD instruction. Try to pattern match
10803 // the simple case of BASE + OFFSET.
10804 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10805 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10806 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10810 // Inside a loop the current BASE pointer is calculated using an ADD and a
10811 // MUL instruction. In this case Ptr is the actual BASE pointer.
10812 // (i64 add (i64 %array_ptr)
10813 // (i64 mul (i64 %induction_var)
10814 // (i64 %element_size)))
10815 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10816 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10818 // Look at Base + Index + Offset cases.
10819 SDValue Base = Ptr->getOperand(0);
10820 SDValue IndexOffset = Ptr->getOperand(1);
10822 // Skip signextends.
10823 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10824 IndexOffset = IndexOffset->getOperand(0);
10825 IsIndexSignExt = true;
10828 // Either the case of Base + Index (no offset) or something else.
10829 if (IndexOffset->getOpcode() != ISD::ADD)
10830 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10832 // Now we have the case of Base + Index + offset.
10833 SDValue Index = IndexOffset->getOperand(0);
10834 SDValue Offset = IndexOffset->getOperand(1);
10836 if (!isa<ConstantSDNode>(Offset))
10837 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10839 // Ignore signextends.
10840 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10841 Index = Index->getOperand(0);
10842 IsIndexSignExt = true;
10843 } else IsIndexSignExt = false;
10845 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10846 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10851 // This is a helper function for visitMUL to check the profitability
10852 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
10853 // MulNode is the original multiply, AddNode is (add x, c1),
10854 // and ConstNode is c2.
10856 // If the (add x, c1) has multiple uses, we could increase
10857 // the number of adds if we make this transformation.
10858 // It would only be worth doing this if we can remove a
10859 // multiply in the process. Check for that here.
10863 // We're checking for cases where we have common "c3 * A" expressions.
10864 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
10866 SDValue &ConstNode) {
10869 // If the add only has one use, this would be OK to do.
10870 if (AddNode.getNode()->hasOneUse())
10873 // Walk all the users of the constant with which we're multiplying.
10874 for (SDNode *Use : ConstNode->uses()) {
10876 if (Use == MulNode) // This use is the one we're on right now. Skip it.
10879 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
10881 SDNode *MulVar = AddNode.getOperand(0).getNode();
10883 // OtherOp is what we're multiplying against the constant.
10884 if (Use->getOperand(0) == ConstNode)
10885 OtherOp = Use->getOperand(1).getNode();
10887 OtherOp = Use->getOperand(0).getNode();
10889 // Check to see if multiply is with the same operand of our "add".
10891 // ConstNode = CONST
10892 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
10894 // AddNode = (A + c1) <-- MulVar is A.
10895 // = AddNode * ConstNode <-- current visiting instruction.
10897 // If we make this transformation, we will have a common
10898 // multiply (ConstNode * A) that we can save.
10899 if (OtherOp == MulVar)
10902 // Now check to see if a future expansion will give us a common
10905 // ConstNode = CONST
10906 // AddNode = (A + c1)
10907 // ... = AddNode * ConstNode <-- current visiting instruction.
10909 // OtherOp = (A + c2)
10910 // Use = OtherOp * ConstNode <-- visiting Use.
10912 // If we make this transformation, we will have a common
10913 // multiply (CONST * A) after we also do the same transformation
10914 // to the "t2" instruction.
10915 if (OtherOp->getOpcode() == ISD::ADD &&
10916 isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
10917 OtherOp->getOperand(0).getNode() == MulVar)
10922 // Didn't find a case where this would be profitable.
10926 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10928 ArrayRef<MemOpLink> Stores,
10929 SmallVectorImpl<SDValue> &Chains,
10931 SmallVector<SDValue, 8> BuildVector;
10933 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10934 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10935 Chains.push_back(St->getChain());
10936 BuildVector.push_back(St->getValue());
10939 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10942 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10943 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10944 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10945 // Make sure we have something to merge.
10949 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10950 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10951 unsigned LatestNodeUsed = 0;
10953 for (unsigned i=0; i < NumStores; ++i) {
10954 // Find a chain for the new wide-store operand. Notice that some
10955 // of the store nodes that we found may not be selected for inclusion
10956 // in the wide store. The chain we use needs to be the chain of the
10957 // latest store node which is *used* and replaced by the wide store.
10958 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10959 LatestNodeUsed = i;
10962 SmallVector<SDValue, 8> Chains;
10964 // The latest Node in the DAG.
10965 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10966 SDLoc DL(StoreNodes[0].MemNode);
10970 bool IsVec = MemVT.isVector();
10971 unsigned Elts = NumStores;
10973 // When merging vector stores, get the total number of elements.
10974 Elts *= MemVT.getVectorNumElements();
10976 // Get the type for the merged vector store.
10977 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10978 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10980 if (IsConstantSrc) {
10981 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10983 SmallVector<SDValue, 8> Ops;
10984 for (unsigned i = 0; i < NumStores; ++i) {
10985 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10986 SDValue Val = St->getValue();
10987 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10988 if (Val.getValueType() != MemVT)
10990 Ops.push_back(Val);
10991 Chains.push_back(St->getChain());
10994 // Build the extracted vector elements back into a vector.
10995 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10998 // We should always use a vector store when merging extracted vector
10999 // elements, so this path implies a store of constants.
11000 assert(IsConstantSrc && "Merged vector elements should use vector store");
11002 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11003 APInt StoreInt(SizeInBits, 0);
11005 // Construct a single integer constant which is made of the smaller
11006 // constant inputs.
11007 bool IsLE = DAG.getDataLayout().isLittleEndian();
11008 for (unsigned i = 0; i < NumStores; ++i) {
11009 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11010 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11011 Chains.push_back(St->getChain());
11013 SDValue Val = St->getValue();
11014 StoreInt <<= ElementSizeBytes * 8;
11015 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11016 StoreInt |= C->getAPIntValue().zext(SizeInBits);
11017 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11018 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11020 llvm_unreachable("Invalid constant element type");
11024 // Create the new Load and Store operations.
11025 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11026 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11029 assert(!Chains.empty());
11031 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11032 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11033 FirstInChain->getBasePtr(),
11034 FirstInChain->getPointerInfo(),
11036 FirstInChain->getAlignment());
11038 // Replace the last store with the new store
11039 CombineTo(LatestOp, NewStore);
11040 // Erase all other stores.
11041 for (unsigned i = 0; i < NumStores; ++i) {
11042 if (StoreNodes[i].MemNode == LatestOp)
11044 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11045 // ReplaceAllUsesWith will replace all uses that existed when it was
11046 // called, but graph optimizations may cause new ones to appear. For
11047 // example, the case in pr14333 looks like
11049 // St's chain -> St -> another store -> X
11051 // And the only difference from St to the other store is the chain.
11052 // When we change it's chain to be St's chain they become identical,
11053 // get CSEed and the net result is that X is now a use of St.
11054 // Since we know that St is redundant, just iterate.
11055 while (!St->use_empty())
11056 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11057 deleteAndRecombine(St);
11063 void DAGCombiner::getStoreMergeAndAliasCandidates(
11064 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11065 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11066 // This holds the base pointer, index, and the offset in bytes from the base
11068 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11070 // We must have a base and an offset.
11071 if (!BasePtr.Base.getNode())
11074 // Do not handle stores to undef base pointers.
11075 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11078 // Walk up the chain and look for nodes with offsets from the same
11079 // base pointer. Stop when reaching an instruction with a different kind
11080 // or instruction which has a different base pointer.
11081 EVT MemVT = St->getMemoryVT();
11083 StoreSDNode *Index = St;
11086 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11087 : DAG.getSubtarget().useAA();
11090 // Look at other users of the same chain. Stores on the same chain do not
11091 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11092 // to be on the same chain, so don't bother looking at adjacent chains.
11094 SDValue Chain = St->getChain();
11095 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11096 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11097 if (I.getOperandNo() != 0)
11100 if (OtherST->isVolatile() || OtherST->isIndexed())
11103 if (OtherST->getMemoryVT() != MemVT)
11106 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11108 if (Ptr.equalBaseIndex(BasePtr))
11109 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11117 // If the chain has more than one use, then we can't reorder the mem ops.
11118 if (Index != St && !SDValue(Index, 0)->hasOneUse())
11121 // Find the base pointer and offset for this memory node.
11122 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11124 // Check that the base pointer is the same as the original one.
11125 if (!Ptr.equalBaseIndex(BasePtr))
11128 // The memory operands must not be volatile.
11129 if (Index->isVolatile() || Index->isIndexed())
11133 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11134 if (St->isTruncatingStore())
11137 // The stored memory type must be the same.
11138 if (Index->getMemoryVT() != MemVT)
11141 // We found a potential memory operand to merge.
11142 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11144 // Find the next memory operand in the chain. If the next operand in the
11145 // chain is a store then move up and continue the scan with the next
11146 // memory operand. If the next operand is a load save it and use alias
11147 // information to check if it interferes with anything.
11148 SDNode *NextInChain = Index->getChain().getNode();
11150 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11151 // We found a store node. Use it for the next iteration.
11154 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11155 if (Ldn->isVolatile()) {
11160 // Save the load node for later. Continue the scan.
11161 AliasLoadNodes.push_back(Ldn);
11162 NextInChain = Ldn->getChain().getNode();
11172 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11173 if (OptLevel == CodeGenOpt::None)
11176 EVT MemVT = St->getMemoryVT();
11177 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11178 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11179 Attribute::NoImplicitFloat);
11181 // This function cannot currently deal with non-byte-sized memory sizes.
11182 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11185 if (!MemVT.isSimple())
11188 // Perform an early exit check. Do not bother looking at stored values that
11189 // are not constants, loads, or extracted vector elements.
11190 SDValue StoredVal = St->getValue();
11191 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11192 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11193 isa<ConstantFPSDNode>(StoredVal);
11194 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11195 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11197 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11200 // Don't merge vectors into wider vectors if the source data comes from loads.
11201 // TODO: This restriction can be lifted by using logic similar to the
11202 // ExtractVecSrc case.
11203 if (MemVT.isVector() && IsLoadSrc)
11206 // Only look at ends of store sequences.
11207 SDValue Chain = SDValue(St, 0);
11208 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11211 // Save the LoadSDNodes that we find in the chain.
11212 // We need to make sure that these nodes do not interfere with
11213 // any of the store nodes.
11214 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11216 // Save the StoreSDNodes that we find in the chain.
11217 SmallVector<MemOpLink, 8> StoreNodes;
11219 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11221 // Check if there is anything to merge.
11222 if (StoreNodes.size() < 2)
11225 // Sort the memory operands according to their distance from the base pointer.
11226 std::sort(StoreNodes.begin(), StoreNodes.end(),
11227 [](MemOpLink LHS, MemOpLink RHS) {
11228 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11229 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11230 LHS.SequenceNum > RHS.SequenceNum);
11233 // Scan the memory operations on the chain and find the first non-consecutive
11234 // store memory address.
11235 unsigned LastConsecutiveStore = 0;
11236 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11237 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11239 // Check that the addresses are consecutive starting from the second
11240 // element in the list of stores.
11242 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11243 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11247 bool Alias = false;
11248 // Check if this store interferes with any of the loads that we found.
11249 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11250 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11254 // We found a load that alias with this store. Stop the sequence.
11258 // Mark this node as useful.
11259 LastConsecutiveStore = i;
11262 // The node with the lowest store address.
11263 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11264 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11265 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11266 LLVMContext &Context = *DAG.getContext();
11267 const DataLayout &DL = DAG.getDataLayout();
11269 // Store the constants into memory as one consecutive store.
11270 if (IsConstantSrc) {
11271 unsigned LastLegalType = 0;
11272 unsigned LastLegalVectorType = 0;
11273 bool NonZero = false;
11274 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11275 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11276 SDValue StoredVal = St->getValue();
11278 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11279 NonZero |= !C->isNullValue();
11280 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11281 NonZero |= !C->getConstantFPValue()->isNullValue();
11287 // Find a legal type for the constant store.
11288 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11289 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11291 if (TLI.isTypeLegal(StoreTy) &&
11292 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11293 FirstStoreAlign, &IsFast) && IsFast) {
11294 LastLegalType = i+1;
11295 // Or check whether a truncstore is legal.
11296 } else if (TLI.getTypeAction(Context, StoreTy) ==
11297 TargetLowering::TypePromoteInteger) {
11298 EVT LegalizedStoredValueTy =
11299 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11300 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11301 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11302 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11304 LastLegalType = i + 1;
11308 // We only use vectors if the constant is known to be zero or the target
11309 // allows it and the function is not marked with the noimplicitfloat
11311 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11314 // Find a legal type for the vector store.
11315 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11316 if (TLI.isTypeLegal(Ty) &&
11317 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11318 FirstStoreAlign, &IsFast) && IsFast)
11319 LastLegalVectorType = i + 1;
11323 // Check if we found a legal integer type to store.
11324 if (LastLegalType == 0 && LastLegalVectorType == 0)
11327 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11328 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11330 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11334 // When extracting multiple vector elements, try to store them
11335 // in one vector store rather than a sequence of scalar stores.
11336 if (IsExtractVecSrc) {
11337 unsigned NumStoresToMerge = 0;
11338 bool IsVec = MemVT.isVector();
11339 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11340 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11341 unsigned StoreValOpcode = St->getValue().getOpcode();
11342 // This restriction could be loosened.
11343 // Bail out if any stored values are not elements extracted from a vector.
11344 // It should be possible to handle mixed sources, but load sources need
11345 // more careful handling (see the block of code below that handles
11346 // consecutive loads).
11347 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11348 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11351 // Find a legal type for the vector store.
11352 unsigned Elts = i + 1;
11354 // When merging vector stores, get the total number of elements.
11355 Elts *= MemVT.getVectorNumElements();
11357 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11359 if (TLI.isTypeLegal(Ty) &&
11360 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11361 FirstStoreAlign, &IsFast) && IsFast)
11362 NumStoresToMerge = i + 1;
11365 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11369 // Below we handle the case of multiple consecutive stores that
11370 // come from multiple consecutive loads. We merge them into a single
11371 // wide load and a single wide store.
11373 // Look for load nodes which are used by the stored values.
11374 SmallVector<MemOpLink, 8> LoadNodes;
11376 // Find acceptable loads. Loads need to have the same chain (token factor),
11377 // must not be zext, volatile, indexed, and they must be consecutive.
11378 BaseIndexOffset LdBasePtr;
11379 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11380 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11381 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11384 // Loads must only have one use.
11385 if (!Ld->hasNUsesOfValue(1, 0))
11388 // The memory operands must not be volatile.
11389 if (Ld->isVolatile() || Ld->isIndexed())
11392 // We do not accept ext loads.
11393 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11396 // The stored memory type must be the same.
11397 if (Ld->getMemoryVT() != MemVT)
11400 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11401 // If this is not the first ptr that we check.
11402 if (LdBasePtr.Base.getNode()) {
11403 // The base ptr must be the same.
11404 if (!LdPtr.equalBaseIndex(LdBasePtr))
11407 // Check that all other base pointers are the same as this one.
11411 // We found a potential memory operand to merge.
11412 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11415 if (LoadNodes.size() < 2)
11418 // If we have load/store pair instructions and we only have two values,
11420 unsigned RequiredAlignment;
11421 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11422 St->getAlignment() >= RequiredAlignment)
11425 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11426 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11427 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11429 // Scan the memory operations on the chain and find the first non-consecutive
11430 // load memory address. These variables hold the index in the store node
11432 unsigned LastConsecutiveLoad = 0;
11433 // This variable refers to the size and not index in the array.
11434 unsigned LastLegalVectorType = 0;
11435 unsigned LastLegalIntegerType = 0;
11436 StartAddress = LoadNodes[0].OffsetFromBase;
11437 SDValue FirstChain = FirstLoad->getChain();
11438 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11439 // All loads much share the same chain.
11440 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11443 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11444 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11446 LastConsecutiveLoad = i;
11447 // Find a legal type for the vector store.
11448 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11449 bool IsFastSt, IsFastLd;
11450 if (TLI.isTypeLegal(StoreTy) &&
11451 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11452 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11453 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11454 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11455 LastLegalVectorType = i + 1;
11458 // Find a legal type for the integer store.
11459 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11460 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11461 if (TLI.isTypeLegal(StoreTy) &&
11462 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11463 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11464 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11465 FirstLoadAlign, &IsFastLd) && IsFastLd)
11466 LastLegalIntegerType = i + 1;
11467 // Or check whether a truncstore and extload is legal.
11468 else if (TLI.getTypeAction(Context, StoreTy) ==
11469 TargetLowering::TypePromoteInteger) {
11470 EVT LegalizedStoredValueTy =
11471 TLI.getTypeToTransformTo(Context, StoreTy);
11472 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11473 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11474 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11475 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11476 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11477 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11479 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11480 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11482 LastLegalIntegerType = i+1;
11486 // Only use vector types if the vector type is larger than the integer type.
11487 // If they are the same, use integers.
11488 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11489 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11491 // We add +1 here because the LastXXX variables refer to location while
11492 // the NumElem refers to array/index size.
11493 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11494 NumElem = std::min(LastLegalType, NumElem);
11499 // Collect the chains from all merged stores.
11500 SmallVector<SDValue, 8> MergeStoreChains;
11501 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11503 // The latest Node in the DAG.
11504 unsigned LatestNodeUsed = 0;
11505 for (unsigned i=1; i<NumElem; ++i) {
11506 // Find a chain for the new wide-store operand. Notice that some
11507 // of the store nodes that we found may not be selected for inclusion
11508 // in the wide store. The chain we use needs to be the chain of the
11509 // latest store node which is *used* and replaced by the wide store.
11510 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11511 LatestNodeUsed = i;
11513 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11516 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11518 // Find if it is better to use vectors or integers to load and store
11522 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11524 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11525 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11528 SDLoc LoadDL(LoadNodes[0].MemNode);
11529 SDLoc StoreDL(StoreNodes[0].MemNode);
11531 // The merged loads are required to have the same chain, so using the first's
11532 // chain is acceptable.
11533 SDValue NewLoad = DAG.getLoad(
11534 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11535 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11537 SDValue NewStoreChain =
11538 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11540 SDValue NewStore = DAG.getStore(
11541 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11542 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11544 // Replace one of the loads with the new load.
11545 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11546 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11547 SDValue(NewLoad.getNode(), 1));
11549 // Remove the rest of the load chains.
11550 for (unsigned i = 1; i < NumElem ; ++i) {
11551 // Replace all chain users of the old load nodes with the chain of the new
11553 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11554 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11557 // Replace the last store with the new store.
11558 CombineTo(LatestOp, NewStore);
11559 // Erase all other stores.
11560 for (unsigned i = 0; i < NumElem ; ++i) {
11561 // Remove all Store nodes.
11562 if (StoreNodes[i].MemNode == LatestOp)
11564 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11565 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11566 deleteAndRecombine(St);
11572 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11576 // Replace the chain to avoid dependency.
11577 if (ST->isTruncatingStore()) {
11578 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11579 ST->getBasePtr(), ST->getMemoryVT(),
11580 ST->getMemOperand());
11582 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11583 ST->getMemOperand());
11586 // Create token to keep both nodes around.
11587 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11588 MVT::Other, ST->getChain(), ReplStore);
11590 // Make sure the new and old chains are cleaned up.
11591 AddToWorklist(Token.getNode());
11593 // Don't add users to work list.
11594 return CombineTo(ST, Token, false);
11597 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11598 SDValue Value = ST->getValue();
11599 if (Value.getOpcode() == ISD::TargetConstantFP)
11604 SDValue Chain = ST->getChain();
11605 SDValue Ptr = ST->getBasePtr();
11607 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11609 // NOTE: If the original store is volatile, this transform must not increase
11610 // the number of stores. For example, on x86-32 an f64 can be stored in one
11611 // processor operation but an i64 (which is not legal) requires two. So the
11612 // transform should not be done in this case.
11615 switch (CFP->getSimpleValueType(0).SimpleTy) {
11617 llvm_unreachable("Unknown FP type");
11618 case MVT::f16: // We don't do this for these yet.
11624 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11625 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11627 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11628 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11630 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11635 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11636 !ST->isVolatile()) ||
11637 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11639 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11640 getZExtValue(), SDLoc(CFP), MVT::i64);
11641 return DAG.getStore(Chain, DL, Tmp,
11642 Ptr, ST->getMemOperand());
11645 if (!ST->isVolatile() &&
11646 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11647 // Many FP stores are not made apparent until after legalize, e.g. for
11648 // argument passing. Since this is so common, custom legalize the
11649 // 64-bit integer store into two 32-bit stores.
11650 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11651 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11652 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11653 if (DAG.getDataLayout().isBigEndian())
11656 unsigned Alignment = ST->getAlignment();
11657 bool isVolatile = ST->isVolatile();
11658 bool isNonTemporal = ST->isNonTemporal();
11659 AAMDNodes AAInfo = ST->getAAInfo();
11661 SDValue St0 = DAG.getStore(Chain, DL, Lo,
11662 Ptr, ST->getPointerInfo(),
11663 isVolatile, isNonTemporal,
11664 ST->getAlignment(), AAInfo);
11665 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11666 DAG.getConstant(4, DL, Ptr.getValueType()));
11667 Alignment = MinAlign(Alignment, 4U);
11668 SDValue St1 = DAG.getStore(Chain, DL, Hi,
11669 Ptr, ST->getPointerInfo().getWithOffset(4),
11670 isVolatile, isNonTemporal,
11671 Alignment, AAInfo);
11672 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11680 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11681 StoreSDNode *ST = cast<StoreSDNode>(N);
11682 SDValue Chain = ST->getChain();
11683 SDValue Value = ST->getValue();
11684 SDValue Ptr = ST->getBasePtr();
11686 // If this is a store of a bit convert, store the input value if the
11687 // resultant store does not need a higher alignment than the original.
11688 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11689 ST->isUnindexed()) {
11690 unsigned OrigAlign = ST->getAlignment();
11691 EVT SVT = Value.getOperand(0).getValueType();
11692 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11693 SVT.getTypeForEVT(*DAG.getContext()));
11694 if (Align <= OrigAlign &&
11695 ((!LegalOperations && !ST->isVolatile()) ||
11696 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11697 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11698 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11699 ST->isNonTemporal(), OrigAlign,
11703 // Turn 'store undef, Ptr' -> nothing.
11704 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11707 // Try to infer better alignment information than the store already has.
11708 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11709 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11710 if (Align > ST->getAlignment()) {
11712 DAG.getTruncStore(Chain, SDLoc(N), Value,
11713 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11714 ST->isVolatile(), ST->isNonTemporal(), Align,
11716 if (NewStore.getNode() != N)
11717 return CombineTo(ST, NewStore, true);
11722 // Try transforming a pair floating point load / store ops to integer
11723 // load / store ops.
11724 if (SDValue NewST = TransformFPLoadStorePair(N))
11727 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11728 : DAG.getSubtarget().useAA();
11730 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11731 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11734 if (UseAA && ST->isUnindexed()) {
11735 // FIXME: We should do this even without AA enabled. AA will just allow
11736 // FindBetterChain to work in more situations. The problem with this is that
11737 // any combine that expects memory operations to be on consecutive chains
11738 // first needs to be updated to look for users of the same chain.
11740 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11741 // adjacent stores.
11742 if (findBetterNeighborChains(ST)) {
11743 // replaceStoreChain uses CombineTo, which handled all of the worklist
11744 // manipulation. Return the original node to not do anything else.
11745 return SDValue(ST, 0);
11749 // Try transforming N to an indexed store.
11750 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11751 return SDValue(N, 0);
11753 // FIXME: is there such a thing as a truncating indexed store?
11754 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11755 Value.getValueType().isInteger()) {
11756 // See if we can simplify the input to this truncstore with knowledge that
11757 // only the low bits are being used. For example:
11758 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11760 GetDemandedBits(Value,
11761 APInt::getLowBitsSet(
11762 Value.getValueType().getScalarType().getSizeInBits(),
11763 ST->getMemoryVT().getScalarType().getSizeInBits()));
11764 AddToWorklist(Value.getNode());
11765 if (Shorter.getNode())
11766 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11767 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11769 // Otherwise, see if we can simplify the operation with
11770 // SimplifyDemandedBits, which only works if the value has a single use.
11771 if (SimplifyDemandedBits(Value,
11772 APInt::getLowBitsSet(
11773 Value.getValueType().getScalarType().getSizeInBits(),
11774 ST->getMemoryVT().getScalarType().getSizeInBits())))
11775 return SDValue(N, 0);
11778 // If this is a load followed by a store to the same location, then the store
11780 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11781 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11782 ST->isUnindexed() && !ST->isVolatile() &&
11783 // There can't be any side effects between the load and store, such as
11784 // a call or store.
11785 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11786 // The store is dead, remove it.
11791 // If this is a store followed by a store with the same value to the same
11792 // location, then the store is dead/noop.
11793 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11794 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11795 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11796 ST1->isUnindexed() && !ST1->isVolatile()) {
11797 // The store is dead, remove it.
11802 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11803 // truncating store. We can do this even if this is already a truncstore.
11804 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11805 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11806 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11807 ST->getMemoryVT())) {
11808 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11809 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11812 // Only perform this optimization before the types are legal, because we
11813 // don't want to perform this optimization on every DAGCombine invocation.
11815 bool EverChanged = false;
11818 // There can be multiple store sequences on the same chain.
11819 // Keep trying to merge store sequences until we are unable to do so
11820 // or until we merge the last store on the chain.
11821 bool Changed = MergeConsecutiveStores(ST);
11822 EverChanged |= Changed;
11823 if (!Changed) break;
11824 } while (ST->getOpcode() != ISD::DELETED_NODE);
11827 return SDValue(N, 0);
11830 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11832 // Make sure to do this only after attempting to merge stores in order to
11833 // avoid changing the types of some subset of stores due to visit order,
11834 // preventing their merging.
11835 if (isa<ConstantFPSDNode>(Value)) {
11836 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11840 return ReduceLoadOpStoreWidth(N);
11843 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11844 SDValue InVec = N->getOperand(0);
11845 SDValue InVal = N->getOperand(1);
11846 SDValue EltNo = N->getOperand(2);
11849 // If the inserted element is an UNDEF, just use the input vector.
11850 if (InVal.getOpcode() == ISD::UNDEF)
11853 EVT VT = InVec.getValueType();
11855 // If we can't generate a legal BUILD_VECTOR, exit
11856 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11859 // Check that we know which element is being inserted
11860 if (!isa<ConstantSDNode>(EltNo))
11862 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11864 // Canonicalize insert_vector_elt dag nodes.
11866 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11867 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11869 // Do this only if the child insert_vector node has one use; also
11870 // do this only if indices are both constants and Idx1 < Idx0.
11871 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11872 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11873 unsigned OtherElt =
11874 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11875 if (Elt < OtherElt) {
11877 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11878 InVec.getOperand(0), InVal, EltNo);
11879 AddToWorklist(NewOp.getNode());
11880 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11881 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11885 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11886 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11887 // vector elements.
11888 SmallVector<SDValue, 8> Ops;
11889 // Do not combine these two vectors if the output vector will not replace
11890 // the input vector.
11891 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11892 Ops.append(InVec.getNode()->op_begin(),
11893 InVec.getNode()->op_end());
11894 } else if (InVec.getOpcode() == ISD::UNDEF) {
11895 unsigned NElts = VT.getVectorNumElements();
11896 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11901 // Insert the element
11902 if (Elt < Ops.size()) {
11903 // All the operands of BUILD_VECTOR must have the same type;
11904 // we enforce that here.
11905 EVT OpVT = Ops[0].getValueType();
11906 if (InVal.getValueType() != OpVT)
11907 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11908 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11909 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11913 // Return the new vector
11914 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11917 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11918 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11919 EVT ResultVT = EVE->getValueType(0);
11920 EVT VecEltVT = InVecVT.getVectorElementType();
11921 unsigned Align = OriginalLoad->getAlignment();
11922 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11923 VecEltVT.getTypeForEVT(*DAG.getContext()));
11925 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11930 SDValue NewPtr = OriginalLoad->getBasePtr();
11932 EVT PtrType = NewPtr.getValueType();
11933 MachinePointerInfo MPI;
11935 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11936 int Elt = ConstEltNo->getZExtValue();
11937 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11938 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11939 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11941 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11942 Offset = DAG.getNode(
11943 ISD::MUL, DL, PtrType, Offset,
11944 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11945 MPI = OriginalLoad->getPointerInfo();
11947 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11949 // The replacement we need to do here is a little tricky: we need to
11950 // replace an extractelement of a load with a load.
11951 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11952 // Note that this replacement assumes that the extractvalue is the only
11953 // use of the load; that's okay because we don't want to perform this
11954 // transformation in other cases anyway.
11957 if (ResultVT.bitsGT(VecEltVT)) {
11958 // If the result type of vextract is wider than the load, then issue an
11959 // extending load instead.
11960 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11964 Load = DAG.getExtLoad(
11965 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11966 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11967 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11968 Chain = Load.getValue(1);
11970 Load = DAG.getLoad(
11971 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11972 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11973 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11974 Chain = Load.getValue(1);
11975 if (ResultVT.bitsLT(VecEltVT))
11976 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11978 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11980 WorklistRemover DeadNodes(*this);
11981 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11982 SDValue To[] = { Load, Chain };
11983 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11984 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11985 // worklist explicitly as well.
11986 AddToWorklist(Load.getNode());
11987 AddUsersToWorklist(Load.getNode()); // Add users too
11988 // Make sure to revisit this node to clean it up; it will usually be dead.
11989 AddToWorklist(EVE);
11991 return SDValue(EVE, 0);
11994 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11995 // (vextract (scalar_to_vector val, 0) -> val
11996 SDValue InVec = N->getOperand(0);
11997 EVT VT = InVec.getValueType();
11998 EVT NVT = N->getValueType(0);
12000 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12001 // Check if the result type doesn't match the inserted element type. A
12002 // SCALAR_TO_VECTOR may truncate the inserted element and the
12003 // EXTRACT_VECTOR_ELT may widen the extracted vector.
12004 SDValue InOp = InVec.getOperand(0);
12005 if (InOp.getValueType() != NVT) {
12006 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12007 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12012 SDValue EltNo = N->getOperand(1);
12013 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12015 // extract_vector_elt (build_vector x, y), 1 -> y
12017 InVec.getOpcode() == ISD::BUILD_VECTOR &&
12018 TLI.isTypeLegal(VT) &&
12019 (InVec.hasOneUse() ||
12020 TLI.aggressivelyPreferBuildVectorSources(VT))) {
12021 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12022 EVT InEltVT = Elt.getValueType();
12024 // Sometimes build_vector's scalar input types do not match result type.
12025 if (NVT == InEltVT)
12028 // TODO: It may be useful to truncate if free if the build_vector implicitly
12032 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12033 // We only perform this optimization before the op legalization phase because
12034 // we may introduce new vector instructions which are not backed by TD
12035 // patterns. For example on AVX, extracting elements from a wide vector
12036 // without using extract_subvector. However, if we can find an underlying
12037 // scalar value, then we can always use that.
12038 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12039 int NumElem = VT.getVectorNumElements();
12040 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12041 // Find the new index to extract from.
12042 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12044 // Extracting an undef index is undef.
12046 return DAG.getUNDEF(NVT);
12048 // Select the right vector half to extract from.
12050 if (OrigElt < NumElem) {
12051 SVInVec = InVec->getOperand(0);
12053 SVInVec = InVec->getOperand(1);
12054 OrigElt -= NumElem;
12057 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12058 SDValue InOp = SVInVec.getOperand(OrigElt);
12059 if (InOp.getValueType() != NVT) {
12060 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12061 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12067 // FIXME: We should handle recursing on other vector shuffles and
12068 // scalar_to_vector here as well.
12070 if (!LegalOperations) {
12071 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12072 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12073 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12077 bool BCNumEltsChanged = false;
12078 EVT ExtVT = VT.getVectorElementType();
12081 // If the result of load has to be truncated, then it's not necessarily
12083 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12086 if (InVec.getOpcode() == ISD::BITCAST) {
12087 // Don't duplicate a load with other uses.
12088 if (!InVec.hasOneUse())
12091 EVT BCVT = InVec.getOperand(0).getValueType();
12092 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12094 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12095 BCNumEltsChanged = true;
12096 InVec = InVec.getOperand(0);
12097 ExtVT = BCVT.getVectorElementType();
12100 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12101 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12102 ISD::isNormalLoad(InVec.getNode()) &&
12103 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12104 SDValue Index = N->getOperand(1);
12105 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12106 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12110 // Perform only after legalization to ensure build_vector / vector_shuffle
12111 // optimizations have already been done.
12112 if (!LegalOperations) return SDValue();
12114 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12115 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12116 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12119 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12121 LoadSDNode *LN0 = nullptr;
12122 const ShuffleVectorSDNode *SVN = nullptr;
12123 if (ISD::isNormalLoad(InVec.getNode())) {
12124 LN0 = cast<LoadSDNode>(InVec);
12125 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12126 InVec.getOperand(0).getValueType() == ExtVT &&
12127 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12128 // Don't duplicate a load with other uses.
12129 if (!InVec.hasOneUse())
12132 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12133 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12134 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12136 // (load $addr+1*size)
12138 // Don't duplicate a load with other uses.
12139 if (!InVec.hasOneUse())
12142 // If the bit convert changed the number of elements, it is unsafe
12143 // to examine the mask.
12144 if (BCNumEltsChanged)
12147 // Select the input vector, guarding against out of range extract vector.
12148 unsigned NumElems = VT.getVectorNumElements();
12149 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12150 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12152 if (InVec.getOpcode() == ISD::BITCAST) {
12153 // Don't duplicate a load with other uses.
12154 if (!InVec.hasOneUse())
12157 InVec = InVec.getOperand(0);
12159 if (ISD::isNormalLoad(InVec.getNode())) {
12160 LN0 = cast<LoadSDNode>(InVec);
12161 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12162 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12166 // Make sure we found a non-volatile load and the extractelement is
12168 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12171 // If Idx was -1 above, Elt is going to be -1, so just return undef.
12173 return DAG.getUNDEF(LVT);
12175 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12181 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12182 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12183 // We perform this optimization post type-legalization because
12184 // the type-legalizer often scalarizes integer-promoted vectors.
12185 // Performing this optimization before may create bit-casts which
12186 // will be type-legalized to complex code sequences.
12187 // We perform this optimization only before the operation legalizer because we
12188 // may introduce illegal operations.
12189 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12192 unsigned NumInScalars = N->getNumOperands();
12194 EVT VT = N->getValueType(0);
12196 // Check to see if this is a BUILD_VECTOR of a bunch of values
12197 // which come from any_extend or zero_extend nodes. If so, we can create
12198 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12199 // optimizations. We do not handle sign-extend because we can't fill the sign
12201 EVT SourceType = MVT::Other;
12202 bool AllAnyExt = true;
12204 for (unsigned i = 0; i != NumInScalars; ++i) {
12205 SDValue In = N->getOperand(i);
12206 // Ignore undef inputs.
12207 if (In.getOpcode() == ISD::UNDEF) continue;
12209 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
12210 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12212 // Abort if the element is not an extension.
12213 if (!ZeroExt && !AnyExt) {
12214 SourceType = MVT::Other;
12218 // The input is a ZeroExt or AnyExt. Check the original type.
12219 EVT InTy = In.getOperand(0).getValueType();
12221 // Check that all of the widened source types are the same.
12222 if (SourceType == MVT::Other)
12225 else if (InTy != SourceType) {
12226 // Multiple income types. Abort.
12227 SourceType = MVT::Other;
12231 // Check if all of the extends are ANY_EXTENDs.
12232 AllAnyExt &= AnyExt;
12235 // In order to have valid types, all of the inputs must be extended from the
12236 // same source type and all of the inputs must be any or zero extend.
12237 // Scalar sizes must be a power of two.
12238 EVT OutScalarTy = VT.getScalarType();
12239 bool ValidTypes = SourceType != MVT::Other &&
12240 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12241 isPowerOf2_32(SourceType.getSizeInBits());
12243 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12244 // turn into a single shuffle instruction.
12248 bool isLE = DAG.getDataLayout().isLittleEndian();
12249 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12250 assert(ElemRatio > 1 && "Invalid element size ratio");
12251 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12252 DAG.getConstant(0, SDLoc(N), SourceType);
12254 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12255 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12257 // Populate the new build_vector
12258 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12259 SDValue Cast = N->getOperand(i);
12260 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12261 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12262 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12264 if (Cast.getOpcode() == ISD::UNDEF)
12265 In = DAG.getUNDEF(SourceType);
12267 In = Cast->getOperand(0);
12268 unsigned Index = isLE ? (i * ElemRatio) :
12269 (i * ElemRatio + (ElemRatio - 1));
12271 assert(Index < Ops.size() && "Invalid index");
12275 // The type of the new BUILD_VECTOR node.
12276 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12277 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12278 "Invalid vector size");
12279 // Check if the new vector type is legal.
12280 if (!isTypeLegal(VecVT)) return SDValue();
12282 // Make the new BUILD_VECTOR.
12283 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12285 // The new BUILD_VECTOR node has the potential to be further optimized.
12286 AddToWorklist(BV.getNode());
12287 // Bitcast to the desired type.
12288 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12291 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12292 EVT VT = N->getValueType(0);
12294 unsigned NumInScalars = N->getNumOperands();
12297 EVT SrcVT = MVT::Other;
12298 unsigned Opcode = ISD::DELETED_NODE;
12299 unsigned NumDefs = 0;
12301 for (unsigned i = 0; i != NumInScalars; ++i) {
12302 SDValue In = N->getOperand(i);
12303 unsigned Opc = In.getOpcode();
12305 if (Opc == ISD::UNDEF)
12308 // If all scalar values are floats and converted from integers.
12309 if (Opcode == ISD::DELETED_NODE &&
12310 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12317 EVT InVT = In.getOperand(0).getValueType();
12319 // If all scalar values are typed differently, bail out. It's chosen to
12320 // simplify BUILD_VECTOR of integer types.
12321 if (SrcVT == MVT::Other)
12328 // If the vector has just one element defined, it's not worth to fold it into
12329 // a vectorized one.
12333 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12334 && "Should only handle conversion from integer to float.");
12335 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12337 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12339 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12342 // Just because the floating-point vector type is legal does not necessarily
12343 // mean that the corresponding integer vector type is.
12344 if (!isTypeLegal(NVT))
12347 SmallVector<SDValue, 8> Opnds;
12348 for (unsigned i = 0; i != NumInScalars; ++i) {
12349 SDValue In = N->getOperand(i);
12351 if (In.getOpcode() == ISD::UNDEF)
12352 Opnds.push_back(DAG.getUNDEF(SrcVT));
12354 Opnds.push_back(In.getOperand(0));
12356 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12357 AddToWorklist(BV.getNode());
12359 return DAG.getNode(Opcode, dl, VT, BV);
12362 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12363 unsigned NumInScalars = N->getNumOperands();
12365 EVT VT = N->getValueType(0);
12367 // A vector built entirely of undefs is undef.
12368 if (ISD::allOperandsUndef(N))
12369 return DAG.getUNDEF(VT);
12371 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12374 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12377 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12378 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12379 // at most two distinct vectors, turn this into a shuffle node.
12381 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12382 if (!isTypeLegal(VT))
12385 // May only combine to shuffle after legalize if shuffle is legal.
12386 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12389 SDValue VecIn1, VecIn2;
12390 bool UsesZeroVector = false;
12391 for (unsigned i = 0; i != NumInScalars; ++i) {
12392 SDValue Op = N->getOperand(i);
12393 // Ignore undef inputs.
12394 if (Op.getOpcode() == ISD::UNDEF) continue;
12396 // See if we can combine this build_vector into a blend with a zero vector.
12397 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12398 UsesZeroVector = true;
12402 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12403 // constant index, bail out.
12404 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12405 !isa<ConstantSDNode>(Op.getOperand(1))) {
12406 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12410 // We allow up to two distinct input vectors.
12411 SDValue ExtractedFromVec = Op.getOperand(0);
12412 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12415 if (!VecIn1.getNode()) {
12416 VecIn1 = ExtractedFromVec;
12417 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12418 VecIn2 = ExtractedFromVec;
12420 // Too many inputs.
12421 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12426 // If everything is good, we can make a shuffle operation.
12427 if (VecIn1.getNode()) {
12428 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12429 SmallVector<int, 8> Mask;
12430 for (unsigned i = 0; i != NumInScalars; ++i) {
12431 unsigned Opcode = N->getOperand(i).getOpcode();
12432 if (Opcode == ISD::UNDEF) {
12433 Mask.push_back(-1);
12437 // Operands can also be zero.
12438 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12439 assert(UsesZeroVector &&
12440 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12441 "Unexpected node found!");
12442 Mask.push_back(NumInScalars+i);
12446 // If extracting from the first vector, just use the index directly.
12447 SDValue Extract = N->getOperand(i);
12448 SDValue ExtVal = Extract.getOperand(1);
12449 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12450 if (Extract.getOperand(0) == VecIn1) {
12451 Mask.push_back(ExtIndex);
12455 // Otherwise, use InIdx + InputVecSize
12456 Mask.push_back(InNumElements + ExtIndex);
12459 // Avoid introducing illegal shuffles with zero.
12460 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12463 // We can't generate a shuffle node with mismatched input and output types.
12464 // Attempt to transform a single input vector to the correct type.
12465 if ((VT != VecIn1.getValueType())) {
12466 // If the input vector type has a different base type to the output
12467 // vector type, bail out.
12468 EVT VTElemType = VT.getVectorElementType();
12469 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12470 (VecIn2.getNode() &&
12471 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12474 // If the input vector is too small, widen it.
12475 // We only support widening of vectors which are half the size of the
12476 // output registers. For example XMM->YMM widening on X86 with AVX.
12477 EVT VecInT = VecIn1.getValueType();
12478 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12479 // If we only have one small input, widen it by adding undef values.
12480 if (!VecIn2.getNode())
12481 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12482 DAG.getUNDEF(VecIn1.getValueType()));
12483 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12484 // If we have two small inputs of the same type, try to concat them.
12485 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12486 VecIn2 = SDValue(nullptr, 0);
12489 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12490 // If the input vector is too large, try to split it.
12491 // We don't support having two input vectors that are too large.
12492 // If the zero vector was used, we can not split the vector,
12493 // since we'd need 3 inputs.
12494 if (UsesZeroVector || VecIn2.getNode())
12497 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12500 // Try to replace VecIn1 with two extract_subvectors
12501 // No need to update the masks, they should still be correct.
12502 VecIn2 = DAG.getNode(
12503 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12504 DAG.getConstant(VT.getVectorNumElements(), dl,
12505 TLI.getVectorIdxTy(DAG.getDataLayout())));
12506 VecIn1 = DAG.getNode(
12507 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12508 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12513 if (UsesZeroVector)
12514 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12515 DAG.getConstantFP(0.0, dl, VT);
12517 // If VecIn2 is unused then change it to undef.
12518 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12520 // Check that we were able to transform all incoming values to the same
12522 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12523 VecIn1.getValueType() != VT)
12526 // Return the new VECTOR_SHUFFLE node.
12530 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12536 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12537 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12538 EVT OpVT = N->getOperand(0).getValueType();
12540 // If the operands are legal vectors, leave them alone.
12541 if (TLI.isTypeLegal(OpVT))
12545 EVT VT = N->getValueType(0);
12546 SmallVector<SDValue, 8> Ops;
12548 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12549 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12551 // Keep track of what we encounter.
12552 bool AnyInteger = false;
12553 bool AnyFP = false;
12554 for (const SDValue &Op : N->ops()) {
12555 if (ISD::BITCAST == Op.getOpcode() &&
12556 !Op.getOperand(0).getValueType().isVector())
12557 Ops.push_back(Op.getOperand(0));
12558 else if (ISD::UNDEF == Op.getOpcode())
12559 Ops.push_back(ScalarUndef);
12563 // Note whether we encounter an integer or floating point scalar.
12564 // If it's neither, bail out, it could be something weird like x86mmx.
12565 EVT LastOpVT = Ops.back().getValueType();
12566 if (LastOpVT.isFloatingPoint())
12568 else if (LastOpVT.isInteger())
12574 // If any of the operands is a floating point scalar bitcast to a vector,
12575 // use floating point types throughout, and bitcast everything.
12576 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12578 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12579 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12581 for (SDValue &Op : Ops) {
12582 if (Op.getValueType() == SVT)
12584 if (Op.getOpcode() == ISD::UNDEF)
12587 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12592 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12593 VT.getSizeInBits() / SVT.getSizeInBits());
12594 return DAG.getNode(ISD::BITCAST, DL, VT,
12595 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12598 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12599 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12600 // most two distinct vectors the same size as the result, attempt to turn this
12601 // into a legal shuffle.
12602 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12603 EVT VT = N->getValueType(0);
12604 EVT OpVT = N->getOperand(0).getValueType();
12605 int NumElts = VT.getVectorNumElements();
12606 int NumOpElts = OpVT.getVectorNumElements();
12608 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12609 SmallVector<int, 8> Mask;
12611 for (SDValue Op : N->ops()) {
12612 // Peek through any bitcast.
12613 while (Op.getOpcode() == ISD::BITCAST)
12614 Op = Op.getOperand(0);
12616 // UNDEF nodes convert to UNDEF shuffle mask values.
12617 if (Op.getOpcode() == ISD::UNDEF) {
12618 Mask.append((unsigned)NumOpElts, -1);
12622 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12625 // What vector are we extracting the subvector from and at what index?
12626 SDValue ExtVec = Op.getOperand(0);
12628 // We want the EVT of the original extraction to correctly scale the
12629 // extraction index.
12630 EVT ExtVT = ExtVec.getValueType();
12632 // Peek through any bitcast.
12633 while (ExtVec.getOpcode() == ISD::BITCAST)
12634 ExtVec = ExtVec.getOperand(0);
12636 // UNDEF nodes convert to UNDEF shuffle mask values.
12637 if (ExtVec.getOpcode() == ISD::UNDEF) {
12638 Mask.append((unsigned)NumOpElts, -1);
12642 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12644 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12646 // Ensure that we are extracting a subvector from a vector the same
12647 // size as the result.
12648 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12651 // Scale the subvector index to account for any bitcast.
12652 int NumExtElts = ExtVT.getVectorNumElements();
12653 if (0 == (NumExtElts % NumElts))
12654 ExtIdx /= (NumExtElts / NumElts);
12655 else if (0 == (NumElts % NumExtElts))
12656 ExtIdx *= (NumElts / NumExtElts);
12660 // At most we can reference 2 inputs in the final shuffle.
12661 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12663 for (int i = 0; i != NumOpElts; ++i)
12664 Mask.push_back(i + ExtIdx);
12665 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12667 for (int i = 0; i != NumOpElts; ++i)
12668 Mask.push_back(i + ExtIdx + NumElts);
12674 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12677 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12678 DAG.getBitcast(VT, SV1), Mask);
12681 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12682 // If we only have one input vector, we don't need to do any concatenation.
12683 if (N->getNumOperands() == 1)
12684 return N->getOperand(0);
12686 // Check if all of the operands are undefs.
12687 EVT VT = N->getValueType(0);
12688 if (ISD::allOperandsUndef(N))
12689 return DAG.getUNDEF(VT);
12691 // Optimize concat_vectors where all but the first of the vectors are undef.
12692 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12693 return Op.getOpcode() == ISD::UNDEF;
12695 SDValue In = N->getOperand(0);
12696 assert(In.getValueType().isVector() && "Must concat vectors");
12698 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12699 if (In->getOpcode() == ISD::BITCAST &&
12700 !In->getOperand(0)->getValueType(0).isVector()) {
12701 SDValue Scalar = In->getOperand(0);
12703 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12704 // look through the trunc so we can still do the transform:
12705 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12706 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12707 !TLI.isTypeLegal(Scalar.getValueType()) &&
12708 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12709 Scalar = Scalar->getOperand(0);
12711 EVT SclTy = Scalar->getValueType(0);
12713 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12716 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12717 VT.getSizeInBits() / SclTy.getSizeInBits());
12718 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12721 SDLoc dl = SDLoc(N);
12722 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12723 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12727 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12728 // We have already tested above for an UNDEF only concatenation.
12729 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12730 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12731 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12732 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12734 bool AllBuildVectorsOrUndefs =
12735 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12736 if (AllBuildVectorsOrUndefs) {
12737 SmallVector<SDValue, 8> Opnds;
12738 EVT SVT = VT.getScalarType();
12741 if (!SVT.isFloatingPoint()) {
12742 // If BUILD_VECTOR are from built from integer, they may have different
12743 // operand types. Get the smallest type and truncate all operands to it.
12744 bool FoundMinVT = false;
12745 for (const SDValue &Op : N->ops())
12746 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12747 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12748 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12751 assert(FoundMinVT && "Concat vector type mismatch");
12754 for (const SDValue &Op : N->ops()) {
12755 EVT OpVT = Op.getValueType();
12756 unsigned NumElts = OpVT.getVectorNumElements();
12758 if (ISD::UNDEF == Op.getOpcode())
12759 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12761 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12762 if (SVT.isFloatingPoint()) {
12763 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12764 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12766 for (unsigned i = 0; i != NumElts; ++i)
12768 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12773 assert(VT.getVectorNumElements() == Opnds.size() &&
12774 "Concat vector type mismatch");
12775 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12778 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12779 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12782 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12783 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12784 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12787 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12788 // nodes often generate nop CONCAT_VECTOR nodes.
12789 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12790 // place the incoming vectors at the exact same location.
12791 SDValue SingleSource = SDValue();
12792 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12794 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12795 SDValue Op = N->getOperand(i);
12797 if (Op.getOpcode() == ISD::UNDEF)
12800 // Check if this is the identity extract:
12801 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12804 // Find the single incoming vector for the extract_subvector.
12805 if (SingleSource.getNode()) {
12806 if (Op.getOperand(0) != SingleSource)
12809 SingleSource = Op.getOperand(0);
12811 // Check the source type is the same as the type of the result.
12812 // If not, this concat may extend the vector, so we can not
12813 // optimize it away.
12814 if (SingleSource.getValueType() != N->getValueType(0))
12818 unsigned IdentityIndex = i * PartNumElem;
12819 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12820 // The extract index must be constant.
12824 // Check that we are reading from the identity index.
12825 if (CS->getZExtValue() != IdentityIndex)
12829 if (SingleSource.getNode())
12830 return SingleSource;
12835 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12836 EVT NVT = N->getValueType(0);
12837 SDValue V = N->getOperand(0);
12839 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12841 // (extract_subvec (concat V1, V2, ...), i)
12844 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12846 if (V->getOperand(0).getValueType() != NVT)
12848 unsigned Idx = N->getConstantOperandVal(1);
12849 unsigned NumElems = NVT.getVectorNumElements();
12850 assert((Idx % NumElems) == 0 &&
12851 "IDX in concat is not a multiple of the result vector length.");
12852 return V->getOperand(Idx / NumElems);
12856 if (V->getOpcode() == ISD::BITCAST)
12857 V = V.getOperand(0);
12859 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12861 // Handle only simple case where vector being inserted and vector
12862 // being extracted are of same type, and are half size of larger vectors.
12863 EVT BigVT = V->getOperand(0).getValueType();
12864 EVT SmallVT = V->getOperand(1).getValueType();
12865 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12868 // Only handle cases where both indexes are constants with the same type.
12869 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12870 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12872 if (InsIdx && ExtIdx &&
12873 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12874 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12876 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12878 // indices are equal or bit offsets are equal => V1
12879 // otherwise => (extract_subvec V1, ExtIdx)
12880 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12881 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12882 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12883 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12884 DAG.getNode(ISD::BITCAST, dl,
12885 N->getOperand(0).getValueType(),
12886 V->getOperand(0)), N->getOperand(1));
12893 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12894 SDValue V, SelectionDAG &DAG) {
12896 EVT VT = V.getValueType();
12898 switch (V.getOpcode()) {
12902 case ISD::CONCAT_VECTORS: {
12903 EVT OpVT = V->getOperand(0).getValueType();
12904 int OpSize = OpVT.getVectorNumElements();
12905 SmallBitVector OpUsedElements(OpSize, false);
12906 bool FoundSimplification = false;
12907 SmallVector<SDValue, 4> NewOps;
12908 NewOps.reserve(V->getNumOperands());
12909 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12910 SDValue Op = V->getOperand(i);
12911 bool OpUsed = false;
12912 for (int j = 0; j < OpSize; ++j)
12913 if (UsedElements[i * OpSize + j]) {
12914 OpUsedElements[j] = true;
12918 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12919 : DAG.getUNDEF(OpVT));
12920 FoundSimplification |= Op == NewOps.back();
12921 OpUsedElements.reset();
12923 if (FoundSimplification)
12924 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12928 case ISD::INSERT_SUBVECTOR: {
12929 SDValue BaseV = V->getOperand(0);
12930 SDValue SubV = V->getOperand(1);
12931 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12935 int SubSize = SubV.getValueType().getVectorNumElements();
12936 int Idx = IdxN->getZExtValue();
12937 bool SubVectorUsed = false;
12938 SmallBitVector SubUsedElements(SubSize, false);
12939 for (int i = 0; i < SubSize; ++i)
12940 if (UsedElements[i + Idx]) {
12941 SubVectorUsed = true;
12942 SubUsedElements[i] = true;
12943 UsedElements[i + Idx] = false;
12946 // Now recurse on both the base and sub vectors.
12947 SDValue SimplifiedSubV =
12949 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12950 : DAG.getUNDEF(SubV.getValueType());
12951 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12952 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12953 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12954 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12960 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12961 SDValue N1, SelectionDAG &DAG) {
12962 EVT VT = SVN->getValueType(0);
12963 int NumElts = VT.getVectorNumElements();
12964 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12965 for (int M : SVN->getMask())
12966 if (M >= 0 && M < NumElts)
12967 N0UsedElements[M] = true;
12968 else if (M >= NumElts)
12969 N1UsedElements[M - NumElts] = true;
12971 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12972 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12973 if (S0 == N0 && S1 == N1)
12976 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12979 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12980 // or turn a shuffle of a single concat into simpler shuffle then concat.
12981 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12982 EVT VT = N->getValueType(0);
12983 unsigned NumElts = VT.getVectorNumElements();
12985 SDValue N0 = N->getOperand(0);
12986 SDValue N1 = N->getOperand(1);
12987 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12989 SmallVector<SDValue, 4> Ops;
12990 EVT ConcatVT = N0.getOperand(0).getValueType();
12991 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12992 unsigned NumConcats = NumElts / NumElemsPerConcat;
12994 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12995 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12996 // half vector elements.
12997 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12998 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12999 SVN->getMask().end(), [](int i) { return i == -1; })) {
13000 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13001 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13002 N1 = DAG.getUNDEF(ConcatVT);
13003 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13006 // Look at every vector that's inserted. We're looking for exact
13007 // subvector-sized copies from a concatenated vector
13008 for (unsigned I = 0; I != NumConcats; ++I) {
13009 // Make sure we're dealing with a copy.
13010 unsigned Begin = I * NumElemsPerConcat;
13011 bool AllUndef = true, NoUndef = true;
13012 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13013 if (SVN->getMaskElt(J) >= 0)
13020 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13023 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13024 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13027 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13028 if (FirstElt < N0.getNumOperands())
13029 Ops.push_back(N0.getOperand(FirstElt));
13031 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13033 } else if (AllUndef) {
13034 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13035 } else { // Mixed with general masks and undefs, can't do optimization.
13040 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13043 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13044 EVT VT = N->getValueType(0);
13045 unsigned NumElts = VT.getVectorNumElements();
13047 SDValue N0 = N->getOperand(0);
13048 SDValue N1 = N->getOperand(1);
13050 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13052 // Canonicalize shuffle undef, undef -> undef
13053 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13054 return DAG.getUNDEF(VT);
13056 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13058 // Canonicalize shuffle v, v -> v, undef
13060 SmallVector<int, 8> NewMask;
13061 for (unsigned i = 0; i != NumElts; ++i) {
13062 int Idx = SVN->getMaskElt(i);
13063 if (Idx >= (int)NumElts) Idx -= NumElts;
13064 NewMask.push_back(Idx);
13066 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13070 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
13071 if (N0.getOpcode() == ISD::UNDEF) {
13072 SmallVector<int, 8> NewMask;
13073 for (unsigned i = 0; i != NumElts; ++i) {
13074 int Idx = SVN->getMaskElt(i);
13076 if (Idx >= (int)NumElts)
13079 Idx = -1; // remove reference to lhs
13081 NewMask.push_back(Idx);
13083 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13087 // Remove references to rhs if it is undef
13088 if (N1.getOpcode() == ISD::UNDEF) {
13089 bool Changed = false;
13090 SmallVector<int, 8> NewMask;
13091 for (unsigned i = 0; i != NumElts; ++i) {
13092 int Idx = SVN->getMaskElt(i);
13093 if (Idx >= (int)NumElts) {
13097 NewMask.push_back(Idx);
13100 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13103 // If it is a splat, check if the argument vector is another splat or a
13105 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13106 SDNode *V = N0.getNode();
13108 // If this is a bit convert that changes the element type of the vector but
13109 // not the number of vector elements, look through it. Be careful not to
13110 // look though conversions that change things like v4f32 to v2f64.
13111 if (V->getOpcode() == ISD::BITCAST) {
13112 SDValue ConvInput = V->getOperand(0);
13113 if (ConvInput.getValueType().isVector() &&
13114 ConvInput.getValueType().getVectorNumElements() == NumElts)
13115 V = ConvInput.getNode();
13118 if (V->getOpcode() == ISD::BUILD_VECTOR) {
13119 assert(V->getNumOperands() == NumElts &&
13120 "BUILD_VECTOR has wrong number of operands");
13122 bool AllSame = true;
13123 for (unsigned i = 0; i != NumElts; ++i) {
13124 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13125 Base = V->getOperand(i);
13129 // Splat of <u, u, u, u>, return <u, u, u, u>
13130 if (!Base.getNode())
13132 for (unsigned i = 0; i != NumElts; ++i) {
13133 if (V->getOperand(i) != Base) {
13138 // Splat of <x, x, x, x>, return <x, x, x, x>
13142 // Canonicalize any other splat as a build_vector.
13143 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13144 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13145 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13146 V->getValueType(0), Ops);
13148 // We may have jumped through bitcasts, so the type of the
13149 // BUILD_VECTOR may not match the type of the shuffle.
13150 if (V->getValueType(0) != VT)
13151 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13156 // There are various patterns used to build up a vector from smaller vectors,
13157 // subvectors, or elements. Scan chains of these and replace unused insertions
13158 // or components with undef.
13159 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13162 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13163 Level < AfterLegalizeVectorOps &&
13164 (N1.getOpcode() == ISD::UNDEF ||
13165 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13166 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13167 SDValue V = partitionShuffleOfConcats(N, DAG);
13173 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13174 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13175 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13176 SmallVector<SDValue, 8> Ops;
13177 for (int M : SVN->getMask()) {
13178 SDValue Op = DAG.getUNDEF(VT.getScalarType());
13180 int Idx = M % NumElts;
13181 SDValue &S = (M < (int)NumElts ? N0 : N1);
13182 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13183 Op = S.getOperand(Idx);
13184 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13186 Op = S.getOperand(0);
13188 // Operand can't be combined - bail out.
13194 if (Ops.size() == VT.getVectorNumElements()) {
13195 // BUILD_VECTOR requires all inputs to be of the same type, find the
13196 // maximum type and extend them all.
13197 EVT SVT = VT.getScalarType();
13198 if (SVT.isInteger())
13199 for (SDValue &Op : Ops)
13200 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13201 if (SVT != VT.getScalarType())
13202 for (SDValue &Op : Ops)
13203 Op = TLI.isZExtFree(Op.getValueType(), SVT)
13204 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13205 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13206 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13210 // If this shuffle only has a single input that is a bitcasted shuffle,
13211 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13212 // back to their original types.
13213 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13214 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13215 TLI.isTypeLegal(VT)) {
13217 // Peek through the bitcast only if there is one user.
13219 while (BC0.getOpcode() == ISD::BITCAST) {
13220 if (!BC0.hasOneUse())
13222 BC0 = BC0.getOperand(0);
13225 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13227 return SmallVector<int, 8>(Mask.begin(), Mask.end());
13229 SmallVector<int, 8> NewMask;
13231 for (int s = 0; s != Scale; ++s)
13232 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13236 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13237 EVT SVT = VT.getScalarType();
13238 EVT InnerVT = BC0->getValueType(0);
13239 EVT InnerSVT = InnerVT.getScalarType();
13241 // Determine which shuffle works with the smaller scalar type.
13242 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13243 EVT ScaleSVT = ScaleVT.getScalarType();
13245 if (TLI.isTypeLegal(ScaleVT) &&
13246 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13247 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13249 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13250 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13252 // Scale the shuffle masks to the smaller scalar type.
13253 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13254 SmallVector<int, 8> InnerMask =
13255 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13256 SmallVector<int, 8> OuterMask =
13257 ScaleShuffleMask(SVN->getMask(), OuterScale);
13259 // Merge the shuffle masks.
13260 SmallVector<int, 8> NewMask;
13261 for (int M : OuterMask)
13262 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13264 // Test for shuffle mask legality over both commutations.
13265 SDValue SV0 = BC0->getOperand(0);
13266 SDValue SV1 = BC0->getOperand(1);
13267 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13269 std::swap(SV0, SV1);
13270 ShuffleVectorSDNode::commuteMask(NewMask);
13271 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13275 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13276 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13277 return DAG.getNode(
13278 ISD::BITCAST, SDLoc(N), VT,
13279 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13285 // Canonicalize shuffles according to rules:
13286 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13287 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13288 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13289 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13290 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13291 TLI.isTypeLegal(VT)) {
13292 // The incoming shuffle must be of the same type as the result of the
13293 // current shuffle.
13294 assert(N1->getOperand(0).getValueType() == VT &&
13295 "Shuffle types don't match");
13297 SDValue SV0 = N1->getOperand(0);
13298 SDValue SV1 = N1->getOperand(1);
13299 bool HasSameOp0 = N0 == SV0;
13300 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13301 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13302 // Commute the operands of this shuffle so that next rule
13304 return DAG.getCommutedVectorShuffle(*SVN);
13307 // Try to fold according to rules:
13308 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13309 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13310 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13311 // Don't try to fold shuffles with illegal type.
13312 // Only fold if this shuffle is the only user of the other shuffle.
13313 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13314 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13315 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13317 // The incoming shuffle must be of the same type as the result of the
13318 // current shuffle.
13319 assert(OtherSV->getOperand(0).getValueType() == VT &&
13320 "Shuffle types don't match");
13323 SmallVector<int, 4> Mask;
13324 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13325 // operand, and SV1 as the second operand.
13326 for (unsigned i = 0; i != NumElts; ++i) {
13327 int Idx = SVN->getMaskElt(i);
13329 // Propagate Undef.
13330 Mask.push_back(Idx);
13334 SDValue CurrentVec;
13335 if (Idx < (int)NumElts) {
13336 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13337 // shuffle mask to identify which vector is actually referenced.
13338 Idx = OtherSV->getMaskElt(Idx);
13340 // Propagate Undef.
13341 Mask.push_back(Idx);
13345 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13346 : OtherSV->getOperand(1);
13348 // This shuffle index references an element within N1.
13352 // Simple case where 'CurrentVec' is UNDEF.
13353 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13354 Mask.push_back(-1);
13358 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13359 // will be the first or second operand of the combined shuffle.
13360 Idx = Idx % NumElts;
13361 if (!SV0.getNode() || SV0 == CurrentVec) {
13362 // Ok. CurrentVec is the left hand side.
13363 // Update the mask accordingly.
13365 Mask.push_back(Idx);
13369 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13370 if (SV1.getNode() && SV1 != CurrentVec)
13373 // Ok. CurrentVec is the right hand side.
13374 // Update the mask accordingly.
13376 Mask.push_back(Idx + NumElts);
13379 // Check if all indices in Mask are Undef. In case, propagate Undef.
13380 bool isUndefMask = true;
13381 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13382 isUndefMask &= Mask[i] < 0;
13385 return DAG.getUNDEF(VT);
13387 if (!SV0.getNode())
13388 SV0 = DAG.getUNDEF(VT);
13389 if (!SV1.getNode())
13390 SV1 = DAG.getUNDEF(VT);
13392 // Avoid introducing shuffles with illegal mask.
13393 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13394 ShuffleVectorSDNode::commuteMask(Mask);
13396 if (!TLI.isShuffleMaskLegal(Mask, VT))
13399 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13400 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13401 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13402 std::swap(SV0, SV1);
13405 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13406 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13407 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13408 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13414 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13415 SDValue InVal = N->getOperand(0);
13416 EVT VT = N->getValueType(0);
13418 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13419 // with a VECTOR_SHUFFLE.
13420 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13421 SDValue InVec = InVal->getOperand(0);
13422 SDValue EltNo = InVal->getOperand(1);
13424 // FIXME: We could support implicit truncation if the shuffle can be
13425 // scaled to a smaller vector scalar type.
13426 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13427 if (C0 && VT == InVec.getValueType() &&
13428 VT.getScalarType() == InVal.getValueType()) {
13429 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13430 int Elt = C0->getZExtValue();
13433 if (TLI.isShuffleMaskLegal(NewMask, VT))
13434 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13442 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13443 SDValue N0 = N->getOperand(0);
13444 SDValue N2 = N->getOperand(2);
13446 // If the input vector is a concatenation, and the insert replaces
13447 // one of the halves, we can optimize into a single concat_vectors.
13448 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13449 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13450 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13451 EVT VT = N->getValueType(0);
13453 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13454 // (concat_vectors Z, Y)
13456 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13457 N->getOperand(1), N0.getOperand(1));
13459 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13460 // (concat_vectors X, Z)
13461 if (InsIdx == VT.getVectorNumElements()/2)
13462 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13463 N0.getOperand(0), N->getOperand(1));
13469 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13470 SDValue N0 = N->getOperand(0);
13472 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13473 if (N0->getOpcode() == ISD::FP16_TO_FP)
13474 return N0->getOperand(0);
13479 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13480 SDValue N0 = N->getOperand(0);
13482 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13483 if (N0->getOpcode() == ISD::AND) {
13484 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13485 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13486 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13494 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13495 /// with the destination vector and a zero vector.
13496 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13497 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13498 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13499 EVT VT = N->getValueType(0);
13500 SDValue LHS = N->getOperand(0);
13501 SDValue RHS = N->getOperand(1);
13504 // Make sure we're not running after operation legalization where it
13505 // may have custom lowered the vector shuffles.
13506 if (LegalOperations)
13509 if (N->getOpcode() != ISD::AND)
13512 if (RHS.getOpcode() == ISD::BITCAST)
13513 RHS = RHS.getOperand(0);
13515 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13518 EVT RVT = RHS.getValueType();
13519 unsigned NumElts = RHS.getNumOperands();
13521 // Attempt to create a valid clear mask, splitting the mask into
13522 // sub elements and checking to see if each is
13523 // all zeros or all ones - suitable for shuffle masking.
13524 auto BuildClearMask = [&](int Split) {
13525 int NumSubElts = NumElts * Split;
13526 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13528 SmallVector<int, 8> Indices;
13529 for (int i = 0; i != NumSubElts; ++i) {
13530 int EltIdx = i / Split;
13531 int SubIdx = i % Split;
13532 SDValue Elt = RHS.getOperand(EltIdx);
13533 if (Elt.getOpcode() == ISD::UNDEF) {
13534 Indices.push_back(-1);
13539 if (isa<ConstantSDNode>(Elt))
13540 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13541 else if (isa<ConstantFPSDNode>(Elt))
13542 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13546 // Extract the sub element from the constant bit mask.
13547 if (DAG.getDataLayout().isBigEndian()) {
13548 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13550 Bits = Bits.lshr(SubIdx * NumSubBits);
13554 Bits = Bits.trunc(NumSubBits);
13556 if (Bits.isAllOnesValue())
13557 Indices.push_back(i);
13558 else if (Bits == 0)
13559 Indices.push_back(i + NumSubElts);
13564 // Let's see if the target supports this vector_shuffle.
13565 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13566 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13567 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13570 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13571 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13572 DAG.getBitcast(ClearVT, LHS),
13573 Zero, &Indices[0]));
13576 // Determine maximum split level (byte level masking).
13578 if (RVT.getScalarSizeInBits() % 8 == 0)
13579 MaxSplit = RVT.getScalarSizeInBits() / 8;
13581 for (int Split = 1; Split <= MaxSplit; ++Split)
13582 if (RVT.getScalarSizeInBits() % Split == 0)
13583 if (SDValue S = BuildClearMask(Split))
13589 /// Visit a binary vector operation, like ADD.
13590 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13591 assert(N->getValueType(0).isVector() &&
13592 "SimplifyVBinOp only works on vectors!");
13594 SDValue LHS = N->getOperand(0);
13595 SDValue RHS = N->getOperand(1);
13596 SDValue Ops[] = {LHS, RHS};
13598 // See if we can constant fold the vector operation.
13599 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13600 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13603 // Try to convert a constant mask AND into a shuffle clear mask.
13604 if (SDValue Shuffle = XformToShuffleWithZero(N))
13607 // Type legalization might introduce new shuffles in the DAG.
13608 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13609 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13610 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13611 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13612 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13613 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13614 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13615 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13617 if (SVN0->getMask().equals(SVN1->getMask())) {
13618 EVT VT = N->getValueType(0);
13619 SDValue UndefVector = LHS.getOperand(1);
13620 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13621 LHS.getOperand(0), RHS.getOperand(0),
13623 AddUsersToWorklist(N);
13624 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13625 &SVN0->getMask()[0]);
13632 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13633 SDValue N1, SDValue N2){
13634 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13636 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13637 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13639 // If we got a simplified select_cc node back from SimplifySelectCC, then
13640 // break it down into a new SETCC node, and a new SELECT node, and then return
13641 // the SELECT node, since we were called with a SELECT node.
13642 if (SCC.getNode()) {
13643 // Check to see if we got a select_cc back (to turn into setcc/select).
13644 // Otherwise, just return whatever node we got back, like fabs.
13645 if (SCC.getOpcode() == ISD::SELECT_CC) {
13646 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13648 SCC.getOperand(0), SCC.getOperand(1),
13649 SCC.getOperand(4));
13650 AddToWorklist(SETCC.getNode());
13651 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13652 SCC.getOperand(2), SCC.getOperand(3));
13660 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13661 /// being selected between, see if we can simplify the select. Callers of this
13662 /// should assume that TheSelect is deleted if this returns true. As such, they
13663 /// should return the appropriate thing (e.g. the node) back to the top-level of
13664 /// the DAG combiner loop to avoid it being looked at.
13665 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13668 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13669 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13670 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13671 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13672 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13673 SDValue Sqrt = RHS;
13676 const ConstantFPSDNode *NegZero = nullptr;
13678 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13679 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13680 CmpLHS = TheSelect->getOperand(0);
13681 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13683 // SELECT or VSELECT
13684 SDValue Cmp = TheSelect->getOperand(0);
13685 if (Cmp.getOpcode() == ISD::SETCC) {
13686 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13687 CmpLHS = Cmp.getOperand(0);
13688 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13691 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13692 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13693 CC == ISD::SETULT || CC == ISD::SETLT)) {
13694 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13695 CombineTo(TheSelect, Sqrt);
13700 // Cannot simplify select with vector condition
13701 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13703 // If this is a select from two identical things, try to pull the operation
13704 // through the select.
13705 if (LHS.getOpcode() != RHS.getOpcode() ||
13706 !LHS.hasOneUse() || !RHS.hasOneUse())
13709 // If this is a load and the token chain is identical, replace the select
13710 // of two loads with a load through a select of the address to load from.
13711 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13712 // constants have been dropped into the constant pool.
13713 if (LHS.getOpcode() == ISD::LOAD) {
13714 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13715 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13717 // Token chains must be identical.
13718 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13719 // Do not let this transformation reduce the number of volatile loads.
13720 LLD->isVolatile() || RLD->isVolatile() ||
13721 // FIXME: If either is a pre/post inc/dec load,
13722 // we'd need to split out the address adjustment.
13723 LLD->isIndexed() || RLD->isIndexed() ||
13724 // If this is an EXTLOAD, the VT's must match.
13725 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13726 // If this is an EXTLOAD, the kind of extension must match.
13727 (LLD->getExtensionType() != RLD->getExtensionType() &&
13728 // The only exception is if one of the extensions is anyext.
13729 LLD->getExtensionType() != ISD::EXTLOAD &&
13730 RLD->getExtensionType() != ISD::EXTLOAD) ||
13731 // FIXME: this discards src value information. This is
13732 // over-conservative. It would be beneficial to be able to remember
13733 // both potential memory locations. Since we are discarding
13734 // src value info, don't do the transformation if the memory
13735 // locations are not in the default address space.
13736 LLD->getPointerInfo().getAddrSpace() != 0 ||
13737 RLD->getPointerInfo().getAddrSpace() != 0 ||
13738 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13739 LLD->getBasePtr().getValueType()))
13742 // Check that the select condition doesn't reach either load. If so,
13743 // folding this will induce a cycle into the DAG. If not, this is safe to
13744 // xform, so create a select of the addresses.
13746 if (TheSelect->getOpcode() == ISD::SELECT) {
13747 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13748 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13749 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13751 // The loads must not depend on one another.
13752 if (LLD->isPredecessorOf(RLD) ||
13753 RLD->isPredecessorOf(LLD))
13755 Addr = DAG.getSelect(SDLoc(TheSelect),
13756 LLD->getBasePtr().getValueType(),
13757 TheSelect->getOperand(0), LLD->getBasePtr(),
13758 RLD->getBasePtr());
13759 } else { // Otherwise SELECT_CC
13760 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13761 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13763 if ((LLD->hasAnyUseOfValue(1) &&
13764 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13765 (RLD->hasAnyUseOfValue(1) &&
13766 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13769 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13770 LLD->getBasePtr().getValueType(),
13771 TheSelect->getOperand(0),
13772 TheSelect->getOperand(1),
13773 LLD->getBasePtr(), RLD->getBasePtr(),
13774 TheSelect->getOperand(4));
13778 // It is safe to replace the two loads if they have different alignments,
13779 // but the new load must be the minimum (most restrictive) alignment of the
13781 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13782 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13783 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13784 Load = DAG.getLoad(TheSelect->getValueType(0),
13786 // FIXME: Discards pointer and AA info.
13787 LLD->getChain(), Addr, MachinePointerInfo(),
13788 LLD->isVolatile(), LLD->isNonTemporal(),
13789 isInvariant, Alignment);
13791 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13792 RLD->getExtensionType() : LLD->getExtensionType(),
13794 TheSelect->getValueType(0),
13795 // FIXME: Discards pointer and AA info.
13796 LLD->getChain(), Addr, MachinePointerInfo(),
13797 LLD->getMemoryVT(), LLD->isVolatile(),
13798 LLD->isNonTemporal(), isInvariant, Alignment);
13801 // Users of the select now use the result of the load.
13802 CombineTo(TheSelect, Load);
13804 // Users of the old loads now use the new load's chain. We know the
13805 // old-load value is dead now.
13806 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13807 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13814 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13815 /// where 'cond' is the comparison specified by CC.
13816 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13817 SDValue N2, SDValue N3,
13818 ISD::CondCode CC, bool NotExtCompare) {
13819 // (x ? y : y) -> y.
13820 if (N2 == N3) return N2;
13822 EVT VT = N2.getValueType();
13823 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13824 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13826 // Determine if the condition we're dealing with is constant
13827 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13828 N0, N1, CC, DL, false);
13829 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13831 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13832 // fold select_cc true, x, y -> x
13833 // fold select_cc false, x, y -> y
13834 return !SCCC->isNullValue() ? N2 : N3;
13837 // Check to see if we can simplify the select into an fabs node
13838 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13839 // Allow either -0.0 or 0.0
13840 if (CFP->isZero()) {
13841 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13842 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13843 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13844 N2 == N3.getOperand(0))
13845 return DAG.getNode(ISD::FABS, DL, VT, N0);
13847 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13848 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13849 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13850 N2.getOperand(0) == N3)
13851 return DAG.getNode(ISD::FABS, DL, VT, N3);
13855 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13856 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13857 // in it. This is a win when the constant is not otherwise available because
13858 // it replaces two constant pool loads with one. We only do this if the FP
13859 // type is known to be legal, because if it isn't, then we are before legalize
13860 // types an we want the other legalization to happen first (e.g. to avoid
13861 // messing with soft float) and if the ConstantFP is not legal, because if
13862 // it is legal, we may not need to store the FP constant in a constant pool.
13863 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13864 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13865 if (TLI.isTypeLegal(N2.getValueType()) &&
13866 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13867 TargetLowering::Legal &&
13868 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13869 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13870 // If both constants have multiple uses, then we won't need to do an
13871 // extra load, they are likely around in registers for other users.
13872 (TV->hasOneUse() || FV->hasOneUse())) {
13873 Constant *Elts[] = {
13874 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13875 const_cast<ConstantFP*>(TV->getConstantFPValue())
13877 Type *FPTy = Elts[0]->getType();
13878 const DataLayout &TD = DAG.getDataLayout();
13880 // Create a ConstantArray of the two constants.
13881 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13883 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13884 TD.getPrefTypeAlignment(FPTy));
13885 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13887 // Get the offsets to the 0 and 1 element of the array so that we can
13888 // select between them.
13889 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13890 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13891 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13893 SDValue Cond = DAG.getSetCC(DL,
13894 getSetCCResultType(N0.getValueType()),
13896 AddToWorklist(Cond.getNode());
13897 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13899 AddToWorklist(CstOffset.getNode());
13900 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13902 AddToWorklist(CPIdx.getNode());
13903 return DAG.getLoad(
13904 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13905 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13906 false, false, false, Alignment);
13910 // Check to see if we can perform the "gzip trick", transforming
13911 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13912 if (isNullConstant(N3) && CC == ISD::SETLT &&
13913 (isNullConstant(N1) || // (a < 0) ? b : 0
13914 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13915 EVT XType = N0.getValueType();
13916 EVT AType = N2.getValueType();
13917 if (XType.bitsGE(AType)) {
13918 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13919 // single-bit constant.
13920 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13921 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13922 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13923 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13924 getShiftAmountTy(N0.getValueType()));
13925 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13927 AddToWorklist(Shift.getNode());
13929 if (XType.bitsGT(AType)) {
13930 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13931 AddToWorklist(Shift.getNode());
13934 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13937 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13939 DAG.getConstant(XType.getSizeInBits() - 1,
13941 getShiftAmountTy(N0.getValueType())));
13942 AddToWorklist(Shift.getNode());
13944 if (XType.bitsGT(AType)) {
13945 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13946 AddToWorklist(Shift.getNode());
13949 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13953 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13954 // where y is has a single bit set.
13955 // A plaintext description would be, we can turn the SELECT_CC into an AND
13956 // when the condition can be materialized as an all-ones register. Any
13957 // single bit-test can be materialized as an all-ones register with
13958 // shift-left and shift-right-arith.
13959 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13960 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13961 SDValue AndLHS = N0->getOperand(0);
13962 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13963 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13964 // Shift the tested bit over the sign bit.
13965 APInt AndMask = ConstAndRHS->getAPIntValue();
13967 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13968 getShiftAmountTy(AndLHS.getValueType()));
13969 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13971 // Now arithmetic right shift it all the way over, so the result is either
13972 // all-ones, or zero.
13974 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13975 getShiftAmountTy(Shl.getValueType()));
13976 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13978 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13982 // fold select C, 16, 0 -> shl C, 4
13983 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13984 TLI.getBooleanContents(N0.getValueType()) ==
13985 TargetLowering::ZeroOrOneBooleanContent) {
13987 // If the caller doesn't want us to simplify this into a zext of a compare,
13989 if (NotExtCompare && N2C->isOne())
13992 // Get a SetCC of the condition
13993 // NOTE: Don't create a SETCC if it's not legal on this target.
13994 if (!LegalOperations ||
13995 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13997 // cast from setcc result type to select result type
13999 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14001 if (N2.getValueType().bitsLT(SCC.getValueType()))
14002 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14003 N2.getValueType());
14005 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14006 N2.getValueType(), SCC);
14008 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14009 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14010 N2.getValueType(), SCC);
14013 AddToWorklist(SCC.getNode());
14014 AddToWorklist(Temp.getNode());
14019 // shl setcc result by log2 n2c
14020 return DAG.getNode(
14021 ISD::SHL, DL, N2.getValueType(), Temp,
14022 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14023 getShiftAmountTy(Temp.getValueType())));
14027 // Check to see if this is an integer abs.
14028 // select_cc setg[te] X, 0, X, -X ->
14029 // select_cc setgt X, -1, X, -X ->
14030 // select_cc setl[te] X, 0, -X, X ->
14031 // select_cc setlt X, 1, -X, X ->
14032 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14034 ConstantSDNode *SubC = nullptr;
14035 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14036 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14037 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14038 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14039 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14040 (N1C->isOne() && CC == ISD::SETLT)) &&
14041 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14042 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14044 EVT XType = N0.getValueType();
14045 if (SubC && SubC->isNullValue() && XType.isInteger()) {
14047 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14049 DAG.getConstant(XType.getSizeInBits() - 1, DL,
14050 getShiftAmountTy(N0.getValueType())));
14051 SDValue Add = DAG.getNode(ISD::ADD, DL,
14053 AddToWorklist(Shift.getNode());
14054 AddToWorklist(Add.getNode());
14055 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14062 /// This is a stub for TargetLowering::SimplifySetCC.
14063 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14064 SDValue N1, ISD::CondCode Cond,
14065 SDLoc DL, bool foldBooleans) {
14066 TargetLowering::DAGCombinerInfo
14067 DagCombineInfo(DAG, Level, false, this);
14068 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14071 /// Given an ISD::SDIV node expressing a divide by constant, return
14072 /// a DAG expression to select that will generate the same value by multiplying
14073 /// by a magic number.
14074 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14075 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14076 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14080 // Avoid division by zero.
14081 if (C->isNullValue())
14084 std::vector<SDNode*> Built;
14086 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14088 for (SDNode *N : Built)
14093 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14094 /// DAG expression that will generate the same value by right shifting.
14095 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14096 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14100 // Avoid division by zero.
14101 if (C->isNullValue())
14104 std::vector<SDNode *> Built;
14105 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14107 for (SDNode *N : Built)
14112 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14113 /// expression that will generate the same value by multiplying by a magic
14115 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14116 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14117 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14121 // Avoid division by zero.
14122 if (C->isNullValue())
14125 std::vector<SDNode*> Built;
14127 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14129 for (SDNode *N : Built)
14134 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14135 if (Level >= AfterLegalizeDAG)
14138 // Expose the DAG combiner to the target combiner implementations.
14139 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14141 unsigned Iterations = 0;
14142 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14144 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14145 // For the reciprocal, we need to find the zero of the function:
14146 // F(X) = A X - 1 [which has a zero at X = 1/A]
14148 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14149 // does not require additional intermediate precision]
14150 EVT VT = Op.getValueType();
14152 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14154 AddToWorklist(Est.getNode());
14156 // Newton iterations: Est = Est + Est (1 - Arg * Est)
14157 for (unsigned i = 0; i < Iterations; ++i) {
14158 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14159 AddToWorklist(NewEst.getNode());
14161 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14162 AddToWorklist(NewEst.getNode());
14164 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14165 AddToWorklist(NewEst.getNode());
14167 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14168 AddToWorklist(Est.getNode());
14177 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14178 /// For the reciprocal sqrt, we need to find the zero of the function:
14179 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14181 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14182 /// As a result, we precompute A/2 prior to the iteration loop.
14183 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14184 unsigned Iterations,
14185 SDNodeFlags *Flags) {
14186 EVT VT = Arg.getValueType();
14188 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14190 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14191 // this entire sequence requires only one FP constant.
14192 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14193 AddToWorklist(HalfArg.getNode());
14195 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14196 AddToWorklist(HalfArg.getNode());
14198 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14199 for (unsigned i = 0; i < Iterations; ++i) {
14200 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14201 AddToWorklist(NewEst.getNode());
14203 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14204 AddToWorklist(NewEst.getNode());
14206 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14207 AddToWorklist(NewEst.getNode());
14209 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14210 AddToWorklist(Est.getNode());
14215 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14216 /// For the reciprocal sqrt, we need to find the zero of the function:
14217 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14219 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14220 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14221 unsigned Iterations,
14222 SDNodeFlags *Flags) {
14223 EVT VT = Arg.getValueType();
14225 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14226 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14228 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14229 for (unsigned i = 0; i < Iterations; ++i) {
14230 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14231 AddToWorklist(HalfEst.getNode());
14233 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14234 AddToWorklist(Est.getNode());
14236 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14237 AddToWorklist(Est.getNode());
14239 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14240 AddToWorklist(Est.getNode());
14242 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14243 AddToWorklist(Est.getNode());
14248 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14249 if (Level >= AfterLegalizeDAG)
14252 // Expose the DAG combiner to the target combiner implementations.
14253 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14254 unsigned Iterations = 0;
14255 bool UseOneConstNR = false;
14256 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14257 AddToWorklist(Est.getNode());
14259 Est = UseOneConstNR ?
14260 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14261 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14269 /// Return true if base is a frame index, which is known not to alias with
14270 /// anything but itself. Provides base object and offset as results.
14271 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14272 const GlobalValue *&GV, const void *&CV) {
14273 // Assume it is a primitive operation.
14274 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14276 // If it's an adding a simple constant then integrate the offset.
14277 if (Base.getOpcode() == ISD::ADD) {
14278 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14279 Base = Base.getOperand(0);
14280 Offset += C->getZExtValue();
14284 // Return the underlying GlobalValue, and update the Offset. Return false
14285 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14286 // by multiple nodes with different offsets.
14287 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14288 GV = G->getGlobal();
14289 Offset += G->getOffset();
14293 // Return the underlying Constant value, and update the Offset. Return false
14294 // for ConstantSDNodes since the same constant pool entry may be represented
14295 // by multiple nodes with different offsets.
14296 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14297 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14298 : (const void *)C->getConstVal();
14299 Offset += C->getOffset();
14302 // If it's any of the following then it can't alias with anything but itself.
14303 return isa<FrameIndexSDNode>(Base);
14306 /// Return true if there is any possibility that the two addresses overlap.
14307 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14308 // If they are the same then they must be aliases.
14309 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14311 // If they are both volatile then they cannot be reordered.
14312 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14314 // If one operation reads from invariant memory, and the other may store, they
14315 // cannot alias. These should really be checking the equivalent of mayWrite,
14316 // but it only matters for memory nodes other than load /store.
14317 if (Op0->isInvariant() && Op1->writeMem())
14320 if (Op1->isInvariant() && Op0->writeMem())
14323 // Gather base node and offset information.
14324 SDValue Base1, Base2;
14325 int64_t Offset1, Offset2;
14326 const GlobalValue *GV1, *GV2;
14327 const void *CV1, *CV2;
14328 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14329 Base1, Offset1, GV1, CV1);
14330 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14331 Base2, Offset2, GV2, CV2);
14333 // If they have a same base address then check to see if they overlap.
14334 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14335 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14336 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14338 // It is possible for different frame indices to alias each other, mostly
14339 // when tail call optimization reuses return address slots for arguments.
14340 // To catch this case, look up the actual index of frame indices to compute
14341 // the real alias relationship.
14342 if (isFrameIndex1 && isFrameIndex2) {
14343 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14344 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14345 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14346 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14347 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14350 // Otherwise, if we know what the bases are, and they aren't identical, then
14351 // we know they cannot alias.
14352 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14355 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14356 // compared to the size and offset of the access, we may be able to prove they
14357 // do not alias. This check is conservative for now to catch cases created by
14358 // splitting vector types.
14359 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14360 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14361 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14362 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14363 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14364 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14365 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14367 // There is no overlap between these relatively aligned accesses of similar
14368 // size, return no alias.
14369 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14370 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14374 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14376 : DAG.getSubtarget().useAA();
14378 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14379 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14383 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14384 // Use alias analysis information.
14385 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14386 Op1->getSrcValueOffset());
14387 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14388 Op0->getSrcValueOffset() - MinOffset;
14389 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14390 Op1->getSrcValueOffset() - MinOffset;
14391 AliasResult AAResult =
14392 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14393 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14394 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14395 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14396 if (AAResult == NoAlias)
14400 // Otherwise we have to assume they alias.
14404 /// Walk up chain skipping non-aliasing memory nodes,
14405 /// looking for aliasing nodes and adding them to the Aliases vector.
14406 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14407 SmallVectorImpl<SDValue> &Aliases) {
14408 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14409 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14411 // Get alias information for node.
14412 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14415 Chains.push_back(OriginalChain);
14416 unsigned Depth = 0;
14418 // Look at each chain and determine if it is an alias. If so, add it to the
14419 // aliases list. If not, then continue up the chain looking for the next
14421 while (!Chains.empty()) {
14422 SDValue Chain = Chains.pop_back_val();
14424 // For TokenFactor nodes, look at each operand and only continue up the
14425 // chain until we reach the depth limit.
14427 // FIXME: The depth check could be made to return the last non-aliasing
14428 // chain we found before we hit a tokenfactor rather than the original
14432 Aliases.push_back(OriginalChain);
14436 // Don't bother if we've been before.
14437 if (!Visited.insert(Chain.getNode()).second)
14440 switch (Chain.getOpcode()) {
14441 case ISD::EntryToken:
14442 // Entry token is ideal chain operand, but handled in FindBetterChain.
14447 // Get alias information for Chain.
14448 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14449 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14451 // If chain is alias then stop here.
14452 if (!(IsLoad && IsOpLoad) &&
14453 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14454 Aliases.push_back(Chain);
14456 // Look further up the chain.
14457 Chains.push_back(Chain.getOperand(0));
14463 case ISD::TokenFactor:
14464 // We have to check each of the operands of the token factor for "small"
14465 // token factors, so we queue them up. Adding the operands to the queue
14466 // (stack) in reverse order maintains the original order and increases the
14467 // likelihood that getNode will find a matching token factor (CSE.)
14468 if (Chain.getNumOperands() > 16) {
14469 Aliases.push_back(Chain);
14472 for (unsigned n = Chain.getNumOperands(); n;)
14473 Chains.push_back(Chain.getOperand(--n));
14478 // For all other instructions we will just have to take what we can get.
14479 Aliases.push_back(Chain);
14484 // We need to be careful here to also search for aliases through the
14485 // value operand of a store, etc. Consider the following situation:
14487 // L1 = load Token1, %52
14488 // S1 = store Token1, L1, %51
14489 // L2 = load Token1, %52+8
14490 // S2 = store Token1, L2, %51+8
14491 // Token2 = Token(S1, S2)
14492 // L3 = load Token2, %53
14493 // S3 = store Token2, L3, %52
14494 // L4 = load Token2, %53+8
14495 // S4 = store Token2, L4, %52+8
14496 // If we search for aliases of S3 (which loads address %52), and we look
14497 // only through the chain, then we'll miss the trivial dependence on L1
14498 // (which also loads from %52). We then might change all loads and
14499 // stores to use Token1 as their chain operand, which could result in
14500 // copying %53 into %52 before copying %52 into %51 (which should
14503 // The problem is, however, that searching for such data dependencies
14504 // can become expensive, and the cost is not directly related to the
14505 // chain depth. Instead, we'll rule out such configurations here by
14506 // insisting that we've visited all chain users (except for users
14507 // of the original chain, which is not necessary). When doing this,
14508 // we need to look through nodes we don't care about (otherwise, things
14509 // like register copies will interfere with trivial cases).
14511 SmallVector<const SDNode *, 16> Worklist;
14512 for (const SDNode *N : Visited)
14513 if (N != OriginalChain.getNode())
14514 Worklist.push_back(N);
14516 while (!Worklist.empty()) {
14517 const SDNode *M = Worklist.pop_back_val();
14519 // We have already visited M, and want to make sure we've visited any uses
14520 // of M that we care about. For uses that we've not visisted, and don't
14521 // care about, queue them to the worklist.
14523 for (SDNode::use_iterator UI = M->use_begin(),
14524 UIE = M->use_end(); UI != UIE; ++UI)
14525 if (UI.getUse().getValueType() == MVT::Other &&
14526 Visited.insert(*UI).second) {
14527 if (isa<MemSDNode>(*UI)) {
14528 // We've not visited this use, and we care about it (it could have an
14529 // ordering dependency with the original node).
14531 Aliases.push_back(OriginalChain);
14535 // We've not visited this use, but we don't care about it. Mark it as
14536 // visited and enqueue it to the worklist.
14537 Worklist.push_back(*UI);
14542 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14543 /// (aliasing node.)
14544 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14545 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14547 // Accumulate all the aliases to this node.
14548 GatherAllAliases(N, OldChain, Aliases);
14550 // If no operands then chain to entry token.
14551 if (Aliases.size() == 0)
14552 return DAG.getEntryNode();
14554 // If a single operand then chain to it. We don't need to revisit it.
14555 if (Aliases.size() == 1)
14558 // Construct a custom tailored token factor.
14559 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14562 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14563 // This holds the base pointer, index, and the offset in bytes from the base
14565 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14567 // We must have a base and an offset.
14568 if (!BasePtr.Base.getNode())
14571 // Do not handle stores to undef base pointers.
14572 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14575 SmallVector<StoreSDNode *, 8> ChainedStores;
14576 ChainedStores.push_back(St);
14578 // Walk up the chain and look for nodes with offsets from the same
14579 // base pointer. Stop when reaching an instruction with a different kind
14580 // or instruction which has a different base pointer.
14581 StoreSDNode *Index = St;
14583 // If the chain has more than one use, then we can't reorder the mem ops.
14584 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14587 if (Index->isVolatile() || Index->isIndexed())
14590 // Find the base pointer and offset for this memory node.
14591 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14593 // Check that the base pointer is the same as the original one.
14594 if (!Ptr.equalBaseIndex(BasePtr))
14597 // Find the next memory operand in the chain. If the next operand in the
14598 // chain is a store then move up and continue the scan with the next
14599 // memory operand. If the next operand is a load save it and use alias
14600 // information to check if it interferes with anything.
14601 SDNode *NextInChain = Index->getChain().getNode();
14603 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14604 // We found a store node. Use it for the next iteration.
14605 ChainedStores.push_back(STn);
14608 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14609 NextInChain = Ldn->getChain().getNode();
14618 bool MadeChange = false;
14619 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14621 for (StoreSDNode *ChainedStore : ChainedStores) {
14622 SDValue Chain = ChainedStore->getChain();
14623 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14625 if (Chain != BetterChain) {
14627 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14631 // Do all replacements after finding the replacements to make to avoid making
14632 // the chains more complicated by introducing new TokenFactors.
14633 for (auto Replacement : BetterChains)
14634 replaceStoreChain(Replacement.first, Replacement.second);
14639 /// This is the entry point for the file.
14640 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14641 CodeGenOpt::Level OptLevel) {
14642 /// This is the main entry point to this class.
14643 DAGCombiner(*this, AA, OptLevel).Run(Level);