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 the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2333 // Otherwise, we break the simplification logic in visitREM().
2334 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2335 if (SDValue DivRem = useDivRem(N))
2339 if (N0.getOpcode() == ISD::UNDEF)
2340 return DAG.getConstant(0, DL, VT);
2341 // X / undef -> undef
2342 if (N1.getOpcode() == ISD::UNDEF)
2348 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2349 SDValue N0 = N->getOperand(0);
2350 SDValue N1 = N->getOperand(1);
2351 EVT VT = N->getValueType(0);
2355 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2360 // fold (udiv c1, c2) -> c1/c2
2361 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2362 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2364 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2367 // fold (udiv x, (1 << c)) -> x >>u c
2368 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2369 return DAG.getNode(ISD::SRL, DL, VT, N0,
2370 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2371 getShiftAmountTy(N0.getValueType())));
2373 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2374 if (N1.getOpcode() == ISD::SHL) {
2375 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2376 if (SHC->getAPIntValue().isPowerOf2()) {
2377 EVT ADDVT = N1.getOperand(1).getValueType();
2378 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2380 DAG.getConstant(SHC->getAPIntValue()
2383 AddToWorklist(Add.getNode());
2384 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2389 // fold (udiv x, c) -> alternate
2390 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2391 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2392 if (SDValue Op = BuildUDIV(N))
2395 // sdiv, srem -> sdivrem
2396 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2397 // Otherwise, we break the simplification logic in visitREM().
2398 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2399 if (SDValue DivRem = useDivRem(N))
2403 if (N0.getOpcode() == ISD::UNDEF)
2404 return DAG.getConstant(0, DL, VT);
2405 // X / undef -> undef
2406 if (N1.getOpcode() == ISD::UNDEF)
2412 // handles ISD::SREM and ISD::UREM
2413 SDValue DAGCombiner::visitREM(SDNode *N) {
2414 unsigned Opcode = N->getOpcode();
2415 SDValue N0 = N->getOperand(0);
2416 SDValue N1 = N->getOperand(1);
2417 EVT VT = N->getValueType(0);
2418 bool isSigned = (Opcode == ISD::SREM);
2421 // fold (rem c1, c2) -> c1%c2
2422 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2423 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2425 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2429 // If we know the sign bits of both operands are zero, strength reduce to a
2430 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2431 if (!VT.isVector()) {
2432 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2433 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2436 // fold (urem x, pow2) -> (and x, pow2-1)
2437 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2438 N1C->getAPIntValue().isPowerOf2()) {
2439 return DAG.getNode(ISD::AND, DL, VT, N0,
2440 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2442 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2443 if (N1.getOpcode() == ISD::SHL) {
2444 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2445 if (SHC->getAPIntValue().isPowerOf2()) {
2447 DAG.getNode(ISD::ADD, DL, VT, N1,
2448 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2450 AddToWorklist(Add.getNode());
2451 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2457 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2459 // If X/C can be simplified by the division-by-constant logic, lower
2460 // X%C to the equivalent of X-X/C*C.
2461 // To avoid mangling nodes, this simplification requires that the combine()
2462 // call for the speculative DIV must not cause a DIVREM conversion. We guard
2463 // against this by skipping the simplification if isIntDivCheap(). When
2464 // div is not cheap, combine will not return a DIVREM. Regardless,
2465 // checking cheapness here makes sense since the simplification results in
2467 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2468 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2469 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2470 AddToWorklist(Div.getNode());
2471 SDValue OptimizedDiv = combine(Div.getNode());
2472 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2473 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2474 (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2475 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2476 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2477 AddToWorklist(Mul.getNode());
2482 // sdiv, srem -> sdivrem
2483 if (SDValue DivRem = useDivRem(N))
2484 return DivRem.getValue(1);
2487 if (N0.getOpcode() == ISD::UNDEF)
2488 return DAG.getConstant(0, DL, VT);
2489 // X % undef -> undef
2490 if (N1.getOpcode() == ISD::UNDEF)
2496 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2497 SDValue N0 = N->getOperand(0);
2498 SDValue N1 = N->getOperand(1);
2499 EVT VT = N->getValueType(0);
2502 // fold (mulhs x, 0) -> 0
2503 if (isNullConstant(N1))
2505 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2506 if (isOneConstant(N1)) {
2508 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2509 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2511 getShiftAmountTy(N0.getValueType())));
2513 // fold (mulhs x, undef) -> 0
2514 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2515 return DAG.getConstant(0, SDLoc(N), VT);
2517 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2519 if (VT.isSimple() && !VT.isVector()) {
2520 MVT Simple = VT.getSimpleVT();
2521 unsigned SimpleSize = Simple.getSizeInBits();
2522 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2523 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2524 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2525 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2526 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2527 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2528 DAG.getConstant(SimpleSize, DL,
2529 getShiftAmountTy(N1.getValueType())));
2530 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2537 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2538 SDValue N0 = N->getOperand(0);
2539 SDValue N1 = N->getOperand(1);
2540 EVT VT = N->getValueType(0);
2543 // fold (mulhu x, 0) -> 0
2544 if (isNullConstant(N1))
2546 // fold (mulhu x, 1) -> 0
2547 if (isOneConstant(N1))
2548 return DAG.getConstant(0, DL, N0.getValueType());
2549 // fold (mulhu x, undef) -> 0
2550 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2551 return DAG.getConstant(0, DL, VT);
2553 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2555 if (VT.isSimple() && !VT.isVector()) {
2556 MVT Simple = VT.getSimpleVT();
2557 unsigned SimpleSize = Simple.getSizeInBits();
2558 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2559 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2560 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2561 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2562 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2563 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2564 DAG.getConstant(SimpleSize, DL,
2565 getShiftAmountTy(N1.getValueType())));
2566 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2573 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2574 /// give the opcodes for the two computations that are being performed. Return
2575 /// true if a simplification was made.
2576 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2578 // If the high half is not needed, just compute the low half.
2579 bool HiExists = N->hasAnyUseOfValue(1);
2581 (!LegalOperations ||
2582 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2583 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2584 return CombineTo(N, Res, Res);
2587 // If the low half is not needed, just compute the high half.
2588 bool LoExists = N->hasAnyUseOfValue(0);
2590 (!LegalOperations ||
2591 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2592 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2593 return CombineTo(N, Res, Res);
2596 // If both halves are used, return as it is.
2597 if (LoExists && HiExists)
2600 // If the two computed results can be simplified separately, separate them.
2602 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2603 AddToWorklist(Lo.getNode());
2604 SDValue LoOpt = combine(Lo.getNode());
2605 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2606 (!LegalOperations ||
2607 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2608 return CombineTo(N, LoOpt, LoOpt);
2612 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2613 AddToWorklist(Hi.getNode());
2614 SDValue HiOpt = combine(Hi.getNode());
2615 if (HiOpt.getNode() && HiOpt != Hi &&
2616 (!LegalOperations ||
2617 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2618 return CombineTo(N, HiOpt, HiOpt);
2624 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2625 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2628 EVT VT = N->getValueType(0);
2631 // If the type is twice as wide is legal, transform the mulhu to a wider
2632 // multiply plus a shift.
2633 if (VT.isSimple() && !VT.isVector()) {
2634 MVT Simple = VT.getSimpleVT();
2635 unsigned SimpleSize = Simple.getSizeInBits();
2636 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2637 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2638 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2639 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2640 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2641 // Compute the high part as N1.
2642 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2643 DAG.getConstant(SimpleSize, DL,
2644 getShiftAmountTy(Lo.getValueType())));
2645 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2646 // Compute the low part as N0.
2647 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2648 return CombineTo(N, Lo, Hi);
2655 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2656 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2659 EVT VT = N->getValueType(0);
2662 // If the type is twice as wide is legal, transform the mulhu to a wider
2663 // multiply plus a shift.
2664 if (VT.isSimple() && !VT.isVector()) {
2665 MVT Simple = VT.getSimpleVT();
2666 unsigned SimpleSize = Simple.getSizeInBits();
2667 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2668 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2669 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2670 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2671 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2672 // Compute the high part as N1.
2673 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2674 DAG.getConstant(SimpleSize, DL,
2675 getShiftAmountTy(Lo.getValueType())));
2676 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2677 // Compute the low part as N0.
2678 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2679 return CombineTo(N, Lo, Hi);
2686 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2687 // (smulo x, 2) -> (saddo x, x)
2688 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2689 if (C2->getAPIntValue() == 2)
2690 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2691 N->getOperand(0), N->getOperand(0));
2696 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2697 // (umulo x, 2) -> (uaddo x, x)
2698 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2699 if (C2->getAPIntValue() == 2)
2700 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2701 N->getOperand(0), N->getOperand(0));
2706 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2707 SDValue N0 = N->getOperand(0);
2708 SDValue N1 = N->getOperand(1);
2709 EVT VT = N0.getValueType();
2713 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2716 // fold (add c1, c2) -> c1+c2
2717 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2718 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2720 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2722 // canonicalize constant to RHS
2723 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2724 !isConstantIntBuildVectorOrConstantInt(N1))
2725 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2730 /// If this is a binary operator with two operands of the same opcode, try to
2732 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2733 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2734 EVT VT = N0.getValueType();
2735 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2737 // Bail early if none of these transforms apply.
2738 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2740 // For each of OP in AND/OR/XOR:
2741 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2742 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2743 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2744 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2745 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2747 // do not sink logical op inside of a vector extend, since it may combine
2749 EVT Op0VT = N0.getOperand(0).getValueType();
2750 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2751 N0.getOpcode() == ISD::SIGN_EXTEND ||
2752 N0.getOpcode() == ISD::BSWAP ||
2753 // Avoid infinite looping with PromoteIntBinOp.
2754 (N0.getOpcode() == ISD::ANY_EXTEND &&
2755 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2756 (N0.getOpcode() == ISD::TRUNCATE &&
2757 (!TLI.isZExtFree(VT, Op0VT) ||
2758 !TLI.isTruncateFree(Op0VT, VT)) &&
2759 TLI.isTypeLegal(Op0VT))) &&
2761 Op0VT == N1.getOperand(0).getValueType() &&
2762 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2763 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2764 N0.getOperand(0).getValueType(),
2765 N0.getOperand(0), N1.getOperand(0));
2766 AddToWorklist(ORNode.getNode());
2767 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2770 // For each of OP in SHL/SRL/SRA/AND...
2771 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2772 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2773 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2774 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2775 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2776 N0.getOperand(1) == N1.getOperand(1)) {
2777 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2778 N0.getOperand(0).getValueType(),
2779 N0.getOperand(0), N1.getOperand(0));
2780 AddToWorklist(ORNode.getNode());
2781 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2782 ORNode, N0.getOperand(1));
2785 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2786 // Only perform this optimization after type legalization and before
2787 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2788 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2789 // we don't want to undo this promotion.
2790 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2792 if ((N0.getOpcode() == ISD::BITCAST ||
2793 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2794 Level == AfterLegalizeTypes) {
2795 SDValue In0 = N0.getOperand(0);
2796 SDValue In1 = N1.getOperand(0);
2797 EVT In0Ty = In0.getValueType();
2798 EVT In1Ty = In1.getValueType();
2800 // If both incoming values are integers, and the original types are the
2802 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2803 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2804 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2805 AddToWorklist(Op.getNode());
2810 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2811 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2812 // If both shuffles use the same mask, and both shuffle within a single
2813 // vector, then it is worthwhile to move the swizzle after the operation.
2814 // The type-legalizer generates this pattern when loading illegal
2815 // vector types from memory. In many cases this allows additional shuffle
2817 // There are other cases where moving the shuffle after the xor/and/or
2818 // is profitable even if shuffles don't perform a swizzle.
2819 // If both shuffles use the same mask, and both shuffles have the same first
2820 // or second operand, then it might still be profitable to move the shuffle
2821 // after the xor/and/or operation.
2822 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2823 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2824 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2826 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2827 "Inputs to shuffles are not the same type");
2829 // Check that both shuffles use the same mask. The masks are known to be of
2830 // the same length because the result vector type is the same.
2831 // Check also that shuffles have only one use to avoid introducing extra
2833 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2834 SVN0->getMask().equals(SVN1->getMask())) {
2835 SDValue ShOp = N0->getOperand(1);
2837 // Don't try to fold this node if it requires introducing a
2838 // build vector of all zeros that might be illegal at this stage.
2839 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2841 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2846 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2847 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2848 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2849 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2850 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2851 N0->getOperand(0), N1->getOperand(0));
2852 AddToWorklist(NewNode.getNode());
2853 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2854 &SVN0->getMask()[0]);
2857 // Don't try to fold this node if it requires introducing a
2858 // build vector of all zeros that might be illegal at this stage.
2859 ShOp = N0->getOperand(0);
2860 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2862 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2867 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2868 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2869 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2870 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2871 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2872 N0->getOperand(1), N1->getOperand(1));
2873 AddToWorklist(NewNode.getNode());
2874 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2875 &SVN0->getMask()[0]);
2883 /// This contains all DAGCombine rules which reduce two values combined by
2884 /// an And operation to a single value. This makes them reusable in the context
2885 /// of visitSELECT(). Rules involving constants are not included as
2886 /// visitSELECT() already handles those cases.
2887 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2888 SDNode *LocReference) {
2889 EVT VT = N1.getValueType();
2891 // fold (and x, undef) -> 0
2892 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2893 return DAG.getConstant(0, SDLoc(LocReference), VT);
2894 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2895 SDValue LL, LR, RL, RR, CC0, CC1;
2896 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2897 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2898 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2900 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2901 LL.getValueType().isInteger()) {
2902 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2903 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2904 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2905 LR.getValueType(), LL, RL);
2906 AddToWorklist(ORNode.getNode());
2907 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2909 if (isAllOnesConstant(LR)) {
2910 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2911 if (Op1 == ISD::SETEQ) {
2912 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2913 LR.getValueType(), LL, RL);
2914 AddToWorklist(ANDNode.getNode());
2915 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2917 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2918 if (Op1 == ISD::SETGT) {
2919 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2920 LR.getValueType(), LL, RL);
2921 AddToWorklist(ORNode.getNode());
2922 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2926 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2927 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2928 Op0 == Op1 && LL.getValueType().isInteger() &&
2929 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2930 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2932 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2933 LL, DAG.getConstant(1, DL,
2934 LL.getValueType()));
2935 AddToWorklist(ADDNode.getNode());
2936 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2937 DAG.getConstant(2, DL, LL.getValueType()),
2940 // canonicalize equivalent to ll == rl
2941 if (LL == RR && LR == RL) {
2942 Op1 = ISD::getSetCCSwappedOperands(Op1);
2945 if (LL == RL && LR == RR) {
2946 bool isInteger = LL.getValueType().isInteger();
2947 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2948 if (Result != ISD::SETCC_INVALID &&
2949 (!LegalOperations ||
2950 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2951 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2952 EVT CCVT = getSetCCResultType(LL.getValueType());
2953 if (N0.getValueType() == CCVT ||
2954 (!LegalOperations && N0.getValueType() == MVT::i1))
2955 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2961 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2962 VT.getSizeInBits() <= 64) {
2963 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2964 APInt ADDC = ADDI->getAPIntValue();
2965 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2966 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2967 // immediate for an add, but it is legal if its top c2 bits are set,
2968 // transform the ADD so the immediate doesn't need to be materialized
2970 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2971 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2972 SRLI->getZExtValue());
2973 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2975 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2978 DAG.getNode(ISD::ADD, DL, VT,
2979 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2980 CombineTo(N0.getNode(), NewAdd);
2981 // Return N so it doesn't get rechecked!
2982 return SDValue(LocReference, 0);
2993 SDValue DAGCombiner::visitAND(SDNode *N) {
2994 SDValue N0 = N->getOperand(0);
2995 SDValue N1 = N->getOperand(1);
2996 EVT VT = N1.getValueType();
2999 if (VT.isVector()) {
3000 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3003 // fold (and x, 0) -> 0, vector edition
3004 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3005 // do not return N0, because undef node may exist in N0
3006 return DAG.getConstant(
3007 APInt::getNullValue(
3008 N0.getValueType().getScalarType().getSizeInBits()),
3009 SDLoc(N), N0.getValueType());
3010 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3011 // do not return N1, because undef node may exist in N1
3012 return DAG.getConstant(
3013 APInt::getNullValue(
3014 N1.getValueType().getScalarType().getSizeInBits()),
3015 SDLoc(N), N1.getValueType());
3017 // fold (and x, -1) -> x, vector edition
3018 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3020 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3024 // fold (and c1, c2) -> c1&c2
3025 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3026 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3027 if (N0C && N1C && !N1C->isOpaque())
3028 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3029 // canonicalize constant to RHS
3030 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3031 !isConstantIntBuildVectorOrConstantInt(N1))
3032 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3033 // fold (and x, -1) -> x
3034 if (isAllOnesConstant(N1))
3036 // if (and x, c) is known to be zero, return 0
3037 unsigned BitWidth = VT.getScalarType().getSizeInBits();
3038 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3039 APInt::getAllOnesValue(BitWidth)))
3040 return DAG.getConstant(0, SDLoc(N), VT);
3042 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3044 // fold (and (or x, C), D) -> D if (C & D) == D
3045 if (N1C && N0.getOpcode() == ISD::OR)
3046 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3047 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3049 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3050 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3051 SDValue N0Op0 = N0.getOperand(0);
3052 APInt Mask = ~N1C->getAPIntValue();
3053 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3054 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3055 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3056 N0.getValueType(), N0Op0);
3058 // Replace uses of the AND with uses of the Zero extend node.
3061 // We actually want to replace all uses of the any_extend with the
3062 // zero_extend, to avoid duplicating things. This will later cause this
3063 // AND to be folded.
3064 CombineTo(N0.getNode(), Zext);
3065 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3068 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3069 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3070 // already be zero by virtue of the width of the base type of the load.
3072 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3074 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3075 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3076 N0.getOpcode() == ISD::LOAD) {
3077 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3078 N0 : N0.getOperand(0) );
3080 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3081 // This can be a pure constant or a vector splat, in which case we treat the
3082 // vector as a scalar and use the splat value.
3083 APInt Constant = APInt::getNullValue(1);
3084 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3085 Constant = C->getAPIntValue();
3086 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3087 APInt SplatValue, SplatUndef;
3088 unsigned SplatBitSize;
3090 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3091 SplatBitSize, HasAnyUndefs);
3093 // Undef bits can contribute to a possible optimisation if set, so
3095 SplatValue |= SplatUndef;
3097 // The splat value may be something like "0x00FFFFFF", which means 0 for
3098 // the first vector value and FF for the rest, repeating. We need a mask
3099 // that will apply equally to all members of the vector, so AND all the
3100 // lanes of the constant together.
3101 EVT VT = Vector->getValueType(0);
3102 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3104 // If the splat value has been compressed to a bitlength lower
3105 // than the size of the vector lane, we need to re-expand it to
3107 if (BitWidth > SplatBitSize)
3108 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3109 SplatBitSize < BitWidth;
3110 SplatBitSize = SplatBitSize * 2)
3111 SplatValue |= SplatValue.shl(SplatBitSize);
3113 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3114 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3115 if (SplatBitSize % BitWidth == 0) {
3116 Constant = APInt::getAllOnesValue(BitWidth);
3117 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3118 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3123 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3124 // actually legal and isn't going to get expanded, else this is a false
3126 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3127 Load->getValueType(0),
3128 Load->getMemoryVT());
3130 // Resize the constant to the same size as the original memory access before
3131 // extension. If it is still the AllOnesValue then this AND is completely
3134 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3137 switch (Load->getExtensionType()) {
3138 default: B = false; break;
3139 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3141 case ISD::NON_EXTLOAD: B = true; break;
3144 if (B && Constant.isAllOnesValue()) {
3145 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3146 // preserve semantics once we get rid of the AND.
3147 SDValue NewLoad(Load, 0);
3148 if (Load->getExtensionType() == ISD::EXTLOAD) {
3149 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3150 Load->getValueType(0), SDLoc(Load),
3151 Load->getChain(), Load->getBasePtr(),
3152 Load->getOffset(), Load->getMemoryVT(),
3153 Load->getMemOperand());
3154 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3155 if (Load->getNumValues() == 3) {
3156 // PRE/POST_INC loads have 3 values.
3157 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3158 NewLoad.getValue(2) };
3159 CombineTo(Load, To, 3, true);
3161 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3165 // Fold the AND away, taking care not to fold to the old load node if we
3167 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3169 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3173 // fold (and (load x), 255) -> (zextload x, i8)
3174 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3175 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3176 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3177 (N0.getOpcode() == ISD::ANY_EXTEND &&
3178 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3179 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3180 LoadSDNode *LN0 = HasAnyExt
3181 ? cast<LoadSDNode>(N0.getOperand(0))
3182 : cast<LoadSDNode>(N0);
3183 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3184 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3185 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3186 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3187 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3188 EVT LoadedVT = LN0->getMemoryVT();
3189 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3191 if (ExtVT == LoadedVT &&
3192 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3196 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3197 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3198 LN0->getMemOperand());
3200 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3201 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3204 // Do not change the width of a volatile load.
3205 // Do not generate loads of non-round integer types since these can
3206 // be expensive (and would be wrong if the type is not byte sized).
3207 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3208 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3210 EVT PtrType = LN0->getOperand(1).getValueType();
3212 unsigned Alignment = LN0->getAlignment();
3213 SDValue NewPtr = LN0->getBasePtr();
3215 // For big endian targets, we need to add an offset to the pointer
3216 // to load the correct bytes. For little endian systems, we merely
3217 // need to read fewer bytes from the same pointer.
3218 if (DAG.getDataLayout().isBigEndian()) {
3219 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3220 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3221 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3223 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3224 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3225 Alignment = MinAlign(Alignment, PtrOff);
3228 AddToWorklist(NewPtr.getNode());
3231 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3232 LN0->getChain(), NewPtr,
3233 LN0->getPointerInfo(),
3234 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3235 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3237 CombineTo(LN0, Load, Load.getValue(1));
3238 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3244 if (SDValue Combined = visitANDLike(N0, N1, N))
3247 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3248 if (N0.getOpcode() == N1.getOpcode())
3249 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3252 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3253 // fold (and (sra)) -> (and (srl)) when possible.
3254 if (!VT.isVector() &&
3255 SimplifyDemandedBits(SDValue(N, 0)))
3256 return SDValue(N, 0);
3258 // fold (zext_inreg (extload x)) -> (zextload x)
3259 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3260 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3261 EVT MemVT = LN0->getMemoryVT();
3262 // If we zero all the possible extended bits, then we can turn this into
3263 // a zextload if we are running before legalize or the operation is legal.
3264 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3265 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3266 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3267 ((!LegalOperations && !LN0->isVolatile()) ||
3268 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3269 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3270 LN0->getChain(), LN0->getBasePtr(),
3271 MemVT, LN0->getMemOperand());
3273 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3274 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3277 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3278 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3280 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3281 EVT MemVT = LN0->getMemoryVT();
3282 // If we zero all the possible extended bits, then we can turn this into
3283 // a zextload if we are running before legalize or the operation is legal.
3284 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3285 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3286 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3287 ((!LegalOperations && !LN0->isVolatile()) ||
3288 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3289 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3290 LN0->getChain(), LN0->getBasePtr(),
3291 MemVT, LN0->getMemOperand());
3293 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3294 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3297 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3298 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3299 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3300 N0.getOperand(1), false);
3301 if (BSwap.getNode())
3308 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3309 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3310 bool DemandHighBits) {
3311 if (!LegalOperations)
3314 EVT VT = N->getValueType(0);
3315 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3317 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3320 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3321 bool LookPassAnd0 = false;
3322 bool LookPassAnd1 = false;
3323 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3325 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3327 if (N0.getOpcode() == ISD::AND) {
3328 if (!N0.getNode()->hasOneUse())
3330 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3331 if (!N01C || N01C->getZExtValue() != 0xFF00)
3333 N0 = N0.getOperand(0);
3334 LookPassAnd0 = true;
3337 if (N1.getOpcode() == ISD::AND) {
3338 if (!N1.getNode()->hasOneUse())
3340 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3341 if (!N11C || N11C->getZExtValue() != 0xFF)
3343 N1 = N1.getOperand(0);
3344 LookPassAnd1 = true;
3347 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3349 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3351 if (!N0.getNode()->hasOneUse() ||
3352 !N1.getNode()->hasOneUse())
3355 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3356 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3359 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3362 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3363 SDValue N00 = N0->getOperand(0);
3364 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3365 if (!N00.getNode()->hasOneUse())
3367 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3368 if (!N001C || N001C->getZExtValue() != 0xFF)
3370 N00 = N00.getOperand(0);
3371 LookPassAnd0 = true;
3374 SDValue N10 = N1->getOperand(0);
3375 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3376 if (!N10.getNode()->hasOneUse())
3378 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3379 if (!N101C || N101C->getZExtValue() != 0xFF00)
3381 N10 = N10.getOperand(0);
3382 LookPassAnd1 = true;
3388 // Make sure everything beyond the low halfword gets set to zero since the SRL
3389 // 16 will clear the top bits.
3390 unsigned OpSizeInBits = VT.getSizeInBits();
3391 if (DemandHighBits && OpSizeInBits > 16) {
3392 // If the left-shift isn't masked out then the only way this is a bswap is
3393 // if all bits beyond the low 8 are 0. In that case the entire pattern
3394 // reduces to a left shift anyway: leave it for other parts of the combiner.
3398 // However, if the right shift isn't masked out then it might be because
3399 // it's not needed. See if we can spot that too.
3400 if (!LookPassAnd1 &&
3401 !DAG.MaskedValueIsZero(
3402 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3406 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3407 if (OpSizeInBits > 16) {
3409 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3410 DAG.getConstant(OpSizeInBits - 16, DL,
3411 getShiftAmountTy(VT)));
3416 /// Return true if the specified node is an element that makes up a 32-bit
3417 /// packed halfword byteswap.
3418 /// ((x & 0x000000ff) << 8) |
3419 /// ((x & 0x0000ff00) >> 8) |
3420 /// ((x & 0x00ff0000) << 8) |
3421 /// ((x & 0xff000000) >> 8)
3422 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3423 if (!N.getNode()->hasOneUse())
3426 unsigned Opc = N.getOpcode();
3427 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3430 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3435 switch (N1C->getZExtValue()) {
3438 case 0xFF: Num = 0; break;
3439 case 0xFF00: Num = 1; break;
3440 case 0xFF0000: Num = 2; break;
3441 case 0xFF000000: Num = 3; break;
3444 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3445 SDValue N0 = N.getOperand(0);
3446 if (Opc == ISD::AND) {
3447 if (Num == 0 || Num == 2) {
3449 // (x >> 8) & 0xff0000
3450 if (N0.getOpcode() != ISD::SRL)
3452 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3453 if (!C || C->getZExtValue() != 8)
3456 // (x << 8) & 0xff00
3457 // (x << 8) & 0xff000000
3458 if (N0.getOpcode() != ISD::SHL)
3460 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3461 if (!C || C->getZExtValue() != 8)
3464 } else if (Opc == ISD::SHL) {
3466 // (x & 0xff0000) << 8
3467 if (Num != 0 && Num != 2)
3469 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3470 if (!C || C->getZExtValue() != 8)
3472 } else { // Opc == ISD::SRL
3473 // (x & 0xff00) >> 8
3474 // (x & 0xff000000) >> 8
3475 if (Num != 1 && Num != 3)
3477 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3478 if (!C || C->getZExtValue() != 8)
3485 Parts[Num] = N0.getOperand(0).getNode();
3489 /// Match a 32-bit packed halfword bswap. That is
3490 /// ((x & 0x000000ff) << 8) |
3491 /// ((x & 0x0000ff00) >> 8) |
3492 /// ((x & 0x00ff0000) << 8) |
3493 /// ((x & 0xff000000) >> 8)
3494 /// => (rotl (bswap x), 16)
3495 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3496 if (!LegalOperations)
3499 EVT VT = N->getValueType(0);
3502 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3506 // (or (or (and), (and)), (or (and), (and)))
3507 // (or (or (or (and), (and)), (and)), (and))
3508 if (N0.getOpcode() != ISD::OR)
3510 SDValue N00 = N0.getOperand(0);
3511 SDValue N01 = N0.getOperand(1);
3512 SDNode *Parts[4] = {};
3514 if (N1.getOpcode() == ISD::OR &&
3515 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3516 // (or (or (and), (and)), (or (and), (and)))
3517 SDValue N000 = N00.getOperand(0);
3518 if (!isBSwapHWordElement(N000, Parts))
3521 SDValue N001 = N00.getOperand(1);
3522 if (!isBSwapHWordElement(N001, Parts))
3524 SDValue N010 = N01.getOperand(0);
3525 if (!isBSwapHWordElement(N010, Parts))
3527 SDValue N011 = N01.getOperand(1);
3528 if (!isBSwapHWordElement(N011, Parts))
3531 // (or (or (or (and), (and)), (and)), (and))
3532 if (!isBSwapHWordElement(N1, Parts))
3534 if (!isBSwapHWordElement(N01, Parts))
3536 if (N00.getOpcode() != ISD::OR)
3538 SDValue N000 = N00.getOperand(0);
3539 if (!isBSwapHWordElement(N000, Parts))
3541 SDValue N001 = N00.getOperand(1);
3542 if (!isBSwapHWordElement(N001, Parts))
3546 // Make sure the parts are all coming from the same node.
3547 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3551 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3552 SDValue(Parts[0], 0));
3554 // Result of the bswap should be rotated by 16. If it's not legal, then
3555 // do (x << 16) | (x >> 16).
3556 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3557 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3558 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3559 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3560 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3561 return DAG.getNode(ISD::OR, DL, VT,
3562 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3563 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3566 /// This contains all DAGCombine rules which reduce two values combined by
3567 /// an Or operation to a single value \see visitANDLike().
3568 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3569 EVT VT = N1.getValueType();
3570 // fold (or x, undef) -> -1
3571 if (!LegalOperations &&
3572 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3573 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3574 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3575 SDLoc(LocReference), VT);
3577 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3578 SDValue LL, LR, RL, RR, CC0, CC1;
3579 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3580 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3581 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3583 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3584 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3585 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3586 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3587 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3588 LR.getValueType(), LL, RL);
3589 AddToWorklist(ORNode.getNode());
3590 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3592 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3593 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3594 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3595 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3596 LR.getValueType(), LL, RL);
3597 AddToWorklist(ANDNode.getNode());
3598 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3601 // canonicalize equivalent to ll == rl
3602 if (LL == RR && LR == RL) {
3603 Op1 = ISD::getSetCCSwappedOperands(Op1);
3606 if (LL == RL && LR == RR) {
3607 bool isInteger = LL.getValueType().isInteger();
3608 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3609 if (Result != ISD::SETCC_INVALID &&
3610 (!LegalOperations ||
3611 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3612 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3613 EVT CCVT = getSetCCResultType(LL.getValueType());
3614 if (N0.getValueType() == CCVT ||
3615 (!LegalOperations && N0.getValueType() == MVT::i1))
3616 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3622 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3623 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3624 // Don't increase # computations.
3625 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3626 // We can only do this xform if we know that bits from X that are set in C2
3627 // but not in C1 are already zero. Likewise for Y.
3628 if (const ConstantSDNode *N0O1C =
3629 getAsNonOpaqueConstant(N0.getOperand(1))) {
3630 if (const ConstantSDNode *N1O1C =
3631 getAsNonOpaqueConstant(N1.getOperand(1))) {
3632 // We can only do this xform if we know that bits from X that are set in
3633 // C2 but not in C1 are already zero. Likewise for Y.
3634 const APInt &LHSMask = N0O1C->getAPIntValue();
3635 const APInt &RHSMask = N1O1C->getAPIntValue();
3637 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3638 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3639 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3640 N0.getOperand(0), N1.getOperand(0));
3641 SDLoc DL(LocReference);
3642 return DAG.getNode(ISD::AND, DL, VT, X,
3643 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3649 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3650 if (N0.getOpcode() == ISD::AND &&
3651 N1.getOpcode() == ISD::AND &&
3652 N0.getOperand(0) == N1.getOperand(0) &&
3653 // Don't increase # computations.
3654 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3655 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3656 N0.getOperand(1), N1.getOperand(1));
3657 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3663 SDValue DAGCombiner::visitOR(SDNode *N) {
3664 SDValue N0 = N->getOperand(0);
3665 SDValue N1 = N->getOperand(1);
3666 EVT VT = N1.getValueType();
3669 if (VT.isVector()) {
3670 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3673 // fold (or x, 0) -> x, vector edition
3674 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3676 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3679 // fold (or x, -1) -> -1, vector edition
3680 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3681 // do not return N0, because undef node may exist in N0
3682 return DAG.getConstant(
3683 APInt::getAllOnesValue(
3684 N0.getValueType().getScalarType().getSizeInBits()),
3685 SDLoc(N), N0.getValueType());
3686 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3687 // do not return N1, because undef node may exist in N1
3688 return DAG.getConstant(
3689 APInt::getAllOnesValue(
3690 N1.getValueType().getScalarType().getSizeInBits()),
3691 SDLoc(N), N1.getValueType());
3693 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3694 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3695 // Do this only if the resulting shuffle is legal.
3696 if (isa<ShuffleVectorSDNode>(N0) &&
3697 isa<ShuffleVectorSDNode>(N1) &&
3698 // Avoid folding a node with illegal type.
3699 TLI.isTypeLegal(VT) &&
3700 N0->getOperand(1) == N1->getOperand(1) &&
3701 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3702 bool CanFold = true;
3703 unsigned NumElts = VT.getVectorNumElements();
3704 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3705 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3706 // We construct two shuffle masks:
3707 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3708 // and N1 as the second operand.
3709 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3710 // and N0 as the second operand.
3711 // We do this because OR is commutable and therefore there might be
3712 // two ways to fold this node into a shuffle.
3713 SmallVector<int,4> Mask1;
3714 SmallVector<int,4> Mask2;
3716 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3717 int M0 = SV0->getMaskElt(i);
3718 int M1 = SV1->getMaskElt(i);
3720 // Both shuffle indexes are undef. Propagate Undef.
3721 if (M0 < 0 && M1 < 0) {
3722 Mask1.push_back(M0);
3723 Mask2.push_back(M0);
3727 if (M0 < 0 || M1 < 0 ||
3728 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3729 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3734 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3735 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3739 // Fold this sequence only if the resulting shuffle is 'legal'.
3740 if (TLI.isShuffleMaskLegal(Mask1, VT))
3741 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3742 N1->getOperand(0), &Mask1[0]);
3743 if (TLI.isShuffleMaskLegal(Mask2, VT))
3744 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3745 N0->getOperand(0), &Mask2[0]);
3750 // fold (or c1, c2) -> c1|c2
3751 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3752 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3753 if (N0C && N1C && !N1C->isOpaque())
3754 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3755 // canonicalize constant to RHS
3756 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3757 !isConstantIntBuildVectorOrConstantInt(N1))
3758 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3759 // fold (or x, 0) -> x
3760 if (isNullConstant(N1))
3762 // fold (or x, -1) -> -1
3763 if (isAllOnesConstant(N1))
3765 // fold (or x, c) -> c iff (x & ~c) == 0
3766 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3769 if (SDValue Combined = visitORLike(N0, N1, N))
3772 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3773 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3775 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3779 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3781 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3782 // iff (c1 & c2) == 0.
3783 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3784 isa<ConstantSDNode>(N0.getOperand(1))) {
3785 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3786 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3787 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3790 ISD::AND, SDLoc(N), VT,
3791 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3795 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3796 if (N0.getOpcode() == N1.getOpcode())
3797 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3800 // See if this is some rotate idiom.
3801 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3802 return SDValue(Rot, 0);
3804 // Simplify the operands using demanded-bits information.
3805 if (!VT.isVector() &&
3806 SimplifyDemandedBits(SDValue(N, 0)))
3807 return SDValue(N, 0);
3812 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3813 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3814 if (Op.getOpcode() == ISD::AND) {
3815 if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3816 Mask = Op.getOperand(1);
3817 Op = Op.getOperand(0);
3823 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3831 // Return true if we can prove that, whenever Neg and Pos are both in the
3832 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
3833 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3835 // (or (shift1 X, Neg), (shift2 X, Pos))
3837 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3838 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
3839 // to consider shift amounts with defined behavior.
3840 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3841 // If EltSize is a power of 2 then:
3843 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3844 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3846 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3847 // for the stronger condition:
3849 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
3851 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3852 // we can just replace Neg with Neg' for the rest of the function.
3854 // In other cases we check for the even stronger condition:
3856 // Neg == EltSize - Pos [B]
3858 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3859 // behavior if Pos == 0 (and consequently Neg == EltSize).
3861 // We could actually use [A] whenever EltSize is a power of 2, but the
3862 // only extra cases that it would match are those uninteresting ones
3863 // where Neg and Pos are never in range at the same time. E.g. for
3864 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3865 // as well as (sub 32, Pos), but:
3867 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3869 // always invokes undefined behavior for 32-bit X.
3871 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3872 unsigned MaskLoBits = 0;
3873 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3874 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3875 if (NegC->getAPIntValue() == EltSize - 1) {
3876 Neg = Neg.getOperand(0);
3877 MaskLoBits = Log2_64(EltSize);
3882 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3883 if (Neg.getOpcode() != ISD::SUB)
3885 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3888 SDValue NegOp1 = Neg.getOperand(1);
3890 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3891 // Pos'. The truncation is redundant for the purpose of the equality.
3892 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3893 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3894 if (PosC->getAPIntValue() == EltSize - 1)
3895 Pos = Pos.getOperand(0);
3897 // The condition we need is now:
3899 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3901 // If NegOp1 == Pos then we need:
3903 // EltSize & Mask == NegC & Mask
3905 // (because "x & Mask" is a truncation and distributes through subtraction).
3908 Width = NegC->getAPIntValue();
3910 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3911 // Then the condition we want to prove becomes:
3913 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3915 // which, again because "x & Mask" is a truncation, becomes:
3917 // NegC & Mask == (EltSize - PosC) & Mask
3918 // EltSize & Mask == (NegC + PosC) & Mask
3919 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3920 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3921 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3927 // Now we just need to check that EltSize & Mask == Width & Mask.
3929 // EltSize & Mask is 0 since Mask is EltSize - 1.
3930 return Width.getLoBits(MaskLoBits) == 0;
3931 return Width == EltSize;
3934 // A subroutine of MatchRotate used once we have found an OR of two opposite
3935 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3936 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3937 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3938 // Neg with outer conversions stripped away.
3939 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3940 SDValue Neg, SDValue InnerPos,
3941 SDValue InnerNeg, unsigned PosOpcode,
3942 unsigned NegOpcode, SDLoc DL) {
3943 // fold (or (shl x, (*ext y)),
3944 // (srl x, (*ext (sub 32, y)))) ->
3945 // (rotl x, y) or (rotr x, (sub 32, y))
3947 // fold (or (shl x, (*ext (sub 32, y))),
3948 // (srl x, (*ext y))) ->
3949 // (rotr x, y) or (rotl x, (sub 32, y))
3950 EVT VT = Shifted.getValueType();
3951 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
3952 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3953 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3954 HasPos ? Pos : Neg).getNode();
3960 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3961 // idioms for rotate, and if the target supports rotation instructions, generate
3963 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3964 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3965 EVT VT = LHS.getValueType();
3966 if (!TLI.isTypeLegal(VT)) return nullptr;
3968 // The target must have at least one rotate flavor.
3969 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3970 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3971 if (!HasROTL && !HasROTR) return nullptr;
3973 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3974 SDValue LHSShift; // The shift.
3975 SDValue LHSMask; // AND value if any.
3976 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3977 return nullptr; // Not part of a rotate.
3979 SDValue RHSShift; // The shift.
3980 SDValue RHSMask; // AND value if any.
3981 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3982 return nullptr; // Not part of a rotate.
3984 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3985 return nullptr; // Not shifting the same value.
3987 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3988 return nullptr; // Shifts must disagree.
3990 // Canonicalize shl to left side in a shl/srl pair.
3991 if (RHSShift.getOpcode() == ISD::SHL) {
3992 std::swap(LHS, RHS);
3993 std::swap(LHSShift, RHSShift);
3994 std::swap(LHSMask, RHSMask);
3997 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3998 SDValue LHSShiftArg = LHSShift.getOperand(0);
3999 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4000 SDValue RHSShiftArg = RHSShift.getOperand(0);
4001 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4003 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4004 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4005 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4006 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4007 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4008 if ((LShVal + RShVal) != EltSizeInBits)
4011 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4012 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4014 // If there is an AND of either shifted operand, apply it to the result.
4015 if (LHSMask.getNode() || RHSMask.getNode()) {
4016 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4017 SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4019 if (LHSMask.getNode()) {
4020 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4021 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4022 DAG.getNode(ISD::OR, DL, VT, LHSMask,
4023 DAG.getConstant(RHSBits, DL, VT)));
4025 if (RHSMask.getNode()) {
4026 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4027 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4028 DAG.getNode(ISD::OR, DL, VT, RHSMask,
4029 DAG.getConstant(LHSBits, DL, VT)));
4032 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4035 return Rot.getNode();
4038 // If there is a mask here, and we have a variable shift, we can't be sure
4039 // that we're masking out the right stuff.
4040 if (LHSMask.getNode() || RHSMask.getNode())
4043 // If the shift amount is sign/zext/any-extended just peel it off.
4044 SDValue LExtOp0 = LHSShiftAmt;
4045 SDValue RExtOp0 = RHSShiftAmt;
4046 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4047 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4048 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4049 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4050 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4051 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4052 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4053 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4054 LExtOp0 = LHSShiftAmt.getOperand(0);
4055 RExtOp0 = RHSShiftAmt.getOperand(0);
4058 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4059 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4063 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4064 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4071 SDValue DAGCombiner::visitXOR(SDNode *N) {
4072 SDValue N0 = N->getOperand(0);
4073 SDValue N1 = N->getOperand(1);
4074 EVT VT = N0.getValueType();
4077 if (VT.isVector()) {
4078 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4081 // fold (xor x, 0) -> x, vector edition
4082 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4084 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4088 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4089 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4090 return DAG.getConstant(0, SDLoc(N), VT);
4091 // fold (xor x, undef) -> undef
4092 if (N0.getOpcode() == ISD::UNDEF)
4094 if (N1.getOpcode() == ISD::UNDEF)
4096 // fold (xor c1, c2) -> c1^c2
4097 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4098 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4100 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4101 // canonicalize constant to RHS
4102 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4103 !isConstantIntBuildVectorOrConstantInt(N1))
4104 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4105 // fold (xor x, 0) -> x
4106 if (isNullConstant(N1))
4109 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4112 // fold !(x cc y) -> (x !cc y)
4113 SDValue LHS, RHS, CC;
4114 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4115 bool isInt = LHS.getValueType().isInteger();
4116 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4119 if (!LegalOperations ||
4120 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4121 switch (N0.getOpcode()) {
4123 llvm_unreachable("Unhandled SetCC Equivalent!");
4125 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4126 case ISD::SELECT_CC:
4127 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4128 N0.getOperand(3), NotCC);
4133 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4134 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4135 N0.getNode()->hasOneUse() &&
4136 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4137 SDValue V = N0.getOperand(0);
4139 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4140 DAG.getConstant(1, DL, V.getValueType()));
4141 AddToWorklist(V.getNode());
4142 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4145 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4146 if (isOneConstant(N1) && VT == MVT::i1 &&
4147 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4148 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4149 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4150 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4151 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4152 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4153 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4154 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4157 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4158 if (isAllOnesConstant(N1) &&
4159 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4160 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4161 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4162 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4163 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4164 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4165 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4166 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4169 // fold (xor (and x, y), y) -> (and (not x), y)
4170 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4171 N0->getOperand(1) == N1) {
4172 SDValue X = N0->getOperand(0);
4173 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4174 AddToWorklist(NotX.getNode());
4175 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4177 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4178 if (N1C && N0.getOpcode() == ISD::XOR) {
4179 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4181 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4182 DAG.getConstant(N1C->getAPIntValue() ^
4183 N00C->getAPIntValue(), DL, VT));
4185 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4187 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4188 DAG.getConstant(N1C->getAPIntValue() ^
4189 N01C->getAPIntValue(), DL, VT));
4192 // fold (xor x, x) -> 0
4194 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4196 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4197 // Here is a concrete example of this equivalence:
4199 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4200 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4204 // i16 ~1 == 0b1111111111111110
4205 // i16 rol(~1, 14) == 0b1011111111111111
4207 // Some additional tips to help conceptualize this transform:
4208 // - Try to see the operation as placing a single zero in a value of all ones.
4209 // - There exists no value for x which would allow the result to contain zero.
4210 // - Values of x larger than the bitwidth are undefined and do not require a
4211 // consistent result.
4212 // - Pushing the zero left requires shifting one bits in from the right.
4213 // A rotate left of ~1 is a nice way of achieving the desired result.
4214 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4215 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4217 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4221 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4222 if (N0.getOpcode() == N1.getOpcode())
4223 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4226 // Simplify the expression using non-local knowledge.
4227 if (!VT.isVector() &&
4228 SimplifyDemandedBits(SDValue(N, 0)))
4229 return SDValue(N, 0);
4234 /// Handle transforms common to the three shifts, when the shift amount is a
4236 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4237 SDNode *LHS = N->getOperand(0).getNode();
4238 if (!LHS->hasOneUse()) return SDValue();
4240 // We want to pull some binops through shifts, so that we have (and (shift))
4241 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4242 // thing happens with address calculations, so it's important to canonicalize
4244 bool HighBitSet = false; // Can we transform this if the high bit is set?
4246 switch (LHS->getOpcode()) {
4247 default: return SDValue();
4250 HighBitSet = false; // We can only transform sra if the high bit is clear.
4253 HighBitSet = true; // We can only transform sra if the high bit is set.
4256 if (N->getOpcode() != ISD::SHL)
4257 return SDValue(); // only shl(add) not sr[al](add).
4258 HighBitSet = false; // We can only transform sra if the high bit is clear.
4262 // We require the RHS of the binop to be a constant and not opaque as well.
4263 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4264 if (!BinOpCst) return SDValue();
4266 // FIXME: disable this unless the input to the binop is a shift by a constant.
4267 // If it is not a shift, it pessimizes some common cases like:
4269 // void foo(int *X, int i) { X[i & 1235] = 1; }
4270 // int bar(int *X, int i) { return X[i & 255]; }
4271 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4272 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4273 BinOpLHSVal->getOpcode() != ISD::SRA &&
4274 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4275 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4278 EVT VT = N->getValueType(0);
4280 // If this is a signed shift right, and the high bit is modified by the
4281 // logical operation, do not perform the transformation. The highBitSet
4282 // boolean indicates the value of the high bit of the constant which would
4283 // cause it to be modified for this operation.
4284 if (N->getOpcode() == ISD::SRA) {
4285 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4286 if (BinOpRHSSignSet != HighBitSet)
4290 if (!TLI.isDesirableToCommuteWithShift(LHS))
4293 // Fold the constants, shifting the binop RHS by the shift amount.
4294 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4296 LHS->getOperand(1), N->getOperand(1));
4297 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4299 // Create the new shift.
4300 SDValue NewShift = DAG.getNode(N->getOpcode(),
4301 SDLoc(LHS->getOperand(0)),
4302 VT, LHS->getOperand(0), N->getOperand(1));
4304 // Create the new binop.
4305 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4308 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4309 assert(N->getOpcode() == ISD::TRUNCATE);
4310 assert(N->getOperand(0).getOpcode() == ISD::AND);
4312 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4313 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4314 SDValue N01 = N->getOperand(0).getOperand(1);
4316 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4317 if (!N01C->isOpaque()) {
4318 EVT TruncVT = N->getValueType(0);
4319 SDValue N00 = N->getOperand(0).getOperand(0);
4320 APInt TruncC = N01C->getAPIntValue();
4321 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4324 return DAG.getNode(ISD::AND, DL, TruncVT,
4325 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4326 DAG.getConstant(TruncC, DL, TruncVT));
4334 SDValue DAGCombiner::visitRotate(SDNode *N) {
4335 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4336 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4337 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4338 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4339 if (NewOp1.getNode())
4340 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4341 N->getOperand(0), NewOp1);
4346 SDValue DAGCombiner::visitSHL(SDNode *N) {
4347 SDValue N0 = N->getOperand(0);
4348 SDValue N1 = N->getOperand(1);
4349 EVT VT = N0.getValueType();
4350 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4353 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4354 if (VT.isVector()) {
4355 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4358 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4359 // If setcc produces all-one true value then:
4360 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4361 if (N1CV && N1CV->isConstant()) {
4362 if (N0.getOpcode() == ISD::AND) {
4363 SDValue N00 = N0->getOperand(0);
4364 SDValue N01 = N0->getOperand(1);
4365 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4367 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4368 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4369 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4370 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4372 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4375 N1C = isConstOrConstSplat(N1);
4380 // fold (shl c1, c2) -> c1<<c2
4381 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4382 if (N0C && N1C && !N1C->isOpaque())
4383 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4384 // fold (shl 0, x) -> 0
4385 if (isNullConstant(N0))
4387 // fold (shl x, c >= size(x)) -> undef
4388 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4389 return DAG.getUNDEF(VT);
4390 // fold (shl x, 0) -> x
4391 if (N1C && N1C->isNullValue())
4393 // fold (shl undef, x) -> 0
4394 if (N0.getOpcode() == ISD::UNDEF)
4395 return DAG.getConstant(0, SDLoc(N), VT);
4396 // if (shl x, c) is known to be zero, return 0
4397 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4398 APInt::getAllOnesValue(OpSizeInBits)))
4399 return DAG.getConstant(0, SDLoc(N), VT);
4400 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4401 if (N1.getOpcode() == ISD::TRUNCATE &&
4402 N1.getOperand(0).getOpcode() == ISD::AND) {
4403 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4404 if (NewOp1.getNode())
4405 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4408 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4409 return SDValue(N, 0);
4411 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4412 if (N1C && N0.getOpcode() == ISD::SHL) {
4413 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4414 uint64_t c1 = N0C1->getZExtValue();
4415 uint64_t c2 = N1C->getZExtValue();
4417 if (c1 + c2 >= OpSizeInBits)
4418 return DAG.getConstant(0, DL, VT);
4419 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4420 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4424 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4425 // For this to be valid, the second form must not preserve any of the bits
4426 // that are shifted out by the inner shift in the first form. This means
4427 // the outer shift size must be >= the number of bits added by the ext.
4428 // As a corollary, we don't care what kind of ext it is.
4429 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4430 N0.getOpcode() == ISD::ANY_EXTEND ||
4431 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4432 N0.getOperand(0).getOpcode() == ISD::SHL) {
4433 SDValue N0Op0 = N0.getOperand(0);
4434 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4435 uint64_t c1 = N0Op0C1->getZExtValue();
4436 uint64_t c2 = N1C->getZExtValue();
4437 EVT InnerShiftVT = N0Op0.getValueType();
4438 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4439 if (c2 >= OpSizeInBits - InnerShiftSize) {
4441 if (c1 + c2 >= OpSizeInBits)
4442 return DAG.getConstant(0, DL, VT);
4443 return DAG.getNode(ISD::SHL, DL, VT,
4444 DAG.getNode(N0.getOpcode(), DL, VT,
4445 N0Op0->getOperand(0)),
4446 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4451 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4452 // Only fold this if the inner zext has no other uses to avoid increasing
4453 // the total number of instructions.
4454 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4455 N0.getOperand(0).getOpcode() == ISD::SRL) {
4456 SDValue N0Op0 = N0.getOperand(0);
4457 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4458 uint64_t c1 = N0Op0C1->getZExtValue();
4459 if (c1 < VT.getScalarSizeInBits()) {
4460 uint64_t c2 = N1C->getZExtValue();
4462 SDValue NewOp0 = N0.getOperand(0);
4463 EVT CountVT = NewOp0.getOperand(1).getValueType();
4465 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4467 DAG.getConstant(c2, DL, CountVT));
4468 AddToWorklist(NewSHL.getNode());
4469 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4475 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4476 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4477 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4478 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4479 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4480 uint64_t C1 = N0C1->getZExtValue();
4481 uint64_t C2 = N1C->getZExtValue();
4484 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4485 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4486 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4487 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4491 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4492 // (and (srl x, (sub c1, c2), MASK)
4493 // Only fold this if the inner shift has no other uses -- if it does, folding
4494 // this will increase the total number of instructions.
4495 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4496 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4497 uint64_t c1 = N0C1->getZExtValue();
4498 if (c1 < OpSizeInBits) {
4499 uint64_t c2 = N1C->getZExtValue();
4500 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4503 Mask = Mask.shl(c2 - c1);
4505 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4506 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4508 Mask = Mask.lshr(c1 - c2);
4510 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4511 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4514 return DAG.getNode(ISD::AND, DL, VT, Shift,
4515 DAG.getConstant(Mask, DL, VT));
4519 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4520 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4521 unsigned BitSize = VT.getScalarSizeInBits();
4523 SDValue HiBitsMask =
4524 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4525 BitSize - N1C->getZExtValue()),
4527 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4531 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4532 // Variant of version done on multiply, except mul by a power of 2 is turned
4535 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4536 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4537 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4538 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4539 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4540 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4543 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4544 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4545 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4546 if (SDValue Folded =
4547 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4548 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4552 if (N1C && !N1C->isOpaque())
4553 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4559 SDValue DAGCombiner::visitSRA(SDNode *N) {
4560 SDValue N0 = N->getOperand(0);
4561 SDValue N1 = N->getOperand(1);
4562 EVT VT = N0.getValueType();
4563 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4566 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4567 if (VT.isVector()) {
4568 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4571 N1C = isConstOrConstSplat(N1);
4574 // fold (sra c1, c2) -> (sra c1, c2)
4575 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4576 if (N0C && N1C && !N1C->isOpaque())
4577 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4578 // fold (sra 0, x) -> 0
4579 if (isNullConstant(N0))
4581 // fold (sra -1, x) -> -1
4582 if (isAllOnesConstant(N0))
4584 // fold (sra x, (setge c, size(x))) -> undef
4585 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4586 return DAG.getUNDEF(VT);
4587 // fold (sra x, 0) -> x
4588 if (N1C && N1C->isNullValue())
4590 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4592 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4593 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4594 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4596 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4597 ExtVT, VT.getVectorNumElements());
4598 if ((!LegalOperations ||
4599 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4600 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4601 N0.getOperand(0), DAG.getValueType(ExtVT));
4604 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4605 if (N1C && N0.getOpcode() == ISD::SRA) {
4606 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4607 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4608 if (Sum >= OpSizeInBits)
4609 Sum = OpSizeInBits - 1;
4611 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4612 DAG.getConstant(Sum, DL, N1.getValueType()));
4616 // fold (sra (shl X, m), (sub result_size, n))
4617 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4618 // result_size - n != m.
4619 // If truncate is free for the target sext(shl) is likely to result in better
4621 if (N0.getOpcode() == ISD::SHL && N1C) {
4622 // Get the two constanst of the shifts, CN0 = m, CN = n.
4623 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4625 LLVMContext &Ctx = *DAG.getContext();
4626 // Determine what the truncate's result bitsize and type would be.
4627 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4630 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4632 // Determine the residual right-shift amount.
4633 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4635 // If the shift is not a no-op (in which case this should be just a sign
4636 // extend already), the truncated to type is legal, sign_extend is legal
4637 // on that type, and the truncate to that type is both legal and free,
4638 // perform the transform.
4639 if ((ShiftAmt > 0) &&
4640 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4641 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4642 TLI.isTruncateFree(VT, TruncVT)) {
4645 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4646 getShiftAmountTy(N0.getOperand(0).getValueType()));
4647 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4648 N0.getOperand(0), Amt);
4649 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4651 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4652 N->getValueType(0), Trunc);
4657 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4658 if (N1.getOpcode() == ISD::TRUNCATE &&
4659 N1.getOperand(0).getOpcode() == ISD::AND) {
4660 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4661 if (NewOp1.getNode())
4662 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4665 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4666 // if c1 is equal to the number of bits the trunc removes
4667 if (N0.getOpcode() == ISD::TRUNCATE &&
4668 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4669 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4670 N0.getOperand(0).hasOneUse() &&
4671 N0.getOperand(0).getOperand(1).hasOneUse() &&
4673 SDValue N0Op0 = N0.getOperand(0);
4674 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4675 unsigned LargeShiftVal = LargeShift->getZExtValue();
4676 EVT LargeVT = N0Op0.getValueType();
4678 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4681 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4682 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4683 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4684 N0Op0.getOperand(0), Amt);
4685 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4690 // Simplify, based on bits shifted out of the LHS.
4691 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4692 return SDValue(N, 0);
4695 // If the sign bit is known to be zero, switch this to a SRL.
4696 if (DAG.SignBitIsZero(N0))
4697 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4699 if (N1C && !N1C->isOpaque())
4700 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4706 SDValue DAGCombiner::visitSRL(SDNode *N) {
4707 SDValue N0 = N->getOperand(0);
4708 SDValue N1 = N->getOperand(1);
4709 EVT VT = N0.getValueType();
4710 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4713 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4714 if (VT.isVector()) {
4715 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4718 N1C = isConstOrConstSplat(N1);
4721 // fold (srl c1, c2) -> c1 >>u c2
4722 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4723 if (N0C && N1C && !N1C->isOpaque())
4724 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4725 // fold (srl 0, x) -> 0
4726 if (isNullConstant(N0))
4728 // fold (srl x, c >= size(x)) -> undef
4729 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4730 return DAG.getUNDEF(VT);
4731 // fold (srl x, 0) -> x
4732 if (N1C && N1C->isNullValue())
4734 // if (srl x, c) is known to be zero, return 0
4735 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4736 APInt::getAllOnesValue(OpSizeInBits)))
4737 return DAG.getConstant(0, SDLoc(N), VT);
4739 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4740 if (N1C && N0.getOpcode() == ISD::SRL) {
4741 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4742 uint64_t c1 = N01C->getZExtValue();
4743 uint64_t c2 = N1C->getZExtValue();
4745 if (c1 + c2 >= OpSizeInBits)
4746 return DAG.getConstant(0, DL, VT);
4747 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4748 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4752 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4753 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4754 N0.getOperand(0).getOpcode() == ISD::SRL &&
4755 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4757 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4758 uint64_t c2 = N1C->getZExtValue();
4759 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4760 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4761 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4762 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4763 if (c1 + OpSizeInBits == InnerShiftSize) {
4765 if (c1 + c2 >= InnerShiftSize)
4766 return DAG.getConstant(0, DL, VT);
4767 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4768 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4769 N0.getOperand(0)->getOperand(0),
4770 DAG.getConstant(c1 + c2, DL,
4775 // fold (srl (shl x, c), c) -> (and x, cst2)
4776 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4777 unsigned BitSize = N0.getScalarValueSizeInBits();
4778 if (BitSize <= 64) {
4779 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4781 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4782 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4786 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4787 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4788 // Shifting in all undef bits?
4789 EVT SmallVT = N0.getOperand(0).getValueType();
4790 unsigned BitSize = SmallVT.getScalarSizeInBits();
4791 if (N1C->getZExtValue() >= BitSize)
4792 return DAG.getUNDEF(VT);
4794 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4795 uint64_t ShiftAmt = N1C->getZExtValue();
4797 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4799 DAG.getConstant(ShiftAmt, DL0,
4800 getShiftAmountTy(SmallVT)));
4801 AddToWorklist(SmallShift.getNode());
4802 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4804 return DAG.getNode(ISD::AND, DL, VT,
4805 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4806 DAG.getConstant(Mask, DL, VT));
4810 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4811 // bit, which is unmodified by sra.
4812 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4813 if (N0.getOpcode() == ISD::SRA)
4814 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4817 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4818 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4819 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4820 APInt KnownZero, KnownOne;
4821 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4823 // If any of the input bits are KnownOne, then the input couldn't be all
4824 // zeros, thus the result of the srl will always be zero.
4825 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4827 // If all of the bits input the to ctlz node are known to be zero, then
4828 // the result of the ctlz is "32" and the result of the shift is one.
4829 APInt UnknownBits = ~KnownZero;
4830 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4832 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4833 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4834 // Okay, we know that only that the single bit specified by UnknownBits
4835 // could be set on input to the CTLZ node. If this bit is set, the SRL
4836 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4837 // to an SRL/XOR pair, which is likely to simplify more.
4838 unsigned ShAmt = UnknownBits.countTrailingZeros();
4839 SDValue Op = N0.getOperand(0);
4843 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4844 DAG.getConstant(ShAmt, DL,
4845 getShiftAmountTy(Op.getValueType())));
4846 AddToWorklist(Op.getNode());
4850 return DAG.getNode(ISD::XOR, DL, VT,
4851 Op, DAG.getConstant(1, DL, VT));
4855 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4856 if (N1.getOpcode() == ISD::TRUNCATE &&
4857 N1.getOperand(0).getOpcode() == ISD::AND) {
4858 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4859 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4862 // fold operands of srl based on knowledge that the low bits are not
4864 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4865 return SDValue(N, 0);
4867 if (N1C && !N1C->isOpaque())
4868 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4871 // Attempt to convert a srl of a load into a narrower zero-extending load.
4872 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4875 // Here is a common situation. We want to optimize:
4878 // %b = and i32 %a, 2
4879 // %c = srl i32 %b, 1
4880 // brcond i32 %c ...
4886 // %c = setcc eq %b, 0
4889 // However when after the source operand of SRL is optimized into AND, the SRL
4890 // itself may not be optimized further. Look for it and add the BRCOND into
4892 if (N->hasOneUse()) {
4893 SDNode *Use = *N->use_begin();
4894 if (Use->getOpcode() == ISD::BRCOND)
4896 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4897 // Also look pass the truncate.
4898 Use = *Use->use_begin();
4899 if (Use->getOpcode() == ISD::BRCOND)
4907 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4908 SDValue N0 = N->getOperand(0);
4909 EVT VT = N->getValueType(0);
4911 // fold (bswap c1) -> c2
4912 if (isConstantIntBuildVectorOrConstantInt(N0))
4913 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4914 // fold (bswap (bswap x)) -> x
4915 if (N0.getOpcode() == ISD::BSWAP)
4916 return N0->getOperand(0);
4920 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4921 SDValue N0 = N->getOperand(0);
4922 EVT VT = N->getValueType(0);
4924 // fold (ctlz c1) -> c2
4925 if (isConstantIntBuildVectorOrConstantInt(N0))
4926 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4930 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4931 SDValue N0 = N->getOperand(0);
4932 EVT VT = N->getValueType(0);
4934 // fold (ctlz_zero_undef c1) -> c2
4935 if (isConstantIntBuildVectorOrConstantInt(N0))
4936 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4940 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4941 SDValue N0 = N->getOperand(0);
4942 EVT VT = N->getValueType(0);
4944 // fold (cttz c1) -> c2
4945 if (isConstantIntBuildVectorOrConstantInt(N0))
4946 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4950 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4951 SDValue N0 = N->getOperand(0);
4952 EVT VT = N->getValueType(0);
4954 // fold (cttz_zero_undef c1) -> c2
4955 if (isConstantIntBuildVectorOrConstantInt(N0))
4956 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4960 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4961 SDValue N0 = N->getOperand(0);
4962 EVT VT = N->getValueType(0);
4964 // fold (ctpop c1) -> c2
4965 if (isConstantIntBuildVectorOrConstantInt(N0))
4966 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4971 /// \brief Generate Min/Max node
4972 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4973 SDValue True, SDValue False,
4974 ISD::CondCode CC, const TargetLowering &TLI,
4975 SelectionDAG &DAG) {
4976 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4986 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4987 if (TLI.isOperationLegal(Opcode, VT))
4988 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4997 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4998 if (TLI.isOperationLegal(Opcode, VT))
4999 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5007 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5008 SDValue N0 = N->getOperand(0);
5009 SDValue N1 = N->getOperand(1);
5010 SDValue N2 = N->getOperand(2);
5011 EVT VT = N->getValueType(0);
5012 EVT VT0 = N0.getValueType();
5014 // fold (select C, X, X) -> X
5017 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5018 // fold (select true, X, Y) -> X
5019 // fold (select false, X, Y) -> Y
5020 return !N0C->isNullValue() ? N1 : N2;
5022 // fold (select C, 1, X) -> (or C, X)
5023 if (VT == MVT::i1 && isOneConstant(N1))
5024 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5025 // fold (select C, 0, 1) -> (xor C, 1)
5026 // We can't do this reliably if integer based booleans have different contents
5027 // to floating point based booleans. This is because we can't tell whether we
5028 // have an integer-based boolean or a floating-point-based boolean unless we
5029 // can find the SETCC that produced it and inspect its operands. This is
5030 // fairly easy if C is the SETCC node, but it can potentially be
5031 // undiscoverable (or not reasonably discoverable). For example, it could be
5032 // in another basic block or it could require searching a complicated
5034 if (VT.isInteger() &&
5035 (VT0 == MVT::i1 || (VT0.isInteger() &&
5036 TLI.getBooleanContents(false, false) ==
5037 TLI.getBooleanContents(false, true) &&
5038 TLI.getBooleanContents(false, false) ==
5039 TargetLowering::ZeroOrOneBooleanContent)) &&
5040 isNullConstant(N1) && isOneConstant(N2)) {
5044 return DAG.getNode(ISD::XOR, DL, VT0,
5045 N0, DAG.getConstant(1, DL, VT0));
5048 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5049 N0, DAG.getConstant(1, DL0, VT0));
5050 AddToWorklist(XORNode.getNode());
5052 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5053 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5055 // fold (select C, 0, X) -> (and (not C), X)
5056 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5057 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5058 AddToWorklist(NOTNode.getNode());
5059 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5061 // fold (select C, X, 1) -> (or (not C), X)
5062 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5063 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5064 AddToWorklist(NOTNode.getNode());
5065 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5067 // fold (select C, X, 0) -> (and C, X)
5068 if (VT == MVT::i1 && isNullConstant(N2))
5069 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5070 // fold (select X, X, Y) -> (or X, Y)
5071 // fold (select X, 1, Y) -> (or X, Y)
5072 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5073 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5074 // fold (select X, Y, X) -> (and X, Y)
5075 // fold (select X, Y, 0) -> (and X, Y)
5076 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5077 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5079 // If we can fold this based on the true/false value, do so.
5080 if (SimplifySelectOps(N, N1, N2))
5081 return SDValue(N, 0); // Don't revisit N.
5083 if (VT0 == MVT::i1) {
5084 // The code in this block deals with the following 2 equivalences:
5085 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5086 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5087 // The target can specify its prefered form with the
5088 // shouldNormalizeToSelectSequence() callback. However we always transform
5089 // to the right anyway if we find the inner select exists in the DAG anyway
5090 // and we always transform to the left side if we know that we can further
5091 // optimize the combination of the conditions.
5092 bool normalizeToSequence
5093 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5094 // select (and Cond0, Cond1), X, Y
5095 // -> select Cond0, (select Cond1, X, Y), Y
5096 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5097 SDValue Cond0 = N0->getOperand(0);
5098 SDValue Cond1 = N0->getOperand(1);
5099 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5100 N1.getValueType(), Cond1, N1, N2);
5101 if (normalizeToSequence || !InnerSelect.use_empty())
5102 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5105 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5106 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5107 SDValue Cond0 = N0->getOperand(0);
5108 SDValue Cond1 = N0->getOperand(1);
5109 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5110 N1.getValueType(), Cond1, N1, N2);
5111 if (normalizeToSequence || !InnerSelect.use_empty())
5112 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5116 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5117 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5118 SDValue N1_0 = N1->getOperand(0);
5119 SDValue N1_1 = N1->getOperand(1);
5120 SDValue N1_2 = N1->getOperand(2);
5121 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5122 // Create the actual and node if we can generate good code for it.
5123 if (!normalizeToSequence) {
5124 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5126 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5129 // Otherwise see if we can optimize the "and" to a better pattern.
5130 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5131 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5135 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5136 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5137 SDValue N2_0 = N2->getOperand(0);
5138 SDValue N2_1 = N2->getOperand(1);
5139 SDValue N2_2 = N2->getOperand(2);
5140 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5141 // Create the actual or node if we can generate good code for it.
5142 if (!normalizeToSequence) {
5143 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5145 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5148 // Otherwise see if we can optimize to a better pattern.
5149 if (SDValue Combined = visitORLike(N0, N2_0, N))
5150 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5156 // fold selects based on a setcc into other things, such as min/max/abs
5157 if (N0.getOpcode() == ISD::SETCC) {
5158 // select x, y (fcmp lt x, y) -> fminnum x, y
5159 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5161 // This is OK if we don't care about what happens if either operand is a
5165 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5166 // no signed zeros as well as no nans.
5167 const TargetOptions &Options = DAG.getTarget().Options;
5168 if (Options.UnsafeFPMath &&
5169 VT.isFloatingPoint() && N0.hasOneUse() &&
5170 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5171 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5173 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5174 N0.getOperand(1), N1, N2, CC,
5179 if ((!LegalOperations &&
5180 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5181 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5182 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5183 N0.getOperand(0), N0.getOperand(1),
5184 N1, N2, N0.getOperand(2));
5185 return SimplifySelect(SDLoc(N), N0, N1, N2);
5192 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5195 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5197 // Split the inputs.
5198 SDValue Lo, Hi, LL, LH, RL, RH;
5199 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5200 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5202 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5203 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5205 return std::make_pair(Lo, Hi);
5208 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5209 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5210 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5212 SDValue Cond = N->getOperand(0);
5213 SDValue LHS = N->getOperand(1);
5214 SDValue RHS = N->getOperand(2);
5215 EVT VT = N->getValueType(0);
5216 int NumElems = VT.getVectorNumElements();
5217 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5218 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5219 Cond.getOpcode() == ISD::BUILD_VECTOR);
5221 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5222 // binary ones here.
5223 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5226 // We're sure we have an even number of elements due to the
5227 // concat_vectors we have as arguments to vselect.
5228 // Skip BV elements until we find one that's not an UNDEF
5229 // After we find an UNDEF element, keep looping until we get to half the
5230 // length of the BV and see if all the non-undef nodes are the same.
5231 ConstantSDNode *BottomHalf = nullptr;
5232 for (int i = 0; i < NumElems / 2; ++i) {
5233 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5236 if (BottomHalf == nullptr)
5237 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5238 else if (Cond->getOperand(i).getNode() != BottomHalf)
5242 // Do the same for the second half of the BuildVector
5243 ConstantSDNode *TopHalf = nullptr;
5244 for (int i = NumElems / 2; i < NumElems; ++i) {
5245 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5248 if (TopHalf == nullptr)
5249 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5250 else if (Cond->getOperand(i).getNode() != TopHalf)
5254 assert(TopHalf && BottomHalf &&
5255 "One half of the selector was all UNDEFs and the other was all the "
5256 "same value. This should have been addressed before this function.");
5258 ISD::CONCAT_VECTORS, dl, VT,
5259 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5260 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5263 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5265 if (Level >= AfterLegalizeTypes)
5268 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5269 SDValue Mask = MSC->getMask();
5270 SDValue Data = MSC->getValue();
5273 // If the MSCATTER data type requires splitting and the mask is provided by a
5274 // SETCC, then split both nodes and its operands before legalization. This
5275 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5276 // and enables future optimizations (e.g. min/max pattern matching on X86).
5277 if (Mask.getOpcode() != ISD::SETCC)
5280 // Check if any splitting is required.
5281 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5282 TargetLowering::TypeSplitVector)
5284 SDValue MaskLo, MaskHi, Lo, Hi;
5285 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5288 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5290 SDValue Chain = MSC->getChain();
5292 EVT MemoryVT = MSC->getMemoryVT();
5293 unsigned Alignment = MSC->getOriginalAlignment();
5295 EVT LoMemVT, HiMemVT;
5296 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5298 SDValue DataLo, DataHi;
5299 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5301 SDValue BasePtr = MSC->getBasePtr();
5302 SDValue IndexLo, IndexHi;
5303 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5305 MachineMemOperand *MMO = DAG.getMachineFunction().
5306 getMachineMemOperand(MSC->getPointerInfo(),
5307 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5308 Alignment, MSC->getAAInfo(), MSC->getRanges());
5310 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5311 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5314 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5315 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5318 AddToWorklist(Lo.getNode());
5319 AddToWorklist(Hi.getNode());
5321 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5324 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5326 if (Level >= AfterLegalizeTypes)
5329 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5330 SDValue Mask = MST->getMask();
5331 SDValue Data = MST->getValue();
5334 // If the MSTORE data type requires splitting and the mask is provided by a
5335 // SETCC, then split both nodes and its operands before legalization. This
5336 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5337 // and enables future optimizations (e.g. min/max pattern matching on X86).
5338 if (Mask.getOpcode() == ISD::SETCC) {
5340 // Check if any splitting is required.
5341 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5342 TargetLowering::TypeSplitVector)
5345 SDValue MaskLo, MaskHi, Lo, Hi;
5346 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5349 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5351 SDValue Chain = MST->getChain();
5352 SDValue Ptr = MST->getBasePtr();
5354 EVT MemoryVT = MST->getMemoryVT();
5355 unsigned Alignment = MST->getOriginalAlignment();
5357 // if Alignment is equal to the vector size,
5358 // take the half of it for the second part
5359 unsigned SecondHalfAlignment =
5360 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5361 Alignment/2 : Alignment;
5363 EVT LoMemVT, HiMemVT;
5364 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5366 SDValue DataLo, DataHi;
5367 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5369 MachineMemOperand *MMO = DAG.getMachineFunction().
5370 getMachineMemOperand(MST->getPointerInfo(),
5371 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5372 Alignment, MST->getAAInfo(), MST->getRanges());
5374 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5375 MST->isTruncatingStore());
5377 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5378 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5379 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5381 MMO = DAG.getMachineFunction().
5382 getMachineMemOperand(MST->getPointerInfo(),
5383 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5384 SecondHalfAlignment, MST->getAAInfo(),
5387 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5388 MST->isTruncatingStore());
5390 AddToWorklist(Lo.getNode());
5391 AddToWorklist(Hi.getNode());
5393 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5398 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5400 if (Level >= AfterLegalizeTypes)
5403 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5404 SDValue Mask = MGT->getMask();
5407 // If the MGATHER result requires splitting and the mask is provided by a
5408 // SETCC, then split both nodes and its operands before legalization. This
5409 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5410 // and enables future optimizations (e.g. min/max pattern matching on X86).
5412 if (Mask.getOpcode() != ISD::SETCC)
5415 EVT VT = N->getValueType(0);
5417 // Check if any splitting is required.
5418 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5419 TargetLowering::TypeSplitVector)
5422 SDValue MaskLo, MaskHi, Lo, Hi;
5423 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5425 SDValue Src0 = MGT->getValue();
5426 SDValue Src0Lo, Src0Hi;
5427 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5430 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5432 SDValue Chain = MGT->getChain();
5433 EVT MemoryVT = MGT->getMemoryVT();
5434 unsigned Alignment = MGT->getOriginalAlignment();
5436 EVT LoMemVT, HiMemVT;
5437 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5439 SDValue BasePtr = MGT->getBasePtr();
5440 SDValue Index = MGT->getIndex();
5441 SDValue IndexLo, IndexHi;
5442 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5444 MachineMemOperand *MMO = DAG.getMachineFunction().
5445 getMachineMemOperand(MGT->getPointerInfo(),
5446 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5447 Alignment, MGT->getAAInfo(), MGT->getRanges());
5449 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5450 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5453 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5454 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5457 AddToWorklist(Lo.getNode());
5458 AddToWorklist(Hi.getNode());
5460 // Build a factor node to remember that this load is independent of the
5462 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5465 // Legalized the chain result - switch anything that used the old chain to
5467 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5469 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5471 SDValue RetOps[] = { GatherRes, Chain };
5472 return DAG.getMergeValues(RetOps, DL);
5475 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5477 if (Level >= AfterLegalizeTypes)
5480 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5481 SDValue Mask = MLD->getMask();
5484 // If the MLOAD result requires splitting and the mask is provided by a
5485 // SETCC, then split both nodes and its operands before legalization. This
5486 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5487 // and enables future optimizations (e.g. min/max pattern matching on X86).
5489 if (Mask.getOpcode() == ISD::SETCC) {
5490 EVT VT = N->getValueType(0);
5492 // Check if any splitting is required.
5493 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5494 TargetLowering::TypeSplitVector)
5497 SDValue MaskLo, MaskHi, Lo, Hi;
5498 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5500 SDValue Src0 = MLD->getSrc0();
5501 SDValue Src0Lo, Src0Hi;
5502 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5505 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5507 SDValue Chain = MLD->getChain();
5508 SDValue Ptr = MLD->getBasePtr();
5509 EVT MemoryVT = MLD->getMemoryVT();
5510 unsigned Alignment = MLD->getOriginalAlignment();
5512 // if Alignment is equal to the vector size,
5513 // take the half of it for the second part
5514 unsigned SecondHalfAlignment =
5515 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5516 Alignment/2 : Alignment;
5518 EVT LoMemVT, HiMemVT;
5519 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5521 MachineMemOperand *MMO = DAG.getMachineFunction().
5522 getMachineMemOperand(MLD->getPointerInfo(),
5523 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5524 Alignment, MLD->getAAInfo(), MLD->getRanges());
5526 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5529 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5530 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5531 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5533 MMO = DAG.getMachineFunction().
5534 getMachineMemOperand(MLD->getPointerInfo(),
5535 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5536 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5538 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5541 AddToWorklist(Lo.getNode());
5542 AddToWorklist(Hi.getNode());
5544 // Build a factor node to remember that this load is independent of the
5546 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5549 // Legalized the chain result - switch anything that used the old chain to
5551 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5553 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5555 SDValue RetOps[] = { LoadRes, Chain };
5556 return DAG.getMergeValues(RetOps, DL);
5561 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5562 SDValue N0 = N->getOperand(0);
5563 SDValue N1 = N->getOperand(1);
5564 SDValue N2 = N->getOperand(2);
5567 // Canonicalize integer abs.
5568 // vselect (setg[te] X, 0), X, -X ->
5569 // vselect (setgt X, -1), X, -X ->
5570 // vselect (setl[te] X, 0), -X, X ->
5571 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5572 if (N0.getOpcode() == ISD::SETCC) {
5573 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5574 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5576 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5578 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5579 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5580 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5581 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5582 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5583 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5584 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5587 EVT VT = LHS.getValueType();
5588 SDValue Shift = DAG.getNode(
5589 ISD::SRA, DL, VT, LHS,
5590 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5591 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5592 AddToWorklist(Shift.getNode());
5593 AddToWorklist(Add.getNode());
5594 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5598 if (SimplifySelectOps(N, N1, N2))
5599 return SDValue(N, 0); // Don't revisit N.
5601 // If the VSELECT result requires splitting and the mask is provided by a
5602 // SETCC, then split both nodes and its operands before legalization. This
5603 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5604 // and enables future optimizations (e.g. min/max pattern matching on X86).
5605 if (N0.getOpcode() == ISD::SETCC) {
5606 EVT VT = N->getValueType(0);
5608 // Check if any splitting is required.
5609 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5610 TargetLowering::TypeSplitVector)
5613 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5614 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5615 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5616 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5618 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5619 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5621 // Add the new VSELECT nodes to the work list in case they need to be split
5623 AddToWorklist(Lo.getNode());
5624 AddToWorklist(Hi.getNode());
5626 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5629 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5630 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5632 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5633 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5636 // The ConvertSelectToConcatVector function is assuming both the above
5637 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5639 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5640 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5641 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5642 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5649 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5650 SDValue N0 = N->getOperand(0);
5651 SDValue N1 = N->getOperand(1);
5652 SDValue N2 = N->getOperand(2);
5653 SDValue N3 = N->getOperand(3);
5654 SDValue N4 = N->getOperand(4);
5655 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5657 // fold select_cc lhs, rhs, x, x, cc -> x
5661 // Determine if the condition we're dealing with is constant
5662 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5663 N0, N1, CC, SDLoc(N), false);
5664 if (SCC.getNode()) {
5665 AddToWorklist(SCC.getNode());
5667 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5668 if (!SCCC->isNullValue())
5669 return N2; // cond always true -> true val
5671 return N3; // cond always false -> false val
5672 } else if (SCC->getOpcode() == ISD::UNDEF) {
5673 // When the condition is UNDEF, just return the first operand. This is
5674 // coherent the DAG creation, no setcc node is created in this case
5676 } else if (SCC.getOpcode() == ISD::SETCC) {
5677 // Fold to a simpler select_cc
5678 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5679 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5684 // If we can fold this based on the true/false value, do so.
5685 if (SimplifySelectOps(N, N2, N3))
5686 return SDValue(N, 0); // Don't revisit N.
5688 // fold select_cc into other things, such as min/max/abs
5689 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5692 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5693 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5694 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5698 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5699 /// a build_vector of constants.
5700 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5701 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5702 /// Vector extends are not folded if operations are legal; this is to
5703 /// avoid introducing illegal build_vector dag nodes.
5704 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5705 SelectionDAG &DAG, bool LegalTypes,
5706 bool LegalOperations) {
5707 unsigned Opcode = N->getOpcode();
5708 SDValue N0 = N->getOperand(0);
5709 EVT VT = N->getValueType(0);
5711 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5712 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5713 && "Expected EXTEND dag node in input!");
5715 // fold (sext c1) -> c1
5716 // fold (zext c1) -> c1
5717 // fold (aext c1) -> c1
5718 if (isa<ConstantSDNode>(N0))
5719 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5721 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5722 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5723 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5724 EVT SVT = VT.getScalarType();
5725 if (!(VT.isVector() &&
5726 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5727 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5730 // We can fold this node into a build_vector.
5731 unsigned VTBits = SVT.getSizeInBits();
5732 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5733 SmallVector<SDValue, 8> Elts;
5734 unsigned NumElts = VT.getVectorNumElements();
5737 for (unsigned i=0; i != NumElts; ++i) {
5738 SDValue Op = N0->getOperand(i);
5739 if (Op->getOpcode() == ISD::UNDEF) {
5740 Elts.push_back(DAG.getUNDEF(SVT));
5745 // Get the constant value and if needed trunc it to the size of the type.
5746 // Nodes like build_vector might have constants wider than the scalar type.
5747 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5748 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5749 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5751 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5754 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5757 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5758 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5759 // transformation. Returns true if extension are possible and the above
5760 // mentioned transformation is profitable.
5761 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5763 SmallVectorImpl<SDNode *> &ExtendNodes,
5764 const TargetLowering &TLI) {
5765 bool HasCopyToRegUses = false;
5766 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5767 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5768 UE = N0.getNode()->use_end();
5773 if (UI.getUse().getResNo() != N0.getResNo())
5775 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5776 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5777 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5778 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5779 // Sign bits will be lost after a zext.
5782 for (unsigned i = 0; i != 2; ++i) {
5783 SDValue UseOp = User->getOperand(i);
5786 if (!isa<ConstantSDNode>(UseOp))
5791 ExtendNodes.push_back(User);
5794 // If truncates aren't free and there are users we can't
5795 // extend, it isn't worthwhile.
5798 // Remember if this value is live-out.
5799 if (User->getOpcode() == ISD::CopyToReg)
5800 HasCopyToRegUses = true;
5803 if (HasCopyToRegUses) {
5804 bool BothLiveOut = false;
5805 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5807 SDUse &Use = UI.getUse();
5808 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5814 // Both unextended and extended values are live out. There had better be
5815 // a good reason for the transformation.
5816 return ExtendNodes.size();
5821 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5822 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5823 ISD::NodeType ExtType) {
5824 // Extend SetCC uses if necessary.
5825 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5826 SDNode *SetCC = SetCCs[i];
5827 SmallVector<SDValue, 4> Ops;
5829 for (unsigned j = 0; j != 2; ++j) {
5830 SDValue SOp = SetCC->getOperand(j);
5832 Ops.push_back(ExtLoad);
5834 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5837 Ops.push_back(SetCC->getOperand(2));
5838 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5842 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5843 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5844 SDValue N0 = N->getOperand(0);
5845 EVT DstVT = N->getValueType(0);
5846 EVT SrcVT = N0.getValueType();
5848 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5849 N->getOpcode() == ISD::ZERO_EXTEND) &&
5850 "Unexpected node type (not an extend)!");
5852 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5853 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5854 // (v8i32 (sext (v8i16 (load x))))
5856 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5857 // (v4i32 (sextload (x + 16)))))
5858 // Where uses of the original load, i.e.:
5860 // are replaced with:
5862 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5863 // (v4i32 (sextload (x + 16)))))))
5865 // This combine is only applicable to illegal, but splittable, vectors.
5866 // All legal types, and illegal non-vector types, are handled elsewhere.
5867 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5869 if (N0->getOpcode() != ISD::LOAD)
5872 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5874 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5875 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5876 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5879 SmallVector<SDNode *, 4> SetCCs;
5880 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5883 ISD::LoadExtType ExtType =
5884 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5886 // Try to split the vector types to get down to legal types.
5887 EVT SplitSrcVT = SrcVT;
5888 EVT SplitDstVT = DstVT;
5889 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5890 SplitSrcVT.getVectorNumElements() > 1) {
5891 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5892 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5895 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5899 const unsigned NumSplits =
5900 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5901 const unsigned Stride = SplitSrcVT.getStoreSize();
5902 SmallVector<SDValue, 4> Loads;
5903 SmallVector<SDValue, 4> Chains;
5905 SDValue BasePtr = LN0->getBasePtr();
5906 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5907 const unsigned Offset = Idx * Stride;
5908 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5910 SDValue SplitLoad = DAG.getExtLoad(
5911 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5912 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5913 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5914 Align, LN0->getAAInfo());
5916 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5917 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5919 Loads.push_back(SplitLoad.getValue(0));
5920 Chains.push_back(SplitLoad.getValue(1));
5923 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5924 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5926 CombineTo(N, NewValue);
5928 // Replace uses of the original load (before extension)
5929 // with a truncate of the concatenated sextloaded vectors.
5931 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5932 CombineTo(N0.getNode(), Trunc, NewChain);
5933 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5934 (ISD::NodeType)N->getOpcode());
5935 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5938 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5939 SDValue N0 = N->getOperand(0);
5940 EVT VT = N->getValueType(0);
5942 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5944 return SDValue(Res, 0);
5946 // fold (sext (sext x)) -> (sext x)
5947 // fold (sext (aext x)) -> (sext x)
5948 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5949 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5952 if (N0.getOpcode() == ISD::TRUNCATE) {
5953 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5954 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5955 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5956 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5957 if (NarrowLoad.getNode() != N0.getNode()) {
5958 CombineTo(N0.getNode(), NarrowLoad);
5959 // CombineTo deleted the truncate, if needed, but not what's under it.
5962 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5965 // See if the value being truncated is already sign extended. If so, just
5966 // eliminate the trunc/sext pair.
5967 SDValue Op = N0.getOperand(0);
5968 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5969 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5970 unsigned DestBits = VT.getScalarType().getSizeInBits();
5971 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5973 if (OpBits == DestBits) {
5974 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5975 // bits, it is already ready.
5976 if (NumSignBits > DestBits-MidBits)
5978 } else if (OpBits < DestBits) {
5979 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5980 // bits, just sext from i32.
5981 if (NumSignBits > OpBits-MidBits)
5982 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5984 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5985 // bits, just truncate to i32.
5986 if (NumSignBits > OpBits-MidBits)
5987 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5990 // fold (sext (truncate x)) -> (sextinreg x).
5991 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5992 N0.getValueType())) {
5993 if (OpBits < DestBits)
5994 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5995 else if (OpBits > DestBits)
5996 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5997 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5998 DAG.getValueType(N0.getValueType()));
6002 // fold (sext (load x)) -> (sext (truncate (sextload x)))
6003 // Only generate vector extloads when 1) they're legal, and 2) they are
6004 // deemed desirable by the target.
6005 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6006 ((!LegalOperations && !VT.isVector() &&
6007 !cast<LoadSDNode>(N0)->isVolatile()) ||
6008 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6009 bool DoXform = true;
6010 SmallVector<SDNode*, 4> SetCCs;
6011 if (!N0.hasOneUse())
6012 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6014 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6016 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6017 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6019 LN0->getBasePtr(), N0.getValueType(),
6020 LN0->getMemOperand());
6021 CombineTo(N, ExtLoad);
6022 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6023 N0.getValueType(), ExtLoad);
6024 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6025 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6027 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6031 // fold (sext (load x)) to multiple smaller sextloads.
6032 // Only on illegal but splittable vectors.
6033 if (SDValue ExtLoad = CombineExtLoad(N))
6036 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6037 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6038 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6039 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6040 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6041 EVT MemVT = LN0->getMemoryVT();
6042 if ((!LegalOperations && !LN0->isVolatile()) ||
6043 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6044 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6046 LN0->getBasePtr(), MemVT,
6047 LN0->getMemOperand());
6048 CombineTo(N, ExtLoad);
6049 CombineTo(N0.getNode(),
6050 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6051 N0.getValueType(), ExtLoad),
6052 ExtLoad.getValue(1));
6053 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6057 // fold (sext (and/or/xor (load x), cst)) ->
6058 // (and/or/xor (sextload x), (sext cst))
6059 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6060 N0.getOpcode() == ISD::XOR) &&
6061 isa<LoadSDNode>(N0.getOperand(0)) &&
6062 N0.getOperand(1).getOpcode() == ISD::Constant &&
6063 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6064 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6065 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6066 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6067 bool DoXform = true;
6068 SmallVector<SDNode*, 4> SetCCs;
6069 if (!N0.hasOneUse())
6070 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6073 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6074 LN0->getChain(), LN0->getBasePtr(),
6076 LN0->getMemOperand());
6077 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6078 Mask = Mask.sext(VT.getSizeInBits());
6080 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6081 ExtLoad, DAG.getConstant(Mask, DL, VT));
6082 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6083 SDLoc(N0.getOperand(0)),
6084 N0.getOperand(0).getValueType(), ExtLoad);
6086 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6087 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6089 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6094 if (N0.getOpcode() == ISD::SETCC) {
6095 EVT N0VT = N0.getOperand(0).getValueType();
6096 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6097 // Only do this before legalize for now.
6098 if (VT.isVector() && !LegalOperations &&
6099 TLI.getBooleanContents(N0VT) ==
6100 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6101 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6102 // of the same size as the compared operands. Only optimize sext(setcc())
6103 // if this is the case.
6104 EVT SVT = getSetCCResultType(N0VT);
6106 // We know that the # elements of the results is the same as the
6107 // # elements of the compare (and the # elements of the compare result
6108 // for that matter). Check to see that they are the same size. If so,
6109 // we know that the element size of the sext'd result matches the
6110 // element size of the compare operands.
6111 if (VT.getSizeInBits() == SVT.getSizeInBits())
6112 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6114 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6116 // If the desired elements are smaller or larger than the source
6117 // elements we can use a matching integer vector type and then
6118 // truncate/sign extend
6119 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6120 if (SVT == MatchingVectorType) {
6121 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6122 N0.getOperand(0), N0.getOperand(1),
6123 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6124 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6128 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6129 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6132 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6134 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6135 NegOne, DAG.getConstant(0, DL, VT),
6136 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6137 if (SCC.getNode()) return SCC;
6139 if (!VT.isVector()) {
6140 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6141 if (!LegalOperations ||
6142 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6144 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6145 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6146 N0.getOperand(0), N0.getOperand(1), CC);
6147 return DAG.getSelect(DL, VT, SetCC,
6148 NegOne, DAG.getConstant(0, DL, VT));
6153 // fold (sext x) -> (zext x) if the sign bit is known zero.
6154 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6155 DAG.SignBitIsZero(N0))
6156 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6161 // isTruncateOf - If N is a truncate of some other value, return true, record
6162 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6163 // This function computes KnownZero to avoid a duplicated call to
6164 // computeKnownBits in the caller.
6165 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6168 if (N->getOpcode() == ISD::TRUNCATE) {
6169 Op = N->getOperand(0);
6170 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6174 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6175 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6178 SDValue Op0 = N->getOperand(0);
6179 SDValue Op1 = N->getOperand(1);
6180 assert(Op0.getValueType() == Op1.getValueType());
6182 if (isNullConstant(Op0))
6184 else if (isNullConstant(Op1))
6189 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6191 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6197 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6198 SDValue N0 = N->getOperand(0);
6199 EVT VT = N->getValueType(0);
6201 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6203 return SDValue(Res, 0);
6205 // fold (zext (zext x)) -> (zext x)
6206 // fold (zext (aext x)) -> (zext x)
6207 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6208 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6211 // fold (zext (truncate x)) -> (zext x) or
6212 // (zext (truncate x)) -> (truncate x)
6213 // This is valid when the truncated bits of x are already zero.
6214 // FIXME: We should extend this to work for vectors too.
6217 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6218 APInt TruncatedBits =
6219 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6220 APInt(Op.getValueSizeInBits(), 0) :
6221 APInt::getBitsSet(Op.getValueSizeInBits(),
6222 N0.getValueSizeInBits(),
6223 std::min(Op.getValueSizeInBits(),
6224 VT.getSizeInBits()));
6225 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6226 if (VT.bitsGT(Op.getValueType()))
6227 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6228 if (VT.bitsLT(Op.getValueType()))
6229 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6235 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6236 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6237 if (N0.getOpcode() == ISD::TRUNCATE) {
6238 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6239 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6240 if (NarrowLoad.getNode() != N0.getNode()) {
6241 CombineTo(N0.getNode(), NarrowLoad);
6242 // CombineTo deleted the truncate, if needed, but not what's under it.
6245 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6249 // fold (zext (truncate x)) -> (and x, mask)
6250 if (N0.getOpcode() == ISD::TRUNCATE) {
6251 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6252 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6253 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6254 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6255 if (NarrowLoad.getNode() != N0.getNode()) {
6256 CombineTo(N0.getNode(), NarrowLoad);
6257 // CombineTo deleted the truncate, if needed, but not what's under it.
6260 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6263 EVT SrcVT = N0.getOperand(0).getValueType();
6264 EVT MinVT = N0.getValueType();
6266 // Try to mask before the extension to avoid having to generate a larger mask,
6267 // possibly over several sub-vectors.
6268 if (SrcVT.bitsLT(VT)) {
6269 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6270 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6271 SDValue Op = N0.getOperand(0);
6272 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6273 AddToWorklist(Op.getNode());
6274 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6278 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6279 SDValue Op = N0.getOperand(0);
6280 if (SrcVT.bitsLT(VT)) {
6281 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6282 AddToWorklist(Op.getNode());
6283 } else if (SrcVT.bitsGT(VT)) {
6284 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6285 AddToWorklist(Op.getNode());
6287 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6291 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6292 // if either of the casts is not free.
6293 if (N0.getOpcode() == ISD::AND &&
6294 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6295 N0.getOperand(1).getOpcode() == ISD::Constant &&
6296 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6297 N0.getValueType()) ||
6298 !TLI.isZExtFree(N0.getValueType(), VT))) {
6299 SDValue X = N0.getOperand(0).getOperand(0);
6300 if (X.getValueType().bitsLT(VT)) {
6301 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6302 } else if (X.getValueType().bitsGT(VT)) {
6303 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6305 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6306 Mask = Mask.zext(VT.getSizeInBits());
6308 return DAG.getNode(ISD::AND, DL, VT,
6309 X, DAG.getConstant(Mask, DL, VT));
6312 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6313 // Only generate vector extloads when 1) they're legal, and 2) they are
6314 // deemed desirable by the target.
6315 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6316 ((!LegalOperations && !VT.isVector() &&
6317 !cast<LoadSDNode>(N0)->isVolatile()) ||
6318 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6319 bool DoXform = true;
6320 SmallVector<SDNode*, 4> SetCCs;
6321 if (!N0.hasOneUse())
6322 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6324 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6326 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6327 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6329 LN0->getBasePtr(), N0.getValueType(),
6330 LN0->getMemOperand());
6331 CombineTo(N, ExtLoad);
6332 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6333 N0.getValueType(), ExtLoad);
6334 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6336 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6338 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6342 // fold (zext (load x)) to multiple smaller zextloads.
6343 // Only on illegal but splittable vectors.
6344 if (SDValue ExtLoad = CombineExtLoad(N))
6347 // fold (zext (and/or/xor (load x), cst)) ->
6348 // (and/or/xor (zextload x), (zext cst))
6349 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6350 N0.getOpcode() == ISD::XOR) &&
6351 isa<LoadSDNode>(N0.getOperand(0)) &&
6352 N0.getOperand(1).getOpcode() == ISD::Constant &&
6353 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6354 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6355 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6356 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6357 bool DoXform = true;
6358 SmallVector<SDNode*, 4> SetCCs;
6359 if (!N0.hasOneUse())
6360 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6363 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6364 LN0->getChain(), LN0->getBasePtr(),
6366 LN0->getMemOperand());
6367 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6368 Mask = Mask.zext(VT.getSizeInBits());
6370 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6371 ExtLoad, DAG.getConstant(Mask, DL, VT));
6372 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6373 SDLoc(N0.getOperand(0)),
6374 N0.getOperand(0).getValueType(), ExtLoad);
6376 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6377 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6379 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6384 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6385 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6386 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6387 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6388 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6389 EVT MemVT = LN0->getMemoryVT();
6390 if ((!LegalOperations && !LN0->isVolatile()) ||
6391 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6392 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6394 LN0->getBasePtr(), MemVT,
6395 LN0->getMemOperand());
6396 CombineTo(N, ExtLoad);
6397 CombineTo(N0.getNode(),
6398 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6400 ExtLoad.getValue(1));
6401 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6405 if (N0.getOpcode() == ISD::SETCC) {
6406 if (!LegalOperations && VT.isVector() &&
6407 N0.getValueType().getVectorElementType() == MVT::i1) {
6408 EVT N0VT = N0.getOperand(0).getValueType();
6409 if (getSetCCResultType(N0VT) == N0.getValueType())
6412 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6413 // Only do this before legalize for now.
6414 EVT EltVT = VT.getVectorElementType();
6416 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6417 DAG.getConstant(1, DL, EltVT));
6418 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6419 // We know that the # elements of the results is the same as the
6420 // # elements of the compare (and the # elements of the compare result
6421 // for that matter). Check to see that they are the same size. If so,
6422 // we know that the element size of the sext'd result matches the
6423 // element size of the compare operands.
6424 return DAG.getNode(ISD::AND, DL, VT,
6425 DAG.getSetCC(DL, VT, N0.getOperand(0),
6427 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6428 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6431 // If the desired elements are smaller or larger than the source
6432 // elements we can use a matching integer vector type and then
6433 // truncate/sign extend
6434 EVT MatchingElementType =
6435 EVT::getIntegerVT(*DAG.getContext(),
6436 N0VT.getScalarType().getSizeInBits());
6437 EVT MatchingVectorType =
6438 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6439 N0VT.getVectorNumElements());
6441 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6443 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6444 return DAG.getNode(ISD::AND, DL, VT,
6445 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6446 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6449 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6452 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6453 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6454 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6455 if (SCC.getNode()) return SCC;
6458 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6459 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6460 isa<ConstantSDNode>(N0.getOperand(1)) &&
6461 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6463 SDValue ShAmt = N0.getOperand(1);
6464 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6465 if (N0.getOpcode() == ISD::SHL) {
6466 SDValue InnerZExt = N0.getOperand(0);
6467 // If the original shl may be shifting out bits, do not perform this
6469 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6470 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6471 if (ShAmtVal > KnownZeroBits)
6477 // Ensure that the shift amount is wide enough for the shifted value.
6478 if (VT.getSizeInBits() >= 256)
6479 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6481 return DAG.getNode(N0.getOpcode(), DL, VT,
6482 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6489 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6490 SDValue N0 = N->getOperand(0);
6491 EVT VT = N->getValueType(0);
6493 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6495 return SDValue(Res, 0);
6497 // fold (aext (aext x)) -> (aext x)
6498 // fold (aext (zext x)) -> (zext x)
6499 // fold (aext (sext x)) -> (sext x)
6500 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6501 N0.getOpcode() == ISD::ZERO_EXTEND ||
6502 N0.getOpcode() == ISD::SIGN_EXTEND)
6503 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6505 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6506 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6507 if (N0.getOpcode() == ISD::TRUNCATE) {
6508 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6509 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6510 if (NarrowLoad.getNode() != N0.getNode()) {
6511 CombineTo(N0.getNode(), NarrowLoad);
6512 // CombineTo deleted the truncate, if needed, but not what's under it.
6515 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6519 // fold (aext (truncate x))
6520 if (N0.getOpcode() == ISD::TRUNCATE) {
6521 SDValue TruncOp = N0.getOperand(0);
6522 if (TruncOp.getValueType() == VT)
6523 return TruncOp; // x iff x size == zext size.
6524 if (TruncOp.getValueType().bitsGT(VT))
6525 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6526 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6529 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6530 // if the trunc is not free.
6531 if (N0.getOpcode() == ISD::AND &&
6532 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6533 N0.getOperand(1).getOpcode() == ISD::Constant &&
6534 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6535 N0.getValueType())) {
6536 SDValue X = N0.getOperand(0).getOperand(0);
6537 if (X.getValueType().bitsLT(VT)) {
6538 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6539 } else if (X.getValueType().bitsGT(VT)) {
6540 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6542 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6543 Mask = Mask.zext(VT.getSizeInBits());
6545 return DAG.getNode(ISD::AND, DL, VT,
6546 X, DAG.getConstant(Mask, DL, VT));
6549 // fold (aext (load x)) -> (aext (truncate (extload x)))
6550 // None of the supported targets knows how to perform load and any_ext
6551 // on vectors in one instruction. We only perform this transformation on
6553 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6554 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6555 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6556 bool DoXform = true;
6557 SmallVector<SDNode*, 4> SetCCs;
6558 if (!N0.hasOneUse())
6559 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6561 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6562 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6564 LN0->getBasePtr(), N0.getValueType(),
6565 LN0->getMemOperand());
6566 CombineTo(N, ExtLoad);
6567 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6568 N0.getValueType(), ExtLoad);
6569 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6570 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6572 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6576 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6577 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6578 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6579 if (N0.getOpcode() == ISD::LOAD &&
6580 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6582 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6583 ISD::LoadExtType ExtType = LN0->getExtensionType();
6584 EVT MemVT = LN0->getMemoryVT();
6585 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6586 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6587 VT, LN0->getChain(), LN0->getBasePtr(),
6588 MemVT, LN0->getMemOperand());
6589 CombineTo(N, ExtLoad);
6590 CombineTo(N0.getNode(),
6591 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6592 N0.getValueType(), ExtLoad),
6593 ExtLoad.getValue(1));
6594 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6598 if (N0.getOpcode() == ISD::SETCC) {
6600 // aext(setcc) -> vsetcc
6601 // aext(setcc) -> truncate(vsetcc)
6602 // aext(setcc) -> aext(vsetcc)
6603 // Only do this before legalize for now.
6604 if (VT.isVector() && !LegalOperations) {
6605 EVT N0VT = N0.getOperand(0).getValueType();
6606 // We know that the # elements of the results is the same as the
6607 // # elements of the compare (and the # elements of the compare result
6608 // for that matter). Check to see that they are the same size. If so,
6609 // we know that the element size of the sext'd result matches the
6610 // element size of the compare operands.
6611 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6612 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6614 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6615 // If the desired elements are smaller or larger than the source
6616 // elements we can use a matching integer vector type and then
6617 // truncate/any extend
6619 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6621 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6623 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6624 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6628 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6631 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6632 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6633 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6641 /// See if the specified operand can be simplified with the knowledge that only
6642 /// the bits specified by Mask are used. If so, return the simpler operand,
6643 /// otherwise return a null SDValue.
6644 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6645 switch (V.getOpcode()) {
6647 case ISD::Constant: {
6648 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6649 assert(CV && "Const value should be ConstSDNode.");
6650 const APInt &CVal = CV->getAPIntValue();
6651 APInt NewVal = CVal & Mask;
6653 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6658 // If the LHS or RHS don't contribute bits to the or, drop them.
6659 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6660 return V.getOperand(1);
6661 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6662 return V.getOperand(0);
6665 // Only look at single-use SRLs.
6666 if (!V.getNode()->hasOneUse())
6668 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6669 // See if we can recursively simplify the LHS.
6670 unsigned Amt = RHSC->getZExtValue();
6672 // Watch out for shift count overflow though.
6673 if (Amt >= Mask.getBitWidth()) break;
6674 APInt NewMask = Mask << Amt;
6675 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6676 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6677 SimplifyLHS, V.getOperand(1));
6683 /// If the result of a wider load is shifted to right of N bits and then
6684 /// truncated to a narrower type and where N is a multiple of number of bits of
6685 /// the narrower type, transform it to a narrower load from address + N / num of
6686 /// bits of new type. If the result is to be extended, also fold the extension
6687 /// to form a extending load.
6688 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6689 unsigned Opc = N->getOpcode();
6691 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6692 SDValue N0 = N->getOperand(0);
6693 EVT VT = N->getValueType(0);
6696 // This transformation isn't valid for vector loads.
6700 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6702 if (Opc == ISD::SIGN_EXTEND_INREG) {
6703 ExtType = ISD::SEXTLOAD;
6704 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6705 } else if (Opc == ISD::SRL) {
6706 // Another special-case: SRL is basically zero-extending a narrower value.
6707 ExtType = ISD::ZEXTLOAD;
6709 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6710 if (!N01) return SDValue();
6711 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6712 VT.getSizeInBits() - N01->getZExtValue());
6714 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6717 unsigned EVTBits = ExtVT.getSizeInBits();
6719 // Do not generate loads of non-round integer types since these can
6720 // be expensive (and would be wrong if the type is not byte sized).
6721 if (!ExtVT.isRound())
6725 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6726 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6727 ShAmt = N01->getZExtValue();
6728 // Is the shift amount a multiple of size of VT?
6729 if ((ShAmt & (EVTBits-1)) == 0) {
6730 N0 = N0.getOperand(0);
6731 // Is the load width a multiple of size of VT?
6732 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6736 // At this point, we must have a load or else we can't do the transform.
6737 if (!isa<LoadSDNode>(N0)) return SDValue();
6739 // Because a SRL must be assumed to *need* to zero-extend the high bits
6740 // (as opposed to anyext the high bits), we can't combine the zextload
6741 // lowering of SRL and an sextload.
6742 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6745 // If the shift amount is larger than the input type then we're not
6746 // accessing any of the loaded bytes. If the load was a zextload/extload
6747 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6748 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6753 // If the load is shifted left (and the result isn't shifted back right),
6754 // we can fold the truncate through the shift.
6755 unsigned ShLeftAmt = 0;
6756 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6757 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6758 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6759 ShLeftAmt = N01->getZExtValue();
6760 N0 = N0.getOperand(0);
6764 // If we haven't found a load, we can't narrow it. Don't transform one with
6765 // multiple uses, this would require adding a new load.
6766 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6769 // Don't change the width of a volatile load.
6770 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6771 if (LN0->isVolatile())
6774 // Verify that we are actually reducing a load width here.
6775 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6778 // For the transform to be legal, the load must produce only two values
6779 // (the value loaded and the chain). Don't transform a pre-increment
6780 // load, for example, which produces an extra value. Otherwise the
6781 // transformation is not equivalent, and the downstream logic to replace
6782 // uses gets things wrong.
6783 if (LN0->getNumValues() > 2)
6786 // If the load that we're shrinking is an extload and we're not just
6787 // discarding the extension we can't simply shrink the load. Bail.
6788 // TODO: It would be possible to merge the extensions in some cases.
6789 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6790 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6793 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6796 EVT PtrType = N0.getOperand(1).getValueType();
6798 if (PtrType == MVT::Untyped || PtrType.isExtended())
6799 // It's not possible to generate a constant of extended or untyped type.
6802 // For big endian targets, we need to adjust the offset to the pointer to
6803 // load the correct bytes.
6804 if (DAG.getDataLayout().isBigEndian()) {
6805 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6806 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6807 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6810 uint64_t PtrOff = ShAmt / 8;
6811 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6813 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6814 PtrType, LN0->getBasePtr(),
6815 DAG.getConstant(PtrOff, DL, PtrType));
6816 AddToWorklist(NewPtr.getNode());
6819 if (ExtType == ISD::NON_EXTLOAD)
6820 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6821 LN0->getPointerInfo().getWithOffset(PtrOff),
6822 LN0->isVolatile(), LN0->isNonTemporal(),
6823 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6825 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6826 LN0->getPointerInfo().getWithOffset(PtrOff),
6827 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6828 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6830 // Replace the old load's chain with the new load's chain.
6831 WorklistRemover DeadNodes(*this);
6832 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6834 // Shift the result left, if we've swallowed a left shift.
6835 SDValue Result = Load;
6836 if (ShLeftAmt != 0) {
6837 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6838 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6840 // If the shift amount is as large as the result size (but, presumably,
6841 // no larger than the source) then the useful bits of the result are
6842 // zero; we can't simply return the shortened shift, because the result
6843 // of that operation is undefined.
6845 if (ShLeftAmt >= VT.getSizeInBits())
6846 Result = DAG.getConstant(0, DL, VT);
6848 Result = DAG.getNode(ISD::SHL, DL, VT,
6849 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6852 // Return the new loaded value.
6856 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6857 SDValue N0 = N->getOperand(0);
6858 SDValue N1 = N->getOperand(1);
6859 EVT VT = N->getValueType(0);
6860 EVT EVT = cast<VTSDNode>(N1)->getVT();
6861 unsigned VTBits = VT.getScalarType().getSizeInBits();
6862 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6865 return DAG.getUNDEF(VT);
6867 // fold (sext_in_reg c1) -> c1
6868 if (isConstantIntBuildVectorOrConstantInt(N0))
6869 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6871 // If the input is already sign extended, just drop the extension.
6872 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6875 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6876 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6877 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6878 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6879 N0.getOperand(0), N1);
6881 // fold (sext_in_reg (sext x)) -> (sext x)
6882 // fold (sext_in_reg (aext x)) -> (sext x)
6883 // if x is small enough.
6884 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6885 SDValue N00 = N0.getOperand(0);
6886 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6887 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6888 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6891 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6892 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6893 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6895 // fold operands of sext_in_reg based on knowledge that the top bits are not
6897 if (SimplifyDemandedBits(SDValue(N, 0)))
6898 return SDValue(N, 0);
6900 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6901 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6902 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6905 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6906 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6907 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6908 if (N0.getOpcode() == ISD::SRL) {
6909 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6910 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6911 // We can turn this into an SRA iff the input to the SRL is already sign
6913 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6914 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6915 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6916 N0.getOperand(0), N0.getOperand(1));
6920 // fold (sext_inreg (extload x)) -> (sextload x)
6921 if (ISD::isEXTLoad(N0.getNode()) &&
6922 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6923 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6924 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6925 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6926 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6927 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6929 LN0->getBasePtr(), EVT,
6930 LN0->getMemOperand());
6931 CombineTo(N, ExtLoad);
6932 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6933 AddToWorklist(ExtLoad.getNode());
6934 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6936 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6937 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6939 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6940 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6941 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6942 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6943 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6945 LN0->getBasePtr(), EVT,
6946 LN0->getMemOperand());
6947 CombineTo(N, ExtLoad);
6948 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6949 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6952 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6953 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6954 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6955 N0.getOperand(1), false);
6956 if (BSwap.getNode())
6957 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6964 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6965 SDValue N0 = N->getOperand(0);
6966 EVT VT = N->getValueType(0);
6968 if (N0.getOpcode() == ISD::UNDEF)
6969 return DAG.getUNDEF(VT);
6971 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6973 return SDValue(Res, 0);
6978 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6979 SDValue N0 = N->getOperand(0);
6980 EVT VT = N->getValueType(0);
6981 bool isLE = DAG.getDataLayout().isLittleEndian();
6984 if (N0.getValueType() == N->getValueType(0))
6986 // fold (truncate c1) -> c1
6987 if (isConstantIntBuildVectorOrConstantInt(N0))
6988 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6989 // fold (truncate (truncate x)) -> (truncate x)
6990 if (N0.getOpcode() == ISD::TRUNCATE)
6991 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6992 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6993 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6994 N0.getOpcode() == ISD::SIGN_EXTEND ||
6995 N0.getOpcode() == ISD::ANY_EXTEND) {
6996 if (N0.getOperand(0).getValueType().bitsLT(VT))
6997 // if the source is smaller than the dest, we still need an extend
6998 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
7000 if (N0.getOperand(0).getValueType().bitsGT(VT))
7001 // if the source is larger than the dest, than we just need the truncate
7002 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7003 // if the source and dest are the same type, we can drop both the extend
7004 // and the truncate.
7005 return N0.getOperand(0);
7008 // Fold extract-and-trunc into a narrow extract. For example:
7009 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7010 // i32 y = TRUNCATE(i64 x)
7012 // v16i8 b = BITCAST (v2i64 val)
7013 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7015 // Note: We only run this optimization after type legalization (which often
7016 // creates this pattern) and before operation legalization after which
7017 // we need to be more careful about the vector instructions that we generate.
7018 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7019 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7021 EVT VecTy = N0.getOperand(0).getValueType();
7022 EVT ExTy = N0.getValueType();
7023 EVT TrTy = N->getValueType(0);
7025 unsigned NumElem = VecTy.getVectorNumElements();
7026 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7028 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7029 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7031 SDValue EltNo = N0->getOperand(1);
7032 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7033 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7034 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7035 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7037 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7038 NVT, N0.getOperand(0));
7041 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7043 DAG.getConstant(Index, DL, IndexTy));
7047 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7048 if (N0.getOpcode() == ISD::SELECT) {
7049 EVT SrcVT = N0.getValueType();
7050 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7051 TLI.isTruncateFree(SrcVT, VT)) {
7053 SDValue Cond = N0.getOperand(0);
7054 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7055 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7056 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7060 // Fold a series of buildvector, bitcast, and truncate if possible.
7062 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7063 // (2xi32 (buildvector x, y)).
7064 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7065 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7066 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7067 N0.getOperand(0).hasOneUse()) {
7069 SDValue BuildVect = N0.getOperand(0);
7070 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7071 EVT TruncVecEltTy = VT.getVectorElementType();
7073 // Check that the element types match.
7074 if (BuildVectEltTy == TruncVecEltTy) {
7075 // Now we only need to compute the offset of the truncated elements.
7076 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7077 unsigned TruncVecNumElts = VT.getVectorNumElements();
7078 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7080 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7081 "Invalid number of elements");
7083 SmallVector<SDValue, 8> Opnds;
7084 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7085 Opnds.push_back(BuildVect.getOperand(i));
7087 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7091 // See if we can simplify the input to this truncate through knowledge that
7092 // only the low bits are being used.
7093 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7094 // Currently we only perform this optimization on scalars because vectors
7095 // may have different active low bits.
7096 if (!VT.isVector()) {
7098 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7099 VT.getSizeInBits()));
7100 if (Shorter.getNode())
7101 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7103 // fold (truncate (load x)) -> (smaller load x)
7104 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7105 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7106 if (SDValue Reduced = ReduceLoadWidth(N))
7109 // Handle the case where the load remains an extending load even
7110 // after truncation.
7111 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7112 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7113 if (!LN0->isVolatile() &&
7114 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7115 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7116 VT, LN0->getChain(), LN0->getBasePtr(),
7118 LN0->getMemOperand());
7119 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7124 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7125 // where ... are all 'undef'.
7126 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7127 SmallVector<EVT, 8> VTs;
7130 unsigned NumDefs = 0;
7132 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7133 SDValue X = N0.getOperand(i);
7134 if (X.getOpcode() != ISD::UNDEF) {
7139 // Stop if more than one members are non-undef.
7142 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7143 VT.getVectorElementType(),
7144 X.getValueType().getVectorNumElements()));
7148 return DAG.getUNDEF(VT);
7151 assert(V.getNode() && "The single defined operand is empty!");
7152 SmallVector<SDValue, 8> Opnds;
7153 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7155 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7158 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7159 AddToWorklist(NV.getNode());
7160 Opnds.push_back(NV);
7162 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7166 // Simplify the operands using demanded-bits information.
7167 if (!VT.isVector() &&
7168 SimplifyDemandedBits(SDValue(N, 0)))
7169 return SDValue(N, 0);
7174 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7175 SDValue Elt = N->getOperand(i);
7176 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7177 return Elt.getNode();
7178 return Elt.getOperand(Elt.getResNo()).getNode();
7181 /// build_pair (load, load) -> load
7182 /// if load locations are consecutive.
7183 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7184 assert(N->getOpcode() == ISD::BUILD_PAIR);
7186 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7187 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7188 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7189 LD1->getAddressSpace() != LD2->getAddressSpace())
7191 EVT LD1VT = LD1->getValueType(0);
7193 if (ISD::isNON_EXTLoad(LD2) &&
7195 // If both are volatile this would reduce the number of volatile loads.
7196 // If one is volatile it might be ok, but play conservative and bail out.
7197 !LD1->isVolatile() &&
7198 !LD2->isVolatile() &&
7199 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7200 unsigned Align = LD1->getAlignment();
7201 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7202 VT.getTypeForEVT(*DAG.getContext()));
7204 if (NewAlign <= Align &&
7205 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7206 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7207 LD1->getBasePtr(), LD1->getPointerInfo(),
7208 false, false, false, Align);
7214 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7215 SDValue N0 = N->getOperand(0);
7216 EVT VT = N->getValueType(0);
7218 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7219 // Only do this before legalize, since afterward the target may be depending
7220 // on the bitconvert.
7221 // First check to see if this is all constant.
7223 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7225 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7227 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7228 assert(!DestEltVT.isVector() &&
7229 "Element type of vector ValueType must not be vector!");
7231 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7234 // If the input is a constant, let getNode fold it.
7235 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7236 // If we can't allow illegal operations, we need to check that this is just
7237 // a fp -> int or int -> conversion and that the resulting operation will
7239 if (!LegalOperations ||
7240 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7241 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7242 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7243 TLI.isOperationLegal(ISD::Constant, VT)))
7244 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7247 // (conv (conv x, t1), t2) -> (conv x, t2)
7248 if (N0.getOpcode() == ISD::BITCAST)
7249 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7252 // fold (conv (load x)) -> (load (conv*)x)
7253 // If the resultant load doesn't need a higher alignment than the original!
7254 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7255 // Do not change the width of a volatile load.
7256 !cast<LoadSDNode>(N0)->isVolatile() &&
7257 // Do not remove the cast if the types differ in endian layout.
7258 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7259 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7260 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7261 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7262 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7263 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7264 VT.getTypeForEVT(*DAG.getContext()));
7265 unsigned OrigAlign = LN0->getAlignment();
7267 if (Align <= OrigAlign) {
7268 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7269 LN0->getBasePtr(), LN0->getPointerInfo(),
7270 LN0->isVolatile(), LN0->isNonTemporal(),
7271 LN0->isInvariant(), OrigAlign,
7273 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7278 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7279 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7280 // This often reduces constant pool loads.
7281 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7282 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7283 N0.getNode()->hasOneUse() && VT.isInteger() &&
7284 !VT.isVector() && !N0.getValueType().isVector()) {
7285 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7287 AddToWorklist(NewConv.getNode());
7290 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7291 if (N0.getOpcode() == ISD::FNEG)
7292 return DAG.getNode(ISD::XOR, DL, VT,
7293 NewConv, DAG.getConstant(SignBit, DL, VT));
7294 assert(N0.getOpcode() == ISD::FABS);
7295 return DAG.getNode(ISD::AND, DL, VT,
7296 NewConv, DAG.getConstant(~SignBit, DL, VT));
7299 // fold (bitconvert (fcopysign cst, x)) ->
7300 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7301 // Note that we don't handle (copysign x, cst) because this can always be
7302 // folded to an fneg or fabs.
7303 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7304 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7305 VT.isInteger() && !VT.isVector()) {
7306 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7307 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7308 if (isTypeLegal(IntXVT)) {
7309 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7310 IntXVT, N0.getOperand(1));
7311 AddToWorklist(X.getNode());
7313 // If X has a different width than the result/lhs, sext it or truncate it.
7314 unsigned VTWidth = VT.getSizeInBits();
7315 if (OrigXWidth < VTWidth) {
7316 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7317 AddToWorklist(X.getNode());
7318 } else if (OrigXWidth > VTWidth) {
7319 // To get the sign bit in the right place, we have to shift it right
7320 // before truncating.
7322 X = DAG.getNode(ISD::SRL, DL,
7323 X.getValueType(), X,
7324 DAG.getConstant(OrigXWidth-VTWidth, DL,
7326 AddToWorklist(X.getNode());
7327 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7328 AddToWorklist(X.getNode());
7331 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7332 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7333 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7334 AddToWorklist(X.getNode());
7336 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7337 VT, N0.getOperand(0));
7338 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7339 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7340 AddToWorklist(Cst.getNode());
7342 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7346 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7347 if (N0.getOpcode() == ISD::BUILD_PAIR)
7348 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7351 // Remove double bitcasts from shuffles - this is often a legacy of
7352 // XformToShuffleWithZero being used to combine bitmaskings (of
7353 // float vectors bitcast to integer vectors) into shuffles.
7354 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7355 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7356 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7357 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7358 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7359 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7361 // If operands are a bitcast, peek through if it casts the original VT.
7362 // If operands are a constant, just bitcast back to original VT.
7363 auto PeekThroughBitcast = [&](SDValue Op) {
7364 if (Op.getOpcode() == ISD::BITCAST &&
7365 Op.getOperand(0).getValueType() == VT)
7366 return SDValue(Op.getOperand(0));
7367 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7368 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7369 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7373 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7374 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7379 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7380 SmallVector<int, 8> NewMask;
7381 for (int M : SVN->getMask())
7382 for (int i = 0; i != MaskScale; ++i)
7383 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7385 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7387 std::swap(SV0, SV1);
7388 ShuffleVectorSDNode::commuteMask(NewMask);
7389 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7393 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7399 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7400 EVT VT = N->getValueType(0);
7401 return CombineConsecutiveLoads(N, VT);
7404 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7405 /// operands. DstEltVT indicates the destination element value type.
7406 SDValue DAGCombiner::
7407 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7408 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7410 // If this is already the right type, we're done.
7411 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7413 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7414 unsigned DstBitSize = DstEltVT.getSizeInBits();
7416 // If this is a conversion of N elements of one type to N elements of another
7417 // type, convert each element. This handles FP<->INT cases.
7418 if (SrcBitSize == DstBitSize) {
7419 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7420 BV->getValueType(0).getVectorNumElements());
7422 // Due to the FP element handling below calling this routine recursively,
7423 // we can end up with a scalar-to-vector node here.
7424 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7425 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7426 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7427 DstEltVT, BV->getOperand(0)));
7429 SmallVector<SDValue, 8> Ops;
7430 for (SDValue Op : BV->op_values()) {
7431 // If the vector element type is not legal, the BUILD_VECTOR operands
7432 // are promoted and implicitly truncated. Make that explicit here.
7433 if (Op.getValueType() != SrcEltVT)
7434 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7435 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7437 AddToWorklist(Ops.back().getNode());
7439 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7442 // Otherwise, we're growing or shrinking the elements. To avoid having to
7443 // handle annoying details of growing/shrinking FP values, we convert them to
7445 if (SrcEltVT.isFloatingPoint()) {
7446 // Convert the input float vector to a int vector where the elements are the
7448 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7449 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7453 // Now we know the input is an integer vector. If the output is a FP type,
7454 // convert to integer first, then to FP of the right size.
7455 if (DstEltVT.isFloatingPoint()) {
7456 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7457 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7459 // Next, convert to FP elements of the same size.
7460 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7465 // Okay, we know the src/dst types are both integers of differing types.
7466 // Handling growing first.
7467 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7468 if (SrcBitSize < DstBitSize) {
7469 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7471 SmallVector<SDValue, 8> Ops;
7472 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7473 i += NumInputsPerOutput) {
7474 bool isLE = DAG.getDataLayout().isLittleEndian();
7475 APInt NewBits = APInt(DstBitSize, 0);
7476 bool EltIsUndef = true;
7477 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7478 // Shift the previously computed bits over.
7479 NewBits <<= SrcBitSize;
7480 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7481 if (Op.getOpcode() == ISD::UNDEF) continue;
7484 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7485 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7489 Ops.push_back(DAG.getUNDEF(DstEltVT));
7491 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7494 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7495 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7498 // Finally, this must be the case where we are shrinking elements: each input
7499 // turns into multiple outputs.
7500 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7501 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7502 NumOutputsPerInput*BV->getNumOperands());
7503 SmallVector<SDValue, 8> Ops;
7505 for (const SDValue &Op : BV->op_values()) {
7506 if (Op.getOpcode() == ISD::UNDEF) {
7507 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7511 APInt OpVal = cast<ConstantSDNode>(Op)->
7512 getAPIntValue().zextOrTrunc(SrcBitSize);
7514 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7515 APInt ThisVal = OpVal.trunc(DstBitSize);
7516 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7517 OpVal = OpVal.lshr(DstBitSize);
7520 // For big endian targets, swap the order of the pieces of each element.
7521 if (DAG.getDataLayout().isBigEndian())
7522 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7525 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7528 /// Try to perform FMA combining on a given FADD node.
7529 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7530 SDValue N0 = N->getOperand(0);
7531 SDValue N1 = N->getOperand(1);
7532 EVT VT = N->getValueType(0);
7535 const TargetOptions &Options = DAG.getTarget().Options;
7537 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7539 // Floating-point multiply-add with intermediate rounding.
7540 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7542 // Floating-point multiply-add without intermediate rounding.
7544 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7545 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7547 // No valid opcode, do not combine.
7548 if (!HasFMAD && !HasFMA)
7551 // Always prefer FMAD to FMA for precision.
7552 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7553 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7554 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7556 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7557 // prefer to fold the multiply with fewer uses.
7558 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7559 N1.getOpcode() == ISD::FMUL) {
7560 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7564 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7565 if (N0.getOpcode() == ISD::FMUL &&
7566 (Aggressive || N0->hasOneUse())) {
7567 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7568 N0.getOperand(0), N0.getOperand(1), N1);
7571 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7572 // Note: Commutes FADD operands.
7573 if (N1.getOpcode() == ISD::FMUL &&
7574 (Aggressive || N1->hasOneUse())) {
7575 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7576 N1.getOperand(0), N1.getOperand(1), N0);
7579 // Look through FP_EXTEND nodes to do more combining.
7580 if (AllowFusion && LookThroughFPExt) {
7581 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7582 if (N0.getOpcode() == ISD::FP_EXTEND) {
7583 SDValue N00 = N0.getOperand(0);
7584 if (N00.getOpcode() == ISD::FMUL)
7585 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7586 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7588 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7589 N00.getOperand(1)), N1);
7592 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7593 // Note: Commutes FADD operands.
7594 if (N1.getOpcode() == ISD::FP_EXTEND) {
7595 SDValue N10 = N1.getOperand(0);
7596 if (N10.getOpcode() == ISD::FMUL)
7597 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7598 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7600 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7601 N10.getOperand(1)), N0);
7605 // More folding opportunities when target permits.
7606 if ((AllowFusion || HasFMAD) && Aggressive) {
7607 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7608 if (N0.getOpcode() == PreferredFusedOpcode &&
7609 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7610 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7611 N0.getOperand(0), N0.getOperand(1),
7612 DAG.getNode(PreferredFusedOpcode, SL, VT,
7613 N0.getOperand(2).getOperand(0),
7614 N0.getOperand(2).getOperand(1),
7618 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7619 if (N1->getOpcode() == PreferredFusedOpcode &&
7620 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7621 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7622 N1.getOperand(0), N1.getOperand(1),
7623 DAG.getNode(PreferredFusedOpcode, SL, VT,
7624 N1.getOperand(2).getOperand(0),
7625 N1.getOperand(2).getOperand(1),
7629 if (AllowFusion && LookThroughFPExt) {
7630 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7631 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7632 auto FoldFAddFMAFPExtFMul = [&] (
7633 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7634 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7635 DAG.getNode(PreferredFusedOpcode, SL, VT,
7636 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7637 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7640 if (N0.getOpcode() == PreferredFusedOpcode) {
7641 SDValue N02 = N0.getOperand(2);
7642 if (N02.getOpcode() == ISD::FP_EXTEND) {
7643 SDValue N020 = N02.getOperand(0);
7644 if (N020.getOpcode() == ISD::FMUL)
7645 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7646 N020.getOperand(0), N020.getOperand(1),
7651 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7652 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7653 // FIXME: This turns two single-precision and one double-precision
7654 // operation into two double-precision operations, which might not be
7655 // interesting for all targets, especially GPUs.
7656 auto FoldFAddFPExtFMAFMul = [&] (
7657 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7658 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7659 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7660 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7661 DAG.getNode(PreferredFusedOpcode, SL, VT,
7662 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7663 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7666 if (N0.getOpcode() == ISD::FP_EXTEND) {
7667 SDValue N00 = N0.getOperand(0);
7668 if (N00.getOpcode() == PreferredFusedOpcode) {
7669 SDValue N002 = N00.getOperand(2);
7670 if (N002.getOpcode() == ISD::FMUL)
7671 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7672 N002.getOperand(0), N002.getOperand(1),
7677 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7678 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7679 if (N1.getOpcode() == PreferredFusedOpcode) {
7680 SDValue N12 = N1.getOperand(2);
7681 if (N12.getOpcode() == ISD::FP_EXTEND) {
7682 SDValue N120 = N12.getOperand(0);
7683 if (N120.getOpcode() == ISD::FMUL)
7684 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7685 N120.getOperand(0), N120.getOperand(1),
7690 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7691 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7692 // FIXME: This turns two single-precision and one double-precision
7693 // operation into two double-precision operations, which might not be
7694 // interesting for all targets, especially GPUs.
7695 if (N1.getOpcode() == ISD::FP_EXTEND) {
7696 SDValue N10 = N1.getOperand(0);
7697 if (N10.getOpcode() == PreferredFusedOpcode) {
7698 SDValue N102 = N10.getOperand(2);
7699 if (N102.getOpcode() == ISD::FMUL)
7700 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7701 N102.getOperand(0), N102.getOperand(1),
7711 /// Try to perform FMA combining on a given FSUB node.
7712 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7713 SDValue N0 = N->getOperand(0);
7714 SDValue N1 = N->getOperand(1);
7715 EVT VT = N->getValueType(0);
7718 const TargetOptions &Options = DAG.getTarget().Options;
7720 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7722 // Floating-point multiply-add with intermediate rounding.
7723 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7725 // Floating-point multiply-add without intermediate rounding.
7727 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7728 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7730 // No valid opcode, do not combine.
7731 if (!HasFMAD && !HasFMA)
7734 // Always prefer FMAD to FMA for precision.
7735 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7736 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7737 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7739 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7740 if (N0.getOpcode() == ISD::FMUL &&
7741 (Aggressive || N0->hasOneUse())) {
7742 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7743 N0.getOperand(0), N0.getOperand(1),
7744 DAG.getNode(ISD::FNEG, SL, VT, N1));
7747 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7748 // Note: Commutes FSUB operands.
7749 if (N1.getOpcode() == ISD::FMUL &&
7750 (Aggressive || N1->hasOneUse()))
7751 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7752 DAG.getNode(ISD::FNEG, SL, VT,
7754 N1.getOperand(1), N0);
7756 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7757 if (N0.getOpcode() == ISD::FNEG &&
7758 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7759 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7760 SDValue N00 = N0.getOperand(0).getOperand(0);
7761 SDValue N01 = N0.getOperand(0).getOperand(1);
7762 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7763 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7764 DAG.getNode(ISD::FNEG, SL, VT, N1));
7767 // Look through FP_EXTEND nodes to do more combining.
7768 if (AllowFusion && LookThroughFPExt) {
7769 // fold (fsub (fpext (fmul x, y)), z)
7770 // -> (fma (fpext x), (fpext y), (fneg z))
7771 if (N0.getOpcode() == ISD::FP_EXTEND) {
7772 SDValue N00 = N0.getOperand(0);
7773 if (N00.getOpcode() == ISD::FMUL)
7774 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7775 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7777 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779 DAG.getNode(ISD::FNEG, SL, VT, N1));
7782 // fold (fsub x, (fpext (fmul y, z)))
7783 // -> (fma (fneg (fpext y)), (fpext z), x)
7784 // Note: Commutes FSUB operands.
7785 if (N1.getOpcode() == ISD::FP_EXTEND) {
7786 SDValue N10 = N1.getOperand(0);
7787 if (N10.getOpcode() == ISD::FMUL)
7788 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7789 DAG.getNode(ISD::FNEG, SL, VT,
7790 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7791 N10.getOperand(0))),
7792 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7797 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7798 // -> (fneg (fma (fpext x), (fpext y), z))
7799 // Note: This could be removed with appropriate canonicalization of the
7800 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7801 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7802 // from implementing the canonicalization in visitFSUB.
7803 if (N0.getOpcode() == ISD::FP_EXTEND) {
7804 SDValue N00 = N0.getOperand(0);
7805 if (N00.getOpcode() == ISD::FNEG) {
7806 SDValue N000 = N00.getOperand(0);
7807 if (N000.getOpcode() == ISD::FMUL) {
7808 return DAG.getNode(ISD::FNEG, SL, VT,
7809 DAG.getNode(PreferredFusedOpcode, SL, VT,
7810 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7811 N000.getOperand(0)),
7812 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7813 N000.getOperand(1)),
7819 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7820 // -> (fneg (fma (fpext x)), (fpext y), z)
7821 // Note: This could be removed with appropriate canonicalization of the
7822 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7823 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7824 // from implementing the canonicalization in visitFSUB.
7825 if (N0.getOpcode() == ISD::FNEG) {
7826 SDValue N00 = N0.getOperand(0);
7827 if (N00.getOpcode() == ISD::FP_EXTEND) {
7828 SDValue N000 = N00.getOperand(0);
7829 if (N000.getOpcode() == ISD::FMUL) {
7830 return DAG.getNode(ISD::FNEG, SL, VT,
7831 DAG.getNode(PreferredFusedOpcode, SL, VT,
7832 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7833 N000.getOperand(0)),
7834 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7835 N000.getOperand(1)),
7843 // More folding opportunities when target permits.
7844 if ((AllowFusion || HasFMAD) && Aggressive) {
7845 // fold (fsub (fma x, y, (fmul u, v)), z)
7846 // -> (fma x, y (fma u, v, (fneg z)))
7847 if (N0.getOpcode() == PreferredFusedOpcode &&
7848 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7849 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7850 N0.getOperand(0), N0.getOperand(1),
7851 DAG.getNode(PreferredFusedOpcode, SL, VT,
7852 N0.getOperand(2).getOperand(0),
7853 N0.getOperand(2).getOperand(1),
7854 DAG.getNode(ISD::FNEG, SL, VT,
7858 // fold (fsub x, (fma y, z, (fmul u, v)))
7859 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7860 if (N1.getOpcode() == PreferredFusedOpcode &&
7861 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7862 SDValue N20 = N1.getOperand(2).getOperand(0);
7863 SDValue N21 = N1.getOperand(2).getOperand(1);
7864 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7865 DAG.getNode(ISD::FNEG, SL, VT,
7868 DAG.getNode(PreferredFusedOpcode, SL, VT,
7869 DAG.getNode(ISD::FNEG, SL, VT, N20),
7874 if (AllowFusion && LookThroughFPExt) {
7875 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7876 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7877 if (N0.getOpcode() == PreferredFusedOpcode) {
7878 SDValue N02 = N0.getOperand(2);
7879 if (N02.getOpcode() == ISD::FP_EXTEND) {
7880 SDValue N020 = N02.getOperand(0);
7881 if (N020.getOpcode() == ISD::FMUL)
7882 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7883 N0.getOperand(0), N0.getOperand(1),
7884 DAG.getNode(PreferredFusedOpcode, SL, VT,
7885 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7886 N020.getOperand(0)),
7887 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7888 N020.getOperand(1)),
7889 DAG.getNode(ISD::FNEG, SL, VT,
7894 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7895 // -> (fma (fpext x), (fpext y),
7896 // (fma (fpext u), (fpext v), (fneg z)))
7897 // FIXME: This turns two single-precision and one double-precision
7898 // operation into two double-precision operations, which might not be
7899 // interesting for all targets, especially GPUs.
7900 if (N0.getOpcode() == ISD::FP_EXTEND) {
7901 SDValue N00 = N0.getOperand(0);
7902 if (N00.getOpcode() == PreferredFusedOpcode) {
7903 SDValue N002 = N00.getOperand(2);
7904 if (N002.getOpcode() == ISD::FMUL)
7905 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7906 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7908 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7910 DAG.getNode(PreferredFusedOpcode, SL, VT,
7911 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7912 N002.getOperand(0)),
7913 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7914 N002.getOperand(1)),
7915 DAG.getNode(ISD::FNEG, SL, VT,
7920 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7921 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7922 if (N1.getOpcode() == PreferredFusedOpcode &&
7923 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7924 SDValue N120 = N1.getOperand(2).getOperand(0);
7925 if (N120.getOpcode() == ISD::FMUL) {
7926 SDValue N1200 = N120.getOperand(0);
7927 SDValue N1201 = N120.getOperand(1);
7928 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7929 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7931 DAG.getNode(PreferredFusedOpcode, SL, VT,
7932 DAG.getNode(ISD::FNEG, SL, VT,
7933 DAG.getNode(ISD::FP_EXTEND, SL,
7935 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7941 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7942 // -> (fma (fneg (fpext y)), (fpext z),
7943 // (fma (fneg (fpext u)), (fpext v), x))
7944 // FIXME: This turns two single-precision and one double-precision
7945 // operation into two double-precision operations, which might not be
7946 // interesting for all targets, especially GPUs.
7947 if (N1.getOpcode() == ISD::FP_EXTEND &&
7948 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7949 SDValue N100 = N1.getOperand(0).getOperand(0);
7950 SDValue N101 = N1.getOperand(0).getOperand(1);
7951 SDValue N102 = N1.getOperand(0).getOperand(2);
7952 if (N102.getOpcode() == ISD::FMUL) {
7953 SDValue N1020 = N102.getOperand(0);
7954 SDValue N1021 = N102.getOperand(1);
7955 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7956 DAG.getNode(ISD::FNEG, SL, VT,
7957 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7959 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7960 DAG.getNode(PreferredFusedOpcode, SL, VT,
7961 DAG.getNode(ISD::FNEG, SL, VT,
7962 DAG.getNode(ISD::FP_EXTEND, SL,
7964 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7975 /// Try to perform FMA combining on a given FMUL node.
7976 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7977 SDValue N0 = N->getOperand(0);
7978 SDValue N1 = N->getOperand(1);
7979 EVT VT = N->getValueType(0);
7982 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7984 const TargetOptions &Options = DAG.getTarget().Options;
7986 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7988 // Floating-point multiply-add with intermediate rounding.
7989 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7991 // Floating-point multiply-add without intermediate rounding.
7993 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7994 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7996 // No valid opcode, do not combine.
7997 if (!HasFMAD && !HasFMA)
8000 // Always prefer FMAD to FMA for precision.
8001 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8002 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8004 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8005 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8006 auto FuseFADD = [&](SDValue X, SDValue Y) {
8007 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8008 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8009 if (XC1 && XC1->isExactlyValue(+1.0))
8010 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8011 if (XC1 && XC1->isExactlyValue(-1.0))
8012 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8013 DAG.getNode(ISD::FNEG, SL, VT, Y));
8018 if (SDValue FMA = FuseFADD(N0, N1))
8020 if (SDValue FMA = FuseFADD(N1, N0))
8023 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8024 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8025 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8026 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8027 auto FuseFSUB = [&](SDValue X, SDValue Y) {
8028 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8029 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8030 if (XC0 && XC0->isExactlyValue(+1.0))
8031 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8032 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8034 if (XC0 && XC0->isExactlyValue(-1.0))
8035 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8036 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8037 DAG.getNode(ISD::FNEG, SL, VT, Y));
8039 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8040 if (XC1 && XC1->isExactlyValue(+1.0))
8041 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8042 DAG.getNode(ISD::FNEG, SL, VT, Y));
8043 if (XC1 && XC1->isExactlyValue(-1.0))
8044 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8049 if (SDValue FMA = FuseFSUB(N0, N1))
8051 if (SDValue FMA = FuseFSUB(N1, N0))
8057 SDValue DAGCombiner::visitFADD(SDNode *N) {
8058 SDValue N0 = N->getOperand(0);
8059 SDValue N1 = N->getOperand(1);
8060 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8061 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8062 EVT VT = N->getValueType(0);
8064 const TargetOptions &Options = DAG.getTarget().Options;
8065 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8069 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8072 // fold (fadd c1, c2) -> c1 + c2
8074 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8076 // canonicalize constant to RHS
8077 if (N0CFP && !N1CFP)
8078 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8080 // fold (fadd A, (fneg B)) -> (fsub A, B)
8081 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8082 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8083 return DAG.getNode(ISD::FSUB, DL, VT, N0,
8084 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8086 // fold (fadd (fneg A), B) -> (fsub B, A)
8087 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8088 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8089 return DAG.getNode(ISD::FSUB, DL, VT, N1,
8090 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8092 // If 'unsafe math' is enabled, fold lots of things.
8093 if (Options.UnsafeFPMath) {
8094 // No FP constant should be created after legalization as Instruction
8095 // Selection pass has a hard time dealing with FP constants.
8096 bool AllowNewConst = (Level < AfterLegalizeDAG);
8098 // fold (fadd A, 0) -> A
8099 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8103 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8104 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8105 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8106 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8107 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8111 // If allowed, fold (fadd (fneg x), x) -> 0.0
8112 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8113 return DAG.getConstantFP(0.0, DL, VT);
8115 // If allowed, fold (fadd x, (fneg x)) -> 0.0
8116 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8117 return DAG.getConstantFP(0.0, DL, VT);
8119 // We can fold chains of FADD's of the same value into multiplications.
8120 // This transform is not safe in general because we are reducing the number
8121 // of rounding steps.
8122 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8123 if (N0.getOpcode() == ISD::FMUL) {
8124 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8125 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8127 // (fadd (fmul x, c), x) -> (fmul x, c+1)
8128 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8129 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8130 DAG.getConstantFP(1.0, DL, VT), Flags);
8131 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8134 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8135 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8136 N1.getOperand(0) == N1.getOperand(1) &&
8137 N0.getOperand(0) == N1.getOperand(0)) {
8138 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8139 DAG.getConstantFP(2.0, DL, VT), Flags);
8140 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8144 if (N1.getOpcode() == ISD::FMUL) {
8145 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8146 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8148 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8149 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8150 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8151 DAG.getConstantFP(1.0, DL, VT), Flags);
8152 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8155 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8156 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8157 N0.getOperand(0) == N0.getOperand(1) &&
8158 N1.getOperand(0) == N0.getOperand(0)) {
8159 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8160 DAG.getConstantFP(2.0, DL, VT), Flags);
8161 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8165 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8166 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8167 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8168 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8169 (N0.getOperand(0) == N1)) {
8170 return DAG.getNode(ISD::FMUL, DL, VT,
8171 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8175 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8176 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8177 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8178 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8179 N1.getOperand(0) == N0) {
8180 return DAG.getNode(ISD::FMUL, DL, VT,
8181 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8185 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8186 if (AllowNewConst &&
8187 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8188 N0.getOperand(0) == N0.getOperand(1) &&
8189 N1.getOperand(0) == N1.getOperand(1) &&
8190 N0.getOperand(0) == N1.getOperand(0)) {
8191 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8192 DAG.getConstantFP(4.0, DL, VT), Flags);
8195 } // enable-unsafe-fp-math
8197 // FADD -> FMA combines:
8198 if (SDValue Fused = visitFADDForFMACombine(N)) {
8199 AddToWorklist(Fused.getNode());
8206 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8207 SDValue N0 = N->getOperand(0);
8208 SDValue N1 = N->getOperand(1);
8209 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8210 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8211 EVT VT = N->getValueType(0);
8213 const TargetOptions &Options = DAG.getTarget().Options;
8214 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8218 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8221 // fold (fsub c1, c2) -> c1-c2
8223 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8225 // fold (fsub A, (fneg B)) -> (fadd A, B)
8226 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8227 return DAG.getNode(ISD::FADD, dl, VT, N0,
8228 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8230 // If 'unsafe math' is enabled, fold lots of things.
8231 if (Options.UnsafeFPMath) {
8233 if (N1CFP && N1CFP->isZero())
8236 // (fsub 0, B) -> -B
8237 if (N0CFP && N0CFP->isZero()) {
8238 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8239 return GetNegatedExpression(N1, DAG, LegalOperations);
8240 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8241 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8244 // (fsub x, x) -> 0.0
8246 return DAG.getConstantFP(0.0f, dl, VT);
8248 // (fsub x, (fadd x, y)) -> (fneg y)
8249 // (fsub x, (fadd y, x)) -> (fneg y)
8250 if (N1.getOpcode() == ISD::FADD) {
8251 SDValue N10 = N1->getOperand(0);
8252 SDValue N11 = N1->getOperand(1);
8254 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8255 return GetNegatedExpression(N11, DAG, LegalOperations);
8257 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8258 return GetNegatedExpression(N10, DAG, LegalOperations);
8262 // FSUB -> FMA combines:
8263 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8264 AddToWorklist(Fused.getNode());
8271 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8272 SDValue N0 = N->getOperand(0);
8273 SDValue N1 = N->getOperand(1);
8274 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8275 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8276 EVT VT = N->getValueType(0);
8278 const TargetOptions &Options = DAG.getTarget().Options;
8279 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8282 if (VT.isVector()) {
8283 // This just handles C1 * C2 for vectors. Other vector folds are below.
8284 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8288 // fold (fmul c1, c2) -> c1*c2
8290 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8292 // canonicalize constant to RHS
8293 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8294 !isConstantFPBuildVectorOrConstantFP(N1))
8295 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8297 // fold (fmul A, 1.0) -> A
8298 if (N1CFP && N1CFP->isExactlyValue(1.0))
8301 if (Options.UnsafeFPMath) {
8302 // fold (fmul A, 0) -> 0
8303 if (N1CFP && N1CFP->isZero())
8306 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8307 if (N0.getOpcode() == ISD::FMUL) {
8308 // Fold scalars or any vector constants (not just splats).
8309 // This fold is done in general by InstCombine, but extra fmul insts
8310 // may have been generated during lowering.
8311 SDValue N00 = N0.getOperand(0);
8312 SDValue N01 = N0.getOperand(1);
8313 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8314 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8315 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8317 // Check 1: Make sure that the first operand of the inner multiply is NOT
8318 // a constant. Otherwise, we may induce infinite looping.
8319 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8320 // Check 2: Make sure that the second operand of the inner multiply and
8321 // the second operand of the outer multiply are constants.
8322 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8323 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8324 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8325 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8330 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8331 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8332 // during an early run of DAGCombiner can prevent folding with fmuls
8333 // inserted during lowering.
8334 if (N0.getOpcode() == ISD::FADD &&
8335 (N0.getOperand(0) == N0.getOperand(1)) &&
8337 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8338 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8339 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8343 // fold (fmul X, 2.0) -> (fadd X, X)
8344 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8345 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8347 // fold (fmul X, -1.0) -> (fneg X)
8348 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8349 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8350 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8352 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8353 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8354 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8355 // Both can be negated for free, check to see if at least one is cheaper
8357 if (LHSNeg == 2 || RHSNeg == 2)
8358 return DAG.getNode(ISD::FMUL, DL, VT,
8359 GetNegatedExpression(N0, DAG, LegalOperations),
8360 GetNegatedExpression(N1, DAG, LegalOperations),
8365 // FMUL -> FMA combines:
8366 if (SDValue Fused = visitFMULForFMACombine(N)) {
8367 AddToWorklist(Fused.getNode());
8374 SDValue DAGCombiner::visitFMA(SDNode *N) {
8375 SDValue N0 = N->getOperand(0);
8376 SDValue N1 = N->getOperand(1);
8377 SDValue N2 = N->getOperand(2);
8378 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8379 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8380 EVT VT = N->getValueType(0);
8382 const TargetOptions &Options = DAG.getTarget().Options;
8384 // Constant fold FMA.
8385 if (isa<ConstantFPSDNode>(N0) &&
8386 isa<ConstantFPSDNode>(N1) &&
8387 isa<ConstantFPSDNode>(N2)) {
8388 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8391 if (Options.UnsafeFPMath) {
8392 if (N0CFP && N0CFP->isZero())
8394 if (N1CFP && N1CFP->isZero())
8397 // TODO: The FMA node should have flags that propagate to these nodes.
8398 if (N0CFP && N0CFP->isExactlyValue(1.0))
8399 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8400 if (N1CFP && N1CFP->isExactlyValue(1.0))
8401 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8403 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8404 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8405 !isConstantFPBuildVectorOrConstantFP(N1))
8406 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8408 // TODO: FMA nodes should have flags that propagate to the created nodes.
8409 // For now, create a Flags object for use with all unsafe math transforms.
8411 Flags.setUnsafeAlgebra(true);
8413 if (Options.UnsafeFPMath) {
8414 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8415 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8416 isConstantFPBuildVectorOrConstantFP(N1) &&
8417 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8418 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8419 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8423 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8424 if (N0.getOpcode() == ISD::FMUL &&
8425 isConstantFPBuildVectorOrConstantFP(N1) &&
8426 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8427 return DAG.getNode(ISD::FMA, dl, VT,
8429 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8435 // (fma x, 1, y) -> (fadd x, y)
8436 // (fma x, -1, y) -> (fadd (fneg x), y)
8438 if (N1CFP->isExactlyValue(1.0))
8439 // TODO: The FMA node should have flags that propagate to this node.
8440 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8442 if (N1CFP->isExactlyValue(-1.0) &&
8443 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8444 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8445 AddToWorklist(RHSNeg.getNode());
8446 // TODO: The FMA node should have flags that propagate to this node.
8447 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8451 if (Options.UnsafeFPMath) {
8452 // (fma x, c, x) -> (fmul x, (c+1))
8453 if (N1CFP && N0 == N2) {
8454 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8455 DAG.getNode(ISD::FADD, dl, VT,
8456 N1, DAG.getConstantFP(1.0, dl, VT),
8460 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8461 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8462 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8463 DAG.getNode(ISD::FADD, dl, VT,
8464 N1, DAG.getConstantFP(-1.0, dl, VT),
8472 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8474 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8475 // Notice that this is not always beneficial. One reason is different target
8476 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8477 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8478 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8479 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8480 if (!DAG.getTarget().Options.UnsafeFPMath)
8483 // Skip if current node is a reciprocal.
8484 SDValue N0 = N->getOperand(0);
8485 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8486 if (N0CFP && N0CFP->isExactlyValue(1.0))
8489 // Exit early if the target does not want this transform or if there can't
8490 // possibly be enough uses of the divisor to make the transform worthwhile.
8491 SDValue N1 = N->getOperand(1);
8492 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8493 if (!MinUses || N1->use_size() < MinUses)
8496 // Find all FDIV users of the same divisor.
8497 // Use a set because duplicates may be present in the user list.
8498 SetVector<SDNode *> Users;
8499 for (auto *U : N1->uses())
8500 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8503 // Now that we have the actual number of divisor uses, make sure it meets
8504 // the minimum threshold specified by the target.
8505 if (Users.size() < MinUses)
8508 EVT VT = N->getValueType(0);
8510 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8511 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8512 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8514 // Dividend / Divisor -> Dividend * Reciprocal
8515 for (auto *U : Users) {
8516 SDValue Dividend = U->getOperand(0);
8517 if (Dividend != FPOne) {
8518 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8520 CombineTo(U, NewNode);
8521 } else if (U != Reciprocal.getNode()) {
8522 // In the absence of fast-math-flags, this user node is always the
8523 // same node as Reciprocal, but with FMF they may be different nodes.
8524 CombineTo(U, Reciprocal);
8527 return SDValue(N, 0); // N was replaced.
8530 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8531 SDValue N0 = N->getOperand(0);
8532 SDValue N1 = N->getOperand(1);
8533 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8534 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8535 EVT VT = N->getValueType(0);
8537 const TargetOptions &Options = DAG.getTarget().Options;
8538 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8542 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8545 // fold (fdiv c1, c2) -> c1/c2
8547 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8549 if (Options.UnsafeFPMath) {
8550 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8552 // Compute the reciprocal 1.0 / c2.
8553 APFloat N1APF = N1CFP->getValueAPF();
8554 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8555 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8556 // Only do the transform if the reciprocal is a legal fp immediate that
8557 // isn't too nasty (eg NaN, denormal, ...).
8558 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8559 (!LegalOperations ||
8560 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8561 // backend)... we should handle this gracefully after Legalize.
8562 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8563 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8564 TLI.isFPImmLegal(Recip, VT)))
8565 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8566 DAG.getConstantFP(Recip, DL, VT), Flags);
8569 // If this FDIV is part of a reciprocal square root, it may be folded
8570 // into a target-specific square root estimate instruction.
8571 if (N1.getOpcode() == ISD::FSQRT) {
8572 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8573 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8575 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8576 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8577 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8579 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8580 AddToWorklist(RV.getNode());
8581 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8583 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8584 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8585 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8587 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8588 AddToWorklist(RV.getNode());
8589 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8591 } else if (N1.getOpcode() == ISD::FMUL) {
8592 // Look through an FMUL. Even though this won't remove the FDIV directly,
8593 // it's still worthwhile to get rid of the FSQRT if possible.
8596 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8597 SqrtOp = N1.getOperand(0);
8598 OtherOp = N1.getOperand(1);
8599 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8600 SqrtOp = N1.getOperand(1);
8601 OtherOp = N1.getOperand(0);
8603 if (SqrtOp.getNode()) {
8604 // We found a FSQRT, so try to make this fold:
8605 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8606 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8607 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8608 AddToWorklist(RV.getNode());
8609 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8614 // Fold into a reciprocal estimate and multiply instead of a real divide.
8615 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8616 AddToWorklist(RV.getNode());
8617 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8621 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8622 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8623 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8624 // Both can be negated for free, check to see if at least one is cheaper
8626 if (LHSNeg == 2 || RHSNeg == 2)
8627 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8628 GetNegatedExpression(N0, DAG, LegalOperations),
8629 GetNegatedExpression(N1, DAG, LegalOperations),
8634 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8635 return CombineRepeatedDivisors;
8640 SDValue DAGCombiner::visitFREM(SDNode *N) {
8641 SDValue N0 = N->getOperand(0);
8642 SDValue N1 = N->getOperand(1);
8643 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8644 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8645 EVT VT = N->getValueType(0);
8647 // fold (frem c1, c2) -> fmod(c1,c2)
8649 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8650 &cast<BinaryWithFlagsSDNode>(N)->Flags);
8655 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8656 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8659 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8660 // For now, create a Flags object for use with all unsafe math transforms.
8662 Flags.setUnsafeAlgebra(true);
8664 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8665 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8669 EVT VT = RV.getValueType();
8671 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8672 AddToWorklist(RV.getNode());
8674 // Unfortunately, RV is now NaN if the input was exactly 0.
8675 // Select out this case and force the answer to 0.
8676 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8677 EVT CCVT = getSetCCResultType(VT);
8678 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8679 AddToWorklist(ZeroCmp.getNode());
8680 AddToWorklist(RV.getNode());
8682 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8686 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8687 SDValue N0 = N->getOperand(0);
8688 SDValue N1 = N->getOperand(1);
8689 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8690 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8691 EVT VT = N->getValueType(0);
8693 if (N0CFP && N1CFP) // Constant fold
8694 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8697 const APFloat& V = N1CFP->getValueAPF();
8698 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8699 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8700 if (!V.isNegative()) {
8701 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8702 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8704 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8705 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8706 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8710 // copysign(fabs(x), y) -> copysign(x, y)
8711 // copysign(fneg(x), y) -> copysign(x, y)
8712 // copysign(copysign(x,z), y) -> copysign(x, y)
8713 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8714 N0.getOpcode() == ISD::FCOPYSIGN)
8715 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8716 N0.getOperand(0), N1);
8718 // copysign(x, abs(y)) -> abs(x)
8719 if (N1.getOpcode() == ISD::FABS)
8720 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8722 // copysign(x, copysign(y,z)) -> copysign(x, z)
8723 if (N1.getOpcode() == ISD::FCOPYSIGN)
8724 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8725 N0, N1.getOperand(1));
8727 // copysign(x, fp_extend(y)) -> copysign(x, y)
8728 // copysign(x, fp_round(y)) -> copysign(x, y)
8729 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8730 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8731 N0, N1.getOperand(0));
8736 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8737 SDValue N0 = N->getOperand(0);
8738 EVT VT = N->getValueType(0);
8739 EVT OpVT = N0.getValueType();
8741 // fold (sint_to_fp c1) -> c1fp
8742 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8743 // ...but only if the target supports immediate floating-point values
8744 (!LegalOperations ||
8745 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8746 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8748 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8749 // but UINT_TO_FP is legal on this target, try to convert.
8750 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8751 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8752 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8753 if (DAG.SignBitIsZero(N0))
8754 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8757 // The next optimizations are desirable only if SELECT_CC can be lowered.
8758 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8759 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8760 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8762 (!LegalOperations ||
8763 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8766 { N0.getOperand(0), N0.getOperand(1),
8767 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8769 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8772 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8773 // (select_cc x, y, 1.0, 0.0,, cc)
8774 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8775 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8776 (!LegalOperations ||
8777 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8780 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8781 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8782 N0.getOperand(0).getOperand(2) };
8783 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8790 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8791 SDValue N0 = N->getOperand(0);
8792 EVT VT = N->getValueType(0);
8793 EVT OpVT = N0.getValueType();
8795 // fold (uint_to_fp c1) -> c1fp
8796 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8797 // ...but only if the target supports immediate floating-point values
8798 (!LegalOperations ||
8799 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8800 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8802 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8803 // but SINT_TO_FP is legal on this target, try to convert.
8804 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8805 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8806 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8807 if (DAG.SignBitIsZero(N0))
8808 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8811 // The next optimizations are desirable only if SELECT_CC can be lowered.
8812 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8813 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8815 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8816 (!LegalOperations ||
8817 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8820 { N0.getOperand(0), N0.getOperand(1),
8821 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8823 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8830 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8831 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8832 SDValue N0 = N->getOperand(0);
8833 EVT VT = N->getValueType(0);
8835 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8838 SDValue Src = N0.getOperand(0);
8839 EVT SrcVT = Src.getValueType();
8840 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8841 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8843 // We can safely assume the conversion won't overflow the output range,
8844 // because (for example) (uint8_t)18293.f is undefined behavior.
8846 // Since we can assume the conversion won't overflow, our decision as to
8847 // whether the input will fit in the float should depend on the minimum
8848 // of the input range and output range.
8850 // This means this is also safe for a signed input and unsigned output, since
8851 // a negative input would lead to undefined behavior.
8852 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8853 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8854 unsigned ActualSize = std::min(InputSize, OutputSize);
8855 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8857 // We can only fold away the float conversion if the input range can be
8858 // represented exactly in the float range.
8859 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8860 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8861 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8863 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8865 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8866 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8869 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8874 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8875 SDValue N0 = N->getOperand(0);
8876 EVT VT = N->getValueType(0);
8878 // fold (fp_to_sint c1fp) -> c1
8879 if (isConstantFPBuildVectorOrConstantFP(N0))
8880 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8882 return FoldIntToFPToInt(N, DAG);
8885 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8886 SDValue N0 = N->getOperand(0);
8887 EVT VT = N->getValueType(0);
8889 // fold (fp_to_uint c1fp) -> c1
8890 if (isConstantFPBuildVectorOrConstantFP(N0))
8891 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8893 return FoldIntToFPToInt(N, DAG);
8896 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8897 SDValue N0 = N->getOperand(0);
8898 SDValue N1 = N->getOperand(1);
8899 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8900 EVT VT = N->getValueType(0);
8902 // fold (fp_round c1fp) -> c1fp
8904 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8906 // fold (fp_round (fp_extend x)) -> x
8907 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8908 return N0.getOperand(0);
8910 // fold (fp_round (fp_round x)) -> (fp_round x)
8911 if (N0.getOpcode() == ISD::FP_ROUND) {
8912 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8913 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8914 // If the first fp_round isn't a value preserving truncation, it might
8915 // introduce a tie in the second fp_round, that wouldn't occur in the
8916 // single-step fp_round we want to fold to.
8917 // In other words, double rounding isn't the same as rounding.
8918 // Also, this is a value preserving truncation iff both fp_round's are.
8919 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8921 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8922 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8926 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8927 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8928 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8929 N0.getOperand(0), N1);
8930 AddToWorklist(Tmp.getNode());
8931 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8932 Tmp, N0.getOperand(1));
8938 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8939 SDValue N0 = N->getOperand(0);
8940 EVT VT = N->getValueType(0);
8941 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8942 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8944 // fold (fp_round_inreg c1fp) -> c1fp
8945 if (N0CFP && isTypeLegal(EVT)) {
8947 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8948 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8954 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8955 SDValue N0 = N->getOperand(0);
8956 EVT VT = N->getValueType(0);
8958 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8959 if (N->hasOneUse() &&
8960 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8963 // fold (fp_extend c1fp) -> c1fp
8964 if (isConstantFPBuildVectorOrConstantFP(N0))
8965 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8967 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8968 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8969 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8970 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8972 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8974 if (N0.getOpcode() == ISD::FP_ROUND
8975 && N0.getNode()->getConstantOperandVal(1) == 1) {
8976 SDValue In = N0.getOperand(0);
8977 if (In.getValueType() == VT) return In;
8978 if (VT.bitsLT(In.getValueType()))
8979 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8980 In, N0.getOperand(1));
8981 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8984 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8985 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8986 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8987 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8988 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8990 LN0->getBasePtr(), N0.getValueType(),
8991 LN0->getMemOperand());
8992 CombineTo(N, ExtLoad);
8993 CombineTo(N0.getNode(),
8994 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8995 N0.getValueType(), ExtLoad,
8996 DAG.getIntPtrConstant(1, SDLoc(N0))),
8997 ExtLoad.getValue(1));
8998 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9004 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9005 SDValue N0 = N->getOperand(0);
9006 EVT VT = N->getValueType(0);
9008 // fold (fceil c1) -> fceil(c1)
9009 if (isConstantFPBuildVectorOrConstantFP(N0))
9010 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9015 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9016 SDValue N0 = N->getOperand(0);
9017 EVT VT = N->getValueType(0);
9019 // fold (ftrunc c1) -> ftrunc(c1)
9020 if (isConstantFPBuildVectorOrConstantFP(N0))
9021 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9026 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9027 SDValue N0 = N->getOperand(0);
9028 EVT VT = N->getValueType(0);
9030 // fold (ffloor c1) -> ffloor(c1)
9031 if (isConstantFPBuildVectorOrConstantFP(N0))
9032 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9037 // FIXME: FNEG and FABS have a lot in common; refactor.
9038 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9039 SDValue N0 = N->getOperand(0);
9040 EVT VT = N->getValueType(0);
9042 // Constant fold FNEG.
9043 if (isConstantFPBuildVectorOrConstantFP(N0))
9044 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9046 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9047 &DAG.getTarget().Options))
9048 return GetNegatedExpression(N0, DAG, LegalOperations);
9050 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9051 // constant pool values.
9052 if (!TLI.isFNegFree(VT) &&
9053 N0.getOpcode() == ISD::BITCAST &&
9054 N0.getNode()->hasOneUse()) {
9055 SDValue Int = N0.getOperand(0);
9056 EVT IntVT = Int.getValueType();
9057 if (IntVT.isInteger() && !IntVT.isVector()) {
9059 if (N0.getValueType().isVector()) {
9060 // For a vector, get a mask such as 0x80... per scalar element
9062 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9063 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9065 // For a scalar, just generate 0x80...
9066 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9069 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9070 DAG.getConstant(SignMask, DL0, IntVT));
9071 AddToWorklist(Int.getNode());
9072 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9076 // (fneg (fmul c, x)) -> (fmul -c, x)
9077 if (N0.getOpcode() == ISD::FMUL &&
9078 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9079 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9081 APFloat CVal = CFP1->getValueAPF();
9083 if (Level >= AfterLegalizeDAG &&
9084 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9085 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9086 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9087 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9089 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9096 SDValue DAGCombiner::visitFMINNUM(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(minnum(C0, C1), SDLoc(N), VT);
9109 // Canonicalize to constant on RHS.
9110 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9111 !isConstantFPBuildVectorOrConstantFP(N1))
9112 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9117 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9118 SDValue N0 = N->getOperand(0);
9119 SDValue N1 = N->getOperand(1);
9120 EVT VT = N->getValueType(0);
9121 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9122 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9124 if (N0CFP && N1CFP) {
9125 const APFloat &C0 = N0CFP->getValueAPF();
9126 const APFloat &C1 = N1CFP->getValueAPF();
9127 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9130 // Canonicalize to constant on RHS.
9131 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9132 !isConstantFPBuildVectorOrConstantFP(N1))
9133 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9138 SDValue DAGCombiner::visitFABS(SDNode *N) {
9139 SDValue N0 = N->getOperand(0);
9140 EVT VT = N->getValueType(0);
9142 // fold (fabs c1) -> fabs(c1)
9143 if (isConstantFPBuildVectorOrConstantFP(N0))
9144 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9146 // fold (fabs (fabs x)) -> (fabs x)
9147 if (N0.getOpcode() == ISD::FABS)
9148 return N->getOperand(0);
9150 // fold (fabs (fneg x)) -> (fabs x)
9151 // fold (fabs (fcopysign x, y)) -> (fabs x)
9152 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9153 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9155 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9156 // constant pool values.
9157 if (!TLI.isFAbsFree(VT) &&
9158 N0.getOpcode() == ISD::BITCAST &&
9159 N0.getNode()->hasOneUse()) {
9160 SDValue Int = N0.getOperand(0);
9161 EVT IntVT = Int.getValueType();
9162 if (IntVT.isInteger() && !IntVT.isVector()) {
9164 if (N0.getValueType().isVector()) {
9165 // For a vector, get a mask such as 0x7f... per scalar element
9167 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9168 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9170 // For a scalar, just generate 0x7f...
9171 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9174 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9175 DAG.getConstant(SignMask, DL, IntVT));
9176 AddToWorklist(Int.getNode());
9177 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9184 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9185 SDValue Chain = N->getOperand(0);
9186 SDValue N1 = N->getOperand(1);
9187 SDValue N2 = N->getOperand(2);
9189 // If N is a constant we could fold this into a fallthrough or unconditional
9190 // branch. However that doesn't happen very often in normal code, because
9191 // Instcombine/SimplifyCFG should have handled the available opportunities.
9192 // If we did this folding here, it would be necessary to update the
9193 // MachineBasicBlock CFG, which is awkward.
9195 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9197 if (N1.getOpcode() == ISD::SETCC &&
9198 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9199 N1.getOperand(0).getValueType())) {
9200 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9201 Chain, N1.getOperand(2),
9202 N1.getOperand(0), N1.getOperand(1), N2);
9205 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9206 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9207 (N1.getOperand(0).hasOneUse() &&
9208 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9209 SDNode *Trunc = nullptr;
9210 if (N1.getOpcode() == ISD::TRUNCATE) {
9211 // Look pass the truncate.
9212 Trunc = N1.getNode();
9213 N1 = N1.getOperand(0);
9216 // Match this pattern so that we can generate simpler code:
9219 // %b = and i32 %a, 2
9220 // %c = srl i32 %b, 1
9221 // brcond i32 %c ...
9226 // %b = and i32 %a, 2
9227 // %c = setcc eq %b, 0
9230 // This applies only when the AND constant value has one bit set and the
9231 // SRL constant is equal to the log2 of the AND constant. The back-end is
9232 // smart enough to convert the result into a TEST/JMP sequence.
9233 SDValue Op0 = N1.getOperand(0);
9234 SDValue Op1 = N1.getOperand(1);
9236 if (Op0.getOpcode() == ISD::AND &&
9237 Op1.getOpcode() == ISD::Constant) {
9238 SDValue AndOp1 = Op0.getOperand(1);
9240 if (AndOp1.getOpcode() == ISD::Constant) {
9241 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9243 if (AndConst.isPowerOf2() &&
9244 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9248 getSetCCResultType(Op0.getValueType()),
9249 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9252 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9253 MVT::Other, Chain, SetCC, N2);
9254 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9255 // will convert it back to (X & C1) >> C2.
9256 CombineTo(N, NewBRCond, false);
9257 // Truncate is dead.
9259 deleteAndRecombine(Trunc);
9260 // Replace the uses of SRL with SETCC
9261 WorklistRemover DeadNodes(*this);
9262 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9263 deleteAndRecombine(N1.getNode());
9264 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9270 // Restore N1 if the above transformation doesn't match.
9271 N1 = N->getOperand(1);
9274 // Transform br(xor(x, y)) -> br(x != y)
9275 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9276 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9277 SDNode *TheXor = N1.getNode();
9278 SDValue Op0 = TheXor->getOperand(0);
9279 SDValue Op1 = TheXor->getOperand(1);
9280 if (Op0.getOpcode() == Op1.getOpcode()) {
9281 // Avoid missing important xor optimizations.
9282 if (SDValue Tmp = visitXOR(TheXor)) {
9283 if (Tmp.getNode() != TheXor) {
9284 DEBUG(dbgs() << "\nReplacing.8 ";
9286 dbgs() << "\nWith: ";
9287 Tmp.getNode()->dump(&DAG);
9289 WorklistRemover DeadNodes(*this);
9290 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9291 deleteAndRecombine(TheXor);
9292 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9293 MVT::Other, Chain, Tmp, N2);
9296 // visitXOR has changed XOR's operands or replaced the XOR completely,
9298 return SDValue(N, 0);
9302 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9304 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9305 Op0.getOpcode() == ISD::XOR) {
9306 TheXor = Op0.getNode();
9310 EVT SetCCVT = N1.getValueType();
9312 SetCCVT = getSetCCResultType(SetCCVT);
9313 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9316 Equal ? ISD::SETEQ : ISD::SETNE);
9317 // Replace the uses of XOR with SETCC
9318 WorklistRemover DeadNodes(*this);
9319 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9320 deleteAndRecombine(N1.getNode());
9321 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9322 MVT::Other, Chain, SetCC, N2);
9329 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9331 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9332 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9333 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9335 // If N is a constant we could fold this into a fallthrough or unconditional
9336 // branch. However that doesn't happen very often in normal code, because
9337 // Instcombine/SimplifyCFG should have handled the available opportunities.
9338 // If we did this folding here, it would be necessary to update the
9339 // MachineBasicBlock CFG, which is awkward.
9341 // Use SimplifySetCC to simplify SETCC's.
9342 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9343 CondLHS, CondRHS, CC->get(), SDLoc(N),
9345 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9347 // fold to a simpler setcc
9348 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9349 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9350 N->getOperand(0), Simp.getOperand(2),
9351 Simp.getOperand(0), Simp.getOperand(1),
9357 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9358 /// and that N may be folded in the load / store addressing mode.
9359 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9361 const TargetLowering &TLI) {
9365 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9366 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9368 VT = LD->getMemoryVT();
9369 AS = LD->getAddressSpace();
9370 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9371 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9373 VT = ST->getMemoryVT();
9374 AS = ST->getAddressSpace();
9378 TargetLowering::AddrMode AM;
9379 if (N->getOpcode() == ISD::ADD) {
9380 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9383 AM.BaseOffs = Offset->getSExtValue();
9387 } else if (N->getOpcode() == ISD::SUB) {
9388 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9391 AM.BaseOffs = -Offset->getSExtValue();
9398 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9399 VT.getTypeForEVT(*DAG.getContext()), AS);
9402 /// Try turning a load/store into a pre-indexed load/store when the base
9403 /// pointer is an add or subtract and it has other uses besides the load/store.
9404 /// After the transformation, the new indexed load/store has effectively folded
9405 /// the add/subtract in and all of its other uses are redirected to the
9407 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9408 if (Level < AfterLegalizeDAG)
9414 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9415 if (LD->isIndexed())
9417 VT = LD->getMemoryVT();
9418 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9419 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9421 Ptr = LD->getBasePtr();
9422 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9423 if (ST->isIndexed())
9425 VT = ST->getMemoryVT();
9426 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9427 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9429 Ptr = ST->getBasePtr();
9435 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9436 // out. There is no reason to make this a preinc/predec.
9437 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9438 Ptr.getNode()->hasOneUse())
9441 // Ask the target to do addressing mode selection.
9444 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9445 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9448 // Backends without true r+i pre-indexed forms may need to pass a
9449 // constant base with a variable offset so that constant coercion
9450 // will work with the patterns in canonical form.
9451 bool Swapped = false;
9452 if (isa<ConstantSDNode>(BasePtr)) {
9453 std::swap(BasePtr, Offset);
9457 // Don't create a indexed load / store with zero offset.
9458 if (isNullConstant(Offset))
9461 // Try turning it into a pre-indexed load / store except when:
9462 // 1) The new base ptr is a frame index.
9463 // 2) If N is a store and the new base ptr is either the same as or is a
9464 // predecessor of the value being stored.
9465 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9466 // that would create a cycle.
9467 // 4) All uses are load / store ops that use it as old base ptr.
9469 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9470 // (plus the implicit offset) to a register to preinc anyway.
9471 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9476 SDValue Val = cast<StoreSDNode>(N)->getValue();
9477 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9481 // If the offset is a constant, there may be other adds of constants that
9482 // can be folded with this one. We should do this to avoid having to keep
9483 // a copy of the original base pointer.
9484 SmallVector<SDNode *, 16> OtherUses;
9485 if (isa<ConstantSDNode>(Offset))
9486 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9487 UE = BasePtr.getNode()->use_end();
9489 SDUse &Use = UI.getUse();
9490 // Skip the use that is Ptr and uses of other results from BasePtr's
9491 // node (important for nodes that return multiple results).
9492 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9495 if (Use.getUser()->isPredecessorOf(N))
9498 if (Use.getUser()->getOpcode() != ISD::ADD &&
9499 Use.getUser()->getOpcode() != ISD::SUB) {
9504 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9505 if (!isa<ConstantSDNode>(Op1)) {
9510 // FIXME: In some cases, we can be smarter about this.
9511 if (Op1.getValueType() != Offset.getValueType()) {
9516 OtherUses.push_back(Use.getUser());
9520 std::swap(BasePtr, Offset);
9522 // Now check for #3 and #4.
9523 bool RealUse = false;
9525 // Caches for hasPredecessorHelper
9526 SmallPtrSet<const SDNode *, 32> Visited;
9527 SmallVector<const SDNode *, 16> Worklist;
9529 for (SDNode *Use : Ptr.getNode()->uses()) {
9532 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9535 // If Ptr may be folded in addressing mode of other use, then it's
9536 // not profitable to do this transformation.
9537 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9546 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9547 BasePtr, Offset, AM);
9549 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9550 BasePtr, Offset, AM);
9553 DEBUG(dbgs() << "\nReplacing.4 ";
9555 dbgs() << "\nWith: ";
9556 Result.getNode()->dump(&DAG);
9558 WorklistRemover DeadNodes(*this);
9560 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9561 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9563 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9566 // Finally, since the node is now dead, remove it from the graph.
9567 deleteAndRecombine(N);
9570 std::swap(BasePtr, Offset);
9572 // Replace other uses of BasePtr that can be updated to use Ptr
9573 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9574 unsigned OffsetIdx = 1;
9575 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9577 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9578 BasePtr.getNode() && "Expected BasePtr operand");
9580 // We need to replace ptr0 in the following expression:
9581 // x0 * offset0 + y0 * ptr0 = t0
9583 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9585 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9586 // indexed load/store and the expresion that needs to be re-written.
9588 // Therefore, we have:
9589 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9591 ConstantSDNode *CN =
9592 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9594 APInt Offset0 = CN->getAPIntValue();
9595 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9597 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9598 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9599 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9600 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9602 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9604 APInt CNV = Offset0;
9605 if (X0 < 0) CNV = -CNV;
9606 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9607 else CNV = CNV - Offset1;
9609 SDLoc DL(OtherUses[i]);
9611 // We can now generate the new expression.
9612 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9613 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9615 SDValue NewUse = DAG.getNode(Opcode,
9617 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9618 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9619 deleteAndRecombine(OtherUses[i]);
9622 // Replace the uses of Ptr with uses of the updated base value.
9623 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9624 deleteAndRecombine(Ptr.getNode());
9629 /// Try to combine a load/store with a add/sub of the base pointer node into a
9630 /// post-indexed load/store. The transformation folded the add/subtract into the
9631 /// new indexed load/store effectively and all of its uses are redirected to the
9633 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9634 if (Level < AfterLegalizeDAG)
9640 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9641 if (LD->isIndexed())
9643 VT = LD->getMemoryVT();
9644 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9645 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9647 Ptr = LD->getBasePtr();
9648 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9649 if (ST->isIndexed())
9651 VT = ST->getMemoryVT();
9652 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9653 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9655 Ptr = ST->getBasePtr();
9661 if (Ptr.getNode()->hasOneUse())
9664 for (SDNode *Op : Ptr.getNode()->uses()) {
9666 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9671 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9672 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9673 // Don't create a indexed load / store with zero offset.
9674 if (isNullConstant(Offset))
9677 // Try turning it into a post-indexed load / store except when
9678 // 1) All uses are load / store ops that use it as base ptr (and
9679 // it may be folded as addressing mmode).
9680 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9681 // nor a successor of N. Otherwise, if Op is folded that would
9684 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9688 bool TryNext = false;
9689 for (SDNode *Use : BasePtr.getNode()->uses()) {
9690 if (Use == Ptr.getNode())
9693 // If all the uses are load / store addresses, then don't do the
9695 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9696 bool RealUse = false;
9697 for (SDNode *UseUse : Use->uses()) {
9698 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9713 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9714 SDValue Result = isLoad
9715 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9716 BasePtr, Offset, AM)
9717 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9718 BasePtr, Offset, AM);
9721 DEBUG(dbgs() << "\nReplacing.5 ";
9723 dbgs() << "\nWith: ";
9724 Result.getNode()->dump(&DAG);
9726 WorklistRemover DeadNodes(*this);
9728 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9729 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9731 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9734 // Finally, since the node is now dead, remove it from the graph.
9735 deleteAndRecombine(N);
9737 // Replace the uses of Use with uses of the updated base value.
9738 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9739 Result.getValue(isLoad ? 1 : 0));
9740 deleteAndRecombine(Op);
9749 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9750 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9751 ISD::MemIndexedMode AM = LD->getAddressingMode();
9752 assert(AM != ISD::UNINDEXED);
9753 SDValue BP = LD->getOperand(1);
9754 SDValue Inc = LD->getOperand(2);
9756 // Some backends use TargetConstants for load offsets, but don't expect
9757 // TargetConstants in general ADD nodes. We can convert these constants into
9758 // regular Constants (if the constant is not opaque).
9759 assert((Inc.getOpcode() != ISD::TargetConstant ||
9760 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9761 "Cannot split out indexing using opaque target constants");
9762 if (Inc.getOpcode() == ISD::TargetConstant) {
9763 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9764 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9765 ConstInc->getValueType(0));
9769 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9770 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9773 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9774 LoadSDNode *LD = cast<LoadSDNode>(N);
9775 SDValue Chain = LD->getChain();
9776 SDValue Ptr = LD->getBasePtr();
9778 // If load is not volatile and there are no uses of the loaded value (and
9779 // the updated indexed value in case of indexed loads), change uses of the
9780 // chain value into uses of the chain input (i.e. delete the dead load).
9781 if (!LD->isVolatile()) {
9782 if (N->getValueType(1) == MVT::Other) {
9784 if (!N->hasAnyUseOfValue(0)) {
9785 // It's not safe to use the two value CombineTo variant here. e.g.
9786 // v1, chain2 = load chain1, loc
9787 // v2, chain3 = load chain2, loc
9789 // Now we replace use of chain2 with chain1. This makes the second load
9790 // isomorphic to the one we are deleting, and thus makes this load live.
9791 DEBUG(dbgs() << "\nReplacing.6 ";
9793 dbgs() << "\nWith chain: ";
9794 Chain.getNode()->dump(&DAG);
9796 WorklistRemover DeadNodes(*this);
9797 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9800 deleteAndRecombine(N);
9802 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9806 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9808 // If this load has an opaque TargetConstant offset, then we cannot split
9809 // the indexing into an add/sub directly (that TargetConstant may not be
9810 // valid for a different type of node, and we cannot convert an opaque
9811 // target constant into a regular constant).
9812 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9813 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9815 if (!N->hasAnyUseOfValue(0) &&
9816 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9817 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9819 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9820 Index = SplitIndexingFromLoad(LD);
9821 // Try to fold the base pointer arithmetic into subsequent loads and
9823 AddUsersToWorklist(N);
9825 Index = DAG.getUNDEF(N->getValueType(1));
9826 DEBUG(dbgs() << "\nReplacing.7 ";
9828 dbgs() << "\nWith: ";
9829 Undef.getNode()->dump(&DAG);
9830 dbgs() << " and 2 other values\n");
9831 WorklistRemover DeadNodes(*this);
9832 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9833 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9834 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9835 deleteAndRecombine(N);
9836 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9841 // If this load is directly stored, replace the load value with the stored
9843 // TODO: Handle store large -> read small portion.
9844 // TODO: Handle TRUNCSTORE/LOADEXT
9845 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9846 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9847 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9848 if (PrevST->getBasePtr() == Ptr &&
9849 PrevST->getValue().getValueType() == N->getValueType(0))
9850 return CombineTo(N, Chain.getOperand(1), Chain);
9854 // Try to infer better alignment information than the load already has.
9855 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9856 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9857 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9859 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9860 LD->getValueType(0),
9861 Chain, Ptr, LD->getPointerInfo(),
9863 LD->isVolatile(), LD->isNonTemporal(),
9864 LD->isInvariant(), Align, LD->getAAInfo());
9865 if (NewLoad.getNode() != N)
9866 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9871 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9872 : DAG.getSubtarget().useAA();
9874 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9875 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9878 if (UseAA && LD->isUnindexed()) {
9879 // Walk up chain skipping non-aliasing memory nodes.
9880 SDValue BetterChain = FindBetterChain(N, Chain);
9882 // If there is a better chain.
9883 if (Chain != BetterChain) {
9886 // Replace the chain to void dependency.
9887 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9888 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9889 BetterChain, Ptr, LD->getMemOperand());
9891 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9892 LD->getValueType(0),
9893 BetterChain, Ptr, LD->getMemoryVT(),
9894 LD->getMemOperand());
9897 // Create token factor to keep old chain connected.
9898 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9899 MVT::Other, Chain, ReplLoad.getValue(1));
9901 // Make sure the new and old chains are cleaned up.
9902 AddToWorklist(Token.getNode());
9904 // Replace uses with load result and token factor. Don't add users
9906 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9910 // Try transforming N to an indexed load.
9911 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9912 return SDValue(N, 0);
9914 // Try to slice up N to more direct loads if the slices are mapped to
9915 // different register banks or pairing can take place.
9917 return SDValue(N, 0);
9923 /// \brief Helper structure used to slice a load in smaller loads.
9924 /// Basically a slice is obtained from the following sequence:
9925 /// Origin = load Ty1, Base
9926 /// Shift = srl Ty1 Origin, CstTy Amount
9927 /// Inst = trunc Shift to Ty2
9929 /// Then, it will be rewriten into:
9930 /// Slice = load SliceTy, Base + SliceOffset
9931 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9933 /// SliceTy is deduced from the number of bits that are actually used to
9935 struct LoadedSlice {
9936 /// \brief Helper structure used to compute the cost of a slice.
9938 /// Are we optimizing for code size.
9943 unsigned CrossRegisterBanksCopies;
9947 Cost(bool ForCodeSize = false)
9948 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9949 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9951 /// \brief Get the cost of one isolated slice.
9952 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9953 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9954 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9955 EVT TruncType = LS.Inst->getValueType(0);
9956 EVT LoadedType = LS.getLoadedType();
9957 if (TruncType != LoadedType &&
9958 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9962 /// \brief Account for slicing gain in the current cost.
9963 /// Slicing provide a few gains like removing a shift or a
9964 /// truncate. This method allows to grow the cost of the original
9965 /// load with the gain from this slice.
9966 void addSliceGain(const LoadedSlice &LS) {
9967 // Each slice saves a truncate.
9968 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9969 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9970 LS.Inst->getValueType(0)))
9972 // If there is a shift amount, this slice gets rid of it.
9975 // If this slice can merge a cross register bank copy, account for it.
9976 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9977 ++CrossRegisterBanksCopies;
9980 Cost &operator+=(const Cost &RHS) {
9982 Truncates += RHS.Truncates;
9983 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9989 bool operator==(const Cost &RHS) const {
9990 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9991 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9992 ZExts == RHS.ZExts && Shift == RHS.Shift;
9995 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9997 bool operator<(const Cost &RHS) const {
9998 // Assume cross register banks copies are as expensive as loads.
9999 // FIXME: Do we want some more target hooks?
10000 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10001 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10002 // Unless we are optimizing for code size, consider the
10003 // expensive operation first.
10004 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10005 return ExpensiveOpsLHS < ExpensiveOpsRHS;
10006 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10007 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10010 bool operator>(const Cost &RHS) const { return RHS < *this; }
10012 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10014 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10016 // The last instruction that represent the slice. This should be a
10017 // truncate instruction.
10019 // The original load instruction.
10020 LoadSDNode *Origin;
10021 // The right shift amount in bits from the original load.
10023 // The DAG from which Origin came from.
10024 // This is used to get some contextual information about legal types, etc.
10027 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10028 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10029 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10031 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10032 /// \return Result is \p BitWidth and has used bits set to 1 and
10033 /// not used bits set to 0.
10034 APInt getUsedBits() const {
10035 // Reproduce the trunc(lshr) sequence:
10036 // - Start from the truncated value.
10037 // - Zero extend to the desired bit width.
10039 assert(Origin && "No original load to compare against.");
10040 unsigned BitWidth = Origin->getValueSizeInBits(0);
10041 assert(Inst && "This slice is not bound to an instruction");
10042 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10043 "Extracted slice is bigger than the whole type!");
10044 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10045 UsedBits.setAllBits();
10046 UsedBits = UsedBits.zext(BitWidth);
10047 UsedBits <<= Shift;
10051 /// \brief Get the size of the slice to be loaded in bytes.
10052 unsigned getLoadedSize() const {
10053 unsigned SliceSize = getUsedBits().countPopulation();
10054 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10055 return SliceSize / 8;
10058 /// \brief Get the type that will be loaded for this slice.
10059 /// Note: This may not be the final type for the slice.
10060 EVT getLoadedType() const {
10061 assert(DAG && "Missing context");
10062 LLVMContext &Ctxt = *DAG->getContext();
10063 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10066 /// \brief Get the alignment of the load used for this slice.
10067 unsigned getAlignment() const {
10068 unsigned Alignment = Origin->getAlignment();
10069 unsigned Offset = getOffsetFromBase();
10071 Alignment = MinAlign(Alignment, Alignment + Offset);
10075 /// \brief Check if this slice can be rewritten with legal operations.
10076 bool isLegal() const {
10077 // An invalid slice is not legal.
10078 if (!Origin || !Inst || !DAG)
10081 // Offsets are for indexed load only, we do not handle that.
10082 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10085 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10087 // Check that the type is legal.
10088 EVT SliceType = getLoadedType();
10089 if (!TLI.isTypeLegal(SliceType))
10092 // Check that the load is legal for this type.
10093 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10096 // Check that the offset can be computed.
10097 // 1. Check its type.
10098 EVT PtrType = Origin->getBasePtr().getValueType();
10099 if (PtrType == MVT::Untyped || PtrType.isExtended())
10102 // 2. Check that it fits in the immediate.
10103 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10106 // 3. Check that the computation is legal.
10107 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10110 // Check that the zext is legal if it needs one.
10111 EVT TruncateType = Inst->getValueType(0);
10112 if (TruncateType != SliceType &&
10113 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10119 /// \brief Get the offset in bytes of this slice in the original chunk of
10121 /// \pre DAG != nullptr.
10122 uint64_t getOffsetFromBase() const {
10123 assert(DAG && "Missing context.");
10124 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10125 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10126 uint64_t Offset = Shift / 8;
10127 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10128 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10129 "The size of the original loaded type is not a multiple of a"
10131 // If Offset is bigger than TySizeInBytes, it means we are loading all
10132 // zeros. This should have been optimized before in the process.
10133 assert(TySizeInBytes > Offset &&
10134 "Invalid shift amount for given loaded size");
10136 Offset = TySizeInBytes - Offset - getLoadedSize();
10140 /// \brief Generate the sequence of instructions to load the slice
10141 /// represented by this object and redirect the uses of this slice to
10142 /// this new sequence of instructions.
10143 /// \pre this->Inst && this->Origin are valid Instructions and this
10144 /// object passed the legal check: LoadedSlice::isLegal returned true.
10145 /// \return The last instruction of the sequence used to load the slice.
10146 SDValue loadSlice() const {
10147 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10148 const SDValue &OldBaseAddr = Origin->getBasePtr();
10149 SDValue BaseAddr = OldBaseAddr;
10150 // Get the offset in that chunk of bytes w.r.t. the endianess.
10151 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10152 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10154 // BaseAddr = BaseAddr + Offset.
10155 EVT ArithType = BaseAddr.getValueType();
10157 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10158 DAG->getConstant(Offset, DL, ArithType));
10161 // Create the type of the loaded slice according to its size.
10162 EVT SliceType = getLoadedType();
10164 // Create the load for the slice.
10165 SDValue LastInst = DAG->getLoad(
10166 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10167 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10168 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10169 // If the final type is not the same as the loaded type, this means that
10170 // we have to pad with zero. Create a zero extend for that.
10171 EVT FinalType = Inst->getValueType(0);
10172 if (SliceType != FinalType)
10174 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10178 /// \brief Check if this slice can be merged with an expensive cross register
10179 /// bank copy. E.g.,
10181 /// f = bitcast i32 i to float
10182 bool canMergeExpensiveCrossRegisterBankCopy() const {
10183 if (!Inst || !Inst->hasOneUse())
10185 SDNode *Use = *Inst->use_begin();
10186 if (Use->getOpcode() != ISD::BITCAST)
10188 assert(DAG && "Missing context");
10189 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10190 EVT ResVT = Use->getValueType(0);
10191 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10192 const TargetRegisterClass *ArgRC =
10193 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10194 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10197 // At this point, we know that we perform a cross-register-bank copy.
10198 // Check if it is expensive.
10199 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10200 // Assume bitcasts are cheap, unless both register classes do not
10201 // explicitly share a common sub class.
10202 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10205 // Check if it will be merged with the load.
10206 // 1. Check the alignment constraint.
10207 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10208 ResVT.getTypeForEVT(*DAG->getContext()));
10210 if (RequiredAlignment > getAlignment())
10213 // 2. Check that the load is a legal operation for that type.
10214 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10217 // 3. Check that we do not have a zext in the way.
10218 if (Inst->getValueType(0) != getLoadedType())
10226 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10227 /// \p UsedBits looks like 0..0 1..1 0..0.
10228 static bool areUsedBitsDense(const APInt &UsedBits) {
10229 // If all the bits are one, this is dense!
10230 if (UsedBits.isAllOnesValue())
10233 // Get rid of the unused bits on the right.
10234 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10235 // Get rid of the unused bits on the left.
10236 if (NarrowedUsedBits.countLeadingZeros())
10237 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10238 // Check that the chunk of bits is completely used.
10239 return NarrowedUsedBits.isAllOnesValue();
10242 /// \brief Check whether or not \p First and \p Second are next to each other
10243 /// in memory. This means that there is no hole between the bits loaded
10244 /// by \p First and the bits loaded by \p Second.
10245 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10246 const LoadedSlice &Second) {
10247 assert(First.Origin == Second.Origin && First.Origin &&
10248 "Unable to match different memory origins.");
10249 APInt UsedBits = First.getUsedBits();
10250 assert((UsedBits & Second.getUsedBits()) == 0 &&
10251 "Slices are not supposed to overlap.");
10252 UsedBits |= Second.getUsedBits();
10253 return areUsedBitsDense(UsedBits);
10256 /// \brief Adjust the \p GlobalLSCost according to the target
10257 /// paring capabilities and the layout of the slices.
10258 /// \pre \p GlobalLSCost should account for at least as many loads as
10259 /// there is in the slices in \p LoadedSlices.
10260 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10261 LoadedSlice::Cost &GlobalLSCost) {
10262 unsigned NumberOfSlices = LoadedSlices.size();
10263 // If there is less than 2 elements, no pairing is possible.
10264 if (NumberOfSlices < 2)
10267 // Sort the slices so that elements that are likely to be next to each
10268 // other in memory are next to each other in the list.
10269 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10270 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10271 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10272 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10274 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10275 // First (resp. Second) is the first (resp. Second) potentially candidate
10276 // to be placed in a paired load.
10277 const LoadedSlice *First = nullptr;
10278 const LoadedSlice *Second = nullptr;
10279 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10280 // Set the beginning of the pair.
10283 Second = &LoadedSlices[CurrSlice];
10285 // If First is NULL, it means we start a new pair.
10286 // Get to the next slice.
10290 EVT LoadedType = First->getLoadedType();
10292 // If the types of the slices are different, we cannot pair them.
10293 if (LoadedType != Second->getLoadedType())
10296 // Check if the target supplies paired loads for this type.
10297 unsigned RequiredAlignment = 0;
10298 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10299 // move to the next pair, this type is hopeless.
10303 // Check if we meet the alignment requirement.
10304 if (RequiredAlignment > First->getAlignment())
10307 // Check that both loads are next to each other in memory.
10308 if (!areSlicesNextToEachOther(*First, *Second))
10311 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10312 --GlobalLSCost.Loads;
10313 // Move to the next pair.
10318 /// \brief Check the profitability of all involved LoadedSlice.
10319 /// Currently, it is considered profitable if there is exactly two
10320 /// involved slices (1) which are (2) next to each other in memory, and
10321 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10323 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10324 /// the elements themselves.
10326 /// FIXME: When the cost model will be mature enough, we can relax
10327 /// constraints (1) and (2).
10328 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10329 const APInt &UsedBits, bool ForCodeSize) {
10330 unsigned NumberOfSlices = LoadedSlices.size();
10331 if (StressLoadSlicing)
10332 return NumberOfSlices > 1;
10335 if (NumberOfSlices != 2)
10339 if (!areUsedBitsDense(UsedBits))
10343 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10344 // The original code has one big load.
10345 OrigCost.Loads = 1;
10346 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10347 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10348 // Accumulate the cost of all the slices.
10349 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10350 GlobalSlicingCost += SliceCost;
10352 // Account as cost in the original configuration the gain obtained
10353 // with the current slices.
10354 OrigCost.addSliceGain(LS);
10357 // If the target supports paired load, adjust the cost accordingly.
10358 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10359 return OrigCost > GlobalSlicingCost;
10362 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10363 /// operations, split it in the various pieces being extracted.
10365 /// This sort of thing is introduced by SROA.
10366 /// This slicing takes care not to insert overlapping loads.
10367 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10368 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10369 if (Level < AfterLegalizeDAG)
10372 LoadSDNode *LD = cast<LoadSDNode>(N);
10373 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10374 !LD->getValueType(0).isInteger())
10377 // Keep track of already used bits to detect overlapping values.
10378 // In that case, we will just abort the transformation.
10379 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10381 SmallVector<LoadedSlice, 4> LoadedSlices;
10383 // Check if this load is used as several smaller chunks of bits.
10384 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10385 // of computation for each trunc.
10386 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10387 UI != UIEnd; ++UI) {
10388 // Skip the uses of the chain.
10389 if (UI.getUse().getResNo() != 0)
10392 SDNode *User = *UI;
10393 unsigned Shift = 0;
10395 // Check if this is a trunc(lshr).
10396 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10397 isa<ConstantSDNode>(User->getOperand(1))) {
10398 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10399 User = *User->use_begin();
10402 // At this point, User is a Truncate, iff we encountered, trunc or
10404 if (User->getOpcode() != ISD::TRUNCATE)
10407 // The width of the type must be a power of 2 and greater than 8-bits.
10408 // Otherwise the load cannot be represented in LLVM IR.
10409 // Moreover, if we shifted with a non-8-bits multiple, the slice
10410 // will be across several bytes. We do not support that.
10411 unsigned Width = User->getValueSizeInBits(0);
10412 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10415 // Build the slice for this chain of computations.
10416 LoadedSlice LS(User, LD, Shift, &DAG);
10417 APInt CurrentUsedBits = LS.getUsedBits();
10419 // Check if this slice overlaps with another.
10420 if ((CurrentUsedBits & UsedBits) != 0)
10422 // Update the bits used globally.
10423 UsedBits |= CurrentUsedBits;
10425 // Check if the new slice would be legal.
10429 // Record the slice.
10430 LoadedSlices.push_back(LS);
10433 // Abort slicing if it does not seem to be profitable.
10434 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10439 // Rewrite each chain to use an independent load.
10440 // By construction, each chain can be represented by a unique load.
10442 // Prepare the argument for the new token factor for all the slices.
10443 SmallVector<SDValue, 8> ArgChains;
10444 for (SmallVectorImpl<LoadedSlice>::const_iterator
10445 LSIt = LoadedSlices.begin(),
10446 LSItEnd = LoadedSlices.end();
10447 LSIt != LSItEnd; ++LSIt) {
10448 SDValue SliceInst = LSIt->loadSlice();
10449 CombineTo(LSIt->Inst, SliceInst, true);
10450 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10451 SliceInst = SliceInst.getOperand(0);
10452 assert(SliceInst->getOpcode() == ISD::LOAD &&
10453 "It takes more than a zext to get to the loaded slice!!");
10454 ArgChains.push_back(SliceInst.getValue(1));
10457 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10459 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10463 /// Check to see if V is (and load (ptr), imm), where the load is having
10464 /// specific bytes cleared out. If so, return the byte size being masked out
10465 /// and the shift amount.
10466 static std::pair<unsigned, unsigned>
10467 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10468 std::pair<unsigned, unsigned> Result(0, 0);
10470 // Check for the structure we're looking for.
10471 if (V->getOpcode() != ISD::AND ||
10472 !isa<ConstantSDNode>(V->getOperand(1)) ||
10473 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10476 // Check the chain and pointer.
10477 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10478 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10480 // The store should be chained directly to the load or be an operand of a
10482 if (LD == Chain.getNode())
10484 else if (Chain->getOpcode() != ISD::TokenFactor)
10485 return Result; // Fail.
10488 for (const SDValue &ChainOp : Chain->op_values())
10489 if (ChainOp.getNode() == LD) {
10493 if (!isOk) return Result;
10496 // This only handles simple types.
10497 if (V.getValueType() != MVT::i16 &&
10498 V.getValueType() != MVT::i32 &&
10499 V.getValueType() != MVT::i64)
10502 // Check the constant mask. Invert it so that the bits being masked out are
10503 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10504 // follow the sign bit for uniformity.
10505 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10506 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10507 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10508 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10509 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10510 if (NotMaskLZ == 64) return Result; // All zero mask.
10512 // See if we have a continuous run of bits. If so, we have 0*1+0*
10513 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10516 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10517 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10518 NotMaskLZ -= 64-V.getValueSizeInBits();
10520 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10521 switch (MaskedBytes) {
10525 default: return Result; // All one mask, or 5-byte mask.
10528 // Verify that the first bit starts at a multiple of mask so that the access
10529 // is aligned the same as the access width.
10530 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10532 Result.first = MaskedBytes;
10533 Result.second = NotMaskTZ/8;
10538 /// Check to see if IVal is something that provides a value as specified by
10539 /// MaskInfo. If so, replace the specified store with a narrower store of
10540 /// truncated IVal.
10542 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10543 SDValue IVal, StoreSDNode *St,
10545 unsigned NumBytes = MaskInfo.first;
10546 unsigned ByteShift = MaskInfo.second;
10547 SelectionDAG &DAG = DC->getDAG();
10549 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10550 // that uses this. If not, this is not a replacement.
10551 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10552 ByteShift*8, (ByteShift+NumBytes)*8);
10553 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10555 // Check that it is legal on the target to do this. It is legal if the new
10556 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10558 MVT VT = MVT::getIntegerVT(NumBytes*8);
10559 if (!DC->isTypeLegal(VT))
10562 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10563 // shifted by ByteShift and truncated down to NumBytes.
10566 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10567 DAG.getConstant(ByteShift*8, DL,
10568 DC->getShiftAmountTy(IVal.getValueType())));
10571 // Figure out the offset for the store and the alignment of the access.
10573 unsigned NewAlign = St->getAlignment();
10575 if (DAG.getDataLayout().isLittleEndian())
10576 StOffset = ByteShift;
10578 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10580 SDValue Ptr = St->getBasePtr();
10583 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10584 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10585 NewAlign = MinAlign(NewAlign, StOffset);
10588 // Truncate down to the new size.
10589 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10592 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10593 St->getPointerInfo().getWithOffset(StOffset),
10594 false, false, NewAlign).getNode();
10598 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10599 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10600 /// narrowing the load and store if it would end up being a win for performance
10602 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10603 StoreSDNode *ST = cast<StoreSDNode>(N);
10604 if (ST->isVolatile())
10607 SDValue Chain = ST->getChain();
10608 SDValue Value = ST->getValue();
10609 SDValue Ptr = ST->getBasePtr();
10610 EVT VT = Value.getValueType();
10612 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10615 unsigned Opc = Value.getOpcode();
10617 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10618 // is a byte mask indicating a consecutive number of bytes, check to see if
10619 // Y is known to provide just those bytes. If so, we try to replace the
10620 // load + replace + store sequence with a single (narrower) store, which makes
10622 if (Opc == ISD::OR) {
10623 std::pair<unsigned, unsigned> MaskedLoad;
10624 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10625 if (MaskedLoad.first)
10626 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10627 Value.getOperand(1), ST,this))
10628 return SDValue(NewST, 0);
10630 // Or is commutative, so try swapping X and Y.
10631 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10632 if (MaskedLoad.first)
10633 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10634 Value.getOperand(0), ST,this))
10635 return SDValue(NewST, 0);
10638 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10639 Value.getOperand(1).getOpcode() != ISD::Constant)
10642 SDValue N0 = Value.getOperand(0);
10643 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10644 Chain == SDValue(N0.getNode(), 1)) {
10645 LoadSDNode *LD = cast<LoadSDNode>(N0);
10646 if (LD->getBasePtr() != Ptr ||
10647 LD->getPointerInfo().getAddrSpace() !=
10648 ST->getPointerInfo().getAddrSpace())
10651 // Find the type to narrow it the load / op / store to.
10652 SDValue N1 = Value.getOperand(1);
10653 unsigned BitWidth = N1.getValueSizeInBits();
10654 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10655 if (Opc == ISD::AND)
10656 Imm ^= APInt::getAllOnesValue(BitWidth);
10657 if (Imm == 0 || Imm.isAllOnesValue())
10659 unsigned ShAmt = Imm.countTrailingZeros();
10660 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10661 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10662 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10663 // The narrowing should be profitable, the load/store operation should be
10664 // legal (or custom) and the store size should be equal to the NewVT width.
10665 while (NewBW < BitWidth &&
10666 (NewVT.getStoreSizeInBits() != NewBW ||
10667 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10668 !TLI.isNarrowingProfitable(VT, NewVT))) {
10669 NewBW = NextPowerOf2(NewBW);
10670 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10672 if (NewBW >= BitWidth)
10675 // If the lsb changed does not start at the type bitwidth boundary,
10676 // start at the previous one.
10678 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10679 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10680 std::min(BitWidth, ShAmt + NewBW));
10681 if ((Imm & Mask) == Imm) {
10682 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10683 if (Opc == ISD::AND)
10684 NewImm ^= APInt::getAllOnesValue(NewBW);
10685 uint64_t PtrOff = ShAmt / 8;
10686 // For big endian targets, we need to adjust the offset to the pointer to
10687 // load the correct bytes.
10688 if (DAG.getDataLayout().isBigEndian())
10689 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10691 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10692 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10693 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10696 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10697 Ptr.getValueType(), Ptr,
10698 DAG.getConstant(PtrOff, SDLoc(LD),
10699 Ptr.getValueType()));
10700 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10701 LD->getChain(), NewPtr,
10702 LD->getPointerInfo().getWithOffset(PtrOff),
10703 LD->isVolatile(), LD->isNonTemporal(),
10704 LD->isInvariant(), NewAlign,
10706 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10707 DAG.getConstant(NewImm, SDLoc(Value),
10709 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10711 ST->getPointerInfo().getWithOffset(PtrOff),
10712 false, false, NewAlign);
10714 AddToWorklist(NewPtr.getNode());
10715 AddToWorklist(NewLD.getNode());
10716 AddToWorklist(NewVal.getNode());
10717 WorklistRemover DeadNodes(*this);
10718 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10727 /// For a given floating point load / store pair, if the load value isn't used
10728 /// by any other operations, then consider transforming the pair to integer
10729 /// load / store operations if the target deems the transformation profitable.
10730 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10731 StoreSDNode *ST = cast<StoreSDNode>(N);
10732 SDValue Chain = ST->getChain();
10733 SDValue Value = ST->getValue();
10734 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10735 Value.hasOneUse() &&
10736 Chain == SDValue(Value.getNode(), 1)) {
10737 LoadSDNode *LD = cast<LoadSDNode>(Value);
10738 EVT VT = LD->getMemoryVT();
10739 if (!VT.isFloatingPoint() ||
10740 VT != ST->getMemoryVT() ||
10741 LD->isNonTemporal() ||
10742 ST->isNonTemporal() ||
10743 LD->getPointerInfo().getAddrSpace() != 0 ||
10744 ST->getPointerInfo().getAddrSpace() != 0)
10747 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10748 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10749 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10750 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10751 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10754 unsigned LDAlign = LD->getAlignment();
10755 unsigned STAlign = ST->getAlignment();
10756 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10757 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10758 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10761 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10762 LD->getChain(), LD->getBasePtr(),
10763 LD->getPointerInfo(),
10764 false, false, false, LDAlign);
10766 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10767 NewLD, ST->getBasePtr(),
10768 ST->getPointerInfo(),
10769 false, false, STAlign);
10771 AddToWorklist(NewLD.getNode());
10772 AddToWorklist(NewST.getNode());
10773 WorklistRemover DeadNodes(*this);
10774 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10783 /// Helper struct to parse and store a memory address as base + index + offset.
10784 /// We ignore sign extensions when it is safe to do so.
10785 /// The following two expressions are not equivalent. To differentiate we need
10786 /// to store whether there was a sign extension involved in the index
10788 /// (load (i64 add (i64 copyfromreg %c)
10789 /// (i64 signextend (add (i8 load %index)
10793 /// (load (i64 add (i64 copyfromreg %c)
10794 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10796 struct BaseIndexOffset {
10800 bool IsIndexSignExt;
10802 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10804 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10805 bool IsIndexSignExt) :
10806 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10808 bool equalBaseIndex(const BaseIndexOffset &Other) {
10809 return Other.Base == Base && Other.Index == Index &&
10810 Other.IsIndexSignExt == IsIndexSignExt;
10813 /// Parses tree in Ptr for base, index, offset addresses.
10814 static BaseIndexOffset match(SDValue Ptr) {
10815 bool IsIndexSignExt = false;
10817 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10818 // instruction, then it could be just the BASE or everything else we don't
10819 // know how to handle. Just use Ptr as BASE and give up.
10820 if (Ptr->getOpcode() != ISD::ADD)
10821 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10823 // We know that we have at least an ADD instruction. Try to pattern match
10824 // the simple case of BASE + OFFSET.
10825 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10826 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10827 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10831 // Inside a loop the current BASE pointer is calculated using an ADD and a
10832 // MUL instruction. In this case Ptr is the actual BASE pointer.
10833 // (i64 add (i64 %array_ptr)
10834 // (i64 mul (i64 %induction_var)
10835 // (i64 %element_size)))
10836 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10837 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10839 // Look at Base + Index + Offset cases.
10840 SDValue Base = Ptr->getOperand(0);
10841 SDValue IndexOffset = Ptr->getOperand(1);
10843 // Skip signextends.
10844 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10845 IndexOffset = IndexOffset->getOperand(0);
10846 IsIndexSignExt = true;
10849 // Either the case of Base + Index (no offset) or something else.
10850 if (IndexOffset->getOpcode() != ISD::ADD)
10851 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10853 // Now we have the case of Base + Index + offset.
10854 SDValue Index = IndexOffset->getOperand(0);
10855 SDValue Offset = IndexOffset->getOperand(1);
10857 if (!isa<ConstantSDNode>(Offset))
10858 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10860 // Ignore signextends.
10861 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10862 Index = Index->getOperand(0);
10863 IsIndexSignExt = true;
10864 } else IsIndexSignExt = false;
10866 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10867 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10872 // This is a helper function for visitMUL to check the profitability
10873 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
10874 // MulNode is the original multiply, AddNode is (add x, c1),
10875 // and ConstNode is c2.
10877 // If the (add x, c1) has multiple uses, we could increase
10878 // the number of adds if we make this transformation.
10879 // It would only be worth doing this if we can remove a
10880 // multiply in the process. Check for that here.
10884 // We're checking for cases where we have common "c3 * A" expressions.
10885 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
10887 SDValue &ConstNode) {
10890 // If the add only has one use, this would be OK to do.
10891 if (AddNode.getNode()->hasOneUse())
10894 // Walk all the users of the constant with which we're multiplying.
10895 for (SDNode *Use : ConstNode->uses()) {
10897 if (Use == MulNode) // This use is the one we're on right now. Skip it.
10900 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
10902 SDNode *MulVar = AddNode.getOperand(0).getNode();
10904 // OtherOp is what we're multiplying against the constant.
10905 if (Use->getOperand(0) == ConstNode)
10906 OtherOp = Use->getOperand(1).getNode();
10908 OtherOp = Use->getOperand(0).getNode();
10910 // Check to see if multiply is with the same operand of our "add".
10912 // ConstNode = CONST
10913 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
10915 // AddNode = (A + c1) <-- MulVar is A.
10916 // = AddNode * ConstNode <-- current visiting instruction.
10918 // If we make this transformation, we will have a common
10919 // multiply (ConstNode * A) that we can save.
10920 if (OtherOp == MulVar)
10923 // Now check to see if a future expansion will give us a common
10926 // ConstNode = CONST
10927 // AddNode = (A + c1)
10928 // ... = AddNode * ConstNode <-- current visiting instruction.
10930 // OtherOp = (A + c2)
10931 // Use = OtherOp * ConstNode <-- visiting Use.
10933 // If we make this transformation, we will have a common
10934 // multiply (CONST * A) after we also do the same transformation
10935 // to the "t2" instruction.
10936 if (OtherOp->getOpcode() == ISD::ADD &&
10937 isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
10938 OtherOp->getOperand(0).getNode() == MulVar)
10943 // Didn't find a case where this would be profitable.
10947 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10949 ArrayRef<MemOpLink> Stores,
10950 SmallVectorImpl<SDValue> &Chains,
10952 SmallVector<SDValue, 8> BuildVector;
10954 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10955 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10956 Chains.push_back(St->getChain());
10957 BuildVector.push_back(St->getValue());
10960 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10963 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10964 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10965 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10966 // Make sure we have something to merge.
10970 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10971 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10972 unsigned LatestNodeUsed = 0;
10974 for (unsigned i=0; i < NumStores; ++i) {
10975 // Find a chain for the new wide-store operand. Notice that some
10976 // of the store nodes that we found may not be selected for inclusion
10977 // in the wide store. The chain we use needs to be the chain of the
10978 // latest store node which is *used* and replaced by the wide store.
10979 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10980 LatestNodeUsed = i;
10983 SmallVector<SDValue, 8> Chains;
10985 // The latest Node in the DAG.
10986 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10987 SDLoc DL(StoreNodes[0].MemNode);
10991 bool IsVec = MemVT.isVector();
10992 unsigned Elts = NumStores;
10994 // When merging vector stores, get the total number of elements.
10995 Elts *= MemVT.getVectorNumElements();
10997 // Get the type for the merged vector store.
10998 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10999 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11001 if (IsConstantSrc) {
11002 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11004 SmallVector<SDValue, 8> Ops;
11005 for (unsigned i = 0; i < NumStores; ++i) {
11006 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11007 SDValue Val = St->getValue();
11008 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11009 if (Val.getValueType() != MemVT)
11011 Ops.push_back(Val);
11012 Chains.push_back(St->getChain());
11015 // Build the extracted vector elements back into a vector.
11016 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11019 // We should always use a vector store when merging extracted vector
11020 // elements, so this path implies a store of constants.
11021 assert(IsConstantSrc && "Merged vector elements should use vector store");
11023 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11024 APInt StoreInt(SizeInBits, 0);
11026 // Construct a single integer constant which is made of the smaller
11027 // constant inputs.
11028 bool IsLE = DAG.getDataLayout().isLittleEndian();
11029 for (unsigned i = 0; i < NumStores; ++i) {
11030 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11031 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11032 Chains.push_back(St->getChain());
11034 SDValue Val = St->getValue();
11035 StoreInt <<= ElementSizeBytes * 8;
11036 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11037 StoreInt |= C->getAPIntValue().zext(SizeInBits);
11038 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11039 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11041 llvm_unreachable("Invalid constant element type");
11045 // Create the new Load and Store operations.
11046 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11047 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11050 assert(!Chains.empty());
11052 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11053 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11054 FirstInChain->getBasePtr(),
11055 FirstInChain->getPointerInfo(),
11057 FirstInChain->getAlignment());
11059 // Replace the last store with the new store
11060 CombineTo(LatestOp, NewStore);
11061 // Erase all other stores.
11062 for (unsigned i = 0; i < NumStores; ++i) {
11063 if (StoreNodes[i].MemNode == LatestOp)
11065 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11066 // ReplaceAllUsesWith will replace all uses that existed when it was
11067 // called, but graph optimizations may cause new ones to appear. For
11068 // example, the case in pr14333 looks like
11070 // St's chain -> St -> another store -> X
11072 // And the only difference from St to the other store is the chain.
11073 // When we change it's chain to be St's chain they become identical,
11074 // get CSEed and the net result is that X is now a use of St.
11075 // Since we know that St is redundant, just iterate.
11076 while (!St->use_empty())
11077 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11078 deleteAndRecombine(St);
11084 void DAGCombiner::getStoreMergeAndAliasCandidates(
11085 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11086 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11087 // This holds the base pointer, index, and the offset in bytes from the base
11089 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11091 // We must have a base and an offset.
11092 if (!BasePtr.Base.getNode())
11095 // Do not handle stores to undef base pointers.
11096 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11099 // Walk up the chain and look for nodes with offsets from the same
11100 // base pointer. Stop when reaching an instruction with a different kind
11101 // or instruction which has a different base pointer.
11102 EVT MemVT = St->getMemoryVT();
11104 StoreSDNode *Index = St;
11107 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11108 : DAG.getSubtarget().useAA();
11111 // Look at other users of the same chain. Stores on the same chain do not
11112 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11113 // to be on the same chain, so don't bother looking at adjacent chains.
11115 SDValue Chain = St->getChain();
11116 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11117 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11118 if (I.getOperandNo() != 0)
11121 if (OtherST->isVolatile() || OtherST->isIndexed())
11124 if (OtherST->getMemoryVT() != MemVT)
11127 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11129 if (Ptr.equalBaseIndex(BasePtr))
11130 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11138 // If the chain has more than one use, then we can't reorder the mem ops.
11139 if (Index != St && !SDValue(Index, 0)->hasOneUse())
11142 // Find the base pointer and offset for this memory node.
11143 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11145 // Check that the base pointer is the same as the original one.
11146 if (!Ptr.equalBaseIndex(BasePtr))
11149 // The memory operands must not be volatile.
11150 if (Index->isVolatile() || Index->isIndexed())
11154 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11155 if (St->isTruncatingStore())
11158 // The stored memory type must be the same.
11159 if (Index->getMemoryVT() != MemVT)
11162 // We found a potential memory operand to merge.
11163 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11165 // Find the next memory operand in the chain. If the next operand in the
11166 // chain is a store then move up and continue the scan with the next
11167 // memory operand. If the next operand is a load save it and use alias
11168 // information to check if it interferes with anything.
11169 SDNode *NextInChain = Index->getChain().getNode();
11171 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11172 // We found a store node. Use it for the next iteration.
11175 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11176 if (Ldn->isVolatile()) {
11181 // Save the load node for later. Continue the scan.
11182 AliasLoadNodes.push_back(Ldn);
11183 NextInChain = Ldn->getChain().getNode();
11193 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11194 if (OptLevel == CodeGenOpt::None)
11197 EVT MemVT = St->getMemoryVT();
11198 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11199 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11200 Attribute::NoImplicitFloat);
11202 // This function cannot currently deal with non-byte-sized memory sizes.
11203 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11206 if (!MemVT.isSimple())
11209 // Perform an early exit check. Do not bother looking at stored values that
11210 // are not constants, loads, or extracted vector elements.
11211 SDValue StoredVal = St->getValue();
11212 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11213 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11214 isa<ConstantFPSDNode>(StoredVal);
11215 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11216 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11218 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11221 // Don't merge vectors into wider vectors if the source data comes from loads.
11222 // TODO: This restriction can be lifted by using logic similar to the
11223 // ExtractVecSrc case.
11224 if (MemVT.isVector() && IsLoadSrc)
11227 // Only look at ends of store sequences.
11228 SDValue Chain = SDValue(St, 0);
11229 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11232 // Save the LoadSDNodes that we find in the chain.
11233 // We need to make sure that these nodes do not interfere with
11234 // any of the store nodes.
11235 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11237 // Save the StoreSDNodes that we find in the chain.
11238 SmallVector<MemOpLink, 8> StoreNodes;
11240 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11242 // Check if there is anything to merge.
11243 if (StoreNodes.size() < 2)
11246 // Sort the memory operands according to their distance from the base pointer.
11247 std::sort(StoreNodes.begin(), StoreNodes.end(),
11248 [](MemOpLink LHS, MemOpLink RHS) {
11249 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11250 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11251 LHS.SequenceNum > RHS.SequenceNum);
11254 // Scan the memory operations on the chain and find the first non-consecutive
11255 // store memory address.
11256 unsigned LastConsecutiveStore = 0;
11257 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11258 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11260 // Check that the addresses are consecutive starting from the second
11261 // element in the list of stores.
11263 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11264 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11268 bool Alias = false;
11269 // Check if this store interferes with any of the loads that we found.
11270 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11271 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11275 // We found a load that alias with this store. Stop the sequence.
11279 // Mark this node as useful.
11280 LastConsecutiveStore = i;
11283 // The node with the lowest store address.
11284 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11285 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11286 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11287 LLVMContext &Context = *DAG.getContext();
11288 const DataLayout &DL = DAG.getDataLayout();
11290 // Store the constants into memory as one consecutive store.
11291 if (IsConstantSrc) {
11292 unsigned LastLegalType = 0;
11293 unsigned LastLegalVectorType = 0;
11294 bool NonZero = false;
11295 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11296 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11297 SDValue StoredVal = St->getValue();
11299 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11300 NonZero |= !C->isNullValue();
11301 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11302 NonZero |= !C->getConstantFPValue()->isNullValue();
11308 // Find a legal type for the constant store.
11309 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11310 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11312 if (TLI.isTypeLegal(StoreTy) &&
11313 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11314 FirstStoreAlign, &IsFast) && IsFast) {
11315 LastLegalType = i+1;
11316 // Or check whether a truncstore is legal.
11317 } else if (TLI.getTypeAction(Context, StoreTy) ==
11318 TargetLowering::TypePromoteInteger) {
11319 EVT LegalizedStoredValueTy =
11320 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11321 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11322 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11323 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11325 LastLegalType = i + 1;
11329 // We only use vectors if the constant is known to be zero or the target
11330 // allows it and the function is not marked with the noimplicitfloat
11332 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11335 // Find a legal type for the vector store.
11336 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11337 if (TLI.isTypeLegal(Ty) &&
11338 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11339 FirstStoreAlign, &IsFast) && IsFast)
11340 LastLegalVectorType = i + 1;
11344 // Check if we found a legal integer type to store.
11345 if (LastLegalType == 0 && LastLegalVectorType == 0)
11348 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11349 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11351 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11355 // When extracting multiple vector elements, try to store them
11356 // in one vector store rather than a sequence of scalar stores.
11357 if (IsExtractVecSrc) {
11358 unsigned NumStoresToMerge = 0;
11359 bool IsVec = MemVT.isVector();
11360 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11361 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11362 unsigned StoreValOpcode = St->getValue().getOpcode();
11363 // This restriction could be loosened.
11364 // Bail out if any stored values are not elements extracted from a vector.
11365 // It should be possible to handle mixed sources, but load sources need
11366 // more careful handling (see the block of code below that handles
11367 // consecutive loads).
11368 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11369 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11372 // Find a legal type for the vector store.
11373 unsigned Elts = i + 1;
11375 // When merging vector stores, get the total number of elements.
11376 Elts *= MemVT.getVectorNumElements();
11378 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11380 if (TLI.isTypeLegal(Ty) &&
11381 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11382 FirstStoreAlign, &IsFast) && IsFast)
11383 NumStoresToMerge = i + 1;
11386 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11390 // Below we handle the case of multiple consecutive stores that
11391 // come from multiple consecutive loads. We merge them into a single
11392 // wide load and a single wide store.
11394 // Look for load nodes which are used by the stored values.
11395 SmallVector<MemOpLink, 8> LoadNodes;
11397 // Find acceptable loads. Loads need to have the same chain (token factor),
11398 // must not be zext, volatile, indexed, and they must be consecutive.
11399 BaseIndexOffset LdBasePtr;
11400 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11401 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11402 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11405 // Loads must only have one use.
11406 if (!Ld->hasNUsesOfValue(1, 0))
11409 // The memory operands must not be volatile.
11410 if (Ld->isVolatile() || Ld->isIndexed())
11413 // We do not accept ext loads.
11414 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11417 // The stored memory type must be the same.
11418 if (Ld->getMemoryVT() != MemVT)
11421 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11422 // If this is not the first ptr that we check.
11423 if (LdBasePtr.Base.getNode()) {
11424 // The base ptr must be the same.
11425 if (!LdPtr.equalBaseIndex(LdBasePtr))
11428 // Check that all other base pointers are the same as this one.
11432 // We found a potential memory operand to merge.
11433 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11436 if (LoadNodes.size() < 2)
11439 // If we have load/store pair instructions and we only have two values,
11441 unsigned RequiredAlignment;
11442 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11443 St->getAlignment() >= RequiredAlignment)
11446 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11447 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11448 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11450 // Scan the memory operations on the chain and find the first non-consecutive
11451 // load memory address. These variables hold the index in the store node
11453 unsigned LastConsecutiveLoad = 0;
11454 // This variable refers to the size and not index in the array.
11455 unsigned LastLegalVectorType = 0;
11456 unsigned LastLegalIntegerType = 0;
11457 StartAddress = LoadNodes[0].OffsetFromBase;
11458 SDValue FirstChain = FirstLoad->getChain();
11459 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11460 // All loads much share the same chain.
11461 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11464 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11465 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11467 LastConsecutiveLoad = i;
11468 // Find a legal type for the vector store.
11469 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11470 bool IsFastSt, IsFastLd;
11471 if (TLI.isTypeLegal(StoreTy) &&
11472 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11473 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11474 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11475 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11476 LastLegalVectorType = i + 1;
11479 // Find a legal type for the integer store.
11480 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11481 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11482 if (TLI.isTypeLegal(StoreTy) &&
11483 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11484 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11485 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11486 FirstLoadAlign, &IsFastLd) && IsFastLd)
11487 LastLegalIntegerType = i + 1;
11488 // Or check whether a truncstore and extload is legal.
11489 else if (TLI.getTypeAction(Context, StoreTy) ==
11490 TargetLowering::TypePromoteInteger) {
11491 EVT LegalizedStoredValueTy =
11492 TLI.getTypeToTransformTo(Context, StoreTy);
11493 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11494 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11495 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11496 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11497 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11498 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11500 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11501 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11503 LastLegalIntegerType = i+1;
11507 // Only use vector types if the vector type is larger than the integer type.
11508 // If they are the same, use integers.
11509 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11510 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11512 // We add +1 here because the LastXXX variables refer to location while
11513 // the NumElem refers to array/index size.
11514 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11515 NumElem = std::min(LastLegalType, NumElem);
11520 // Collect the chains from all merged stores.
11521 SmallVector<SDValue, 8> MergeStoreChains;
11522 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11524 // The latest Node in the DAG.
11525 unsigned LatestNodeUsed = 0;
11526 for (unsigned i=1; i<NumElem; ++i) {
11527 // Find a chain for the new wide-store operand. Notice that some
11528 // of the store nodes that we found may not be selected for inclusion
11529 // in the wide store. The chain we use needs to be the chain of the
11530 // latest store node which is *used* and replaced by the wide store.
11531 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11532 LatestNodeUsed = i;
11534 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11537 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11539 // Find if it is better to use vectors or integers to load and store
11543 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11545 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11546 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11549 SDLoc LoadDL(LoadNodes[0].MemNode);
11550 SDLoc StoreDL(StoreNodes[0].MemNode);
11552 // The merged loads are required to have the same chain, so using the first's
11553 // chain is acceptable.
11554 SDValue NewLoad = DAG.getLoad(
11555 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11556 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11558 SDValue NewStoreChain =
11559 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11561 SDValue NewStore = DAG.getStore(
11562 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11563 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11565 // Replace one of the loads with the new load.
11566 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11567 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11568 SDValue(NewLoad.getNode(), 1));
11570 // Remove the rest of the load chains.
11571 for (unsigned i = 1; i < NumElem ; ++i) {
11572 // Replace all chain users of the old load nodes with the chain of the new
11574 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11575 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11578 // Replace the last store with the new store.
11579 CombineTo(LatestOp, NewStore);
11580 // Erase all other stores.
11581 for (unsigned i = 0; i < NumElem ; ++i) {
11582 // Remove all Store nodes.
11583 if (StoreNodes[i].MemNode == LatestOp)
11585 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11586 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11587 deleteAndRecombine(St);
11593 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11597 // Replace the chain to avoid dependency.
11598 if (ST->isTruncatingStore()) {
11599 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11600 ST->getBasePtr(), ST->getMemoryVT(),
11601 ST->getMemOperand());
11603 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11604 ST->getMemOperand());
11607 // Create token to keep both nodes around.
11608 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11609 MVT::Other, ST->getChain(), ReplStore);
11611 // Make sure the new and old chains are cleaned up.
11612 AddToWorklist(Token.getNode());
11614 // Don't add users to work list.
11615 return CombineTo(ST, Token, false);
11618 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11619 SDValue Value = ST->getValue();
11620 if (Value.getOpcode() == ISD::TargetConstantFP)
11625 SDValue Chain = ST->getChain();
11626 SDValue Ptr = ST->getBasePtr();
11628 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11630 // NOTE: If the original store is volatile, this transform must not increase
11631 // the number of stores. For example, on x86-32 an f64 can be stored in one
11632 // processor operation but an i64 (which is not legal) requires two. So the
11633 // transform should not be done in this case.
11636 switch (CFP->getSimpleValueType(0).SimpleTy) {
11638 llvm_unreachable("Unknown FP type");
11639 case MVT::f16: // We don't do this for these yet.
11645 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11646 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11648 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11649 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11651 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11656 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11657 !ST->isVolatile()) ||
11658 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11660 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11661 getZExtValue(), SDLoc(CFP), MVT::i64);
11662 return DAG.getStore(Chain, DL, Tmp,
11663 Ptr, ST->getMemOperand());
11666 if (!ST->isVolatile() &&
11667 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11668 // Many FP stores are not made apparent until after legalize, e.g. for
11669 // argument passing. Since this is so common, custom legalize the
11670 // 64-bit integer store into two 32-bit stores.
11671 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11672 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11673 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11674 if (DAG.getDataLayout().isBigEndian())
11677 unsigned Alignment = ST->getAlignment();
11678 bool isVolatile = ST->isVolatile();
11679 bool isNonTemporal = ST->isNonTemporal();
11680 AAMDNodes AAInfo = ST->getAAInfo();
11682 SDValue St0 = DAG.getStore(Chain, DL, Lo,
11683 Ptr, ST->getPointerInfo(),
11684 isVolatile, isNonTemporal,
11685 ST->getAlignment(), AAInfo);
11686 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11687 DAG.getConstant(4, DL, Ptr.getValueType()));
11688 Alignment = MinAlign(Alignment, 4U);
11689 SDValue St1 = DAG.getStore(Chain, DL, Hi,
11690 Ptr, ST->getPointerInfo().getWithOffset(4),
11691 isVolatile, isNonTemporal,
11692 Alignment, AAInfo);
11693 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11701 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11702 StoreSDNode *ST = cast<StoreSDNode>(N);
11703 SDValue Chain = ST->getChain();
11704 SDValue Value = ST->getValue();
11705 SDValue Ptr = ST->getBasePtr();
11707 // If this is a store of a bit convert, store the input value if the
11708 // resultant store does not need a higher alignment than the original.
11709 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11710 ST->isUnindexed()) {
11711 unsigned OrigAlign = ST->getAlignment();
11712 EVT SVT = Value.getOperand(0).getValueType();
11713 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11714 SVT.getTypeForEVT(*DAG.getContext()));
11715 if (Align <= OrigAlign &&
11716 ((!LegalOperations && !ST->isVolatile()) ||
11717 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11718 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11719 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11720 ST->isNonTemporal(), OrigAlign,
11724 // Turn 'store undef, Ptr' -> nothing.
11725 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11728 // Try to infer better alignment information than the store already has.
11729 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11730 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11731 if (Align > ST->getAlignment()) {
11733 DAG.getTruncStore(Chain, SDLoc(N), Value,
11734 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11735 ST->isVolatile(), ST->isNonTemporal(), Align,
11737 if (NewStore.getNode() != N)
11738 return CombineTo(ST, NewStore, true);
11743 // Try transforming a pair floating point load / store ops to integer
11744 // load / store ops.
11745 if (SDValue NewST = TransformFPLoadStorePair(N))
11748 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11749 : DAG.getSubtarget().useAA();
11751 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11752 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11755 if (UseAA && ST->isUnindexed()) {
11756 // FIXME: We should do this even without AA enabled. AA will just allow
11757 // FindBetterChain to work in more situations. The problem with this is that
11758 // any combine that expects memory operations to be on consecutive chains
11759 // first needs to be updated to look for users of the same chain.
11761 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11762 // adjacent stores.
11763 if (findBetterNeighborChains(ST)) {
11764 // replaceStoreChain uses CombineTo, which handled all of the worklist
11765 // manipulation. Return the original node to not do anything else.
11766 return SDValue(ST, 0);
11770 // Try transforming N to an indexed store.
11771 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11772 return SDValue(N, 0);
11774 // FIXME: is there such a thing as a truncating indexed store?
11775 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11776 Value.getValueType().isInteger()) {
11777 // See if we can simplify the input to this truncstore with knowledge that
11778 // only the low bits are being used. For example:
11779 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11781 GetDemandedBits(Value,
11782 APInt::getLowBitsSet(
11783 Value.getValueType().getScalarType().getSizeInBits(),
11784 ST->getMemoryVT().getScalarType().getSizeInBits()));
11785 AddToWorklist(Value.getNode());
11786 if (Shorter.getNode())
11787 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11788 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11790 // Otherwise, see if we can simplify the operation with
11791 // SimplifyDemandedBits, which only works if the value has a single use.
11792 if (SimplifyDemandedBits(Value,
11793 APInt::getLowBitsSet(
11794 Value.getValueType().getScalarType().getSizeInBits(),
11795 ST->getMemoryVT().getScalarType().getSizeInBits())))
11796 return SDValue(N, 0);
11799 // If this is a load followed by a store to the same location, then the store
11801 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11802 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11803 ST->isUnindexed() && !ST->isVolatile() &&
11804 // There can't be any side effects between the load and store, such as
11805 // a call or store.
11806 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11807 // The store is dead, remove it.
11812 // If this is a store followed by a store with the same value to the same
11813 // location, then the store is dead/noop.
11814 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11815 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11816 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11817 ST1->isUnindexed() && !ST1->isVolatile()) {
11818 // The store is dead, remove it.
11823 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11824 // truncating store. We can do this even if this is already a truncstore.
11825 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11826 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11827 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11828 ST->getMemoryVT())) {
11829 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11830 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11833 // Only perform this optimization before the types are legal, because we
11834 // don't want to perform this optimization on every DAGCombine invocation.
11836 bool EverChanged = false;
11839 // There can be multiple store sequences on the same chain.
11840 // Keep trying to merge store sequences until we are unable to do so
11841 // or until we merge the last store on the chain.
11842 bool Changed = MergeConsecutiveStores(ST);
11843 EverChanged |= Changed;
11844 if (!Changed) break;
11845 } while (ST->getOpcode() != ISD::DELETED_NODE);
11848 return SDValue(N, 0);
11851 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11853 // Make sure to do this only after attempting to merge stores in order to
11854 // avoid changing the types of some subset of stores due to visit order,
11855 // preventing their merging.
11856 if (isa<ConstantFPSDNode>(Value)) {
11857 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11861 return ReduceLoadOpStoreWidth(N);
11864 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11865 SDValue InVec = N->getOperand(0);
11866 SDValue InVal = N->getOperand(1);
11867 SDValue EltNo = N->getOperand(2);
11870 // If the inserted element is an UNDEF, just use the input vector.
11871 if (InVal.getOpcode() == ISD::UNDEF)
11874 EVT VT = InVec.getValueType();
11876 // If we can't generate a legal BUILD_VECTOR, exit
11877 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11880 // Check that we know which element is being inserted
11881 if (!isa<ConstantSDNode>(EltNo))
11883 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11885 // Canonicalize insert_vector_elt dag nodes.
11887 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11888 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11890 // Do this only if the child insert_vector node has one use; also
11891 // do this only if indices are both constants and Idx1 < Idx0.
11892 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11893 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11894 unsigned OtherElt =
11895 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11896 if (Elt < OtherElt) {
11898 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11899 InVec.getOperand(0), InVal, EltNo);
11900 AddToWorklist(NewOp.getNode());
11901 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11902 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11906 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11907 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11908 // vector elements.
11909 SmallVector<SDValue, 8> Ops;
11910 // Do not combine these two vectors if the output vector will not replace
11911 // the input vector.
11912 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11913 Ops.append(InVec.getNode()->op_begin(),
11914 InVec.getNode()->op_end());
11915 } else if (InVec.getOpcode() == ISD::UNDEF) {
11916 unsigned NElts = VT.getVectorNumElements();
11917 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11922 // Insert the element
11923 if (Elt < Ops.size()) {
11924 // All the operands of BUILD_VECTOR must have the same type;
11925 // we enforce that here.
11926 EVT OpVT = Ops[0].getValueType();
11927 if (InVal.getValueType() != OpVT)
11928 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11929 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11930 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11934 // Return the new vector
11935 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11938 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11939 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11940 EVT ResultVT = EVE->getValueType(0);
11941 EVT VecEltVT = InVecVT.getVectorElementType();
11942 unsigned Align = OriginalLoad->getAlignment();
11943 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11944 VecEltVT.getTypeForEVT(*DAG.getContext()));
11946 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11951 SDValue NewPtr = OriginalLoad->getBasePtr();
11953 EVT PtrType = NewPtr.getValueType();
11954 MachinePointerInfo MPI;
11956 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11957 int Elt = ConstEltNo->getZExtValue();
11958 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11959 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11960 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11962 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11963 Offset = DAG.getNode(
11964 ISD::MUL, DL, PtrType, Offset,
11965 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11966 MPI = OriginalLoad->getPointerInfo();
11968 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11970 // The replacement we need to do here is a little tricky: we need to
11971 // replace an extractelement of a load with a load.
11972 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11973 // Note that this replacement assumes that the extractvalue is the only
11974 // use of the load; that's okay because we don't want to perform this
11975 // transformation in other cases anyway.
11978 if (ResultVT.bitsGT(VecEltVT)) {
11979 // If the result type of vextract is wider than the load, then issue an
11980 // extending load instead.
11981 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11985 Load = DAG.getExtLoad(
11986 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11987 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11988 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11989 Chain = Load.getValue(1);
11991 Load = DAG.getLoad(
11992 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11993 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11994 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11995 Chain = Load.getValue(1);
11996 if (ResultVT.bitsLT(VecEltVT))
11997 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11999 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12001 WorklistRemover DeadNodes(*this);
12002 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12003 SDValue To[] = { Load, Chain };
12004 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12005 // Since we're explicitly calling ReplaceAllUses, add the new node to the
12006 // worklist explicitly as well.
12007 AddToWorklist(Load.getNode());
12008 AddUsersToWorklist(Load.getNode()); // Add users too
12009 // Make sure to revisit this node to clean it up; it will usually be dead.
12010 AddToWorklist(EVE);
12012 return SDValue(EVE, 0);
12015 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12016 // (vextract (scalar_to_vector val, 0) -> val
12017 SDValue InVec = N->getOperand(0);
12018 EVT VT = InVec.getValueType();
12019 EVT NVT = N->getValueType(0);
12021 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12022 // Check if the result type doesn't match the inserted element type. A
12023 // SCALAR_TO_VECTOR may truncate the inserted element and the
12024 // EXTRACT_VECTOR_ELT may widen the extracted vector.
12025 SDValue InOp = InVec.getOperand(0);
12026 if (InOp.getValueType() != NVT) {
12027 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12028 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12033 SDValue EltNo = N->getOperand(1);
12034 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12036 // extract_vector_elt (build_vector x, y), 1 -> y
12038 InVec.getOpcode() == ISD::BUILD_VECTOR &&
12039 TLI.isTypeLegal(VT) &&
12040 (InVec.hasOneUse() ||
12041 TLI.aggressivelyPreferBuildVectorSources(VT))) {
12042 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12043 EVT InEltVT = Elt.getValueType();
12045 // Sometimes build_vector's scalar input types do not match result type.
12046 if (NVT == InEltVT)
12049 // TODO: It may be useful to truncate if free if the build_vector implicitly
12053 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12054 // We only perform this optimization before the op legalization phase because
12055 // we may introduce new vector instructions which are not backed by TD
12056 // patterns. For example on AVX, extracting elements from a wide vector
12057 // without using extract_subvector. However, if we can find an underlying
12058 // scalar value, then we can always use that.
12059 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12060 int NumElem = VT.getVectorNumElements();
12061 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12062 // Find the new index to extract from.
12063 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12065 // Extracting an undef index is undef.
12067 return DAG.getUNDEF(NVT);
12069 // Select the right vector half to extract from.
12071 if (OrigElt < NumElem) {
12072 SVInVec = InVec->getOperand(0);
12074 SVInVec = InVec->getOperand(1);
12075 OrigElt -= NumElem;
12078 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12079 SDValue InOp = SVInVec.getOperand(OrigElt);
12080 if (InOp.getValueType() != NVT) {
12081 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12082 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12088 // FIXME: We should handle recursing on other vector shuffles and
12089 // scalar_to_vector here as well.
12091 if (!LegalOperations) {
12092 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12093 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12094 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12098 bool BCNumEltsChanged = false;
12099 EVT ExtVT = VT.getVectorElementType();
12102 // If the result of load has to be truncated, then it's not necessarily
12104 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12107 if (InVec.getOpcode() == ISD::BITCAST) {
12108 // Don't duplicate a load with other uses.
12109 if (!InVec.hasOneUse())
12112 EVT BCVT = InVec.getOperand(0).getValueType();
12113 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12115 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12116 BCNumEltsChanged = true;
12117 InVec = InVec.getOperand(0);
12118 ExtVT = BCVT.getVectorElementType();
12121 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12122 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12123 ISD::isNormalLoad(InVec.getNode()) &&
12124 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12125 SDValue Index = N->getOperand(1);
12126 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12127 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12131 // Perform only after legalization to ensure build_vector / vector_shuffle
12132 // optimizations have already been done.
12133 if (!LegalOperations) return SDValue();
12135 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12136 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12137 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12140 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12142 LoadSDNode *LN0 = nullptr;
12143 const ShuffleVectorSDNode *SVN = nullptr;
12144 if (ISD::isNormalLoad(InVec.getNode())) {
12145 LN0 = cast<LoadSDNode>(InVec);
12146 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12147 InVec.getOperand(0).getValueType() == ExtVT &&
12148 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12149 // Don't duplicate a load with other uses.
12150 if (!InVec.hasOneUse())
12153 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12154 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12155 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12157 // (load $addr+1*size)
12159 // Don't duplicate a load with other uses.
12160 if (!InVec.hasOneUse())
12163 // If the bit convert changed the number of elements, it is unsafe
12164 // to examine the mask.
12165 if (BCNumEltsChanged)
12168 // Select the input vector, guarding against out of range extract vector.
12169 unsigned NumElems = VT.getVectorNumElements();
12170 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12171 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12173 if (InVec.getOpcode() == ISD::BITCAST) {
12174 // Don't duplicate a load with other uses.
12175 if (!InVec.hasOneUse())
12178 InVec = InVec.getOperand(0);
12180 if (ISD::isNormalLoad(InVec.getNode())) {
12181 LN0 = cast<LoadSDNode>(InVec);
12182 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12183 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12187 // Make sure we found a non-volatile load and the extractelement is
12189 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12192 // If Idx was -1 above, Elt is going to be -1, so just return undef.
12194 return DAG.getUNDEF(LVT);
12196 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12202 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12203 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12204 // We perform this optimization post type-legalization because
12205 // the type-legalizer often scalarizes integer-promoted vectors.
12206 // Performing this optimization before may create bit-casts which
12207 // will be type-legalized to complex code sequences.
12208 // We perform this optimization only before the operation legalizer because we
12209 // may introduce illegal operations.
12210 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12213 unsigned NumInScalars = N->getNumOperands();
12215 EVT VT = N->getValueType(0);
12217 // Check to see if this is a BUILD_VECTOR of a bunch of values
12218 // which come from any_extend or zero_extend nodes. If so, we can create
12219 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12220 // optimizations. We do not handle sign-extend because we can't fill the sign
12222 EVT SourceType = MVT::Other;
12223 bool AllAnyExt = true;
12225 for (unsigned i = 0; i != NumInScalars; ++i) {
12226 SDValue In = N->getOperand(i);
12227 // Ignore undef inputs.
12228 if (In.getOpcode() == ISD::UNDEF) continue;
12230 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
12231 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12233 // Abort if the element is not an extension.
12234 if (!ZeroExt && !AnyExt) {
12235 SourceType = MVT::Other;
12239 // The input is a ZeroExt or AnyExt. Check the original type.
12240 EVT InTy = In.getOperand(0).getValueType();
12242 // Check that all of the widened source types are the same.
12243 if (SourceType == MVT::Other)
12246 else if (InTy != SourceType) {
12247 // Multiple income types. Abort.
12248 SourceType = MVT::Other;
12252 // Check if all of the extends are ANY_EXTENDs.
12253 AllAnyExt &= AnyExt;
12256 // In order to have valid types, all of the inputs must be extended from the
12257 // same source type and all of the inputs must be any or zero extend.
12258 // Scalar sizes must be a power of two.
12259 EVT OutScalarTy = VT.getScalarType();
12260 bool ValidTypes = SourceType != MVT::Other &&
12261 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12262 isPowerOf2_32(SourceType.getSizeInBits());
12264 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12265 // turn into a single shuffle instruction.
12269 bool isLE = DAG.getDataLayout().isLittleEndian();
12270 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12271 assert(ElemRatio > 1 && "Invalid element size ratio");
12272 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12273 DAG.getConstant(0, SDLoc(N), SourceType);
12275 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12276 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12278 // Populate the new build_vector
12279 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12280 SDValue Cast = N->getOperand(i);
12281 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12282 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12283 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12285 if (Cast.getOpcode() == ISD::UNDEF)
12286 In = DAG.getUNDEF(SourceType);
12288 In = Cast->getOperand(0);
12289 unsigned Index = isLE ? (i * ElemRatio) :
12290 (i * ElemRatio + (ElemRatio - 1));
12292 assert(Index < Ops.size() && "Invalid index");
12296 // The type of the new BUILD_VECTOR node.
12297 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12298 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12299 "Invalid vector size");
12300 // Check if the new vector type is legal.
12301 if (!isTypeLegal(VecVT)) return SDValue();
12303 // Make the new BUILD_VECTOR.
12304 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12306 // The new BUILD_VECTOR node has the potential to be further optimized.
12307 AddToWorklist(BV.getNode());
12308 // Bitcast to the desired type.
12309 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12312 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12313 EVT VT = N->getValueType(0);
12315 unsigned NumInScalars = N->getNumOperands();
12318 EVT SrcVT = MVT::Other;
12319 unsigned Opcode = ISD::DELETED_NODE;
12320 unsigned NumDefs = 0;
12322 for (unsigned i = 0; i != NumInScalars; ++i) {
12323 SDValue In = N->getOperand(i);
12324 unsigned Opc = In.getOpcode();
12326 if (Opc == ISD::UNDEF)
12329 // If all scalar values are floats and converted from integers.
12330 if (Opcode == ISD::DELETED_NODE &&
12331 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12338 EVT InVT = In.getOperand(0).getValueType();
12340 // If all scalar values are typed differently, bail out. It's chosen to
12341 // simplify BUILD_VECTOR of integer types.
12342 if (SrcVT == MVT::Other)
12349 // If the vector has just one element defined, it's not worth to fold it into
12350 // a vectorized one.
12354 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12355 && "Should only handle conversion from integer to float.");
12356 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12358 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12360 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12363 // Just because the floating-point vector type is legal does not necessarily
12364 // mean that the corresponding integer vector type is.
12365 if (!isTypeLegal(NVT))
12368 SmallVector<SDValue, 8> Opnds;
12369 for (unsigned i = 0; i != NumInScalars; ++i) {
12370 SDValue In = N->getOperand(i);
12372 if (In.getOpcode() == ISD::UNDEF)
12373 Opnds.push_back(DAG.getUNDEF(SrcVT));
12375 Opnds.push_back(In.getOperand(0));
12377 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12378 AddToWorklist(BV.getNode());
12380 return DAG.getNode(Opcode, dl, VT, BV);
12383 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12384 unsigned NumInScalars = N->getNumOperands();
12386 EVT VT = N->getValueType(0);
12388 // A vector built entirely of undefs is undef.
12389 if (ISD::allOperandsUndef(N))
12390 return DAG.getUNDEF(VT);
12392 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12395 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12398 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12399 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12400 // at most two distinct vectors, turn this into a shuffle node.
12402 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12403 if (!isTypeLegal(VT))
12406 // May only combine to shuffle after legalize if shuffle is legal.
12407 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12410 SDValue VecIn1, VecIn2;
12411 bool UsesZeroVector = false;
12412 for (unsigned i = 0; i != NumInScalars; ++i) {
12413 SDValue Op = N->getOperand(i);
12414 // Ignore undef inputs.
12415 if (Op.getOpcode() == ISD::UNDEF) continue;
12417 // See if we can combine this build_vector into a blend with a zero vector.
12418 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12419 UsesZeroVector = true;
12423 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12424 // constant index, bail out.
12425 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12426 !isa<ConstantSDNode>(Op.getOperand(1))) {
12427 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12431 // We allow up to two distinct input vectors.
12432 SDValue ExtractedFromVec = Op.getOperand(0);
12433 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12436 if (!VecIn1.getNode()) {
12437 VecIn1 = ExtractedFromVec;
12438 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12439 VecIn2 = ExtractedFromVec;
12441 // Too many inputs.
12442 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12447 // If everything is good, we can make a shuffle operation.
12448 if (VecIn1.getNode()) {
12449 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12450 SmallVector<int, 8> Mask;
12451 for (unsigned i = 0; i != NumInScalars; ++i) {
12452 unsigned Opcode = N->getOperand(i).getOpcode();
12453 if (Opcode == ISD::UNDEF) {
12454 Mask.push_back(-1);
12458 // Operands can also be zero.
12459 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12460 assert(UsesZeroVector &&
12461 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12462 "Unexpected node found!");
12463 Mask.push_back(NumInScalars+i);
12467 // If extracting from the first vector, just use the index directly.
12468 SDValue Extract = N->getOperand(i);
12469 SDValue ExtVal = Extract.getOperand(1);
12470 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12471 if (Extract.getOperand(0) == VecIn1) {
12472 Mask.push_back(ExtIndex);
12476 // Otherwise, use InIdx + InputVecSize
12477 Mask.push_back(InNumElements + ExtIndex);
12480 // Avoid introducing illegal shuffles with zero.
12481 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12484 // We can't generate a shuffle node with mismatched input and output types.
12485 // Attempt to transform a single input vector to the correct type.
12486 if ((VT != VecIn1.getValueType())) {
12487 // If the input vector type has a different base type to the output
12488 // vector type, bail out.
12489 EVT VTElemType = VT.getVectorElementType();
12490 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12491 (VecIn2.getNode() &&
12492 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12495 // If the input vector is too small, widen it.
12496 // We only support widening of vectors which are half the size of the
12497 // output registers. For example XMM->YMM widening on X86 with AVX.
12498 EVT VecInT = VecIn1.getValueType();
12499 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12500 // If we only have one small input, widen it by adding undef values.
12501 if (!VecIn2.getNode())
12502 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12503 DAG.getUNDEF(VecIn1.getValueType()));
12504 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12505 // If we have two small inputs of the same type, try to concat them.
12506 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12507 VecIn2 = SDValue(nullptr, 0);
12510 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12511 // If the input vector is too large, try to split it.
12512 // We don't support having two input vectors that are too large.
12513 // If the zero vector was used, we can not split the vector,
12514 // since we'd need 3 inputs.
12515 if (UsesZeroVector || VecIn2.getNode())
12518 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12521 // Try to replace VecIn1 with two extract_subvectors
12522 // No need to update the masks, they should still be correct.
12523 VecIn2 = DAG.getNode(
12524 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12525 DAG.getConstant(VT.getVectorNumElements(), dl,
12526 TLI.getVectorIdxTy(DAG.getDataLayout())));
12527 VecIn1 = DAG.getNode(
12528 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12529 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12534 if (UsesZeroVector)
12535 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12536 DAG.getConstantFP(0.0, dl, VT);
12538 // If VecIn2 is unused then change it to undef.
12539 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12541 // Check that we were able to transform all incoming values to the same
12543 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12544 VecIn1.getValueType() != VT)
12547 // Return the new VECTOR_SHUFFLE node.
12551 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12557 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12558 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12559 EVT OpVT = N->getOperand(0).getValueType();
12561 // If the operands are legal vectors, leave them alone.
12562 if (TLI.isTypeLegal(OpVT))
12566 EVT VT = N->getValueType(0);
12567 SmallVector<SDValue, 8> Ops;
12569 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12570 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12572 // Keep track of what we encounter.
12573 bool AnyInteger = false;
12574 bool AnyFP = false;
12575 for (const SDValue &Op : N->ops()) {
12576 if (ISD::BITCAST == Op.getOpcode() &&
12577 !Op.getOperand(0).getValueType().isVector())
12578 Ops.push_back(Op.getOperand(0));
12579 else if (ISD::UNDEF == Op.getOpcode())
12580 Ops.push_back(ScalarUndef);
12584 // Note whether we encounter an integer or floating point scalar.
12585 // If it's neither, bail out, it could be something weird like x86mmx.
12586 EVT LastOpVT = Ops.back().getValueType();
12587 if (LastOpVT.isFloatingPoint())
12589 else if (LastOpVT.isInteger())
12595 // If any of the operands is a floating point scalar bitcast to a vector,
12596 // use floating point types throughout, and bitcast everything.
12597 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12599 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12600 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12602 for (SDValue &Op : Ops) {
12603 if (Op.getValueType() == SVT)
12605 if (Op.getOpcode() == ISD::UNDEF)
12608 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12613 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12614 VT.getSizeInBits() / SVT.getSizeInBits());
12615 return DAG.getNode(ISD::BITCAST, DL, VT,
12616 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12619 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12620 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12621 // most two distinct vectors the same size as the result, attempt to turn this
12622 // into a legal shuffle.
12623 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12624 EVT VT = N->getValueType(0);
12625 EVT OpVT = N->getOperand(0).getValueType();
12626 int NumElts = VT.getVectorNumElements();
12627 int NumOpElts = OpVT.getVectorNumElements();
12629 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12630 SmallVector<int, 8> Mask;
12632 for (SDValue Op : N->ops()) {
12633 // Peek through any bitcast.
12634 while (Op.getOpcode() == ISD::BITCAST)
12635 Op = Op.getOperand(0);
12637 // UNDEF nodes convert to UNDEF shuffle mask values.
12638 if (Op.getOpcode() == ISD::UNDEF) {
12639 Mask.append((unsigned)NumOpElts, -1);
12643 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12646 // What vector are we extracting the subvector from and at what index?
12647 SDValue ExtVec = Op.getOperand(0);
12649 // We want the EVT of the original extraction to correctly scale the
12650 // extraction index.
12651 EVT ExtVT = ExtVec.getValueType();
12653 // Peek through any bitcast.
12654 while (ExtVec.getOpcode() == ISD::BITCAST)
12655 ExtVec = ExtVec.getOperand(0);
12657 // UNDEF nodes convert to UNDEF shuffle mask values.
12658 if (ExtVec.getOpcode() == ISD::UNDEF) {
12659 Mask.append((unsigned)NumOpElts, -1);
12663 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12665 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12667 // Ensure that we are extracting a subvector from a vector the same
12668 // size as the result.
12669 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12672 // Scale the subvector index to account for any bitcast.
12673 int NumExtElts = ExtVT.getVectorNumElements();
12674 if (0 == (NumExtElts % NumElts))
12675 ExtIdx /= (NumExtElts / NumElts);
12676 else if (0 == (NumElts % NumExtElts))
12677 ExtIdx *= (NumElts / NumExtElts);
12681 // At most we can reference 2 inputs in the final shuffle.
12682 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12684 for (int i = 0; i != NumOpElts; ++i)
12685 Mask.push_back(i + ExtIdx);
12686 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12688 for (int i = 0; i != NumOpElts; ++i)
12689 Mask.push_back(i + ExtIdx + NumElts);
12695 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12698 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12699 DAG.getBitcast(VT, SV1), Mask);
12702 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12703 // If we only have one input vector, we don't need to do any concatenation.
12704 if (N->getNumOperands() == 1)
12705 return N->getOperand(0);
12707 // Check if all of the operands are undefs.
12708 EVT VT = N->getValueType(0);
12709 if (ISD::allOperandsUndef(N))
12710 return DAG.getUNDEF(VT);
12712 // Optimize concat_vectors where all but the first of the vectors are undef.
12713 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12714 return Op.getOpcode() == ISD::UNDEF;
12716 SDValue In = N->getOperand(0);
12717 assert(In.getValueType().isVector() && "Must concat vectors");
12719 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12720 if (In->getOpcode() == ISD::BITCAST &&
12721 !In->getOperand(0)->getValueType(0).isVector()) {
12722 SDValue Scalar = In->getOperand(0);
12724 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12725 // look through the trunc so we can still do the transform:
12726 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12727 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12728 !TLI.isTypeLegal(Scalar.getValueType()) &&
12729 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12730 Scalar = Scalar->getOperand(0);
12732 EVT SclTy = Scalar->getValueType(0);
12734 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12737 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12738 VT.getSizeInBits() / SclTy.getSizeInBits());
12739 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12742 SDLoc dl = SDLoc(N);
12743 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12744 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12748 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12749 // We have already tested above for an UNDEF only concatenation.
12750 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12751 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12752 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12753 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12755 bool AllBuildVectorsOrUndefs =
12756 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12757 if (AllBuildVectorsOrUndefs) {
12758 SmallVector<SDValue, 8> Opnds;
12759 EVT SVT = VT.getScalarType();
12762 if (!SVT.isFloatingPoint()) {
12763 // If BUILD_VECTOR are from built from integer, they may have different
12764 // operand types. Get the smallest type and truncate all operands to it.
12765 bool FoundMinVT = false;
12766 for (const SDValue &Op : N->ops())
12767 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12768 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12769 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12772 assert(FoundMinVT && "Concat vector type mismatch");
12775 for (const SDValue &Op : N->ops()) {
12776 EVT OpVT = Op.getValueType();
12777 unsigned NumElts = OpVT.getVectorNumElements();
12779 if (ISD::UNDEF == Op.getOpcode())
12780 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12782 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12783 if (SVT.isFloatingPoint()) {
12784 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12785 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12787 for (unsigned i = 0; i != NumElts; ++i)
12789 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12794 assert(VT.getVectorNumElements() == Opnds.size() &&
12795 "Concat vector type mismatch");
12796 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12799 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12800 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12803 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12804 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12805 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12808 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12809 // nodes often generate nop CONCAT_VECTOR nodes.
12810 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12811 // place the incoming vectors at the exact same location.
12812 SDValue SingleSource = SDValue();
12813 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12815 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12816 SDValue Op = N->getOperand(i);
12818 if (Op.getOpcode() == ISD::UNDEF)
12821 // Check if this is the identity extract:
12822 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12825 // Find the single incoming vector for the extract_subvector.
12826 if (SingleSource.getNode()) {
12827 if (Op.getOperand(0) != SingleSource)
12830 SingleSource = Op.getOperand(0);
12832 // Check the source type is the same as the type of the result.
12833 // If not, this concat may extend the vector, so we can not
12834 // optimize it away.
12835 if (SingleSource.getValueType() != N->getValueType(0))
12839 unsigned IdentityIndex = i * PartNumElem;
12840 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12841 // The extract index must be constant.
12845 // Check that we are reading from the identity index.
12846 if (CS->getZExtValue() != IdentityIndex)
12850 if (SingleSource.getNode())
12851 return SingleSource;
12856 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12857 EVT NVT = N->getValueType(0);
12858 SDValue V = N->getOperand(0);
12860 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12862 // (extract_subvec (concat V1, V2, ...), i)
12865 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12867 if (V->getOperand(0).getValueType() != NVT)
12869 unsigned Idx = N->getConstantOperandVal(1);
12870 unsigned NumElems = NVT.getVectorNumElements();
12871 assert((Idx % NumElems) == 0 &&
12872 "IDX in concat is not a multiple of the result vector length.");
12873 return V->getOperand(Idx / NumElems);
12877 if (V->getOpcode() == ISD::BITCAST)
12878 V = V.getOperand(0);
12880 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12882 // Handle only simple case where vector being inserted and vector
12883 // being extracted are of same type, and are half size of larger vectors.
12884 EVT BigVT = V->getOperand(0).getValueType();
12885 EVT SmallVT = V->getOperand(1).getValueType();
12886 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12889 // Only handle cases where both indexes are constants with the same type.
12890 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12891 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12893 if (InsIdx && ExtIdx &&
12894 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12895 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12897 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12899 // indices are equal or bit offsets are equal => V1
12900 // otherwise => (extract_subvec V1, ExtIdx)
12901 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12902 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12903 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12904 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12905 DAG.getNode(ISD::BITCAST, dl,
12906 N->getOperand(0).getValueType(),
12907 V->getOperand(0)), N->getOperand(1));
12914 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12915 SDValue V, SelectionDAG &DAG) {
12917 EVT VT = V.getValueType();
12919 switch (V.getOpcode()) {
12923 case ISD::CONCAT_VECTORS: {
12924 EVT OpVT = V->getOperand(0).getValueType();
12925 int OpSize = OpVT.getVectorNumElements();
12926 SmallBitVector OpUsedElements(OpSize, false);
12927 bool FoundSimplification = false;
12928 SmallVector<SDValue, 4> NewOps;
12929 NewOps.reserve(V->getNumOperands());
12930 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12931 SDValue Op = V->getOperand(i);
12932 bool OpUsed = false;
12933 for (int j = 0; j < OpSize; ++j)
12934 if (UsedElements[i * OpSize + j]) {
12935 OpUsedElements[j] = true;
12939 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12940 : DAG.getUNDEF(OpVT));
12941 FoundSimplification |= Op == NewOps.back();
12942 OpUsedElements.reset();
12944 if (FoundSimplification)
12945 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12949 case ISD::INSERT_SUBVECTOR: {
12950 SDValue BaseV = V->getOperand(0);
12951 SDValue SubV = V->getOperand(1);
12952 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12956 int SubSize = SubV.getValueType().getVectorNumElements();
12957 int Idx = IdxN->getZExtValue();
12958 bool SubVectorUsed = false;
12959 SmallBitVector SubUsedElements(SubSize, false);
12960 for (int i = 0; i < SubSize; ++i)
12961 if (UsedElements[i + Idx]) {
12962 SubVectorUsed = true;
12963 SubUsedElements[i] = true;
12964 UsedElements[i + Idx] = false;
12967 // Now recurse on both the base and sub vectors.
12968 SDValue SimplifiedSubV =
12970 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12971 : DAG.getUNDEF(SubV.getValueType());
12972 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12973 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12974 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12975 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12981 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12982 SDValue N1, SelectionDAG &DAG) {
12983 EVT VT = SVN->getValueType(0);
12984 int NumElts = VT.getVectorNumElements();
12985 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12986 for (int M : SVN->getMask())
12987 if (M >= 0 && M < NumElts)
12988 N0UsedElements[M] = true;
12989 else if (M >= NumElts)
12990 N1UsedElements[M - NumElts] = true;
12992 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12993 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12994 if (S0 == N0 && S1 == N1)
12997 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13000 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13001 // or turn a shuffle of a single concat into simpler shuffle then concat.
13002 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13003 EVT VT = N->getValueType(0);
13004 unsigned NumElts = VT.getVectorNumElements();
13006 SDValue N0 = N->getOperand(0);
13007 SDValue N1 = N->getOperand(1);
13008 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13010 SmallVector<SDValue, 4> Ops;
13011 EVT ConcatVT = N0.getOperand(0).getValueType();
13012 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13013 unsigned NumConcats = NumElts / NumElemsPerConcat;
13015 // Special case: shuffle(concat(A,B)) can be more efficiently represented
13016 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13017 // half vector elements.
13018 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
13019 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13020 SVN->getMask().end(), [](int i) { return i == -1; })) {
13021 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13022 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13023 N1 = DAG.getUNDEF(ConcatVT);
13024 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13027 // Look at every vector that's inserted. We're looking for exact
13028 // subvector-sized copies from a concatenated vector
13029 for (unsigned I = 0; I != NumConcats; ++I) {
13030 // Make sure we're dealing with a copy.
13031 unsigned Begin = I * NumElemsPerConcat;
13032 bool AllUndef = true, NoUndef = true;
13033 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13034 if (SVN->getMaskElt(J) >= 0)
13041 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13044 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13045 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13048 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13049 if (FirstElt < N0.getNumOperands())
13050 Ops.push_back(N0.getOperand(FirstElt));
13052 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13054 } else if (AllUndef) {
13055 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13056 } else { // Mixed with general masks and undefs, can't do optimization.
13061 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13064 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13065 EVT VT = N->getValueType(0);
13066 unsigned NumElts = VT.getVectorNumElements();
13068 SDValue N0 = N->getOperand(0);
13069 SDValue N1 = N->getOperand(1);
13071 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13073 // Canonicalize shuffle undef, undef -> undef
13074 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13075 return DAG.getUNDEF(VT);
13077 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13079 // Canonicalize shuffle v, v -> v, undef
13081 SmallVector<int, 8> NewMask;
13082 for (unsigned i = 0; i != NumElts; ++i) {
13083 int Idx = SVN->getMaskElt(i);
13084 if (Idx >= (int)NumElts) Idx -= NumElts;
13085 NewMask.push_back(Idx);
13087 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13091 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
13092 if (N0.getOpcode() == ISD::UNDEF) {
13093 SmallVector<int, 8> NewMask;
13094 for (unsigned i = 0; i != NumElts; ++i) {
13095 int Idx = SVN->getMaskElt(i);
13097 if (Idx >= (int)NumElts)
13100 Idx = -1; // remove reference to lhs
13102 NewMask.push_back(Idx);
13104 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13108 // Remove references to rhs if it is undef
13109 if (N1.getOpcode() == ISD::UNDEF) {
13110 bool Changed = false;
13111 SmallVector<int, 8> NewMask;
13112 for (unsigned i = 0; i != NumElts; ++i) {
13113 int Idx = SVN->getMaskElt(i);
13114 if (Idx >= (int)NumElts) {
13118 NewMask.push_back(Idx);
13121 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13124 // If it is a splat, check if the argument vector is another splat or a
13126 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13127 SDNode *V = N0.getNode();
13129 // If this is a bit convert that changes the element type of the vector but
13130 // not the number of vector elements, look through it. Be careful not to
13131 // look though conversions that change things like v4f32 to v2f64.
13132 if (V->getOpcode() == ISD::BITCAST) {
13133 SDValue ConvInput = V->getOperand(0);
13134 if (ConvInput.getValueType().isVector() &&
13135 ConvInput.getValueType().getVectorNumElements() == NumElts)
13136 V = ConvInput.getNode();
13139 if (V->getOpcode() == ISD::BUILD_VECTOR) {
13140 assert(V->getNumOperands() == NumElts &&
13141 "BUILD_VECTOR has wrong number of operands");
13143 bool AllSame = true;
13144 for (unsigned i = 0; i != NumElts; ++i) {
13145 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13146 Base = V->getOperand(i);
13150 // Splat of <u, u, u, u>, return <u, u, u, u>
13151 if (!Base.getNode())
13153 for (unsigned i = 0; i != NumElts; ++i) {
13154 if (V->getOperand(i) != Base) {
13159 // Splat of <x, x, x, x>, return <x, x, x, x>
13163 // Canonicalize any other splat as a build_vector.
13164 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13165 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13166 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13167 V->getValueType(0), Ops);
13169 // We may have jumped through bitcasts, so the type of the
13170 // BUILD_VECTOR may not match the type of the shuffle.
13171 if (V->getValueType(0) != VT)
13172 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13177 // There are various patterns used to build up a vector from smaller vectors,
13178 // subvectors, or elements. Scan chains of these and replace unused insertions
13179 // or components with undef.
13180 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13183 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13184 Level < AfterLegalizeVectorOps &&
13185 (N1.getOpcode() == ISD::UNDEF ||
13186 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13187 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13188 SDValue V = partitionShuffleOfConcats(N, DAG);
13194 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13195 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13196 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13197 SmallVector<SDValue, 8> Ops;
13198 for (int M : SVN->getMask()) {
13199 SDValue Op = DAG.getUNDEF(VT.getScalarType());
13201 int Idx = M % NumElts;
13202 SDValue &S = (M < (int)NumElts ? N0 : N1);
13203 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13204 Op = S.getOperand(Idx);
13205 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13207 Op = S.getOperand(0);
13209 // Operand can't be combined - bail out.
13215 if (Ops.size() == VT.getVectorNumElements()) {
13216 // BUILD_VECTOR requires all inputs to be of the same type, find the
13217 // maximum type and extend them all.
13218 EVT SVT = VT.getScalarType();
13219 if (SVT.isInteger())
13220 for (SDValue &Op : Ops)
13221 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13222 if (SVT != VT.getScalarType())
13223 for (SDValue &Op : Ops)
13224 Op = TLI.isZExtFree(Op.getValueType(), SVT)
13225 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13226 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13227 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13231 // If this shuffle only has a single input that is a bitcasted shuffle,
13232 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13233 // back to their original types.
13234 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13235 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13236 TLI.isTypeLegal(VT)) {
13238 // Peek through the bitcast only if there is one user.
13240 while (BC0.getOpcode() == ISD::BITCAST) {
13241 if (!BC0.hasOneUse())
13243 BC0 = BC0.getOperand(0);
13246 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13248 return SmallVector<int, 8>(Mask.begin(), Mask.end());
13250 SmallVector<int, 8> NewMask;
13252 for (int s = 0; s != Scale; ++s)
13253 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13257 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13258 EVT SVT = VT.getScalarType();
13259 EVT InnerVT = BC0->getValueType(0);
13260 EVT InnerSVT = InnerVT.getScalarType();
13262 // Determine which shuffle works with the smaller scalar type.
13263 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13264 EVT ScaleSVT = ScaleVT.getScalarType();
13266 if (TLI.isTypeLegal(ScaleVT) &&
13267 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13268 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13270 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13271 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13273 // Scale the shuffle masks to the smaller scalar type.
13274 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13275 SmallVector<int, 8> InnerMask =
13276 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13277 SmallVector<int, 8> OuterMask =
13278 ScaleShuffleMask(SVN->getMask(), OuterScale);
13280 // Merge the shuffle masks.
13281 SmallVector<int, 8> NewMask;
13282 for (int M : OuterMask)
13283 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13285 // Test for shuffle mask legality over both commutations.
13286 SDValue SV0 = BC0->getOperand(0);
13287 SDValue SV1 = BC0->getOperand(1);
13288 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13290 std::swap(SV0, SV1);
13291 ShuffleVectorSDNode::commuteMask(NewMask);
13292 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13296 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13297 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13298 return DAG.getNode(
13299 ISD::BITCAST, SDLoc(N), VT,
13300 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13306 // Canonicalize shuffles according to rules:
13307 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13308 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13309 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13310 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13311 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13312 TLI.isTypeLegal(VT)) {
13313 // The incoming shuffle must be of the same type as the result of the
13314 // current shuffle.
13315 assert(N1->getOperand(0).getValueType() == VT &&
13316 "Shuffle types don't match");
13318 SDValue SV0 = N1->getOperand(0);
13319 SDValue SV1 = N1->getOperand(1);
13320 bool HasSameOp0 = N0 == SV0;
13321 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13322 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13323 // Commute the operands of this shuffle so that next rule
13325 return DAG.getCommutedVectorShuffle(*SVN);
13328 // Try to fold according to rules:
13329 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13330 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13331 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13332 // Don't try to fold shuffles with illegal type.
13333 // Only fold if this shuffle is the only user of the other shuffle.
13334 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13335 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13336 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13338 // The incoming shuffle must be of the same type as the result of the
13339 // current shuffle.
13340 assert(OtherSV->getOperand(0).getValueType() == VT &&
13341 "Shuffle types don't match");
13344 SmallVector<int, 4> Mask;
13345 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13346 // operand, and SV1 as the second operand.
13347 for (unsigned i = 0; i != NumElts; ++i) {
13348 int Idx = SVN->getMaskElt(i);
13350 // Propagate Undef.
13351 Mask.push_back(Idx);
13355 SDValue CurrentVec;
13356 if (Idx < (int)NumElts) {
13357 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13358 // shuffle mask to identify which vector is actually referenced.
13359 Idx = OtherSV->getMaskElt(Idx);
13361 // Propagate Undef.
13362 Mask.push_back(Idx);
13366 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13367 : OtherSV->getOperand(1);
13369 // This shuffle index references an element within N1.
13373 // Simple case where 'CurrentVec' is UNDEF.
13374 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13375 Mask.push_back(-1);
13379 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13380 // will be the first or second operand of the combined shuffle.
13381 Idx = Idx % NumElts;
13382 if (!SV0.getNode() || SV0 == CurrentVec) {
13383 // Ok. CurrentVec is the left hand side.
13384 // Update the mask accordingly.
13386 Mask.push_back(Idx);
13390 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13391 if (SV1.getNode() && SV1 != CurrentVec)
13394 // Ok. CurrentVec is the right hand side.
13395 // Update the mask accordingly.
13397 Mask.push_back(Idx + NumElts);
13400 // Check if all indices in Mask are Undef. In case, propagate Undef.
13401 bool isUndefMask = true;
13402 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13403 isUndefMask &= Mask[i] < 0;
13406 return DAG.getUNDEF(VT);
13408 if (!SV0.getNode())
13409 SV0 = DAG.getUNDEF(VT);
13410 if (!SV1.getNode())
13411 SV1 = DAG.getUNDEF(VT);
13413 // Avoid introducing shuffles with illegal mask.
13414 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13415 ShuffleVectorSDNode::commuteMask(Mask);
13417 if (!TLI.isShuffleMaskLegal(Mask, VT))
13420 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13421 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13422 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13423 std::swap(SV0, SV1);
13426 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13427 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13428 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13429 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13435 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13436 SDValue InVal = N->getOperand(0);
13437 EVT VT = N->getValueType(0);
13439 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13440 // with a VECTOR_SHUFFLE.
13441 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13442 SDValue InVec = InVal->getOperand(0);
13443 SDValue EltNo = InVal->getOperand(1);
13445 // FIXME: We could support implicit truncation if the shuffle can be
13446 // scaled to a smaller vector scalar type.
13447 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13448 if (C0 && VT == InVec.getValueType() &&
13449 VT.getScalarType() == InVal.getValueType()) {
13450 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13451 int Elt = C0->getZExtValue();
13454 if (TLI.isShuffleMaskLegal(NewMask, VT))
13455 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13463 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13464 SDValue N0 = N->getOperand(0);
13465 SDValue N2 = N->getOperand(2);
13467 // If the input vector is a concatenation, and the insert replaces
13468 // one of the halves, we can optimize into a single concat_vectors.
13469 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13470 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13471 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13472 EVT VT = N->getValueType(0);
13474 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13475 // (concat_vectors Z, Y)
13477 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13478 N->getOperand(1), N0.getOperand(1));
13480 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13481 // (concat_vectors X, Z)
13482 if (InsIdx == VT.getVectorNumElements()/2)
13483 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13484 N0.getOperand(0), N->getOperand(1));
13490 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13491 SDValue N0 = N->getOperand(0);
13493 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13494 if (N0->getOpcode() == ISD::FP16_TO_FP)
13495 return N0->getOperand(0);
13500 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13501 SDValue N0 = N->getOperand(0);
13503 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13504 if (N0->getOpcode() == ISD::AND) {
13505 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13506 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13507 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13515 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13516 /// with the destination vector and a zero vector.
13517 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13518 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13519 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13520 EVT VT = N->getValueType(0);
13521 SDValue LHS = N->getOperand(0);
13522 SDValue RHS = N->getOperand(1);
13525 // Make sure we're not running after operation legalization where it
13526 // may have custom lowered the vector shuffles.
13527 if (LegalOperations)
13530 if (N->getOpcode() != ISD::AND)
13533 if (RHS.getOpcode() == ISD::BITCAST)
13534 RHS = RHS.getOperand(0);
13536 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13539 EVT RVT = RHS.getValueType();
13540 unsigned NumElts = RHS.getNumOperands();
13542 // Attempt to create a valid clear mask, splitting the mask into
13543 // sub elements and checking to see if each is
13544 // all zeros or all ones - suitable for shuffle masking.
13545 auto BuildClearMask = [&](int Split) {
13546 int NumSubElts = NumElts * Split;
13547 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13549 SmallVector<int, 8> Indices;
13550 for (int i = 0; i != NumSubElts; ++i) {
13551 int EltIdx = i / Split;
13552 int SubIdx = i % Split;
13553 SDValue Elt = RHS.getOperand(EltIdx);
13554 if (Elt.getOpcode() == ISD::UNDEF) {
13555 Indices.push_back(-1);
13560 if (isa<ConstantSDNode>(Elt))
13561 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13562 else if (isa<ConstantFPSDNode>(Elt))
13563 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13567 // Extract the sub element from the constant bit mask.
13568 if (DAG.getDataLayout().isBigEndian()) {
13569 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13571 Bits = Bits.lshr(SubIdx * NumSubBits);
13575 Bits = Bits.trunc(NumSubBits);
13577 if (Bits.isAllOnesValue())
13578 Indices.push_back(i);
13579 else if (Bits == 0)
13580 Indices.push_back(i + NumSubElts);
13585 // Let's see if the target supports this vector_shuffle.
13586 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13587 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13588 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13591 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13592 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13593 DAG.getBitcast(ClearVT, LHS),
13594 Zero, &Indices[0]));
13597 // Determine maximum split level (byte level masking).
13599 if (RVT.getScalarSizeInBits() % 8 == 0)
13600 MaxSplit = RVT.getScalarSizeInBits() / 8;
13602 for (int Split = 1; Split <= MaxSplit; ++Split)
13603 if (RVT.getScalarSizeInBits() % Split == 0)
13604 if (SDValue S = BuildClearMask(Split))
13610 /// Visit a binary vector operation, like ADD.
13611 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13612 assert(N->getValueType(0).isVector() &&
13613 "SimplifyVBinOp only works on vectors!");
13615 SDValue LHS = N->getOperand(0);
13616 SDValue RHS = N->getOperand(1);
13617 SDValue Ops[] = {LHS, RHS};
13619 // See if we can constant fold the vector operation.
13620 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13621 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13624 // Try to convert a constant mask AND into a shuffle clear mask.
13625 if (SDValue Shuffle = XformToShuffleWithZero(N))
13628 // Type legalization might introduce new shuffles in the DAG.
13629 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13630 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13631 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13632 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13633 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13634 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13635 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13636 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13638 if (SVN0->getMask().equals(SVN1->getMask())) {
13639 EVT VT = N->getValueType(0);
13640 SDValue UndefVector = LHS.getOperand(1);
13641 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13642 LHS.getOperand(0), RHS.getOperand(0),
13644 AddUsersToWorklist(N);
13645 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13646 &SVN0->getMask()[0]);
13653 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13654 SDValue N1, SDValue N2){
13655 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13657 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13658 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13660 // If we got a simplified select_cc node back from SimplifySelectCC, then
13661 // break it down into a new SETCC node, and a new SELECT node, and then return
13662 // the SELECT node, since we were called with a SELECT node.
13663 if (SCC.getNode()) {
13664 // Check to see if we got a select_cc back (to turn into setcc/select).
13665 // Otherwise, just return whatever node we got back, like fabs.
13666 if (SCC.getOpcode() == ISD::SELECT_CC) {
13667 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13669 SCC.getOperand(0), SCC.getOperand(1),
13670 SCC.getOperand(4));
13671 AddToWorklist(SETCC.getNode());
13672 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13673 SCC.getOperand(2), SCC.getOperand(3));
13681 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13682 /// being selected between, see if we can simplify the select. Callers of this
13683 /// should assume that TheSelect is deleted if this returns true. As such, they
13684 /// should return the appropriate thing (e.g. the node) back to the top-level of
13685 /// the DAG combiner loop to avoid it being looked at.
13686 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13689 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13690 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13691 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13692 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13693 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13694 SDValue Sqrt = RHS;
13697 const ConstantFPSDNode *NegZero = nullptr;
13699 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13700 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13701 CmpLHS = TheSelect->getOperand(0);
13702 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13704 // SELECT or VSELECT
13705 SDValue Cmp = TheSelect->getOperand(0);
13706 if (Cmp.getOpcode() == ISD::SETCC) {
13707 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13708 CmpLHS = Cmp.getOperand(0);
13709 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13712 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13713 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13714 CC == ISD::SETULT || CC == ISD::SETLT)) {
13715 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13716 CombineTo(TheSelect, Sqrt);
13721 // Cannot simplify select with vector condition
13722 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13724 // If this is a select from two identical things, try to pull the operation
13725 // through the select.
13726 if (LHS.getOpcode() != RHS.getOpcode() ||
13727 !LHS.hasOneUse() || !RHS.hasOneUse())
13730 // If this is a load and the token chain is identical, replace the select
13731 // of two loads with a load through a select of the address to load from.
13732 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13733 // constants have been dropped into the constant pool.
13734 if (LHS.getOpcode() == ISD::LOAD) {
13735 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13736 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13738 // Token chains must be identical.
13739 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13740 // Do not let this transformation reduce the number of volatile loads.
13741 LLD->isVolatile() || RLD->isVolatile() ||
13742 // FIXME: If either is a pre/post inc/dec load,
13743 // we'd need to split out the address adjustment.
13744 LLD->isIndexed() || RLD->isIndexed() ||
13745 // If this is an EXTLOAD, the VT's must match.
13746 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13747 // If this is an EXTLOAD, the kind of extension must match.
13748 (LLD->getExtensionType() != RLD->getExtensionType() &&
13749 // The only exception is if one of the extensions is anyext.
13750 LLD->getExtensionType() != ISD::EXTLOAD &&
13751 RLD->getExtensionType() != ISD::EXTLOAD) ||
13752 // FIXME: this discards src value information. This is
13753 // over-conservative. It would be beneficial to be able to remember
13754 // both potential memory locations. Since we are discarding
13755 // src value info, don't do the transformation if the memory
13756 // locations are not in the default address space.
13757 LLD->getPointerInfo().getAddrSpace() != 0 ||
13758 RLD->getPointerInfo().getAddrSpace() != 0 ||
13759 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13760 LLD->getBasePtr().getValueType()))
13763 // Check that the select condition doesn't reach either load. If so,
13764 // folding this will induce a cycle into the DAG. If not, this is safe to
13765 // xform, so create a select of the addresses.
13767 if (TheSelect->getOpcode() == ISD::SELECT) {
13768 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13769 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13770 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13772 // The loads must not depend on one another.
13773 if (LLD->isPredecessorOf(RLD) ||
13774 RLD->isPredecessorOf(LLD))
13776 Addr = DAG.getSelect(SDLoc(TheSelect),
13777 LLD->getBasePtr().getValueType(),
13778 TheSelect->getOperand(0), LLD->getBasePtr(),
13779 RLD->getBasePtr());
13780 } else { // Otherwise SELECT_CC
13781 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13782 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13784 if ((LLD->hasAnyUseOfValue(1) &&
13785 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13786 (RLD->hasAnyUseOfValue(1) &&
13787 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13790 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13791 LLD->getBasePtr().getValueType(),
13792 TheSelect->getOperand(0),
13793 TheSelect->getOperand(1),
13794 LLD->getBasePtr(), RLD->getBasePtr(),
13795 TheSelect->getOperand(4));
13799 // It is safe to replace the two loads if they have different alignments,
13800 // but the new load must be the minimum (most restrictive) alignment of the
13802 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13803 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13804 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13805 Load = DAG.getLoad(TheSelect->getValueType(0),
13807 // FIXME: Discards pointer and AA info.
13808 LLD->getChain(), Addr, MachinePointerInfo(),
13809 LLD->isVolatile(), LLD->isNonTemporal(),
13810 isInvariant, Alignment);
13812 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13813 RLD->getExtensionType() : LLD->getExtensionType(),
13815 TheSelect->getValueType(0),
13816 // FIXME: Discards pointer and AA info.
13817 LLD->getChain(), Addr, MachinePointerInfo(),
13818 LLD->getMemoryVT(), LLD->isVolatile(),
13819 LLD->isNonTemporal(), isInvariant, Alignment);
13822 // Users of the select now use the result of the load.
13823 CombineTo(TheSelect, Load);
13825 // Users of the old loads now use the new load's chain. We know the
13826 // old-load value is dead now.
13827 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13828 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13835 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13836 /// where 'cond' is the comparison specified by CC.
13837 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13838 SDValue N2, SDValue N3,
13839 ISD::CondCode CC, bool NotExtCompare) {
13840 // (x ? y : y) -> y.
13841 if (N2 == N3) return N2;
13843 EVT VT = N2.getValueType();
13844 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13845 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13847 // Determine if the condition we're dealing with is constant
13848 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13849 N0, N1, CC, DL, false);
13850 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13852 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13853 // fold select_cc true, x, y -> x
13854 // fold select_cc false, x, y -> y
13855 return !SCCC->isNullValue() ? N2 : N3;
13858 // Check to see if we can simplify the select into an fabs node
13859 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13860 // Allow either -0.0 or 0.0
13861 if (CFP->isZero()) {
13862 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13863 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13864 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13865 N2 == N3.getOperand(0))
13866 return DAG.getNode(ISD::FABS, DL, VT, N0);
13868 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13869 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13870 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13871 N2.getOperand(0) == N3)
13872 return DAG.getNode(ISD::FABS, DL, VT, N3);
13876 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13877 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13878 // in it. This is a win when the constant is not otherwise available because
13879 // it replaces two constant pool loads with one. We only do this if the FP
13880 // type is known to be legal, because if it isn't, then we are before legalize
13881 // types an we want the other legalization to happen first (e.g. to avoid
13882 // messing with soft float) and if the ConstantFP is not legal, because if
13883 // it is legal, we may not need to store the FP constant in a constant pool.
13884 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13885 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13886 if (TLI.isTypeLegal(N2.getValueType()) &&
13887 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13888 TargetLowering::Legal &&
13889 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13890 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13891 // If both constants have multiple uses, then we won't need to do an
13892 // extra load, they are likely around in registers for other users.
13893 (TV->hasOneUse() || FV->hasOneUse())) {
13894 Constant *Elts[] = {
13895 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13896 const_cast<ConstantFP*>(TV->getConstantFPValue())
13898 Type *FPTy = Elts[0]->getType();
13899 const DataLayout &TD = DAG.getDataLayout();
13901 // Create a ConstantArray of the two constants.
13902 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13904 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13905 TD.getPrefTypeAlignment(FPTy));
13906 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13908 // Get the offsets to the 0 and 1 element of the array so that we can
13909 // select between them.
13910 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13911 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13912 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13914 SDValue Cond = DAG.getSetCC(DL,
13915 getSetCCResultType(N0.getValueType()),
13917 AddToWorklist(Cond.getNode());
13918 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13920 AddToWorklist(CstOffset.getNode());
13921 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13923 AddToWorklist(CPIdx.getNode());
13924 return DAG.getLoad(
13925 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13926 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13927 false, false, false, Alignment);
13931 // Check to see if we can perform the "gzip trick", transforming
13932 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13933 if (isNullConstant(N3) && CC == ISD::SETLT &&
13934 (isNullConstant(N1) || // (a < 0) ? b : 0
13935 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13936 EVT XType = N0.getValueType();
13937 EVT AType = N2.getValueType();
13938 if (XType.bitsGE(AType)) {
13939 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13940 // single-bit constant.
13941 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13942 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13943 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13944 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13945 getShiftAmountTy(N0.getValueType()));
13946 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13948 AddToWorklist(Shift.getNode());
13950 if (XType.bitsGT(AType)) {
13951 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13952 AddToWorklist(Shift.getNode());
13955 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13958 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13960 DAG.getConstant(XType.getSizeInBits() - 1,
13962 getShiftAmountTy(N0.getValueType())));
13963 AddToWorklist(Shift.getNode());
13965 if (XType.bitsGT(AType)) {
13966 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13967 AddToWorklist(Shift.getNode());
13970 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13974 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13975 // where y is has a single bit set.
13976 // A plaintext description would be, we can turn the SELECT_CC into an AND
13977 // when the condition can be materialized as an all-ones register. Any
13978 // single bit-test can be materialized as an all-ones register with
13979 // shift-left and shift-right-arith.
13980 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13981 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13982 SDValue AndLHS = N0->getOperand(0);
13983 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13984 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13985 // Shift the tested bit over the sign bit.
13986 APInt AndMask = ConstAndRHS->getAPIntValue();
13988 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13989 getShiftAmountTy(AndLHS.getValueType()));
13990 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13992 // Now arithmetic right shift it all the way over, so the result is either
13993 // all-ones, or zero.
13995 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13996 getShiftAmountTy(Shl.getValueType()));
13997 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13999 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14003 // fold select C, 16, 0 -> shl C, 4
14004 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14005 TLI.getBooleanContents(N0.getValueType()) ==
14006 TargetLowering::ZeroOrOneBooleanContent) {
14008 // If the caller doesn't want us to simplify this into a zext of a compare,
14010 if (NotExtCompare && N2C->isOne())
14013 // Get a SetCC of the condition
14014 // NOTE: Don't create a SETCC if it's not legal on this target.
14015 if (!LegalOperations ||
14016 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14018 // cast from setcc result type to select result type
14020 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14022 if (N2.getValueType().bitsLT(SCC.getValueType()))
14023 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14024 N2.getValueType());
14026 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14027 N2.getValueType(), SCC);
14029 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14030 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14031 N2.getValueType(), SCC);
14034 AddToWorklist(SCC.getNode());
14035 AddToWorklist(Temp.getNode());
14040 // shl setcc result by log2 n2c
14041 return DAG.getNode(
14042 ISD::SHL, DL, N2.getValueType(), Temp,
14043 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14044 getShiftAmountTy(Temp.getValueType())));
14048 // Check to see if this is an integer abs.
14049 // select_cc setg[te] X, 0, X, -X ->
14050 // select_cc setgt X, -1, X, -X ->
14051 // select_cc setl[te] X, 0, -X, X ->
14052 // select_cc setlt X, 1, -X, X ->
14053 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14055 ConstantSDNode *SubC = nullptr;
14056 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14057 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14058 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14059 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14060 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14061 (N1C->isOne() && CC == ISD::SETLT)) &&
14062 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14063 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14065 EVT XType = N0.getValueType();
14066 if (SubC && SubC->isNullValue() && XType.isInteger()) {
14068 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14070 DAG.getConstant(XType.getSizeInBits() - 1, DL,
14071 getShiftAmountTy(N0.getValueType())));
14072 SDValue Add = DAG.getNode(ISD::ADD, DL,
14074 AddToWorklist(Shift.getNode());
14075 AddToWorklist(Add.getNode());
14076 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14083 /// This is a stub for TargetLowering::SimplifySetCC.
14084 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14085 SDValue N1, ISD::CondCode Cond,
14086 SDLoc DL, bool foldBooleans) {
14087 TargetLowering::DAGCombinerInfo
14088 DagCombineInfo(DAG, Level, false, this);
14089 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14092 /// Given an ISD::SDIV node expressing a divide by constant, return
14093 /// a DAG expression to select that will generate the same value by multiplying
14094 /// by a magic number.
14095 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14096 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14097 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14101 // Avoid division by zero.
14102 if (C->isNullValue())
14105 std::vector<SDNode*> Built;
14107 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14109 for (SDNode *N : Built)
14114 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14115 /// DAG expression that will generate the same value by right shifting.
14116 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14117 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14121 // Avoid division by zero.
14122 if (C->isNullValue())
14125 std::vector<SDNode *> Built;
14126 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14128 for (SDNode *N : Built)
14133 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14134 /// expression that will generate the same value by multiplying by a magic
14136 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14137 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14138 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14142 // Avoid division by zero.
14143 if (C->isNullValue())
14146 std::vector<SDNode*> Built;
14148 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14150 for (SDNode *N : Built)
14155 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14156 if (Level >= AfterLegalizeDAG)
14159 // Expose the DAG combiner to the target combiner implementations.
14160 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14162 unsigned Iterations = 0;
14163 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14165 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14166 // For the reciprocal, we need to find the zero of the function:
14167 // F(X) = A X - 1 [which has a zero at X = 1/A]
14169 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14170 // does not require additional intermediate precision]
14171 EVT VT = Op.getValueType();
14173 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14175 AddToWorklist(Est.getNode());
14177 // Newton iterations: Est = Est + Est (1 - Arg * Est)
14178 for (unsigned i = 0; i < Iterations; ++i) {
14179 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14180 AddToWorklist(NewEst.getNode());
14182 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14183 AddToWorklist(NewEst.getNode());
14185 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14186 AddToWorklist(NewEst.getNode());
14188 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14189 AddToWorklist(Est.getNode());
14198 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14199 /// For the reciprocal sqrt, we need to find the zero of the function:
14200 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14202 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14203 /// As a result, we precompute A/2 prior to the iteration loop.
14204 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14205 unsigned Iterations,
14206 SDNodeFlags *Flags) {
14207 EVT VT = Arg.getValueType();
14209 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14211 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14212 // this entire sequence requires only one FP constant.
14213 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14214 AddToWorklist(HalfArg.getNode());
14216 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14217 AddToWorklist(HalfArg.getNode());
14219 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14220 for (unsigned i = 0; i < Iterations; ++i) {
14221 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14222 AddToWorklist(NewEst.getNode());
14224 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14225 AddToWorklist(NewEst.getNode());
14227 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14228 AddToWorklist(NewEst.getNode());
14230 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14231 AddToWorklist(Est.getNode());
14236 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14237 /// For the reciprocal sqrt, we need to find the zero of the function:
14238 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14240 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14241 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14242 unsigned Iterations,
14243 SDNodeFlags *Flags) {
14244 EVT VT = Arg.getValueType();
14246 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14247 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14249 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14250 for (unsigned i = 0; i < Iterations; ++i) {
14251 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14252 AddToWorklist(HalfEst.getNode());
14254 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14255 AddToWorklist(Est.getNode());
14257 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14258 AddToWorklist(Est.getNode());
14260 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14261 AddToWorklist(Est.getNode());
14263 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14264 AddToWorklist(Est.getNode());
14269 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14270 if (Level >= AfterLegalizeDAG)
14273 // Expose the DAG combiner to the target combiner implementations.
14274 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14275 unsigned Iterations = 0;
14276 bool UseOneConstNR = false;
14277 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14278 AddToWorklist(Est.getNode());
14280 Est = UseOneConstNR ?
14281 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14282 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14290 /// Return true if base is a frame index, which is known not to alias with
14291 /// anything but itself. Provides base object and offset as results.
14292 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14293 const GlobalValue *&GV, const void *&CV) {
14294 // Assume it is a primitive operation.
14295 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14297 // If it's an adding a simple constant then integrate the offset.
14298 if (Base.getOpcode() == ISD::ADD) {
14299 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14300 Base = Base.getOperand(0);
14301 Offset += C->getZExtValue();
14305 // Return the underlying GlobalValue, and update the Offset. Return false
14306 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14307 // by multiple nodes with different offsets.
14308 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14309 GV = G->getGlobal();
14310 Offset += G->getOffset();
14314 // Return the underlying Constant value, and update the Offset. Return false
14315 // for ConstantSDNodes since the same constant pool entry may be represented
14316 // by multiple nodes with different offsets.
14317 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14318 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14319 : (const void *)C->getConstVal();
14320 Offset += C->getOffset();
14323 // If it's any of the following then it can't alias with anything but itself.
14324 return isa<FrameIndexSDNode>(Base);
14327 /// Return true if there is any possibility that the two addresses overlap.
14328 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14329 // If they are the same then they must be aliases.
14330 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14332 // If they are both volatile then they cannot be reordered.
14333 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14335 // If one operation reads from invariant memory, and the other may store, they
14336 // cannot alias. These should really be checking the equivalent of mayWrite,
14337 // but it only matters for memory nodes other than load /store.
14338 if (Op0->isInvariant() && Op1->writeMem())
14341 if (Op1->isInvariant() && Op0->writeMem())
14344 // Gather base node and offset information.
14345 SDValue Base1, Base2;
14346 int64_t Offset1, Offset2;
14347 const GlobalValue *GV1, *GV2;
14348 const void *CV1, *CV2;
14349 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14350 Base1, Offset1, GV1, CV1);
14351 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14352 Base2, Offset2, GV2, CV2);
14354 // If they have a same base address then check to see if they overlap.
14355 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14356 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14357 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14359 // It is possible for different frame indices to alias each other, mostly
14360 // when tail call optimization reuses return address slots for arguments.
14361 // To catch this case, look up the actual index of frame indices to compute
14362 // the real alias relationship.
14363 if (isFrameIndex1 && isFrameIndex2) {
14364 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14365 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14366 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14367 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14368 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14371 // Otherwise, if we know what the bases are, and they aren't identical, then
14372 // we know they cannot alias.
14373 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14376 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14377 // compared to the size and offset of the access, we may be able to prove they
14378 // do not alias. This check is conservative for now to catch cases created by
14379 // splitting vector types.
14380 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14381 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14382 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14383 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14384 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14385 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14386 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14388 // There is no overlap between these relatively aligned accesses of similar
14389 // size, return no alias.
14390 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14391 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14395 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14397 : DAG.getSubtarget().useAA();
14399 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14400 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14404 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14405 // Use alias analysis information.
14406 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14407 Op1->getSrcValueOffset());
14408 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14409 Op0->getSrcValueOffset() - MinOffset;
14410 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14411 Op1->getSrcValueOffset() - MinOffset;
14412 AliasResult AAResult =
14413 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14414 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14415 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14416 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14417 if (AAResult == NoAlias)
14421 // Otherwise we have to assume they alias.
14425 /// Walk up chain skipping non-aliasing memory nodes,
14426 /// looking for aliasing nodes and adding them to the Aliases vector.
14427 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14428 SmallVectorImpl<SDValue> &Aliases) {
14429 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14430 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14432 // Get alias information for node.
14433 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14436 Chains.push_back(OriginalChain);
14437 unsigned Depth = 0;
14439 // Look at each chain and determine if it is an alias. If so, add it to the
14440 // aliases list. If not, then continue up the chain looking for the next
14442 while (!Chains.empty()) {
14443 SDValue Chain = Chains.pop_back_val();
14445 // For TokenFactor nodes, look at each operand and only continue up the
14446 // chain until we reach the depth limit.
14448 // FIXME: The depth check could be made to return the last non-aliasing
14449 // chain we found before we hit a tokenfactor rather than the original
14453 Aliases.push_back(OriginalChain);
14457 // Don't bother if we've been before.
14458 if (!Visited.insert(Chain.getNode()).second)
14461 switch (Chain.getOpcode()) {
14462 case ISD::EntryToken:
14463 // Entry token is ideal chain operand, but handled in FindBetterChain.
14468 // Get alias information for Chain.
14469 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14470 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14472 // If chain is alias then stop here.
14473 if (!(IsLoad && IsOpLoad) &&
14474 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14475 Aliases.push_back(Chain);
14477 // Look further up the chain.
14478 Chains.push_back(Chain.getOperand(0));
14484 case ISD::TokenFactor:
14485 // We have to check each of the operands of the token factor for "small"
14486 // token factors, so we queue them up. Adding the operands to the queue
14487 // (stack) in reverse order maintains the original order and increases the
14488 // likelihood that getNode will find a matching token factor (CSE.)
14489 if (Chain.getNumOperands() > 16) {
14490 Aliases.push_back(Chain);
14493 for (unsigned n = Chain.getNumOperands(); n;)
14494 Chains.push_back(Chain.getOperand(--n));
14499 // For all other instructions we will just have to take what we can get.
14500 Aliases.push_back(Chain);
14505 // We need to be careful here to also search for aliases through the
14506 // value operand of a store, etc. Consider the following situation:
14508 // L1 = load Token1, %52
14509 // S1 = store Token1, L1, %51
14510 // L2 = load Token1, %52+8
14511 // S2 = store Token1, L2, %51+8
14512 // Token2 = Token(S1, S2)
14513 // L3 = load Token2, %53
14514 // S3 = store Token2, L3, %52
14515 // L4 = load Token2, %53+8
14516 // S4 = store Token2, L4, %52+8
14517 // If we search for aliases of S3 (which loads address %52), and we look
14518 // only through the chain, then we'll miss the trivial dependence on L1
14519 // (which also loads from %52). We then might change all loads and
14520 // stores to use Token1 as their chain operand, which could result in
14521 // copying %53 into %52 before copying %52 into %51 (which should
14524 // The problem is, however, that searching for such data dependencies
14525 // can become expensive, and the cost is not directly related to the
14526 // chain depth. Instead, we'll rule out such configurations here by
14527 // insisting that we've visited all chain users (except for users
14528 // of the original chain, which is not necessary). When doing this,
14529 // we need to look through nodes we don't care about (otherwise, things
14530 // like register copies will interfere with trivial cases).
14532 SmallVector<const SDNode *, 16> Worklist;
14533 for (const SDNode *N : Visited)
14534 if (N != OriginalChain.getNode())
14535 Worklist.push_back(N);
14537 while (!Worklist.empty()) {
14538 const SDNode *M = Worklist.pop_back_val();
14540 // We have already visited M, and want to make sure we've visited any uses
14541 // of M that we care about. For uses that we've not visisted, and don't
14542 // care about, queue them to the worklist.
14544 for (SDNode::use_iterator UI = M->use_begin(),
14545 UIE = M->use_end(); UI != UIE; ++UI)
14546 if (UI.getUse().getValueType() == MVT::Other &&
14547 Visited.insert(*UI).second) {
14548 if (isa<MemSDNode>(*UI)) {
14549 // We've not visited this use, and we care about it (it could have an
14550 // ordering dependency with the original node).
14552 Aliases.push_back(OriginalChain);
14556 // We've not visited this use, but we don't care about it. Mark it as
14557 // visited and enqueue it to the worklist.
14558 Worklist.push_back(*UI);
14563 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14564 /// (aliasing node.)
14565 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14566 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14568 // Accumulate all the aliases to this node.
14569 GatherAllAliases(N, OldChain, Aliases);
14571 // If no operands then chain to entry token.
14572 if (Aliases.size() == 0)
14573 return DAG.getEntryNode();
14575 // If a single operand then chain to it. We don't need to revisit it.
14576 if (Aliases.size() == 1)
14579 // Construct a custom tailored token factor.
14580 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14583 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14584 // This holds the base pointer, index, and the offset in bytes from the base
14586 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14588 // We must have a base and an offset.
14589 if (!BasePtr.Base.getNode())
14592 // Do not handle stores to undef base pointers.
14593 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14596 SmallVector<StoreSDNode *, 8> ChainedStores;
14597 ChainedStores.push_back(St);
14599 // Walk up the chain and look for nodes with offsets from the same
14600 // base pointer. Stop when reaching an instruction with a different kind
14601 // or instruction which has a different base pointer.
14602 StoreSDNode *Index = St;
14604 // If the chain has more than one use, then we can't reorder the mem ops.
14605 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14608 if (Index->isVolatile() || Index->isIndexed())
14611 // Find the base pointer and offset for this memory node.
14612 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14614 // Check that the base pointer is the same as the original one.
14615 if (!Ptr.equalBaseIndex(BasePtr))
14618 // Find the next memory operand in the chain. If the next operand in the
14619 // chain is a store then move up and continue the scan with the next
14620 // memory operand. If the next operand is a load save it and use alias
14621 // information to check if it interferes with anything.
14622 SDNode *NextInChain = Index->getChain().getNode();
14624 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14625 // We found a store node. Use it for the next iteration.
14626 ChainedStores.push_back(STn);
14629 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14630 NextInChain = Ldn->getChain().getNode();
14639 bool MadeChange = false;
14640 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14642 for (StoreSDNode *ChainedStore : ChainedStores) {
14643 SDValue Chain = ChainedStore->getChain();
14644 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14646 if (Chain != BetterChain) {
14648 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14652 // Do all replacements after finding the replacements to make to avoid making
14653 // the chains more complicated by introducing new TokenFactors.
14654 for (auto Replacement : BetterChains)
14655 replaceStoreChain(Replacement.first, Replacement.second);
14660 /// This is the entry point for the file.
14661 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14662 CodeGenOpt::Level OptLevel) {
14663 /// This is the main entry point to this class.
14664 DAGCombiner(*this, AA, OptLevel).Run(Level);