1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250 SDValue visitOR(SDNode *N);
251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
254 SDValue visitSHL(SDNode *N);
255 SDValue visitSRA(SDNode *N);
256 SDValue visitSRL(SDNode *N);
257 SDValue visitRotate(SDNode *N);
258 SDValue visitCTLZ(SDNode *N);
259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260 SDValue visitCTTZ(SDNode *N);
261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262 SDValue visitCTPOP(SDNode *N);
263 SDValue visitSELECT(SDNode *N);
264 SDValue visitVSELECT(SDNode *N);
265 SDValue visitSELECT_CC(SDNode *N);
266 SDValue visitSETCC(SDNode *N);
267 SDValue visitSIGN_EXTEND(SDNode *N);
268 SDValue visitZERO_EXTEND(SDNode *N);
269 SDValue visitANY_EXTEND(SDNode *N);
270 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271 SDValue visitTRUNCATE(SDNode *N);
272 SDValue visitBITCAST(SDNode *N);
273 SDValue visitBUILD_PAIR(SDNode *N);
274 SDValue visitFADD(SDNode *N);
275 SDValue visitFSUB(SDNode *N);
276 SDValue visitFMUL(SDNode *N);
277 SDValue visitFMA(SDNode *N);
278 SDValue visitFDIV(SDNode *N);
279 SDValue visitFREM(SDNode *N);
280 SDValue visitFSQRT(SDNode *N);
281 SDValue visitFCOPYSIGN(SDNode *N);
282 SDValue visitSINT_TO_FP(SDNode *N);
283 SDValue visitUINT_TO_FP(SDNode *N);
284 SDValue visitFP_TO_SINT(SDNode *N);
285 SDValue visitFP_TO_UINT(SDNode *N);
286 SDValue visitFP_ROUND(SDNode *N);
287 SDValue visitFP_ROUND_INREG(SDNode *N);
288 SDValue visitFP_EXTEND(SDNode *N);
289 SDValue visitFNEG(SDNode *N);
290 SDValue visitFABS(SDNode *N);
291 SDValue visitFCEIL(SDNode *N);
292 SDValue visitFTRUNC(SDNode *N);
293 SDValue visitFFLOOR(SDNode *N);
294 SDValue visitFMINNUM(SDNode *N);
295 SDValue visitFMAXNUM(SDNode *N);
296 SDValue visitBRCOND(SDNode *N);
297 SDValue visitBR_CC(SDNode *N);
298 SDValue visitLOAD(SDNode *N);
299 SDValue visitSTORE(SDNode *N);
300 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302 SDValue visitBUILD_VECTOR(SDNode *N);
303 SDValue visitCONCAT_VECTORS(SDNode *N);
304 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305 SDValue visitVECTOR_SHUFFLE(SDNode *N);
306 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307 SDValue visitINSERT_SUBVECTOR(SDNode *N);
308 SDValue visitMLOAD(SDNode *N);
309 SDValue visitMSTORE(SDNode *N);
310 SDValue visitMGATHER(SDNode *N);
311 SDValue visitMSCATTER(SDNode *N);
312 SDValue visitFP_TO_FP16(SDNode *N);
314 SDValue visitFADDForFMACombine(SDNode *N);
315 SDValue visitFSUBForFMACombine(SDNode *N);
317 SDValue XformToShuffleWithZero(SDNode *N);
318 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
320 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
322 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
323 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
324 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
325 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
326 SDValue N3, ISD::CondCode CC,
327 bool NotExtCompare = false);
328 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
329 SDLoc DL, bool foldBooleans = true);
331 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
333 bool isOneUseSetCC(SDValue N) const;
335 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
337 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
338 SDValue CombineExtLoad(SDNode *N);
339 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
340 SDValue BuildSDIV(SDNode *N);
341 SDValue BuildSDIVPow2(SDNode *N);
342 SDValue BuildUDIV(SDNode *N);
343 SDValue BuildReciprocalEstimate(SDValue Op);
344 SDValue BuildRsqrtEstimate(SDValue Op);
345 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
346 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
347 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
348 bool DemandHighBits = true);
349 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
350 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
351 SDValue InnerPos, SDValue InnerNeg,
352 unsigned PosOpcode, unsigned NegOpcode,
354 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
355 SDValue ReduceLoadWidth(SDNode *N);
356 SDValue ReduceLoadOpStoreWidth(SDNode *N);
357 SDValue TransformFPLoadStorePair(SDNode *N);
358 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
359 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
361 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
363 /// Walk up chain skipping non-aliasing memory nodes,
364 /// looking for aliasing nodes and adding them to the Aliases vector.
365 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
366 SmallVectorImpl<SDValue> &Aliases);
368 /// Return true if there is any possibility that the two addresses overlap.
369 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
371 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
372 /// chain (aliasing node.)
373 SDValue FindBetterChain(SDNode *N, SDValue Chain);
375 /// Holds a pointer to an LSBaseSDNode as well as information on where it
376 /// is located in a sequence of memory operations connected by a chain.
378 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
379 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
380 // Ptr to the mem node.
381 LSBaseSDNode *MemNode;
382 // Offset from the base ptr.
383 int64_t OffsetFromBase;
384 // What is the sequence number of this mem node.
385 // Lowest mem operand in the DAG starts at zero.
386 unsigned SequenceNum;
389 /// This is a helper function for MergeConsecutiveStores. When the source
390 /// elements of the consecutive stores are all constants or all extracted
391 /// vector elements, try to merge them into one larger store.
392 /// \return True if a merged store was created.
393 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
394 EVT MemVT, unsigned NumElem,
395 bool IsConstantSrc, bool UseVector);
397 /// Merge consecutive store operations into a wide store.
398 /// This optimization uses wide integers or vectors when possible.
399 /// \return True if some memory operations were changed.
400 bool MergeConsecutiveStores(StoreSDNode *N);
402 /// \brief Try to transform a truncation where C is a constant:
403 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
405 /// \p N needs to be a truncation and its first operand an AND. Other
406 /// requirements are checked by the function (e.g. that trunc is
407 /// single-use) and if missed an empty SDValue is returned.
408 SDValue distributeTruncateThroughAnd(SDNode *N);
411 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
412 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
413 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
414 auto *F = DAG.getMachineFunction().getFunction();
415 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
416 F->hasFnAttribute(Attribute::MinSize);
419 /// Runs the dag combiner on all nodes in the work list
420 void Run(CombineLevel AtLevel);
422 SelectionDAG &getDAG() const { return DAG; }
424 /// Returns a type large enough to hold any valid shift amount - before type
425 /// legalization these can be huge.
426 EVT getShiftAmountTy(EVT LHSTy) {
427 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
428 if (LHSTy.isVector())
430 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
431 : TLI.getPointerTy();
434 /// This method returns true if we are running before type legalization or
435 /// if the specified VT is legal.
436 bool isTypeLegal(const EVT &VT) {
437 if (!LegalTypes) return true;
438 return TLI.isTypeLegal(VT);
441 /// Convenience wrapper around TargetLowering::getSetCCResultType
442 EVT getSetCCResultType(EVT VT) const {
443 return TLI.getSetCCResultType(*DAG.getContext(), VT);
450 /// This class is a DAGUpdateListener that removes any deleted
451 /// nodes from the worklist.
452 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
455 explicit WorklistRemover(DAGCombiner &dc)
456 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
458 void NodeDeleted(SDNode *N, SDNode *E) override {
459 DC.removeFromWorklist(N);
464 //===----------------------------------------------------------------------===//
465 // TargetLowering::DAGCombinerInfo implementation
466 //===----------------------------------------------------------------------===//
468 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
469 ((DAGCombiner*)DC)->AddToWorklist(N);
472 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
473 ((DAGCombiner*)DC)->removeFromWorklist(N);
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
478 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
483 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
487 SDValue TargetLowering::DAGCombinerInfo::
488 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
489 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
492 void TargetLowering::DAGCombinerInfo::
493 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
494 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
497 //===----------------------------------------------------------------------===//
499 //===----------------------------------------------------------------------===//
501 void DAGCombiner::deleteAndRecombine(SDNode *N) {
502 removeFromWorklist(N);
504 // If the operands of this node are only used by the node, they will now be
505 // dead. Make sure to re-visit them and recursively delete dead nodes.
506 for (const SDValue &Op : N->ops())
507 // For an operand generating multiple values, one of the values may
508 // become dead allowing further simplification (e.g. split index
509 // arithmetic from an indexed load).
510 if (Op->hasOneUse() || Op->getNumValues() > 1)
511 AddToWorklist(Op.getNode());
516 /// Return 1 if we can compute the negated form of the specified expression for
517 /// the same cost as the expression itself, or 2 if we can compute the negated
518 /// form more cheaply than the expression itself.
519 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
520 const TargetLowering &TLI,
521 const TargetOptions *Options,
522 unsigned Depth = 0) {
523 // fneg is removable even if it has multiple uses.
524 if (Op.getOpcode() == ISD::FNEG) return 2;
526 // Don't allow anything with multiple uses.
527 if (!Op.hasOneUse()) return 0;
529 // Don't recurse exponentially.
530 if (Depth > 6) return 0;
532 switch (Op.getOpcode()) {
533 default: return false;
534 case ISD::ConstantFP:
535 // Don't invert constant FP values after legalize. The negated constant
536 // isn't necessarily legal.
537 return LegalOperations ? 0 : 1;
539 // FIXME: determine better conditions for this xform.
540 if (!Options->UnsafeFPMath) return 0;
542 // After operation legalization, it might not be legal to create new FSUBs.
543 if (LegalOperations &&
544 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
547 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
548 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
551 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
552 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
555 // We can't turn -(A-B) into B-A when we honor signed zeros.
556 if (!Options->UnsafeFPMath) return 0;
558 // fold (fneg (fsub A, B)) -> (fsub B, A)
563 if (Options->HonorSignDependentRoundingFPMath()) return 0;
565 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
566 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
570 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
576 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
581 /// If isNegatibleForFree returns true, return the newly negated expression.
582 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
583 bool LegalOperations, unsigned Depth = 0) {
584 const TargetOptions &Options = DAG.getTarget().Options;
585 // fneg is removable even if it has multiple uses.
586 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
588 // Don't allow anything with multiple uses.
589 assert(Op.hasOneUse() && "Unknown reuse!");
591 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
592 switch (Op.getOpcode()) {
593 default: llvm_unreachable("Unknown code");
594 case ISD::ConstantFP: {
595 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
597 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
600 // FIXME: determine better conditions for this xform.
601 assert(Options.UnsafeFPMath);
603 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
604 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
605 DAG.getTargetLoweringInfo(), &Options, Depth+1))
606 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607 GetNegatedExpression(Op.getOperand(0), DAG,
608 LegalOperations, Depth+1),
610 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
611 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
612 GetNegatedExpression(Op.getOperand(1), DAG,
613 LegalOperations, Depth+1),
616 // We can't turn -(A-B) into B-A when we honor signed zeros.
617 assert(Options.UnsafeFPMath);
619 // fold (fneg (fsub 0, B)) -> B
620 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
621 if (N0CFP->getValueAPF().isZero())
622 return Op.getOperand(1);
624 // fold (fneg (fsub A, B)) -> (fsub B, A)
625 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
626 Op.getOperand(1), Op.getOperand(0));
630 assert(!Options.HonorSignDependentRoundingFPMath());
632 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
633 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
634 DAG.getTargetLoweringInfo(), &Options, Depth+1))
635 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
636 GetNegatedExpression(Op.getOperand(0), DAG,
637 LegalOperations, Depth+1),
640 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
641 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
643 GetNegatedExpression(Op.getOperand(1), DAG,
644 LegalOperations, Depth+1));
648 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
649 GetNegatedExpression(Op.getOperand(0), DAG,
650 LegalOperations, Depth+1));
652 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
653 GetNegatedExpression(Op.getOperand(0), DAG,
654 LegalOperations, Depth+1),
659 // Return true if this node is a setcc, or is a select_cc
660 // that selects between the target values used for true and false, making it
661 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
662 // the appropriate nodes based on the type of node we are checking. This
663 // simplifies life a bit for the callers.
664 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
666 if (N.getOpcode() == ISD::SETCC) {
667 LHS = N.getOperand(0);
668 RHS = N.getOperand(1);
669 CC = N.getOperand(2);
673 if (N.getOpcode() != ISD::SELECT_CC ||
674 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
675 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
678 if (TLI.getBooleanContents(N.getValueType()) ==
679 TargetLowering::UndefinedBooleanContent)
682 LHS = N.getOperand(0);
683 RHS = N.getOperand(1);
684 CC = N.getOperand(4);
688 /// Return true if this is a SetCC-equivalent operation with only one use.
689 /// If this is true, it allows the users to invert the operation for free when
690 /// it is profitable to do so.
691 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
693 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
698 /// Returns true if N is a BUILD_VECTOR node whose
699 /// elements are all the same constant or undefined.
700 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
701 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
706 unsigned SplatBitSize;
708 EVT EltVT = N->getValueType(0).getVectorElementType();
709 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
711 EltVT.getSizeInBits() >= SplatBitSize);
714 // \brief Returns the SDNode if it is a constant integer BuildVector
715 // or constant integer.
716 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
717 if (isa<ConstantSDNode>(N))
719 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
724 // \brief Returns the SDNode if it is a constant float BuildVector
725 // or constant float.
726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
727 if (isa<ConstantFPSDNode>(N))
729 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
736 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
737 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
740 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
741 BitVector UndefElements;
742 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
744 // BuildVectors can truncate their operands. Ignore that case here.
745 // FIXME: We blindly ignore splats which include undef which is overly
747 if (CN && UndefElements.none() &&
748 CN->getValueType(0) == N.getValueType().getScalarType())
755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
758 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
761 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
762 BitVector UndefElements;
763 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
765 if (CN && UndefElements.none())
772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
773 SDValue N0, SDValue N1) {
774 EVT VT = N0.getValueType();
775 if (N0.getOpcode() == Opc) {
776 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
777 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
778 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
779 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
780 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
783 if (N0.hasOneUse()) {
784 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
786 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
787 if (!OpNode.getNode())
789 AddToWorklist(OpNode.getNode());
790 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
795 if (N1.getOpcode() == Opc) {
796 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
797 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
798 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
799 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
800 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
803 if (N1.hasOneUse()) {
804 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
806 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
807 if (!OpNode.getNode())
809 AddToWorklist(OpNode.getNode());
810 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
820 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
822 DEBUG(dbgs() << "\nReplacing.1 ";
824 dbgs() << "\nWith: ";
825 To[0].getNode()->dump(&DAG);
826 dbgs() << " and " << NumTo-1 << " other values\n");
827 for (unsigned i = 0, e = NumTo; i != e; ++i)
828 assert((!To[i].getNode() ||
829 N->getValueType(i) == To[i].getValueType()) &&
830 "Cannot combine value to value of different type!");
832 WorklistRemover DeadNodes(*this);
833 DAG.ReplaceAllUsesWith(N, To);
835 // Push the new nodes and any users onto the worklist
836 for (unsigned i = 0, e = NumTo; i != e; ++i) {
837 if (To[i].getNode()) {
838 AddToWorklist(To[i].getNode());
839 AddUsersToWorklist(To[i].getNode());
844 // Finally, if the node is now dead, remove it from the graph. The node
845 // may not be dead if the replacement process recursively simplified to
846 // something else needing this node.
848 deleteAndRecombine(N);
849 return SDValue(N, 0);
853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
854 // Replace all uses. If any nodes become isomorphic to other nodes and
855 // are deleted, make sure to remove them from our worklist.
856 WorklistRemover DeadNodes(*this);
857 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
859 // Push the new node and any (possibly new) users onto the worklist.
860 AddToWorklist(TLO.New.getNode());
861 AddUsersToWorklist(TLO.New.getNode());
863 // Finally, if the node is now dead, remove it from the graph. The node
864 // may not be dead if the replacement process recursively simplified to
865 // something else needing this node.
866 if (TLO.Old.getNode()->use_empty())
867 deleteAndRecombine(TLO.Old.getNode());
870 /// Check the specified integer node value to see if it can be simplified or if
871 /// things it uses can be simplified by bit propagation. If so, return true.
872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
873 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
874 APInt KnownZero, KnownOne;
875 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
879 AddToWorklist(Op.getNode());
881 // Replace the old value with the new one.
883 DEBUG(dbgs() << "\nReplacing.2 ";
884 TLO.Old.getNode()->dump(&DAG);
885 dbgs() << "\nWith: ";
886 TLO.New.getNode()->dump(&DAG);
889 CommitTargetLoweringOpt(TLO);
893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
895 EVT VT = Load->getValueType(0);
896 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
898 DEBUG(dbgs() << "\nReplacing.9 ";
900 dbgs() << "\nWith: ";
901 Trunc.getNode()->dump(&DAG);
903 WorklistRemover DeadNodes(*this);
904 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
905 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
906 deleteAndRecombine(Load);
907 AddToWorklist(Trunc.getNode());
910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
913 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
914 EVT MemVT = LD->getMemoryVT();
915 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
916 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
918 : LD->getExtensionType();
920 return DAG.getExtLoad(ExtType, dl, PVT,
921 LD->getChain(), LD->getBasePtr(),
922 MemVT, LD->getMemOperand());
925 unsigned Opc = Op.getOpcode();
928 case ISD::AssertSext:
929 return DAG.getNode(ISD::AssertSext, dl, PVT,
930 SExtPromoteOperand(Op.getOperand(0), PVT),
932 case ISD::AssertZext:
933 return DAG.getNode(ISD::AssertZext, dl, PVT,
934 ZExtPromoteOperand(Op.getOperand(0), PVT),
936 case ISD::Constant: {
938 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
939 return DAG.getNode(ExtOpc, dl, PVT, Op);
943 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
945 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
949 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
951 EVT OldVT = Op.getValueType();
953 bool Replace = false;
954 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955 if (!NewOp.getNode())
957 AddToWorklist(NewOp.getNode());
960 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
962 DAG.getValueType(OldVT));
965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
966 EVT OldVT = Op.getValueType();
968 bool Replace = false;
969 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
970 if (!NewOp.getNode())
972 AddToWorklist(NewOp.getNode());
975 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
976 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
979 /// Promote the specified integer binary operation if the target indicates it is
980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
981 /// i32 since i16 instructions are longer.
982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
983 if (!LegalOperations)
986 EVT VT = Op.getValueType();
987 if (VT.isVector() || !VT.isInteger())
990 // If operation type is 'undesirable', e.g. i16 on x86, consider
992 unsigned Opc = Op.getOpcode();
993 if (TLI.isTypeDesirableForOp(Opc, VT))
997 // Consult target whether it is a good idea to promote this operation and
998 // what's the right type to promote it to.
999 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000 assert(PVT != VT && "Don't know what type to promote to!");
1002 bool Replace0 = false;
1003 SDValue N0 = Op.getOperand(0);
1004 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1008 bool Replace1 = false;
1009 SDValue N1 = Op.getOperand(1);
1014 NN1 = PromoteOperand(N1, PVT, Replace1);
1019 AddToWorklist(NN0.getNode());
1021 AddToWorklist(NN1.getNode());
1024 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1026 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1028 DEBUG(dbgs() << "\nPromoting ";
1029 Op.getNode()->dump(&DAG));
1031 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1032 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1037 /// Promote the specified integer shift operation if the target indicates it is
1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1039 /// i32 since i16 instructions are longer.
1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1041 if (!LegalOperations)
1044 EVT VT = Op.getValueType();
1045 if (VT.isVector() || !VT.isInteger())
1048 // If operation type is 'undesirable', e.g. i16 on x86, consider
1050 unsigned Opc = Op.getOpcode();
1051 if (TLI.isTypeDesirableForOp(Opc, VT))
1055 // Consult target whether it is a good idea to promote this operation and
1056 // what's the right type to promote it to.
1057 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058 assert(PVT != VT && "Don't know what type to promote to!");
1060 bool Replace = false;
1061 SDValue N0 = Op.getOperand(0);
1062 if (Opc == ISD::SRA)
1063 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1064 else if (Opc == ISD::SRL)
1065 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1067 N0 = PromoteOperand(N0, PVT, Replace);
1071 AddToWorklist(N0.getNode());
1073 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1075 DEBUG(dbgs() << "\nPromoting ";
1076 Op.getNode()->dump(&DAG));
1078 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1079 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1085 if (!LegalOperations)
1088 EVT VT = Op.getValueType();
1089 if (VT.isVector() || !VT.isInteger())
1092 // If operation type is 'undesirable', e.g. i16 on x86, consider
1094 unsigned Opc = Op.getOpcode();
1095 if (TLI.isTypeDesirableForOp(Opc, VT))
1099 // Consult target whether it is a good idea to promote this operation and
1100 // what's the right type to promote it to.
1101 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102 assert(PVT != VT && "Don't know what type to promote to!");
1103 // fold (aext (aext x)) -> (aext x)
1104 // fold (aext (zext x)) -> (zext x)
1105 // fold (aext (sext x)) -> (sext x)
1106 DEBUG(dbgs() << "\nPromoting ";
1107 Op.getNode()->dump(&DAG));
1108 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1113 bool DAGCombiner::PromoteLoad(SDValue Op) {
1114 if (!LegalOperations)
1117 EVT VT = Op.getValueType();
1118 if (VT.isVector() || !VT.isInteger())
1121 // If operation type is 'undesirable', e.g. i16 on x86, consider
1123 unsigned Opc = Op.getOpcode();
1124 if (TLI.isTypeDesirableForOp(Opc, VT))
1128 // Consult target whether it is a good idea to promote this operation and
1129 // what's the right type to promote it to.
1130 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131 assert(PVT != VT && "Don't know what type to promote to!");
1134 SDNode *N = Op.getNode();
1135 LoadSDNode *LD = cast<LoadSDNode>(N);
1136 EVT MemVT = LD->getMemoryVT();
1137 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1138 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1140 : LD->getExtensionType();
1141 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1142 LD->getChain(), LD->getBasePtr(),
1143 MemVT, LD->getMemOperand());
1144 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1146 DEBUG(dbgs() << "\nPromoting ";
1149 Result.getNode()->dump(&DAG);
1151 WorklistRemover DeadNodes(*this);
1152 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1153 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1154 deleteAndRecombine(N);
1155 AddToWorklist(Result.getNode());
1161 /// \brief Recursively delete a node which has no uses and any operands for
1162 /// which it is the only use.
1164 /// Note that this both deletes the nodes and removes them from the worklist.
1165 /// It also adds any nodes who have had a user deleted to the worklist as they
1166 /// may now have only one use and subject to other combines.
1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1168 if (!N->use_empty())
1171 SmallSetVector<SDNode *, 16> Nodes;
1174 N = Nodes.pop_back_val();
1178 if (N->use_empty()) {
1179 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180 Nodes.insert(N->getOperand(i).getNode());
1182 removeFromWorklist(N);
1187 } while (!Nodes.empty());
1191 //===----------------------------------------------------------------------===//
1192 // Main DAG Combiner implementation
1193 //===----------------------------------------------------------------------===//
1195 void DAGCombiner::Run(CombineLevel AtLevel) {
1196 // set the instance variables, so that the various visit routines may use it.
1198 LegalOperations = Level >= AfterLegalizeVectorOps;
1199 LegalTypes = Level >= AfterLegalizeTypes;
1201 // Add all the dag nodes to the worklist.
1202 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1203 E = DAG.allnodes_end(); I != E; ++I)
1206 // Create a dummy node (which is not added to allnodes), that adds a reference
1207 // to the root node, preventing it from being deleted, and tracking any
1208 // changes of the root.
1209 HandleSDNode Dummy(DAG.getRoot());
1211 // while the worklist isn't empty, find a node and
1212 // try and combine it.
1213 while (!WorklistMap.empty()) {
1215 // The Worklist holds the SDNodes in order, but it may contain null entries.
1217 N = Worklist.pop_back_val();
1220 bool GoodWorklistEntry = WorklistMap.erase(N);
1221 (void)GoodWorklistEntry;
1222 assert(GoodWorklistEntry &&
1223 "Found a worklist entry without a corresponding map entry!");
1225 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1226 // N is deleted from the DAG, since they too may now be dead or may have a
1227 // reduced number of uses, allowing other xforms.
1228 if (recursivelyDeleteUnusedNodes(N))
1231 WorklistRemover DeadNodes(*this);
1233 // If this combine is running after legalizing the DAG, re-legalize any
1234 // nodes pulled off the worklist.
1235 if (Level == AfterLegalizeDAG) {
1236 SmallSetVector<SDNode *, 16> UpdatedNodes;
1237 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1239 for (SDNode *LN : UpdatedNodes) {
1241 AddUsersToWorklist(LN);
1247 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1249 // Add any operands of the new node which have not yet been combined to the
1250 // worklist as well. Because the worklist uniques things already, this
1251 // won't repeatedly process the same operand.
1252 CombinedNodes.insert(N);
1253 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1254 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1255 AddToWorklist(N->getOperand(i).getNode());
1257 SDValue RV = combine(N);
1264 // If we get back the same node we passed in, rather than a new node or
1265 // zero, we know that the node must have defined multiple values and
1266 // CombineTo was used. Since CombineTo takes care of the worklist
1267 // mechanics for us, we have no work to do in this case.
1268 if (RV.getNode() == N)
1271 assert(N->getOpcode() != ISD::DELETED_NODE &&
1272 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1273 "Node was deleted but visit returned new node!");
1275 DEBUG(dbgs() << " ... into: ";
1276 RV.getNode()->dump(&DAG));
1278 // Transfer debug value.
1279 DAG.TransferDbgValues(SDValue(N, 0), RV);
1280 if (N->getNumValues() == RV.getNode()->getNumValues())
1281 DAG.ReplaceAllUsesWith(N, RV.getNode());
1283 assert(N->getValueType(0) == RV.getValueType() &&
1284 N->getNumValues() == 1 && "Type mismatch");
1286 DAG.ReplaceAllUsesWith(N, &OpV);
1289 // Push the new node and any users onto the worklist
1290 AddToWorklist(RV.getNode());
1291 AddUsersToWorklist(RV.getNode());
1293 // Finally, if the node is now dead, remove it from the graph. The node
1294 // may not be dead if the replacement process recursively simplified to
1295 // something else needing this node. This will also take care of adding any
1296 // operands which have lost a user to the worklist.
1297 recursivelyDeleteUnusedNodes(N);
1300 // If the root changed (e.g. it was a dead load, update the root).
1301 DAG.setRoot(Dummy.getValue());
1302 DAG.RemoveDeadNodes();
1305 SDValue DAGCombiner::visit(SDNode *N) {
1306 switch (N->getOpcode()) {
1308 case ISD::TokenFactor: return visitTokenFactor(N);
1309 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1310 case ISD::ADD: return visitADD(N);
1311 case ISD::SUB: return visitSUB(N);
1312 case ISD::ADDC: return visitADDC(N);
1313 case ISD::SUBC: return visitSUBC(N);
1314 case ISD::ADDE: return visitADDE(N);
1315 case ISD::SUBE: return visitSUBE(N);
1316 case ISD::MUL: return visitMUL(N);
1317 case ISD::SDIV: return visitSDIV(N);
1318 case ISD::UDIV: return visitUDIV(N);
1319 case ISD::SREM: return visitSREM(N);
1320 case ISD::UREM: return visitUREM(N);
1321 case ISD::MULHU: return visitMULHU(N);
1322 case ISD::MULHS: return visitMULHS(N);
1323 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1324 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1325 case ISD::SMULO: return visitSMULO(N);
1326 case ISD::UMULO: return visitUMULO(N);
1327 case ISD::SDIVREM: return visitSDIVREM(N);
1328 case ISD::UDIVREM: return visitUDIVREM(N);
1329 case ISD::AND: return visitAND(N);
1330 case ISD::OR: return visitOR(N);
1331 case ISD::XOR: return visitXOR(N);
1332 case ISD::SHL: return visitSHL(N);
1333 case ISD::SRA: return visitSRA(N);
1334 case ISD::SRL: return visitSRL(N);
1336 case ISD::ROTL: return visitRotate(N);
1337 case ISD::CTLZ: return visitCTLZ(N);
1338 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1339 case ISD::CTTZ: return visitCTTZ(N);
1340 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1341 case ISD::CTPOP: return visitCTPOP(N);
1342 case ISD::SELECT: return visitSELECT(N);
1343 case ISD::VSELECT: return visitVSELECT(N);
1344 case ISD::SELECT_CC: return visitSELECT_CC(N);
1345 case ISD::SETCC: return visitSETCC(N);
1346 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1347 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1348 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1349 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1350 case ISD::TRUNCATE: return visitTRUNCATE(N);
1351 case ISD::BITCAST: return visitBITCAST(N);
1352 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1353 case ISD::FADD: return visitFADD(N);
1354 case ISD::FSUB: return visitFSUB(N);
1355 case ISD::FMUL: return visitFMUL(N);
1356 case ISD::FMA: return visitFMA(N);
1357 case ISD::FDIV: return visitFDIV(N);
1358 case ISD::FREM: return visitFREM(N);
1359 case ISD::FSQRT: return visitFSQRT(N);
1360 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1361 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1362 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1363 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1364 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1365 case ISD::FP_ROUND: return visitFP_ROUND(N);
1366 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1367 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1368 case ISD::FNEG: return visitFNEG(N);
1369 case ISD::FABS: return visitFABS(N);
1370 case ISD::FFLOOR: return visitFFLOOR(N);
1371 case ISD::FMINNUM: return visitFMINNUM(N);
1372 case ISD::FMAXNUM: return visitFMAXNUM(N);
1373 case ISD::FCEIL: return visitFCEIL(N);
1374 case ISD::FTRUNC: return visitFTRUNC(N);
1375 case ISD::BRCOND: return visitBRCOND(N);
1376 case ISD::BR_CC: return visitBR_CC(N);
1377 case ISD::LOAD: return visitLOAD(N);
1378 case ISD::STORE: return visitSTORE(N);
1379 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1380 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1381 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1382 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1383 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1384 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1385 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1386 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1387 case ISD::MGATHER: return visitMGATHER(N);
1388 case ISD::MLOAD: return visitMLOAD(N);
1389 case ISD::MSCATTER: return visitMSCATTER(N);
1390 case ISD::MSTORE: return visitMSTORE(N);
1391 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1396 SDValue DAGCombiner::combine(SDNode *N) {
1397 SDValue RV = visit(N);
1399 // If nothing happened, try a target-specific DAG combine.
1400 if (!RV.getNode()) {
1401 assert(N->getOpcode() != ISD::DELETED_NODE &&
1402 "Node was deleted but visit returned NULL!");
1404 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1405 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1407 // Expose the DAG combiner to the target combiner impls.
1408 TargetLowering::DAGCombinerInfo
1409 DagCombineInfo(DAG, Level, false, this);
1411 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1415 // If nothing happened still, try promoting the operation.
1416 if (!RV.getNode()) {
1417 switch (N->getOpcode()) {
1425 RV = PromoteIntBinOp(SDValue(N, 0));
1430 RV = PromoteIntShiftOp(SDValue(N, 0));
1432 case ISD::SIGN_EXTEND:
1433 case ISD::ZERO_EXTEND:
1434 case ISD::ANY_EXTEND:
1435 RV = PromoteExtend(SDValue(N, 0));
1438 if (PromoteLoad(SDValue(N, 0)))
1444 // If N is a commutative binary node, try commuting it to enable more
1446 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1447 N->getNumValues() == 1) {
1448 SDValue N0 = N->getOperand(0);
1449 SDValue N1 = N->getOperand(1);
1451 // Constant operands are canonicalized to RHS.
1452 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1453 SDValue Ops[] = {N1, N0};
1455 if (const BinaryWithFlagsSDNode *BinNode =
1456 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1457 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1458 BinNode->Flags.hasNoUnsignedWrap(),
1459 BinNode->Flags.hasNoSignedWrap(),
1460 BinNode->Flags.hasExact());
1462 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1465 return SDValue(CSENode, 0);
1472 /// Given a node, return its input chain if it has one, otherwise return a null
1474 static SDValue getInputChainForNode(SDNode *N) {
1475 if (unsigned NumOps = N->getNumOperands()) {
1476 if (N->getOperand(0).getValueType() == MVT::Other)
1477 return N->getOperand(0);
1478 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1479 return N->getOperand(NumOps-1);
1480 for (unsigned i = 1; i < NumOps-1; ++i)
1481 if (N->getOperand(i).getValueType() == MVT::Other)
1482 return N->getOperand(i);
1487 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1488 // If N has two operands, where one has an input chain equal to the other,
1489 // the 'other' chain is redundant.
1490 if (N->getNumOperands() == 2) {
1491 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1492 return N->getOperand(0);
1493 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1494 return N->getOperand(1);
1497 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1498 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1499 SmallPtrSet<SDNode*, 16> SeenOps;
1500 bool Changed = false; // If we should replace this token factor.
1502 // Start out with this token factor.
1505 // Iterate through token factors. The TFs grows when new token factors are
1507 for (unsigned i = 0; i < TFs.size(); ++i) {
1508 SDNode *TF = TFs[i];
1510 // Check each of the operands.
1511 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1512 SDValue Op = TF->getOperand(i);
1514 switch (Op.getOpcode()) {
1515 case ISD::EntryToken:
1516 // Entry tokens don't need to be added to the list. They are
1521 case ISD::TokenFactor:
1522 if (Op.hasOneUse() &&
1523 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1524 // Queue up for processing.
1525 TFs.push_back(Op.getNode());
1526 // Clean up in case the token factor is removed.
1527 AddToWorklist(Op.getNode());
1534 // Only add if it isn't already in the list.
1535 if (SeenOps.insert(Op.getNode()).second)
1546 // If we've changed things around then replace token factor.
1549 // The entry token is the only possible outcome.
1550 Result = DAG.getEntryNode();
1552 // New and improved token factor.
1553 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1556 // Add users to worklist if AA is enabled, since it may introduce
1557 // a lot of new chained token factors while removing memory deps.
1558 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1559 : DAG.getSubtarget().useAA();
1560 return CombineTo(N, Result, UseAA /*add to worklist*/);
1566 /// MERGE_VALUES can always be eliminated.
1567 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1568 WorklistRemover DeadNodes(*this);
1569 // Replacing results may cause a different MERGE_VALUES to suddenly
1570 // be CSE'd with N, and carry its uses with it. Iterate until no
1571 // uses remain, to ensure that the node can be safely deleted.
1572 // First add the users of this node to the work list so that they
1573 // can be tried again once they have new operands.
1574 AddUsersToWorklist(N);
1576 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1577 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1578 } while (!N->use_empty());
1579 deleteAndRecombine(N);
1580 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1583 static bool isNullConstant(SDValue V) {
1584 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1585 return Const != nullptr && Const->isNullValue();
1588 static bool isAllOnesConstant(SDValue V) {
1589 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1590 return Const != nullptr && Const->isAllOnesValue();
1593 static bool isOneConstant(SDValue V) {
1594 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1595 return Const != nullptr && Const->isOne();
1598 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1599 /// ContantSDNode pointer else nullptr.
1600 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1601 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1602 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1605 SDValue DAGCombiner::visitADD(SDNode *N) {
1606 SDValue N0 = N->getOperand(0);
1607 SDValue N1 = N->getOperand(1);
1608 EVT VT = N0.getValueType();
1611 if (VT.isVector()) {
1612 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1615 // fold (add x, 0) -> x, vector edition
1616 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1618 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1622 // fold (add x, undef) -> undef
1623 if (N0.getOpcode() == ISD::UNDEF)
1625 if (N1.getOpcode() == ISD::UNDEF)
1627 // fold (add c1, c2) -> c1+c2
1628 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1629 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1631 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1632 // canonicalize constant to RHS
1633 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1634 !isConstantIntBuildVectorOrConstantInt(N1))
1635 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1636 // fold (add x, 0) -> x
1637 if (isNullConstant(N1))
1639 // fold (add Sym, c) -> Sym+c
1640 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1641 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1642 GA->getOpcode() == ISD::GlobalAddress)
1643 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1645 (uint64_t)N1C->getSExtValue());
1646 // fold ((c1-A)+c2) -> (c1+c2)-A
1647 if (N1C && N0.getOpcode() == ISD::SUB)
1648 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1650 return DAG.getNode(ISD::SUB, DL, VT,
1651 DAG.getConstant(N1C->getAPIntValue()+
1652 N0C->getAPIntValue(), DL, VT),
1656 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1658 // fold ((0-A) + B) -> B-A
1659 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1660 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1661 // fold (A + (0-B)) -> A-B
1662 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1663 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1664 // fold (A+(B-A)) -> B
1665 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1666 return N1.getOperand(0);
1667 // fold ((B-A)+A) -> B
1668 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1669 return N0.getOperand(0);
1670 // fold (A+(B-(A+C))) to (B-C)
1671 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1672 N0 == N1.getOperand(1).getOperand(0))
1673 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1674 N1.getOperand(1).getOperand(1));
1675 // fold (A+(B-(C+A))) to (B-C)
1676 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1677 N0 == N1.getOperand(1).getOperand(1))
1678 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1679 N1.getOperand(1).getOperand(0));
1680 // fold (A+((B-A)+or-C)) to (B+or-C)
1681 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1682 N1.getOperand(0).getOpcode() == ISD::SUB &&
1683 N0 == N1.getOperand(0).getOperand(1))
1684 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1685 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1687 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1688 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1689 SDValue N00 = N0.getOperand(0);
1690 SDValue N01 = N0.getOperand(1);
1691 SDValue N10 = N1.getOperand(0);
1692 SDValue N11 = N1.getOperand(1);
1694 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1695 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1696 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1697 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1700 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1701 return SDValue(N, 0);
1703 // fold (a+b) -> (a|b) iff a and b share no bits.
1704 if (VT.isInteger() && !VT.isVector()) {
1705 APInt LHSZero, LHSOne;
1706 APInt RHSZero, RHSOne;
1707 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1709 if (LHSZero.getBoolValue()) {
1710 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1712 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1713 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1714 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1715 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1716 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1721 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1722 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1723 isNullConstant(N1.getOperand(0).getOperand(0)))
1724 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1725 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1726 N1.getOperand(0).getOperand(1),
1728 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1729 isNullConstant(N0.getOperand(0).getOperand(0)))
1730 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1731 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1732 N0.getOperand(0).getOperand(1),
1735 if (N1.getOpcode() == ISD::AND) {
1736 SDValue AndOp0 = N1.getOperand(0);
1737 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1738 unsigned DestBits = VT.getScalarType().getSizeInBits();
1740 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1741 // and similar xforms where the inner op is either ~0 or 0.
1742 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1744 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1748 // add (sext i1), X -> sub X, (zext i1)
1749 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1750 N0.getOperand(0).getValueType() == MVT::i1 &&
1751 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1753 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1754 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1757 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1758 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1759 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1760 if (TN->getVT() == MVT::i1) {
1762 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1763 DAG.getConstant(1, DL, VT));
1764 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1771 SDValue DAGCombiner::visitADDC(SDNode *N) {
1772 SDValue N0 = N->getOperand(0);
1773 SDValue N1 = N->getOperand(1);
1774 EVT VT = N0.getValueType();
1776 // If the flag result is dead, turn this into an ADD.
1777 if (!N->hasAnyUseOfValue(1))
1778 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1779 DAG.getNode(ISD::CARRY_FALSE,
1780 SDLoc(N), MVT::Glue));
1782 // canonicalize constant to RHS.
1783 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1784 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1786 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1788 // fold (addc x, 0) -> x + no carry out
1789 if (isNullConstant(N1))
1790 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1791 SDLoc(N), MVT::Glue));
1793 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1794 APInt LHSZero, LHSOne;
1795 APInt RHSZero, RHSOne;
1796 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1798 if (LHSZero.getBoolValue()) {
1799 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1801 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1802 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1803 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1804 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1805 DAG.getNode(ISD::CARRY_FALSE,
1806 SDLoc(N), MVT::Glue));
1812 SDValue DAGCombiner::visitADDE(SDNode *N) {
1813 SDValue N0 = N->getOperand(0);
1814 SDValue N1 = N->getOperand(1);
1815 SDValue CarryIn = N->getOperand(2);
1817 // canonicalize constant to RHS
1818 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1819 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1821 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1824 // fold (adde x, y, false) -> (addc x, y)
1825 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1826 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1831 // Since it may not be valid to emit a fold to zero for vector initializers
1832 // check if we can before folding.
1833 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1835 bool LegalOperations, bool LegalTypes) {
1837 return DAG.getConstant(0, DL, VT);
1838 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1839 return DAG.getConstant(0, DL, VT);
1843 SDValue DAGCombiner::visitSUB(SDNode *N) {
1844 SDValue N0 = N->getOperand(0);
1845 SDValue N1 = N->getOperand(1);
1846 EVT VT = N0.getValueType();
1849 if (VT.isVector()) {
1850 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1853 // fold (sub x, 0) -> x, vector edition
1854 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1858 // fold (sub x, x) -> 0
1859 // FIXME: Refactor this and xor and other similar operations together.
1861 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1862 // fold (sub c1, c2) -> c1-c2
1863 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1864 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1866 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1867 // fold (sub x, c) -> (add x, -c)
1870 return DAG.getNode(ISD::ADD, DL, VT, N0,
1871 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1873 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1874 if (isAllOnesConstant(N0))
1875 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1876 // fold A-(A-B) -> B
1877 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1878 return N1.getOperand(1);
1879 // fold (A+B)-A -> B
1880 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1881 return N0.getOperand(1);
1882 // fold (A+B)-B -> A
1883 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1884 return N0.getOperand(0);
1885 // fold C2-(A+C1) -> (C2-C1)-A
1886 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1887 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1888 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1890 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1892 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1895 // fold ((A+(B+or-C))-B) -> A+or-C
1896 if (N0.getOpcode() == ISD::ADD &&
1897 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1898 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1899 N0.getOperand(1).getOperand(0) == N1)
1900 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1901 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1902 // fold ((A+(C+B))-B) -> A+C
1903 if (N0.getOpcode() == ISD::ADD &&
1904 N0.getOperand(1).getOpcode() == ISD::ADD &&
1905 N0.getOperand(1).getOperand(1) == N1)
1906 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1907 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1908 // fold ((A-(B-C))-C) -> A-B
1909 if (N0.getOpcode() == ISD::SUB &&
1910 N0.getOperand(1).getOpcode() == ISD::SUB &&
1911 N0.getOperand(1).getOperand(1) == N1)
1912 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1913 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1915 // If either operand of a sub is undef, the result is undef
1916 if (N0.getOpcode() == ISD::UNDEF)
1918 if (N1.getOpcode() == ISD::UNDEF)
1921 // If the relocation model supports it, consider symbol offsets.
1922 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1923 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1924 // fold (sub Sym, c) -> Sym-c
1925 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1926 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1928 (uint64_t)N1C->getSExtValue());
1929 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1930 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1931 if (GA->getGlobal() == GB->getGlobal())
1932 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1936 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1937 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1938 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1939 if (TN->getVT() == MVT::i1) {
1941 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1942 DAG.getConstant(1, DL, VT));
1943 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1950 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1951 SDValue N0 = N->getOperand(0);
1952 SDValue N1 = N->getOperand(1);
1953 EVT VT = N0.getValueType();
1955 // If the flag result is dead, turn this into an SUB.
1956 if (!N->hasAnyUseOfValue(1))
1957 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1958 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1961 // fold (subc x, x) -> 0 + no borrow
1964 return CombineTo(N, DAG.getConstant(0, DL, VT),
1965 DAG.getNode(ISD::CARRY_FALSE, DL,
1969 // fold (subc x, 0) -> x + no borrow
1970 if (isNullConstant(N1))
1971 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1974 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1975 if (isAllOnesConstant(N0))
1976 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1977 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1983 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1984 SDValue N0 = N->getOperand(0);
1985 SDValue N1 = N->getOperand(1);
1986 SDValue CarryIn = N->getOperand(2);
1988 // fold (sube x, y, false) -> (subc x, y)
1989 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1990 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1995 SDValue DAGCombiner::visitMUL(SDNode *N) {
1996 SDValue N0 = N->getOperand(0);
1997 SDValue N1 = N->getOperand(1);
1998 EVT VT = N0.getValueType();
2000 // fold (mul x, undef) -> 0
2001 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2002 return DAG.getConstant(0, SDLoc(N), VT);
2004 bool N0IsConst = false;
2005 bool N1IsConst = false;
2006 bool N1IsOpaqueConst = false;
2007 bool N0IsOpaqueConst = false;
2008 APInt ConstValue0, ConstValue1;
2010 if (VT.isVector()) {
2011 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2014 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2015 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2017 N0IsConst = isa<ConstantSDNode>(N0);
2019 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2020 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2022 N1IsConst = isa<ConstantSDNode>(N1);
2024 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2025 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2029 // fold (mul c1, c2) -> c1*c2
2030 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2031 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2032 N0.getNode(), N1.getNode());
2034 // canonicalize constant to RHS (vector doesn't have to splat)
2035 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2036 !isConstantIntBuildVectorOrConstantInt(N1))
2037 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2038 // fold (mul x, 0) -> 0
2039 if (N1IsConst && ConstValue1 == 0)
2041 // We require a splat of the entire scalar bit width for non-contiguous
2044 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2045 // fold (mul x, 1) -> x
2046 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2048 // fold (mul x, -1) -> 0-x
2049 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2051 return DAG.getNode(ISD::SUB, DL, VT,
2052 DAG.getConstant(0, DL, VT), N0);
2054 // fold (mul x, (1 << c)) -> x << c
2055 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2058 return DAG.getNode(ISD::SHL, DL, VT, N0,
2059 DAG.getConstant(ConstValue1.logBase2(), DL,
2060 getShiftAmountTy(N0.getValueType())));
2062 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2063 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2065 unsigned Log2Val = (-ConstValue1).logBase2();
2067 // FIXME: If the input is something that is easily negated (e.g. a
2068 // single-use add), we should put the negate there.
2069 return DAG.getNode(ISD::SUB, DL, VT,
2070 DAG.getConstant(0, DL, VT),
2071 DAG.getNode(ISD::SHL, DL, VT, N0,
2072 DAG.getConstant(Log2Val, DL,
2073 getShiftAmountTy(N0.getValueType()))));
2077 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2078 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2079 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2080 isa<ConstantSDNode>(N0.getOperand(1)))) {
2081 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2082 N1, N0.getOperand(1));
2083 AddToWorklist(C3.getNode());
2084 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2085 N0.getOperand(0), C3);
2088 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2091 SDValue Sh(nullptr,0), Y(nullptr,0);
2092 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2093 if (N0.getOpcode() == ISD::SHL &&
2094 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2095 isa<ConstantSDNode>(N0.getOperand(1))) &&
2096 N0.getNode()->hasOneUse()) {
2098 } else if (N1.getOpcode() == ISD::SHL &&
2099 isa<ConstantSDNode>(N1.getOperand(1)) &&
2100 N1.getNode()->hasOneUse()) {
2105 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2106 Sh.getOperand(0), Y);
2107 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2108 Mul, Sh.getOperand(1));
2112 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2113 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2114 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2115 isa<ConstantSDNode>(N0.getOperand(1))))
2116 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2117 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2118 N0.getOperand(0), N1),
2119 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2120 N0.getOperand(1), N1));
2123 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2129 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2130 SDValue N0 = N->getOperand(0);
2131 SDValue N1 = N->getOperand(1);
2132 EVT VT = N->getValueType(0);
2136 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2139 // fold (sdiv c1, c2) -> c1/c2
2140 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2141 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2142 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2143 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2144 // fold (sdiv X, 1) -> X
2145 if (N1C && N1C->isOne())
2147 // fold (sdiv X, -1) -> 0-X
2148 if (N1C && N1C->isAllOnesValue()) {
2150 return DAG.getNode(ISD::SUB, DL, VT,
2151 DAG.getConstant(0, DL, VT), N0);
2153 // If we know the sign bits of both operands are zero, strength reduce to a
2154 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2155 if (!VT.isVector()) {
2156 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2157 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2161 // fold (sdiv X, pow2) -> simple ops after legalize
2162 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2163 (N1C->getAPIntValue().isPowerOf2() ||
2164 (-N1C->getAPIntValue()).isPowerOf2())) {
2165 // If dividing by powers of two is cheap, then don't perform the following
2167 if (TLI.isPow2SDivCheap())
2170 // Target-specific implementation of sdiv x, pow2.
2171 SDValue Res = BuildSDIVPow2(N);
2175 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2178 // Splat the sign bit into the register
2180 DAG.getNode(ISD::SRA, DL, VT, N0,
2181 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2182 getShiftAmountTy(N0.getValueType())));
2183 AddToWorklist(SGN.getNode());
2185 // Add (N0 < 0) ? abs2 - 1 : 0;
2187 DAG.getNode(ISD::SRL, DL, VT, SGN,
2188 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2189 getShiftAmountTy(SGN.getValueType())));
2190 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2191 AddToWorklist(SRL.getNode());
2192 AddToWorklist(ADD.getNode()); // Divide by pow2
2193 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2194 DAG.getConstant(lg2, DL,
2195 getShiftAmountTy(ADD.getValueType())));
2197 // If we're dividing by a positive value, we're done. Otherwise, we must
2198 // negate the result.
2199 if (N1C->getAPIntValue().isNonNegative())
2202 AddToWorklist(SRA.getNode());
2203 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2206 // If integer divide is expensive and we satisfy the requirements, emit an
2207 // alternate sequence.
2208 if (N1C && !TLI.isIntDivCheap()) {
2209 SDValue Op = BuildSDIV(N);
2210 if (Op.getNode()) return Op;
2214 if (N0.getOpcode() == ISD::UNDEF)
2215 return DAG.getConstant(0, SDLoc(N), VT);
2216 // X / undef -> undef
2217 if (N1.getOpcode() == ISD::UNDEF)
2223 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2224 SDValue N0 = N->getOperand(0);
2225 SDValue N1 = N->getOperand(1);
2226 EVT VT = N->getValueType(0);
2230 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2233 // fold (udiv c1, c2) -> c1/c2
2234 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2235 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2237 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2240 // fold (udiv x, (1 << c)) -> x >>u c
2241 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2243 return DAG.getNode(ISD::SRL, DL, VT, N0,
2244 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2245 getShiftAmountTy(N0.getValueType())));
2247 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2248 if (N1.getOpcode() == ISD::SHL) {
2249 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2250 if (SHC->getAPIntValue().isPowerOf2()) {
2251 EVT ADDVT = N1.getOperand(1).getValueType();
2253 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2255 DAG.getConstant(SHC->getAPIntValue()
2258 AddToWorklist(Add.getNode());
2259 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2263 // fold (udiv x, c) -> alternate
2264 if (N1C && !TLI.isIntDivCheap()) {
2265 SDValue Op = BuildUDIV(N);
2266 if (Op.getNode()) return Op;
2270 if (N0.getOpcode() == ISD::UNDEF)
2271 return DAG.getConstant(0, SDLoc(N), VT);
2272 // X / undef -> undef
2273 if (N1.getOpcode() == ISD::UNDEF)
2279 SDValue DAGCombiner::visitSREM(SDNode *N) {
2280 SDValue N0 = N->getOperand(0);
2281 SDValue N1 = N->getOperand(1);
2282 EVT VT = N->getValueType(0);
2284 // fold (srem c1, c2) -> c1%c2
2285 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2286 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2288 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2291 // If we know the sign bits of both operands are zero, strength reduce to a
2292 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2293 if (!VT.isVector()) {
2294 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2295 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2298 // If X/C can be simplified by the division-by-constant logic, lower
2299 // X%C to the equivalent of X-X/C*C.
2300 if (N1C && !N1C->isNullValue()) {
2301 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2302 AddToWorklist(Div.getNode());
2303 SDValue OptimizedDiv = combine(Div.getNode());
2304 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2305 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2307 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2308 AddToWorklist(Mul.getNode());
2314 if (N0.getOpcode() == ISD::UNDEF)
2315 return DAG.getConstant(0, SDLoc(N), VT);
2316 // X % undef -> undef
2317 if (N1.getOpcode() == ISD::UNDEF)
2323 SDValue DAGCombiner::visitUREM(SDNode *N) {
2324 SDValue N0 = N->getOperand(0);
2325 SDValue N1 = N->getOperand(1);
2326 EVT VT = N->getValueType(0);
2328 // fold (urem c1, c2) -> c1%c2
2329 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2330 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2332 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2335 // fold (urem x, pow2) -> (and x, pow2-1)
2336 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2337 N1C->getAPIntValue().isPowerOf2()) {
2339 return DAG.getNode(ISD::AND, DL, VT, N0,
2340 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2342 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2343 if (N1.getOpcode() == ISD::SHL) {
2344 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2345 if (SHC->getAPIntValue().isPowerOf2()) {
2348 DAG.getNode(ISD::ADD, DL, VT, N1,
2349 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2351 AddToWorklist(Add.getNode());
2352 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2357 // If X/C can be simplified by the division-by-constant logic, lower
2358 // X%C to the equivalent of X-X/C*C.
2359 if (N1C && !N1C->isNullValue()) {
2360 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2361 AddToWorklist(Div.getNode());
2362 SDValue OptimizedDiv = combine(Div.getNode());
2363 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2364 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2366 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2367 AddToWorklist(Mul.getNode());
2373 if (N0.getOpcode() == ISD::UNDEF)
2374 return DAG.getConstant(0, SDLoc(N), VT);
2375 // X % undef -> undef
2376 if (N1.getOpcode() == ISD::UNDEF)
2382 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2383 SDValue N0 = N->getOperand(0);
2384 SDValue N1 = N->getOperand(1);
2385 EVT VT = N->getValueType(0);
2388 // fold (mulhs x, 0) -> 0
2389 if (isNullConstant(N1))
2391 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2392 if (isOneConstant(N1)) {
2394 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2395 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2397 getShiftAmountTy(N0.getValueType())));
2399 // fold (mulhs x, undef) -> 0
2400 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2401 return DAG.getConstant(0, SDLoc(N), VT);
2403 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2405 if (VT.isSimple() && !VT.isVector()) {
2406 MVT Simple = VT.getSimpleVT();
2407 unsigned SimpleSize = Simple.getSizeInBits();
2408 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2409 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2410 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2411 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2412 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2413 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2414 DAG.getConstant(SimpleSize, DL,
2415 getShiftAmountTy(N1.getValueType())));
2416 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2423 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2424 SDValue N0 = N->getOperand(0);
2425 SDValue N1 = N->getOperand(1);
2426 EVT VT = N->getValueType(0);
2429 // fold (mulhu x, 0) -> 0
2430 if (isNullConstant(N1))
2432 // fold (mulhu x, 1) -> 0
2433 if (isOneConstant(N1))
2434 return DAG.getConstant(0, DL, N0.getValueType());
2435 // fold (mulhu x, undef) -> 0
2436 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2437 return DAG.getConstant(0, DL, VT);
2439 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2441 if (VT.isSimple() && !VT.isVector()) {
2442 MVT Simple = VT.getSimpleVT();
2443 unsigned SimpleSize = Simple.getSizeInBits();
2444 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2445 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2446 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2447 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2448 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2449 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2450 DAG.getConstant(SimpleSize, DL,
2451 getShiftAmountTy(N1.getValueType())));
2452 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2459 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2460 /// give the opcodes for the two computations that are being performed. Return
2461 /// true if a simplification was made.
2462 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2464 // If the high half is not needed, just compute the low half.
2465 bool HiExists = N->hasAnyUseOfValue(1);
2467 (!LegalOperations ||
2468 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2469 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2470 return CombineTo(N, Res, Res);
2473 // If the low half is not needed, just compute the high half.
2474 bool LoExists = N->hasAnyUseOfValue(0);
2476 (!LegalOperations ||
2477 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2478 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2479 return CombineTo(N, Res, Res);
2482 // If both halves are used, return as it is.
2483 if (LoExists && HiExists)
2486 // If the two computed results can be simplified separately, separate them.
2488 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2489 AddToWorklist(Lo.getNode());
2490 SDValue LoOpt = combine(Lo.getNode());
2491 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2492 (!LegalOperations ||
2493 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2494 return CombineTo(N, LoOpt, LoOpt);
2498 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2499 AddToWorklist(Hi.getNode());
2500 SDValue HiOpt = combine(Hi.getNode());
2501 if (HiOpt.getNode() && HiOpt != Hi &&
2502 (!LegalOperations ||
2503 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2504 return CombineTo(N, HiOpt, HiOpt);
2510 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2511 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2512 if (Res.getNode()) return Res;
2514 EVT VT = N->getValueType(0);
2517 // If the type is twice as wide is legal, transform the mulhu to a wider
2518 // multiply plus a shift.
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 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2525 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2526 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2527 // Compute the high part as N1.
2528 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2529 DAG.getConstant(SimpleSize, DL,
2530 getShiftAmountTy(Lo.getValueType())));
2531 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2532 // Compute the low part as N0.
2533 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2534 return CombineTo(N, Lo, Hi);
2541 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2542 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2543 if (Res.getNode()) return Res;
2545 EVT VT = N->getValueType(0);
2548 // If the type is twice as wide is legal, transform the mulhu to a wider
2549 // multiply plus a shift.
2550 if (VT.isSimple() && !VT.isVector()) {
2551 MVT Simple = VT.getSimpleVT();
2552 unsigned SimpleSize = Simple.getSizeInBits();
2553 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2554 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2555 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2556 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2557 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2558 // Compute the high part as N1.
2559 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2560 DAG.getConstant(SimpleSize, DL,
2561 getShiftAmountTy(Lo.getValueType())));
2562 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2563 // Compute the low part as N0.
2564 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2565 return CombineTo(N, Lo, Hi);
2572 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2573 // (smulo x, 2) -> (saddo x, x)
2574 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2575 if (C2->getAPIntValue() == 2)
2576 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2577 N->getOperand(0), N->getOperand(0));
2582 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2583 // (umulo x, 2) -> (uaddo x, x)
2584 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2585 if (C2->getAPIntValue() == 2)
2586 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2587 N->getOperand(0), N->getOperand(0));
2592 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2593 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2594 if (Res.getNode()) return Res;
2599 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2600 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2601 if (Res.getNode()) return Res;
2606 /// If this is a binary operator with two operands of the same opcode, try to
2608 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2609 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2610 EVT VT = N0.getValueType();
2611 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2613 // Bail early if none of these transforms apply.
2614 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2616 // For each of OP in AND/OR/XOR:
2617 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2618 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2619 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2620 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2621 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2623 // do not sink logical op inside of a vector extend, since it may combine
2625 EVT Op0VT = N0.getOperand(0).getValueType();
2626 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2627 N0.getOpcode() == ISD::SIGN_EXTEND ||
2628 N0.getOpcode() == ISD::BSWAP ||
2629 // Avoid infinite looping with PromoteIntBinOp.
2630 (N0.getOpcode() == ISD::ANY_EXTEND &&
2631 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2632 (N0.getOpcode() == ISD::TRUNCATE &&
2633 (!TLI.isZExtFree(VT, Op0VT) ||
2634 !TLI.isTruncateFree(Op0VT, VT)) &&
2635 TLI.isTypeLegal(Op0VT))) &&
2637 Op0VT == N1.getOperand(0).getValueType() &&
2638 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2639 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2640 N0.getOperand(0).getValueType(),
2641 N0.getOperand(0), N1.getOperand(0));
2642 AddToWorklist(ORNode.getNode());
2643 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2646 // For each of OP in SHL/SRL/SRA/AND...
2647 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2648 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2649 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2650 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2651 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2652 N0.getOperand(1) == N1.getOperand(1)) {
2653 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2654 N0.getOperand(0).getValueType(),
2655 N0.getOperand(0), N1.getOperand(0));
2656 AddToWorklist(ORNode.getNode());
2657 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2658 ORNode, N0.getOperand(1));
2661 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2662 // Only perform this optimization after type legalization and before
2663 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2664 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2665 // we don't want to undo this promotion.
2666 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2668 if ((N0.getOpcode() == ISD::BITCAST ||
2669 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2670 Level == AfterLegalizeTypes) {
2671 SDValue In0 = N0.getOperand(0);
2672 SDValue In1 = N1.getOperand(0);
2673 EVT In0Ty = In0.getValueType();
2674 EVT In1Ty = In1.getValueType();
2676 // If both incoming values are integers, and the original types are the
2678 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2679 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2680 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2681 AddToWorklist(Op.getNode());
2686 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2687 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2688 // If both shuffles use the same mask, and both shuffle within a single
2689 // vector, then it is worthwhile to move the swizzle after the operation.
2690 // The type-legalizer generates this pattern when loading illegal
2691 // vector types from memory. In many cases this allows additional shuffle
2693 // There are other cases where moving the shuffle after the xor/and/or
2694 // is profitable even if shuffles don't perform a swizzle.
2695 // If both shuffles use the same mask, and both shuffles have the same first
2696 // or second operand, then it might still be profitable to move the shuffle
2697 // after the xor/and/or operation.
2698 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2699 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2700 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2702 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2703 "Inputs to shuffles are not the same type");
2705 // Check that both shuffles use the same mask. The masks are known to be of
2706 // the same length because the result vector type is the same.
2707 // Check also that shuffles have only one use to avoid introducing extra
2709 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2710 SVN0->getMask().equals(SVN1->getMask())) {
2711 SDValue ShOp = N0->getOperand(1);
2713 // Don't try to fold this node if it requires introducing a
2714 // build vector of all zeros that might be illegal at this stage.
2715 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2717 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2722 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2723 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2724 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2725 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2726 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2727 N0->getOperand(0), N1->getOperand(0));
2728 AddToWorklist(NewNode.getNode());
2729 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2730 &SVN0->getMask()[0]);
2733 // Don't try to fold this node if it requires introducing a
2734 // build vector of all zeros that might be illegal at this stage.
2735 ShOp = N0->getOperand(0);
2736 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2738 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2743 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2744 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2745 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2746 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2747 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2748 N0->getOperand(1), N1->getOperand(1));
2749 AddToWorklist(NewNode.getNode());
2750 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2751 &SVN0->getMask()[0]);
2759 /// This contains all DAGCombine rules which reduce two values combined by
2760 /// an And operation to a single value. This makes them reusable in the context
2761 /// of visitSELECT(). Rules involving constants are not included as
2762 /// visitSELECT() already handles those cases.
2763 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2764 SDNode *LocReference) {
2765 EVT VT = N1.getValueType();
2767 // fold (and x, undef) -> 0
2768 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2769 return DAG.getConstant(0, SDLoc(LocReference), VT);
2770 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2771 SDValue LL, LR, RL, RR, CC0, CC1;
2772 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2773 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2774 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2776 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2777 LL.getValueType().isInteger()) {
2778 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2779 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2780 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2781 LR.getValueType(), LL, RL);
2782 AddToWorklist(ORNode.getNode());
2783 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2785 if (isAllOnesConstant(LR)) {
2786 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2787 if (Op1 == ISD::SETEQ) {
2788 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2789 LR.getValueType(), LL, RL);
2790 AddToWorklist(ANDNode.getNode());
2791 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2793 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2794 if (Op1 == ISD::SETGT) {
2795 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2796 LR.getValueType(), LL, RL);
2797 AddToWorklist(ORNode.getNode());
2798 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2802 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2803 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2804 Op0 == Op1 && LL.getValueType().isInteger() &&
2805 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2806 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2808 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2809 LL, DAG.getConstant(1, DL,
2810 LL.getValueType()));
2811 AddToWorklist(ADDNode.getNode());
2812 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2813 DAG.getConstant(2, DL, LL.getValueType()),
2816 // canonicalize equivalent to ll == rl
2817 if (LL == RR && LR == RL) {
2818 Op1 = ISD::getSetCCSwappedOperands(Op1);
2821 if (LL == RL && LR == RR) {
2822 bool isInteger = LL.getValueType().isInteger();
2823 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2824 if (Result != ISD::SETCC_INVALID &&
2825 (!LegalOperations ||
2826 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2827 TLI.isOperationLegal(ISD::SETCC,
2828 getSetCCResultType(N0.getSimpleValueType())))))
2829 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2834 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2835 VT.getSizeInBits() <= 64) {
2836 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2837 APInt ADDC = ADDI->getAPIntValue();
2838 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2839 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2840 // immediate for an add, but it is legal if its top c2 bits are set,
2841 // transform the ADD so the immediate doesn't need to be materialized
2843 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2844 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2845 SRLI->getZExtValue());
2846 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2848 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2851 DAG.getNode(ISD::ADD, DL, VT,
2852 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2853 CombineTo(N0.getNode(), NewAdd);
2854 // Return N so it doesn't get rechecked!
2855 return SDValue(LocReference, 0);
2866 SDValue DAGCombiner::visitAND(SDNode *N) {
2867 SDValue N0 = N->getOperand(0);
2868 SDValue N1 = N->getOperand(1);
2869 EVT VT = N1.getValueType();
2872 if (VT.isVector()) {
2873 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2876 // fold (and x, 0) -> 0, vector edition
2877 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2878 // do not return N0, because undef node may exist in N0
2879 return DAG.getConstant(
2880 APInt::getNullValue(
2881 N0.getValueType().getScalarType().getSizeInBits()),
2882 SDLoc(N), N0.getValueType());
2883 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2884 // do not return N1, because undef node may exist in N1
2885 return DAG.getConstant(
2886 APInt::getNullValue(
2887 N1.getValueType().getScalarType().getSizeInBits()),
2888 SDLoc(N), N1.getValueType());
2890 // fold (and x, -1) -> x, vector edition
2891 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2893 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2897 // fold (and c1, c2) -> c1&c2
2898 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2899 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2900 if (N0C && N1C && !N1C->isOpaque())
2901 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2902 // canonicalize constant to RHS
2903 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2904 !isConstantIntBuildVectorOrConstantInt(N1))
2905 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2906 // fold (and x, -1) -> x
2907 if (isAllOnesConstant(N1))
2909 // if (and x, c) is known to be zero, return 0
2910 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2911 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2912 APInt::getAllOnesValue(BitWidth)))
2913 return DAG.getConstant(0, SDLoc(N), VT);
2915 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2917 // fold (and (or x, C), D) -> D if (C & D) == D
2918 if (N1C && N0.getOpcode() == ISD::OR)
2919 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2920 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2922 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2923 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2924 SDValue N0Op0 = N0.getOperand(0);
2925 APInt Mask = ~N1C->getAPIntValue();
2926 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2927 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2928 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2929 N0.getValueType(), N0Op0);
2931 // Replace uses of the AND with uses of the Zero extend node.
2934 // We actually want to replace all uses of the any_extend with the
2935 // zero_extend, to avoid duplicating things. This will later cause this
2936 // AND to be folded.
2937 CombineTo(N0.getNode(), Zext);
2938 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2941 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2942 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2943 // already be zero by virtue of the width of the base type of the load.
2945 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2947 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2948 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2949 N0.getOpcode() == ISD::LOAD) {
2950 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2951 N0 : N0.getOperand(0) );
2953 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2954 // This can be a pure constant or a vector splat, in which case we treat the
2955 // vector as a scalar and use the splat value.
2956 APInt Constant = APInt::getNullValue(1);
2957 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2958 Constant = C->getAPIntValue();
2959 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2960 APInt SplatValue, SplatUndef;
2961 unsigned SplatBitSize;
2963 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2964 SplatBitSize, HasAnyUndefs);
2966 // Undef bits can contribute to a possible optimisation if set, so
2968 SplatValue |= SplatUndef;
2970 // The splat value may be something like "0x00FFFFFF", which means 0 for
2971 // the first vector value and FF for the rest, repeating. We need a mask
2972 // that will apply equally to all members of the vector, so AND all the
2973 // lanes of the constant together.
2974 EVT VT = Vector->getValueType(0);
2975 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2977 // If the splat value has been compressed to a bitlength lower
2978 // than the size of the vector lane, we need to re-expand it to
2980 if (BitWidth > SplatBitSize)
2981 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2982 SplatBitSize < BitWidth;
2983 SplatBitSize = SplatBitSize * 2)
2984 SplatValue |= SplatValue.shl(SplatBitSize);
2986 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2987 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2988 if (SplatBitSize % BitWidth == 0) {
2989 Constant = APInt::getAllOnesValue(BitWidth);
2990 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2991 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2996 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2997 // actually legal and isn't going to get expanded, else this is a false
2999 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3000 Load->getValueType(0),
3001 Load->getMemoryVT());
3003 // Resize the constant to the same size as the original memory access before
3004 // extension. If it is still the AllOnesValue then this AND is completely
3007 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3010 switch (Load->getExtensionType()) {
3011 default: B = false; break;
3012 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3014 case ISD::NON_EXTLOAD: B = true; break;
3017 if (B && Constant.isAllOnesValue()) {
3018 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3019 // preserve semantics once we get rid of the AND.
3020 SDValue NewLoad(Load, 0);
3021 if (Load->getExtensionType() == ISD::EXTLOAD) {
3022 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3023 Load->getValueType(0), SDLoc(Load),
3024 Load->getChain(), Load->getBasePtr(),
3025 Load->getOffset(), Load->getMemoryVT(),
3026 Load->getMemOperand());
3027 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3028 if (Load->getNumValues() == 3) {
3029 // PRE/POST_INC loads have 3 values.
3030 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3031 NewLoad.getValue(2) };
3032 CombineTo(Load, To, 3, true);
3034 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3038 // Fold the AND away, taking care not to fold to the old load node if we
3040 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3042 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3046 // fold (and (load x), 255) -> (zextload x, i8)
3047 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3048 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3049 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3050 (N0.getOpcode() == ISD::ANY_EXTEND &&
3051 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3052 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3053 LoadSDNode *LN0 = HasAnyExt
3054 ? cast<LoadSDNode>(N0.getOperand(0))
3055 : cast<LoadSDNode>(N0);
3056 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3057 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3058 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3059 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3060 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3061 EVT LoadedVT = LN0->getMemoryVT();
3062 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3064 if (ExtVT == LoadedVT &&
3065 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3069 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3070 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3071 LN0->getMemOperand());
3073 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3074 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3077 // Do not change the width of a volatile load.
3078 // Do not generate loads of non-round integer types since these can
3079 // be expensive (and would be wrong if the type is not byte sized).
3080 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3081 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3083 EVT PtrType = LN0->getOperand(1).getValueType();
3085 unsigned Alignment = LN0->getAlignment();
3086 SDValue NewPtr = LN0->getBasePtr();
3088 // For big endian targets, we need to add an offset to the pointer
3089 // to load the correct bytes. For little endian systems, we merely
3090 // need to read fewer bytes from the same pointer.
3091 if (TLI.isBigEndian()) {
3092 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3093 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3094 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3096 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3097 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3098 Alignment = MinAlign(Alignment, PtrOff);
3101 AddToWorklist(NewPtr.getNode());
3104 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3105 LN0->getChain(), NewPtr,
3106 LN0->getPointerInfo(),
3107 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3108 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3110 CombineTo(LN0, Load, Load.getValue(1));
3111 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3117 if (SDValue Combined = visitANDLike(N0, N1, N))
3120 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3121 if (N0.getOpcode() == N1.getOpcode()) {
3122 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3123 if (Tmp.getNode()) return Tmp;
3126 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3127 // fold (and (sra)) -> (and (srl)) when possible.
3128 if (!VT.isVector() &&
3129 SimplifyDemandedBits(SDValue(N, 0)))
3130 return SDValue(N, 0);
3132 // fold (zext_inreg (extload x)) -> (zextload x)
3133 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3134 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3135 EVT MemVT = LN0->getMemoryVT();
3136 // If we zero all the possible extended bits, then we can turn this into
3137 // a zextload if we are running before legalize or the operation is legal.
3138 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3139 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3140 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3141 ((!LegalOperations && !LN0->isVolatile()) ||
3142 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3143 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3144 LN0->getChain(), LN0->getBasePtr(),
3145 MemVT, LN0->getMemOperand());
3147 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3148 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3151 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3152 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3154 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3155 EVT MemVT = LN0->getMemoryVT();
3156 // If we zero all the possible extended bits, then we can turn this into
3157 // a zextload if we are running before legalize or the operation is legal.
3158 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3159 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3160 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3161 ((!LegalOperations && !LN0->isVolatile()) ||
3162 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3163 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3164 LN0->getChain(), LN0->getBasePtr(),
3165 MemVT, LN0->getMemOperand());
3167 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3168 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3171 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3172 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3173 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3174 N0.getOperand(1), false);
3175 if (BSwap.getNode())
3182 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3183 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3184 bool DemandHighBits) {
3185 if (!LegalOperations)
3188 EVT VT = N->getValueType(0);
3189 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3191 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3194 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3195 bool LookPassAnd0 = false;
3196 bool LookPassAnd1 = false;
3197 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3199 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3201 if (N0.getOpcode() == ISD::AND) {
3202 if (!N0.getNode()->hasOneUse())
3204 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205 if (!N01C || N01C->getZExtValue() != 0xFF00)
3207 N0 = N0.getOperand(0);
3208 LookPassAnd0 = true;
3211 if (N1.getOpcode() == ISD::AND) {
3212 if (!N1.getNode()->hasOneUse())
3214 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3215 if (!N11C || N11C->getZExtValue() != 0xFF)
3217 N1 = N1.getOperand(0);
3218 LookPassAnd1 = true;
3221 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3223 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3225 if (!N0.getNode()->hasOneUse() ||
3226 !N1.getNode()->hasOneUse())
3229 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3230 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3233 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3236 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3237 SDValue N00 = N0->getOperand(0);
3238 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3239 if (!N00.getNode()->hasOneUse())
3241 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3242 if (!N001C || N001C->getZExtValue() != 0xFF)
3244 N00 = N00.getOperand(0);
3245 LookPassAnd0 = true;
3248 SDValue N10 = N1->getOperand(0);
3249 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3250 if (!N10.getNode()->hasOneUse())
3252 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3253 if (!N101C || N101C->getZExtValue() != 0xFF00)
3255 N10 = N10.getOperand(0);
3256 LookPassAnd1 = true;
3262 // Make sure everything beyond the low halfword gets set to zero since the SRL
3263 // 16 will clear the top bits.
3264 unsigned OpSizeInBits = VT.getSizeInBits();
3265 if (DemandHighBits && OpSizeInBits > 16) {
3266 // If the left-shift isn't masked out then the only way this is a bswap is
3267 // if all bits beyond the low 8 are 0. In that case the entire pattern
3268 // reduces to a left shift anyway: leave it for other parts of the combiner.
3272 // However, if the right shift isn't masked out then it might be because
3273 // it's not needed. See if we can spot that too.
3274 if (!LookPassAnd1 &&
3275 !DAG.MaskedValueIsZero(
3276 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3280 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3281 if (OpSizeInBits > 16) {
3283 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3284 DAG.getConstant(OpSizeInBits - 16, DL,
3285 getShiftAmountTy(VT)));
3290 /// Return true if the specified node is an element that makes up a 32-bit
3291 /// packed halfword byteswap.
3292 /// ((x & 0x000000ff) << 8) |
3293 /// ((x & 0x0000ff00) >> 8) |
3294 /// ((x & 0x00ff0000) << 8) |
3295 /// ((x & 0xff000000) >> 8)
3296 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3297 if (!N.getNode()->hasOneUse())
3300 unsigned Opc = N.getOpcode();
3301 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3304 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3309 switch (N1C->getZExtValue()) {
3312 case 0xFF: Num = 0; break;
3313 case 0xFF00: Num = 1; break;
3314 case 0xFF0000: Num = 2; break;
3315 case 0xFF000000: Num = 3; break;
3318 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3319 SDValue N0 = N.getOperand(0);
3320 if (Opc == ISD::AND) {
3321 if (Num == 0 || Num == 2) {
3323 // (x >> 8) & 0xff0000
3324 if (N0.getOpcode() != ISD::SRL)
3326 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3327 if (!C || C->getZExtValue() != 8)
3330 // (x << 8) & 0xff00
3331 // (x << 8) & 0xff000000
3332 if (N0.getOpcode() != ISD::SHL)
3334 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3335 if (!C || C->getZExtValue() != 8)
3338 } else if (Opc == ISD::SHL) {
3340 // (x & 0xff0000) << 8
3341 if (Num != 0 && Num != 2)
3343 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3344 if (!C || C->getZExtValue() != 8)
3346 } else { // Opc == ISD::SRL
3347 // (x & 0xff00) >> 8
3348 // (x & 0xff000000) >> 8
3349 if (Num != 1 && Num != 3)
3351 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3352 if (!C || C->getZExtValue() != 8)
3359 Parts[Num] = N0.getOperand(0).getNode();
3363 /// Match a 32-bit packed halfword bswap. That is
3364 /// ((x & 0x000000ff) << 8) |
3365 /// ((x & 0x0000ff00) >> 8) |
3366 /// ((x & 0x00ff0000) << 8) |
3367 /// ((x & 0xff000000) >> 8)
3368 /// => (rotl (bswap x), 16)
3369 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3370 if (!LegalOperations)
3373 EVT VT = N->getValueType(0);
3376 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3380 // (or (or (and), (and)), (or (and), (and)))
3381 // (or (or (or (and), (and)), (and)), (and))
3382 if (N0.getOpcode() != ISD::OR)
3384 SDValue N00 = N0.getOperand(0);
3385 SDValue N01 = N0.getOperand(1);
3386 SDNode *Parts[4] = {};
3388 if (N1.getOpcode() == ISD::OR &&
3389 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3390 // (or (or (and), (and)), (or (and), (and)))
3391 SDValue N000 = N00.getOperand(0);
3392 if (!isBSwapHWordElement(N000, Parts))
3395 SDValue N001 = N00.getOperand(1);
3396 if (!isBSwapHWordElement(N001, Parts))
3398 SDValue N010 = N01.getOperand(0);
3399 if (!isBSwapHWordElement(N010, Parts))
3401 SDValue N011 = N01.getOperand(1);
3402 if (!isBSwapHWordElement(N011, Parts))
3405 // (or (or (or (and), (and)), (and)), (and))
3406 if (!isBSwapHWordElement(N1, Parts))
3408 if (!isBSwapHWordElement(N01, Parts))
3410 if (N00.getOpcode() != ISD::OR)
3412 SDValue N000 = N00.getOperand(0);
3413 if (!isBSwapHWordElement(N000, Parts))
3415 SDValue N001 = N00.getOperand(1);
3416 if (!isBSwapHWordElement(N001, Parts))
3420 // Make sure the parts are all coming from the same node.
3421 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3425 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3426 SDValue(Parts[0], 0));
3428 // Result of the bswap should be rotated by 16. If it's not legal, then
3429 // do (x << 16) | (x >> 16).
3430 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3431 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3432 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3433 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3434 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3435 return DAG.getNode(ISD::OR, DL, VT,
3436 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3437 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3440 /// This contains all DAGCombine rules which reduce two values combined by
3441 /// an Or operation to a single value \see visitANDLike().
3442 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3443 EVT VT = N1.getValueType();
3444 // fold (or x, undef) -> -1
3445 if (!LegalOperations &&
3446 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3447 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3448 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3449 SDLoc(LocReference), VT);
3451 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3452 SDValue LL, LR, RL, RR, CC0, CC1;
3453 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3454 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3455 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3457 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3458 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3459 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3460 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3461 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3462 LR.getValueType(), LL, RL);
3463 AddToWorklist(ORNode.getNode());
3464 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3466 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3467 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3468 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3469 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3470 LR.getValueType(), LL, RL);
3471 AddToWorklist(ANDNode.getNode());
3472 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3475 // canonicalize equivalent to ll == rl
3476 if (LL == RR && LR == RL) {
3477 Op1 = ISD::getSetCCSwappedOperands(Op1);
3480 if (LL == RL && LR == RR) {
3481 bool isInteger = LL.getValueType().isInteger();
3482 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3483 if (Result != ISD::SETCC_INVALID &&
3484 (!LegalOperations ||
3485 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3486 TLI.isOperationLegal(ISD::SETCC,
3487 getSetCCResultType(N0.getValueType())))))
3488 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3493 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3494 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3495 // Don't increase # computations.
3496 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3497 // We can only do this xform if we know that bits from X that are set in C2
3498 // but not in C1 are already zero. Likewise for Y.
3499 if (const ConstantSDNode *N0O1C =
3500 getAsNonOpaqueConstant(N0.getOperand(1))) {
3501 if (const ConstantSDNode *N1O1C =
3502 getAsNonOpaqueConstant(N1.getOperand(1))) {
3503 // We can only do this xform if we know that bits from X that are set in
3504 // C2 but not in C1 are already zero. Likewise for Y.
3505 const APInt &LHSMask = N0O1C->getAPIntValue();
3506 const APInt &RHSMask = N1O1C->getAPIntValue();
3508 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3509 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3510 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3511 N0.getOperand(0), N1.getOperand(0));
3512 SDLoc DL(LocReference);
3513 return DAG.getNode(ISD::AND, DL, VT, X,
3514 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3520 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3521 if (N0.getOpcode() == ISD::AND &&
3522 N1.getOpcode() == ISD::AND &&
3523 N0.getOperand(0) == N1.getOperand(0) &&
3524 // Don't increase # computations.
3525 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3526 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3527 N0.getOperand(1), N1.getOperand(1));
3528 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3534 SDValue DAGCombiner::visitOR(SDNode *N) {
3535 SDValue N0 = N->getOperand(0);
3536 SDValue N1 = N->getOperand(1);
3537 EVT VT = N1.getValueType();
3540 if (VT.isVector()) {
3541 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3544 // fold (or x, 0) -> x, vector edition
3545 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3547 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3550 // fold (or x, -1) -> -1, vector edition
3551 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3552 // do not return N0, because undef node may exist in N0
3553 return DAG.getConstant(
3554 APInt::getAllOnesValue(
3555 N0.getValueType().getScalarType().getSizeInBits()),
3556 SDLoc(N), N0.getValueType());
3557 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3558 // do not return N1, because undef node may exist in N1
3559 return DAG.getConstant(
3560 APInt::getAllOnesValue(
3561 N1.getValueType().getScalarType().getSizeInBits()),
3562 SDLoc(N), N1.getValueType());
3564 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3565 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3566 // Do this only if the resulting shuffle is legal.
3567 if (isa<ShuffleVectorSDNode>(N0) &&
3568 isa<ShuffleVectorSDNode>(N1) &&
3569 // Avoid folding a node with illegal type.
3570 TLI.isTypeLegal(VT) &&
3571 N0->getOperand(1) == N1->getOperand(1) &&
3572 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3573 bool CanFold = true;
3574 unsigned NumElts = VT.getVectorNumElements();
3575 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3576 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3577 // We construct two shuffle masks:
3578 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3579 // and N1 as the second operand.
3580 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3581 // and N0 as the second operand.
3582 // We do this because OR is commutable and therefore there might be
3583 // two ways to fold this node into a shuffle.
3584 SmallVector<int,4> Mask1;
3585 SmallVector<int,4> Mask2;
3587 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3588 int M0 = SV0->getMaskElt(i);
3589 int M1 = SV1->getMaskElt(i);
3591 // Both shuffle indexes are undef. Propagate Undef.
3592 if (M0 < 0 && M1 < 0) {
3593 Mask1.push_back(M0);
3594 Mask2.push_back(M0);
3598 if (M0 < 0 || M1 < 0 ||
3599 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3600 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3605 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3606 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3610 // Fold this sequence only if the resulting shuffle is 'legal'.
3611 if (TLI.isShuffleMaskLegal(Mask1, VT))
3612 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3613 N1->getOperand(0), &Mask1[0]);
3614 if (TLI.isShuffleMaskLegal(Mask2, VT))
3615 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3616 N0->getOperand(0), &Mask2[0]);
3621 // fold (or c1, c2) -> c1|c2
3622 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3623 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3624 if (N0C && N1C && !N1C->isOpaque())
3625 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3626 // canonicalize constant to RHS
3627 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3628 !isConstantIntBuildVectorOrConstantInt(N1))
3629 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3630 // fold (or x, 0) -> x
3631 if (isNullConstant(N1))
3633 // fold (or x, -1) -> -1
3634 if (isAllOnesConstant(N1))
3636 // fold (or x, c) -> c iff (x & ~c) == 0
3637 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3640 if (SDValue Combined = visitORLike(N0, N1, N))
3643 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3644 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3645 if (BSwap.getNode())
3647 BSwap = MatchBSwapHWordLow(N, N0, N1);
3648 if (BSwap.getNode())
3652 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3654 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3655 // iff (c1 & c2) == 0.
3656 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3657 isa<ConstantSDNode>(N0.getOperand(1))) {
3658 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3659 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3660 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3663 ISD::AND, SDLoc(N), VT,
3664 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3668 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3669 if (N0.getOpcode() == N1.getOpcode()) {
3670 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3671 if (Tmp.getNode()) return Tmp;
3674 // See if this is some rotate idiom.
3675 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3676 return SDValue(Rot, 0);
3678 // Simplify the operands using demanded-bits information.
3679 if (!VT.isVector() &&
3680 SimplifyDemandedBits(SDValue(N, 0)))
3681 return SDValue(N, 0);
3686 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3687 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3688 if (Op.getOpcode() == ISD::AND) {
3689 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3690 Mask = Op.getOperand(1);
3691 Op = Op.getOperand(0);
3697 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3705 // Return true if we can prove that, whenever Neg and Pos are both in the
3706 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3707 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3709 // (or (shift1 X, Neg), (shift2 X, Pos))
3711 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3712 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3713 // to consider shift amounts with defined behavior.
3714 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3715 // If OpSize is a power of 2 then:
3717 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3718 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3720 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3721 // for the stronger condition:
3723 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3725 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3726 // we can just replace Neg with Neg' for the rest of the function.
3728 // In other cases we check for the even stronger condition:
3730 // Neg == OpSize - Pos [B]
3732 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3733 // behavior if Pos == 0 (and consequently Neg == OpSize).
3735 // We could actually use [A] whenever OpSize is a power of 2, but the
3736 // only extra cases that it would match are those uninteresting ones
3737 // where Neg and Pos are never in range at the same time. E.g. for
3738 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3739 // as well as (sub 32, Pos), but:
3741 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3743 // always invokes undefined behavior for 32-bit X.
3745 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3746 unsigned MaskLoBits = 0;
3747 if (Neg.getOpcode() == ISD::AND &&
3748 isPowerOf2_64(OpSize) &&
3749 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3750 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3751 Neg = Neg.getOperand(0);
3752 MaskLoBits = Log2_64(OpSize);
3755 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3756 if (Neg.getOpcode() != ISD::SUB)
3758 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3761 SDValue NegOp1 = Neg.getOperand(1);
3763 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3764 // Pos'. The truncation is redundant for the purpose of the equality.
3766 Pos.getOpcode() == ISD::AND &&
3767 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3768 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3769 Pos = Pos.getOperand(0);
3771 // The condition we need is now:
3773 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3775 // If NegOp1 == Pos then we need:
3777 // OpSize & Mask == NegC & Mask
3779 // (because "x & Mask" is a truncation and distributes through subtraction).
3782 Width = NegC->getAPIntValue();
3783 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3784 // Then the condition we want to prove becomes:
3786 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3788 // which, again because "x & Mask" is a truncation, becomes:
3790 // NegC & Mask == (OpSize - PosC) & Mask
3791 // OpSize & Mask == (NegC + PosC) & Mask
3792 else if (Pos.getOpcode() == ISD::ADD &&
3793 Pos.getOperand(0) == NegOp1 &&
3794 Pos.getOperand(1).getOpcode() == ISD::Constant)
3795 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3796 NegC->getAPIntValue());
3800 // Now we just need to check that OpSize & Mask == Width & Mask.
3802 // Opsize & Mask is 0 since Mask is Opsize - 1.
3803 return Width.getLoBits(MaskLoBits) == 0;
3804 return Width == OpSize;
3807 // A subroutine of MatchRotate used once we have found an OR of two opposite
3808 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3809 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3810 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3811 // Neg with outer conversions stripped away.
3812 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3813 SDValue Neg, SDValue InnerPos,
3814 SDValue InnerNeg, unsigned PosOpcode,
3815 unsigned NegOpcode, SDLoc DL) {
3816 // fold (or (shl x, (*ext y)),
3817 // (srl x, (*ext (sub 32, y)))) ->
3818 // (rotl x, y) or (rotr x, (sub 32, y))
3820 // fold (or (shl x, (*ext (sub 32, y))),
3821 // (srl x, (*ext y))) ->
3822 // (rotr x, y) or (rotl x, (sub 32, y))
3823 EVT VT = Shifted.getValueType();
3824 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3825 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3826 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3827 HasPos ? Pos : Neg).getNode();
3833 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3834 // idioms for rotate, and if the target supports rotation instructions, generate
3836 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3837 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3838 EVT VT = LHS.getValueType();
3839 if (!TLI.isTypeLegal(VT)) return nullptr;
3841 // The target must have at least one rotate flavor.
3842 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3843 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3844 if (!HasROTL && !HasROTR) return nullptr;
3846 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3847 SDValue LHSShift; // The shift.
3848 SDValue LHSMask; // AND value if any.
3849 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3850 return nullptr; // Not part of a rotate.
3852 SDValue RHSShift; // The shift.
3853 SDValue RHSMask; // AND value if any.
3854 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3855 return nullptr; // Not part of a rotate.
3857 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3858 return nullptr; // Not shifting the same value.
3860 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3861 return nullptr; // Shifts must disagree.
3863 // Canonicalize shl to left side in a shl/srl pair.
3864 if (RHSShift.getOpcode() == ISD::SHL) {
3865 std::swap(LHS, RHS);
3866 std::swap(LHSShift, RHSShift);
3867 std::swap(LHSMask , RHSMask );
3870 unsigned OpSizeInBits = VT.getSizeInBits();
3871 SDValue LHSShiftArg = LHSShift.getOperand(0);
3872 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3873 SDValue RHSShiftArg = RHSShift.getOperand(0);
3874 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3876 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3877 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3878 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3879 RHSShiftAmt.getOpcode() == ISD::Constant) {
3880 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3881 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3882 if ((LShVal + RShVal) != OpSizeInBits)
3885 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3886 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3888 // If there is an AND of either shifted operand, apply it to the result.
3889 if (LHSMask.getNode() || RHSMask.getNode()) {
3890 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3892 if (LHSMask.getNode()) {
3893 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3894 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3896 if (RHSMask.getNode()) {
3897 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3898 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3901 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3904 return Rot.getNode();
3907 // If there is a mask here, and we have a variable shift, we can't be sure
3908 // that we're masking out the right stuff.
3909 if (LHSMask.getNode() || RHSMask.getNode())
3912 // If the shift amount is sign/zext/any-extended just peel it off.
3913 SDValue LExtOp0 = LHSShiftAmt;
3914 SDValue RExtOp0 = RHSShiftAmt;
3915 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3916 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3917 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3918 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3919 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3920 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3921 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3922 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3923 LExtOp0 = LHSShiftAmt.getOperand(0);
3924 RExtOp0 = RHSShiftAmt.getOperand(0);
3927 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3928 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3932 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3933 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3940 SDValue DAGCombiner::visitXOR(SDNode *N) {
3941 SDValue N0 = N->getOperand(0);
3942 SDValue N1 = N->getOperand(1);
3943 EVT VT = N0.getValueType();
3946 if (VT.isVector()) {
3947 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3950 // fold (xor x, 0) -> x, vector edition
3951 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3953 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3957 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3958 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3959 return DAG.getConstant(0, SDLoc(N), VT);
3960 // fold (xor x, undef) -> undef
3961 if (N0.getOpcode() == ISD::UNDEF)
3963 if (N1.getOpcode() == ISD::UNDEF)
3965 // fold (xor c1, c2) -> c1^c2
3966 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3967 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3969 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3970 // canonicalize constant to RHS
3971 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3972 !isConstantIntBuildVectorOrConstantInt(N1))
3973 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3974 // fold (xor x, 0) -> x
3975 if (isNullConstant(N1))
3978 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3981 // fold !(x cc y) -> (x !cc y)
3982 SDValue LHS, RHS, CC;
3983 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3984 bool isInt = LHS.getValueType().isInteger();
3985 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3988 if (!LegalOperations ||
3989 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3990 switch (N0.getOpcode()) {
3992 llvm_unreachable("Unhandled SetCC Equivalent!");
3994 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3995 case ISD::SELECT_CC:
3996 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3997 N0.getOperand(3), NotCC);
4002 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4003 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4004 N0.getNode()->hasOneUse() &&
4005 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4006 SDValue V = N0.getOperand(0);
4008 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4009 DAG.getConstant(1, DL, V.getValueType()));
4010 AddToWorklist(V.getNode());
4011 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4014 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4015 if (isOneConstant(N1) && VT == MVT::i1 &&
4016 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4017 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4018 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4019 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4020 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4021 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4022 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4023 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4026 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4027 if (isAllOnesConstant(N1) &&
4028 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4029 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4030 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4031 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4032 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4033 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4034 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4035 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4038 // fold (xor (and x, y), y) -> (and (not x), y)
4039 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4040 N0->getOperand(1) == N1) {
4041 SDValue X = N0->getOperand(0);
4042 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4043 AddToWorklist(NotX.getNode());
4044 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4046 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4047 if (N1C && N0.getOpcode() == ISD::XOR) {
4048 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4050 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4051 DAG.getConstant(N1C->getAPIntValue() ^
4052 N00C->getAPIntValue(), DL, VT));
4054 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4056 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4057 DAG.getConstant(N1C->getAPIntValue() ^
4058 N01C->getAPIntValue(), DL, VT));
4061 // fold (xor x, x) -> 0
4063 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4065 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4066 // Here is a concrete example of this equivalence:
4068 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4069 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4073 // i16 ~1 == 0b1111111111111110
4074 // i16 rol(~1, 14) == 0b1011111111111111
4076 // Some additional tips to help conceptualize this transform:
4077 // - Try to see the operation as placing a single zero in a value of all ones.
4078 // - There exists no value for x which would allow the result to contain zero.
4079 // - Values of x larger than the bitwidth are undefined and do not require a
4080 // consistent result.
4081 // - Pushing the zero left requires shifting one bits in from the right.
4082 // A rotate left of ~1 is a nice way of achieving the desired result.
4083 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4084 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4086 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4090 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4091 if (N0.getOpcode() == N1.getOpcode()) {
4092 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4093 if (Tmp.getNode()) return Tmp;
4096 // Simplify the expression using non-local knowledge.
4097 if (!VT.isVector() &&
4098 SimplifyDemandedBits(SDValue(N, 0)))
4099 return SDValue(N, 0);
4104 /// Handle transforms common to the three shifts, when the shift amount is a
4106 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4107 SDNode *LHS = N->getOperand(0).getNode();
4108 if (!LHS->hasOneUse()) return SDValue();
4110 // We want to pull some binops through shifts, so that we have (and (shift))
4111 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4112 // thing happens with address calculations, so it's important to canonicalize
4114 bool HighBitSet = false; // Can we transform this if the high bit is set?
4116 switch (LHS->getOpcode()) {
4117 default: return SDValue();
4120 HighBitSet = false; // We can only transform sra if the high bit is clear.
4123 HighBitSet = true; // We can only transform sra if the high bit is set.
4126 if (N->getOpcode() != ISD::SHL)
4127 return SDValue(); // only shl(add) not sr[al](add).
4128 HighBitSet = false; // We can only transform sra if the high bit is clear.
4132 // We require the RHS of the binop to be a constant and not opaque as well.
4133 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4134 if (!BinOpCst) return SDValue();
4136 // FIXME: disable this unless the input to the binop is a shift by a constant.
4137 // If it is not a shift, it pessimizes some common cases like:
4139 // void foo(int *X, int i) { X[i & 1235] = 1; }
4140 // int bar(int *X, int i) { return X[i & 255]; }
4141 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4142 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4143 BinOpLHSVal->getOpcode() != ISD::SRA &&
4144 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4145 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4148 EVT VT = N->getValueType(0);
4150 // If this is a signed shift right, and the high bit is modified by the
4151 // logical operation, do not perform the transformation. The highBitSet
4152 // boolean indicates the value of the high bit of the constant which would
4153 // cause it to be modified for this operation.
4154 if (N->getOpcode() == ISD::SRA) {
4155 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4156 if (BinOpRHSSignSet != HighBitSet)
4160 if (!TLI.isDesirableToCommuteWithShift(LHS))
4163 // Fold the constants, shifting the binop RHS by the shift amount.
4164 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4166 LHS->getOperand(1), N->getOperand(1));
4167 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4169 // Create the new shift.
4170 SDValue NewShift = DAG.getNode(N->getOpcode(),
4171 SDLoc(LHS->getOperand(0)),
4172 VT, LHS->getOperand(0), N->getOperand(1));
4174 // Create the new binop.
4175 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4178 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4179 assert(N->getOpcode() == ISD::TRUNCATE);
4180 assert(N->getOperand(0).getOpcode() == ISD::AND);
4182 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4183 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4184 SDValue N01 = N->getOperand(0).getOperand(1);
4186 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4187 if (!N01C->isOpaque()) {
4188 EVT TruncVT = N->getValueType(0);
4189 SDValue N00 = N->getOperand(0).getOperand(0);
4190 APInt TruncC = N01C->getAPIntValue();
4191 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4194 return DAG.getNode(ISD::AND, DL, TruncVT,
4195 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4196 DAG.getConstant(TruncC, DL, TruncVT));
4204 SDValue DAGCombiner::visitRotate(SDNode *N) {
4205 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4206 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4207 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4208 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4209 if (NewOp1.getNode())
4210 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4211 N->getOperand(0), NewOp1);
4216 SDValue DAGCombiner::visitSHL(SDNode *N) {
4217 SDValue N0 = N->getOperand(0);
4218 SDValue N1 = N->getOperand(1);
4219 EVT VT = N0.getValueType();
4220 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4223 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4224 if (VT.isVector()) {
4225 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4228 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4229 // If setcc produces all-one true value then:
4230 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4231 if (N1CV && N1CV->isConstant()) {
4232 if (N0.getOpcode() == ISD::AND) {
4233 SDValue N00 = N0->getOperand(0);
4234 SDValue N01 = N0->getOperand(1);
4235 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4237 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4238 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4239 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4240 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4242 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4245 N1C = isConstOrConstSplat(N1);
4250 // fold (shl c1, c2) -> c1<<c2
4251 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4252 if (N0C && N1C && !N1C->isOpaque())
4253 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4254 // fold (shl 0, x) -> 0
4255 if (isNullConstant(N0))
4257 // fold (shl x, c >= size(x)) -> undef
4258 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4259 return DAG.getUNDEF(VT);
4260 // fold (shl x, 0) -> x
4261 if (N1C && N1C->isNullValue())
4263 // fold (shl undef, x) -> 0
4264 if (N0.getOpcode() == ISD::UNDEF)
4265 return DAG.getConstant(0, SDLoc(N), VT);
4266 // if (shl x, c) is known to be zero, return 0
4267 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4268 APInt::getAllOnesValue(OpSizeInBits)))
4269 return DAG.getConstant(0, SDLoc(N), VT);
4270 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4271 if (N1.getOpcode() == ISD::TRUNCATE &&
4272 N1.getOperand(0).getOpcode() == ISD::AND) {
4273 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4274 if (NewOp1.getNode())
4275 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4278 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4279 return SDValue(N, 0);
4281 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4282 if (N1C && N0.getOpcode() == ISD::SHL) {
4283 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4284 uint64_t c1 = N0C1->getZExtValue();
4285 uint64_t c2 = N1C->getZExtValue();
4287 if (c1 + c2 >= OpSizeInBits)
4288 return DAG.getConstant(0, DL, VT);
4289 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4290 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4294 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4295 // For this to be valid, the second form must not preserve any of the bits
4296 // that are shifted out by the inner shift in the first form. This means
4297 // the outer shift size must be >= the number of bits added by the ext.
4298 // As a corollary, we don't care what kind of ext it is.
4299 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4300 N0.getOpcode() == ISD::ANY_EXTEND ||
4301 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4302 N0.getOperand(0).getOpcode() == ISD::SHL) {
4303 SDValue N0Op0 = N0.getOperand(0);
4304 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4305 uint64_t c1 = N0Op0C1->getZExtValue();
4306 uint64_t c2 = N1C->getZExtValue();
4307 EVT InnerShiftVT = N0Op0.getValueType();
4308 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4309 if (c2 >= OpSizeInBits - InnerShiftSize) {
4311 if (c1 + c2 >= OpSizeInBits)
4312 return DAG.getConstant(0, DL, VT);
4313 return DAG.getNode(ISD::SHL, DL, VT,
4314 DAG.getNode(N0.getOpcode(), DL, VT,
4315 N0Op0->getOperand(0)),
4316 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4321 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4322 // Only fold this if the inner zext has no other uses to avoid increasing
4323 // the total number of instructions.
4324 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4325 N0.getOperand(0).getOpcode() == ISD::SRL) {
4326 SDValue N0Op0 = N0.getOperand(0);
4327 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4328 uint64_t c1 = N0Op0C1->getZExtValue();
4329 if (c1 < VT.getScalarSizeInBits()) {
4330 uint64_t c2 = N1C->getZExtValue();
4332 SDValue NewOp0 = N0.getOperand(0);
4333 EVT CountVT = NewOp0.getOperand(1).getValueType();
4335 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4337 DAG.getConstant(c2, DL, CountVT));
4338 AddToWorklist(NewSHL.getNode());
4339 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4345 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4346 // (and (srl x, (sub c1, c2), MASK)
4347 // Only fold this if the inner shift has no other uses -- if it does, folding
4348 // this will increase the total number of instructions.
4349 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4350 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4351 uint64_t c1 = N0C1->getZExtValue();
4352 if (c1 < OpSizeInBits) {
4353 uint64_t c2 = N1C->getZExtValue();
4354 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4357 Mask = Mask.shl(c2 - c1);
4359 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4360 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4362 Mask = Mask.lshr(c1 - c2);
4364 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4365 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4368 return DAG.getNode(ISD::AND, DL, VT, Shift,
4369 DAG.getConstant(Mask, DL, VT));
4373 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4374 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4375 unsigned BitSize = VT.getScalarSizeInBits();
4377 SDValue HiBitsMask =
4378 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4379 BitSize - N1C->getZExtValue()),
4381 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4385 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4386 // Variant of version done on multiply, except mul by a power of 2 is turned
4389 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4390 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4391 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4392 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4393 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4394 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4397 if (N1C && !N1C->isOpaque()) {
4398 SDValue NewSHL = visitShiftByConstant(N, N1C);
4399 if (NewSHL.getNode())
4406 SDValue DAGCombiner::visitSRA(SDNode *N) {
4407 SDValue N0 = N->getOperand(0);
4408 SDValue N1 = N->getOperand(1);
4409 EVT VT = N0.getValueType();
4410 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4413 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4414 if (VT.isVector()) {
4415 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4418 N1C = isConstOrConstSplat(N1);
4421 // fold (sra c1, c2) -> (sra c1, c2)
4422 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4423 if (N0C && N1C && !N1C->isOpaque())
4424 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4425 // fold (sra 0, x) -> 0
4426 if (isNullConstant(N0))
4428 // fold (sra -1, x) -> -1
4429 if (isAllOnesConstant(N0))
4431 // fold (sra x, (setge c, size(x))) -> undef
4432 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4433 return DAG.getUNDEF(VT);
4434 // fold (sra x, 0) -> x
4435 if (N1C && N1C->isNullValue())
4437 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4439 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4440 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4441 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4443 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4444 ExtVT, VT.getVectorNumElements());
4445 if ((!LegalOperations ||
4446 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4447 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4448 N0.getOperand(0), DAG.getValueType(ExtVT));
4451 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4452 if (N1C && N0.getOpcode() == ISD::SRA) {
4453 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4454 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4455 if (Sum >= OpSizeInBits)
4456 Sum = OpSizeInBits - 1;
4458 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4459 DAG.getConstant(Sum, DL, N1.getValueType()));
4463 // fold (sra (shl X, m), (sub result_size, n))
4464 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4465 // result_size - n != m.
4466 // If truncate is free for the target sext(shl) is likely to result in better
4468 if (N0.getOpcode() == ISD::SHL && N1C) {
4469 // Get the two constanst of the shifts, CN0 = m, CN = n.
4470 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4472 LLVMContext &Ctx = *DAG.getContext();
4473 // Determine what the truncate's result bitsize and type would be.
4474 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4477 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4479 // Determine the residual right-shift amount.
4480 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4482 // If the shift is not a no-op (in which case this should be just a sign
4483 // extend already), the truncated to type is legal, sign_extend is legal
4484 // on that type, and the truncate to that type is both legal and free,
4485 // perform the transform.
4486 if ((ShiftAmt > 0) &&
4487 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4488 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4489 TLI.isTruncateFree(VT, TruncVT)) {
4492 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4493 getShiftAmountTy(N0.getOperand(0).getValueType()));
4494 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4495 N0.getOperand(0), Amt);
4496 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4498 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4499 N->getValueType(0), Trunc);
4504 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4505 if (N1.getOpcode() == ISD::TRUNCATE &&
4506 N1.getOperand(0).getOpcode() == ISD::AND) {
4507 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4508 if (NewOp1.getNode())
4509 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4512 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4513 // if c1 is equal to the number of bits the trunc removes
4514 if (N0.getOpcode() == ISD::TRUNCATE &&
4515 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4516 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4517 N0.getOperand(0).hasOneUse() &&
4518 N0.getOperand(0).getOperand(1).hasOneUse() &&
4520 SDValue N0Op0 = N0.getOperand(0);
4521 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4522 unsigned LargeShiftVal = LargeShift->getZExtValue();
4523 EVT LargeVT = N0Op0.getValueType();
4525 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4528 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4529 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4530 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4531 N0Op0.getOperand(0), Amt);
4532 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4537 // Simplify, based on bits shifted out of the LHS.
4538 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4539 return SDValue(N, 0);
4542 // If the sign bit is known to be zero, switch this to a SRL.
4543 if (DAG.SignBitIsZero(N0))
4544 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4546 if (N1C && !N1C->isOpaque()) {
4547 SDValue NewSRA = visitShiftByConstant(N, N1C);
4548 if (NewSRA.getNode())
4555 SDValue DAGCombiner::visitSRL(SDNode *N) {
4556 SDValue N0 = N->getOperand(0);
4557 SDValue N1 = N->getOperand(1);
4558 EVT VT = N0.getValueType();
4559 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4562 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4563 if (VT.isVector()) {
4564 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4567 N1C = isConstOrConstSplat(N1);
4570 // fold (srl c1, c2) -> c1 >>u c2
4571 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4572 if (N0C && N1C && !N1C->isOpaque())
4573 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4574 // fold (srl 0, x) -> 0
4575 if (isNullConstant(N0))
4577 // fold (srl x, c >= size(x)) -> undef
4578 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4579 return DAG.getUNDEF(VT);
4580 // fold (srl x, 0) -> x
4581 if (N1C && N1C->isNullValue())
4583 // if (srl x, c) is known to be zero, return 0
4584 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4585 APInt::getAllOnesValue(OpSizeInBits)))
4586 return DAG.getConstant(0, SDLoc(N), VT);
4588 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4589 if (N1C && N0.getOpcode() == ISD::SRL) {
4590 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4591 uint64_t c1 = N01C->getZExtValue();
4592 uint64_t c2 = N1C->getZExtValue();
4594 if (c1 + c2 >= OpSizeInBits)
4595 return DAG.getConstant(0, DL, VT);
4596 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4597 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4601 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4602 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4603 N0.getOperand(0).getOpcode() == ISD::SRL &&
4604 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4606 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4607 uint64_t c2 = N1C->getZExtValue();
4608 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4609 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4610 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4611 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4612 if (c1 + OpSizeInBits == InnerShiftSize) {
4614 if (c1 + c2 >= InnerShiftSize)
4615 return DAG.getConstant(0, DL, VT);
4616 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4617 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4618 N0.getOperand(0)->getOperand(0),
4619 DAG.getConstant(c1 + c2, DL,
4624 // fold (srl (shl x, c), c) -> (and x, cst2)
4625 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4626 unsigned BitSize = N0.getScalarValueSizeInBits();
4627 if (BitSize <= 64) {
4628 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4630 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4631 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4635 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4636 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4637 // Shifting in all undef bits?
4638 EVT SmallVT = N0.getOperand(0).getValueType();
4639 unsigned BitSize = SmallVT.getScalarSizeInBits();
4640 if (N1C->getZExtValue() >= BitSize)
4641 return DAG.getUNDEF(VT);
4643 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4644 uint64_t ShiftAmt = N1C->getZExtValue();
4646 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4648 DAG.getConstant(ShiftAmt, DL0,
4649 getShiftAmountTy(SmallVT)));
4650 AddToWorklist(SmallShift.getNode());
4651 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4653 return DAG.getNode(ISD::AND, DL, VT,
4654 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4655 DAG.getConstant(Mask, DL, VT));
4659 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4660 // bit, which is unmodified by sra.
4661 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4662 if (N0.getOpcode() == ISD::SRA)
4663 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4666 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4667 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4668 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4669 APInt KnownZero, KnownOne;
4670 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4672 // If any of the input bits are KnownOne, then the input couldn't be all
4673 // zeros, thus the result of the srl will always be zero.
4674 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4676 // If all of the bits input the to ctlz node are known to be zero, then
4677 // the result of the ctlz is "32" and the result of the shift is one.
4678 APInt UnknownBits = ~KnownZero;
4679 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4681 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4682 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4683 // Okay, we know that only that the single bit specified by UnknownBits
4684 // could be set on input to the CTLZ node. If this bit is set, the SRL
4685 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4686 // to an SRL/XOR pair, which is likely to simplify more.
4687 unsigned ShAmt = UnknownBits.countTrailingZeros();
4688 SDValue Op = N0.getOperand(0);
4692 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4693 DAG.getConstant(ShAmt, DL,
4694 getShiftAmountTy(Op.getValueType())));
4695 AddToWorklist(Op.getNode());
4699 return DAG.getNode(ISD::XOR, DL, VT,
4700 Op, DAG.getConstant(1, DL, VT));
4704 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4705 if (N1.getOpcode() == ISD::TRUNCATE &&
4706 N1.getOperand(0).getOpcode() == ISD::AND) {
4707 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4708 if (NewOp1.getNode())
4709 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4712 // fold operands of srl based on knowledge that the low bits are not
4714 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4715 return SDValue(N, 0);
4717 if (N1C && !N1C->isOpaque()) {
4718 SDValue NewSRL = visitShiftByConstant(N, N1C);
4719 if (NewSRL.getNode())
4723 // Attempt to convert a srl of a load into a narrower zero-extending load.
4724 SDValue NarrowLoad = ReduceLoadWidth(N);
4725 if (NarrowLoad.getNode())
4728 // Here is a common situation. We want to optimize:
4731 // %b = and i32 %a, 2
4732 // %c = srl i32 %b, 1
4733 // brcond i32 %c ...
4739 // %c = setcc eq %b, 0
4742 // However when after the source operand of SRL is optimized into AND, the SRL
4743 // itself may not be optimized further. Look for it and add the BRCOND into
4745 if (N->hasOneUse()) {
4746 SDNode *Use = *N->use_begin();
4747 if (Use->getOpcode() == ISD::BRCOND)
4749 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4750 // Also look pass the truncate.
4751 Use = *Use->use_begin();
4752 if (Use->getOpcode() == ISD::BRCOND)
4760 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4761 SDValue N0 = N->getOperand(0);
4762 EVT VT = N->getValueType(0);
4764 // fold (ctlz c1) -> c2
4765 if (isa<ConstantSDNode>(N0))
4766 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4770 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4771 SDValue N0 = N->getOperand(0);
4772 EVT VT = N->getValueType(0);
4774 // fold (ctlz_zero_undef c1) -> c2
4775 if (isa<ConstantSDNode>(N0))
4776 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4780 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4781 SDValue N0 = N->getOperand(0);
4782 EVT VT = N->getValueType(0);
4784 // fold (cttz c1) -> c2
4785 if (isa<ConstantSDNode>(N0))
4786 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4790 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4791 SDValue N0 = N->getOperand(0);
4792 EVT VT = N->getValueType(0);
4794 // fold (cttz_zero_undef c1) -> c2
4795 if (isa<ConstantSDNode>(N0))
4796 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4800 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4801 SDValue N0 = N->getOperand(0);
4802 EVT VT = N->getValueType(0);
4804 // fold (ctpop c1) -> c2
4805 if (isa<ConstantSDNode>(N0))
4806 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4811 /// \brief Generate Min/Max node
4812 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4813 SDValue True, SDValue False,
4814 ISD::CondCode CC, const TargetLowering &TLI,
4815 SelectionDAG &DAG) {
4816 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4826 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4827 if (TLI.isOperationLegal(Opcode, VT))
4828 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4837 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4838 if (TLI.isOperationLegal(Opcode, VT))
4839 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4847 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4848 SDValue N0 = N->getOperand(0);
4849 SDValue N1 = N->getOperand(1);
4850 SDValue N2 = N->getOperand(2);
4851 EVT VT = N->getValueType(0);
4852 EVT VT0 = N0.getValueType();
4854 // fold (select C, X, X) -> X
4857 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4858 // fold (select true, X, Y) -> X
4859 // fold (select false, X, Y) -> Y
4860 return !N0C->isNullValue() ? N1 : N2;
4862 // fold (select C, 1, X) -> (or C, X)
4863 if (VT == MVT::i1 && isOneConstant(N1))
4864 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4865 // fold (select C, 0, 1) -> (xor C, 1)
4866 // We can't do this reliably if integer based booleans have different contents
4867 // to floating point based booleans. This is because we can't tell whether we
4868 // have an integer-based boolean or a floating-point-based boolean unless we
4869 // can find the SETCC that produced it and inspect its operands. This is
4870 // fairly easy if C is the SETCC node, but it can potentially be
4871 // undiscoverable (or not reasonably discoverable). For example, it could be
4872 // in another basic block or it could require searching a complicated
4874 if (VT.isInteger() &&
4875 (VT0 == MVT::i1 || (VT0.isInteger() &&
4876 TLI.getBooleanContents(false, false) ==
4877 TLI.getBooleanContents(false, true) &&
4878 TLI.getBooleanContents(false, false) ==
4879 TargetLowering::ZeroOrOneBooleanContent)) &&
4880 isNullConstant(N1) && isOneConstant(N2)) {
4884 return DAG.getNode(ISD::XOR, DL, VT0,
4885 N0, DAG.getConstant(1, DL, VT0));
4888 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4889 N0, DAG.getConstant(1, DL0, VT0));
4890 AddToWorklist(XORNode.getNode());
4892 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4893 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4895 // fold (select C, 0, X) -> (and (not C), X)
4896 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4897 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4898 AddToWorklist(NOTNode.getNode());
4899 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4901 // fold (select C, X, 1) -> (or (not C), X)
4902 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4903 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4904 AddToWorklist(NOTNode.getNode());
4905 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4907 // fold (select C, X, 0) -> (and C, X)
4908 if (VT == MVT::i1 && isNullConstant(N2))
4909 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4910 // fold (select X, X, Y) -> (or X, Y)
4911 // fold (select X, 1, Y) -> (or X, Y)
4912 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4913 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4914 // fold (select X, Y, X) -> (and X, Y)
4915 // fold (select X, Y, 0) -> (and X, Y)
4916 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4917 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4919 // If we can fold this based on the true/false value, do so.
4920 if (SimplifySelectOps(N, N1, N2))
4921 return SDValue(N, 0); // Don't revisit N.
4923 // fold selects based on a setcc into other things, such as min/max/abs
4924 if (N0.getOpcode() == ISD::SETCC) {
4925 // select x, y (fcmp lt x, y) -> fminnum x, y
4926 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4928 // This is OK if we don't care about what happens if either operand is a
4932 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4933 // no signed zeros as well as no nans.
4934 const TargetOptions &Options = DAG.getTarget().Options;
4935 if (Options.UnsafeFPMath &&
4936 VT.isFloatingPoint() && N0.hasOneUse() &&
4937 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4938 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4941 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4942 N1, N2, CC, TLI, DAG);
4947 if ((!LegalOperations &&
4948 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4949 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4950 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4951 N0.getOperand(0), N0.getOperand(1),
4952 N1, N2, N0.getOperand(2));
4953 return SimplifySelect(SDLoc(N), N0, N1, N2);
4956 if (VT0 == MVT::i1) {
4957 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4958 // select (and Cond0, Cond1), X, Y
4959 // -> select Cond0, (select Cond1, X, Y), Y
4960 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4961 SDValue Cond0 = N0->getOperand(0);
4962 SDValue Cond1 = N0->getOperand(1);
4963 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4964 N1.getValueType(), Cond1, N1, N2);
4965 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4968 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4969 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4970 SDValue Cond0 = N0->getOperand(0);
4971 SDValue Cond1 = N0->getOperand(1);
4972 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4973 N1.getValueType(), Cond1, N1, N2);
4974 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4979 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4980 if (N1->getOpcode() == ISD::SELECT) {
4981 SDValue N1_0 = N1->getOperand(0);
4982 SDValue N1_1 = N1->getOperand(1);
4983 SDValue N1_2 = N1->getOperand(2);
4984 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4985 // Create the actual and node if we can generate good code for it.
4986 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4987 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4989 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4992 // Otherwise see if we can optimize the "and" to a better pattern.
4993 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4994 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4998 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4999 if (N2->getOpcode() == ISD::SELECT) {
5000 SDValue N2_0 = N2->getOperand(0);
5001 SDValue N2_1 = N2->getOperand(1);
5002 SDValue N2_2 = N2->getOperand(2);
5003 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5004 // Create the actual or node if we can generate good code for it.
5005 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5006 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5008 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5011 // Otherwise see if we can optimize to a better pattern.
5012 if (SDValue Combined = visitORLike(N0, N2_0, N))
5013 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5023 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5026 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5028 // Split the inputs.
5029 SDValue Lo, Hi, LL, LH, RL, RH;
5030 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5031 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5033 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5034 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5036 return std::make_pair(Lo, Hi);
5039 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5040 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5041 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5043 SDValue Cond = N->getOperand(0);
5044 SDValue LHS = N->getOperand(1);
5045 SDValue RHS = N->getOperand(2);
5046 EVT VT = N->getValueType(0);
5047 int NumElems = VT.getVectorNumElements();
5048 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5049 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5050 Cond.getOpcode() == ISD::BUILD_VECTOR);
5052 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5053 // binary ones here.
5054 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5057 // We're sure we have an even number of elements due to the
5058 // concat_vectors we have as arguments to vselect.
5059 // Skip BV elements until we find one that's not an UNDEF
5060 // After we find an UNDEF element, keep looping until we get to half the
5061 // length of the BV and see if all the non-undef nodes are the same.
5062 ConstantSDNode *BottomHalf = nullptr;
5063 for (int i = 0; i < NumElems / 2; ++i) {
5064 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5067 if (BottomHalf == nullptr)
5068 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5069 else if (Cond->getOperand(i).getNode() != BottomHalf)
5073 // Do the same for the second half of the BuildVector
5074 ConstantSDNode *TopHalf = nullptr;
5075 for (int i = NumElems / 2; i < NumElems; ++i) {
5076 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5079 if (TopHalf == nullptr)
5080 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5081 else if (Cond->getOperand(i).getNode() != TopHalf)
5085 assert(TopHalf && BottomHalf &&
5086 "One half of the selector was all UNDEFs and the other was all the "
5087 "same value. This should have been addressed before this function.");
5089 ISD::CONCAT_VECTORS, dl, VT,
5090 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5091 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5094 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5096 if (Level >= AfterLegalizeTypes)
5099 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5100 SDValue Mask = MSC->getMask();
5101 SDValue Data = MSC->getValue();
5104 // If the MSCATTER data type requires splitting and the mask is provided by a
5105 // SETCC, then split both nodes and its operands before legalization. This
5106 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5107 // and enables future optimizations (e.g. min/max pattern matching on X86).
5108 if (Mask.getOpcode() != ISD::SETCC)
5111 // Check if any splitting is required.
5112 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5113 TargetLowering::TypeSplitVector)
5115 SDValue MaskLo, MaskHi, Lo, Hi;
5116 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5119 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5121 SDValue Chain = MSC->getChain();
5123 EVT MemoryVT = MSC->getMemoryVT();
5124 unsigned Alignment = MSC->getOriginalAlignment();
5126 EVT LoMemVT, HiMemVT;
5127 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5129 SDValue DataLo, DataHi;
5130 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5132 SDValue BasePtr = MSC->getBasePtr();
5133 SDValue IndexLo, IndexHi;
5134 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5136 MachineMemOperand *MMO = DAG.getMachineFunction().
5137 getMachineMemOperand(MSC->getPointerInfo(),
5138 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5139 Alignment, MSC->getAAInfo(), MSC->getRanges());
5141 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5142 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5145 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5146 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5149 AddToWorklist(Lo.getNode());
5150 AddToWorklist(Hi.getNode());
5152 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5155 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5157 if (Level >= AfterLegalizeTypes)
5160 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5161 SDValue Mask = MST->getMask();
5162 SDValue Data = MST->getValue();
5165 // If the MSTORE data type requires splitting and the mask is provided by a
5166 // SETCC, then split both nodes and its operands before legalization. This
5167 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5168 // and enables future optimizations (e.g. min/max pattern matching on X86).
5169 if (Mask.getOpcode() == ISD::SETCC) {
5171 // Check if any splitting is required.
5172 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5173 TargetLowering::TypeSplitVector)
5176 SDValue MaskLo, MaskHi, Lo, Hi;
5177 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5180 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5182 SDValue Chain = MST->getChain();
5183 SDValue Ptr = MST->getBasePtr();
5185 EVT MemoryVT = MST->getMemoryVT();
5186 unsigned Alignment = MST->getOriginalAlignment();
5188 // if Alignment is equal to the vector size,
5189 // take the half of it for the second part
5190 unsigned SecondHalfAlignment =
5191 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5192 Alignment/2 : Alignment;
5194 EVT LoMemVT, HiMemVT;
5195 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5197 SDValue DataLo, DataHi;
5198 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5200 MachineMemOperand *MMO = DAG.getMachineFunction().
5201 getMachineMemOperand(MST->getPointerInfo(),
5202 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5203 Alignment, MST->getAAInfo(), MST->getRanges());
5205 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5206 MST->isTruncatingStore());
5208 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5209 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5210 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5212 MMO = DAG.getMachineFunction().
5213 getMachineMemOperand(MST->getPointerInfo(),
5214 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5215 SecondHalfAlignment, MST->getAAInfo(),
5218 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5219 MST->isTruncatingStore());
5221 AddToWorklist(Lo.getNode());
5222 AddToWorklist(Hi.getNode());
5224 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5229 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5231 if (Level >= AfterLegalizeTypes)
5234 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5235 SDValue Mask = MGT->getMask();
5238 // If the MGATHER result requires splitting and the mask is provided by a
5239 // SETCC, then split both nodes and its operands before legalization. This
5240 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5241 // and enables future optimizations (e.g. min/max pattern matching on X86).
5243 if (Mask.getOpcode() != ISD::SETCC)
5246 EVT VT = N->getValueType(0);
5248 // Check if any splitting is required.
5249 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5250 TargetLowering::TypeSplitVector)
5253 SDValue MaskLo, MaskHi, Lo, Hi;
5254 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5256 SDValue Src0 = MGT->getValue();
5257 SDValue Src0Lo, Src0Hi;
5258 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5261 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5263 SDValue Chain = MGT->getChain();
5264 EVT MemoryVT = MGT->getMemoryVT();
5265 unsigned Alignment = MGT->getOriginalAlignment();
5267 EVT LoMemVT, HiMemVT;
5268 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5270 SDValue BasePtr = MGT->getBasePtr();
5271 SDValue Index = MGT->getIndex();
5272 SDValue IndexLo, IndexHi;
5273 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5275 MachineMemOperand *MMO = DAG.getMachineFunction().
5276 getMachineMemOperand(MGT->getPointerInfo(),
5277 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5278 Alignment, MGT->getAAInfo(), MGT->getRanges());
5280 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5281 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5284 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5285 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5288 AddToWorklist(Lo.getNode());
5289 AddToWorklist(Hi.getNode());
5291 // Build a factor node to remember that this load is independent of the
5293 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5296 // Legalized the chain result - switch anything that used the old chain to
5298 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5300 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5302 SDValue RetOps[] = { GatherRes, Chain };
5303 return DAG.getMergeValues(RetOps, DL);
5306 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5308 if (Level >= AfterLegalizeTypes)
5311 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5312 SDValue Mask = MLD->getMask();
5315 // If the MLOAD result requires splitting and the mask is provided by a
5316 // SETCC, then split both nodes and its operands before legalization. This
5317 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5318 // and enables future optimizations (e.g. min/max pattern matching on X86).
5320 if (Mask.getOpcode() == ISD::SETCC) {
5321 EVT VT = N->getValueType(0);
5323 // Check if any splitting is required.
5324 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5325 TargetLowering::TypeSplitVector)
5328 SDValue MaskLo, MaskHi, Lo, Hi;
5329 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5331 SDValue Src0 = MLD->getSrc0();
5332 SDValue Src0Lo, Src0Hi;
5333 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5336 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5338 SDValue Chain = MLD->getChain();
5339 SDValue Ptr = MLD->getBasePtr();
5340 EVT MemoryVT = MLD->getMemoryVT();
5341 unsigned Alignment = MLD->getOriginalAlignment();
5343 // if Alignment is equal to the vector size,
5344 // take the half of it for the second part
5345 unsigned SecondHalfAlignment =
5346 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5347 Alignment/2 : Alignment;
5349 EVT LoMemVT, HiMemVT;
5350 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5352 MachineMemOperand *MMO = DAG.getMachineFunction().
5353 getMachineMemOperand(MLD->getPointerInfo(),
5354 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5355 Alignment, MLD->getAAInfo(), MLD->getRanges());
5357 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5360 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5361 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5362 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5364 MMO = DAG.getMachineFunction().
5365 getMachineMemOperand(MLD->getPointerInfo(),
5366 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5367 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5369 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5372 AddToWorklist(Lo.getNode());
5373 AddToWorklist(Hi.getNode());
5375 // Build a factor node to remember that this load is independent of the
5377 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5380 // Legalized the chain result - switch anything that used the old chain to
5382 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5384 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5386 SDValue RetOps[] = { LoadRes, Chain };
5387 return DAG.getMergeValues(RetOps, DL);
5392 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5393 SDValue N0 = N->getOperand(0);
5394 SDValue N1 = N->getOperand(1);
5395 SDValue N2 = N->getOperand(2);
5398 // Canonicalize integer abs.
5399 // vselect (setg[te] X, 0), X, -X ->
5400 // vselect (setgt X, -1), X, -X ->
5401 // vselect (setl[te] X, 0), -X, X ->
5402 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5403 if (N0.getOpcode() == ISD::SETCC) {
5404 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5405 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5407 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5409 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5410 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5411 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5412 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5413 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5414 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5415 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5418 EVT VT = LHS.getValueType();
5419 SDValue Shift = DAG.getNode(
5420 ISD::SRA, DL, VT, LHS,
5421 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5422 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5423 AddToWorklist(Shift.getNode());
5424 AddToWorklist(Add.getNode());
5425 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5429 if (SimplifySelectOps(N, N1, N2))
5430 return SDValue(N, 0); // Don't revisit N.
5432 // If the VSELECT result requires splitting and the mask is provided by a
5433 // SETCC, then split both nodes and its operands before legalization. This
5434 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5435 // and enables future optimizations (e.g. min/max pattern matching on X86).
5436 if (N0.getOpcode() == ISD::SETCC) {
5437 EVT VT = N->getValueType(0);
5439 // Check if any splitting is required.
5440 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5441 TargetLowering::TypeSplitVector)
5444 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5445 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5446 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5447 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5449 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5450 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5452 // Add the new VSELECT nodes to the work list in case they need to be split
5454 AddToWorklist(Lo.getNode());
5455 AddToWorklist(Hi.getNode());
5457 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5460 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5461 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5463 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5464 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5467 // The ConvertSelectToConcatVector function is assuming both the above
5468 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5470 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5471 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5472 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5473 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5481 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5482 SDValue N0 = N->getOperand(0);
5483 SDValue N1 = N->getOperand(1);
5484 SDValue N2 = N->getOperand(2);
5485 SDValue N3 = N->getOperand(3);
5486 SDValue N4 = N->getOperand(4);
5487 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5489 // fold select_cc lhs, rhs, x, x, cc -> x
5493 // Determine if the condition we're dealing with is constant
5494 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5495 N0, N1, CC, SDLoc(N), false);
5496 if (SCC.getNode()) {
5497 AddToWorklist(SCC.getNode());
5499 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5500 if (!SCCC->isNullValue())
5501 return N2; // cond always true -> true val
5503 return N3; // cond always false -> false val
5504 } else if (SCC->getOpcode() == ISD::UNDEF) {
5505 // When the condition is UNDEF, just return the first operand. This is
5506 // coherent the DAG creation, no setcc node is created in this case
5508 } else if (SCC.getOpcode() == ISD::SETCC) {
5509 // Fold to a simpler select_cc
5510 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5511 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5516 // If we can fold this based on the true/false value, do so.
5517 if (SimplifySelectOps(N, N2, N3))
5518 return SDValue(N, 0); // Don't revisit N.
5520 // fold select_cc into other things, such as min/max/abs
5521 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5524 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5525 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5526 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5530 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5531 // dag node into a ConstantSDNode or a build_vector of constants.
5532 // This function is called by the DAGCombiner when visiting sext/zext/aext
5533 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5534 // Vector extends are not folded if operations are legal; this is to
5535 // avoid introducing illegal build_vector dag nodes.
5536 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5537 SelectionDAG &DAG, bool LegalTypes,
5538 bool LegalOperations) {
5539 unsigned Opcode = N->getOpcode();
5540 SDValue N0 = N->getOperand(0);
5541 EVT VT = N->getValueType(0);
5543 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5544 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5546 // fold (sext c1) -> c1
5547 // fold (zext c1) -> c1
5548 // fold (aext c1) -> c1
5549 if (isa<ConstantSDNode>(N0))
5550 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5552 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5553 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5554 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5555 EVT SVT = VT.getScalarType();
5556 if (!(VT.isVector() &&
5557 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5558 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5561 // We can fold this node into a build_vector.
5562 unsigned VTBits = SVT.getSizeInBits();
5563 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5564 unsigned ShAmt = VTBits - EVTBits;
5565 SmallVector<SDValue, 8> Elts;
5566 unsigned NumElts = N0->getNumOperands();
5569 for (unsigned i=0; i != NumElts; ++i) {
5570 SDValue Op = N0->getOperand(i);
5571 if (Op->getOpcode() == ISD::UNDEF) {
5572 Elts.push_back(DAG.getUNDEF(SVT));
5577 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5578 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5579 if (Opcode == ISD::SIGN_EXTEND)
5580 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5583 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5587 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5590 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5591 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5592 // transformation. Returns true if extension are possible and the above
5593 // mentioned transformation is profitable.
5594 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5596 SmallVectorImpl<SDNode *> &ExtendNodes,
5597 const TargetLowering &TLI) {
5598 bool HasCopyToRegUses = false;
5599 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5600 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5601 UE = N0.getNode()->use_end();
5606 if (UI.getUse().getResNo() != N0.getResNo())
5608 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5609 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5610 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5611 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5612 // Sign bits will be lost after a zext.
5615 for (unsigned i = 0; i != 2; ++i) {
5616 SDValue UseOp = User->getOperand(i);
5619 if (!isa<ConstantSDNode>(UseOp))
5624 ExtendNodes.push_back(User);
5627 // If truncates aren't free and there are users we can't
5628 // extend, it isn't worthwhile.
5631 // Remember if this value is live-out.
5632 if (User->getOpcode() == ISD::CopyToReg)
5633 HasCopyToRegUses = true;
5636 if (HasCopyToRegUses) {
5637 bool BothLiveOut = false;
5638 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5640 SDUse &Use = UI.getUse();
5641 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5647 // Both unextended and extended values are live out. There had better be
5648 // a good reason for the transformation.
5649 return ExtendNodes.size();
5654 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5655 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5656 ISD::NodeType ExtType) {
5657 // Extend SetCC uses if necessary.
5658 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5659 SDNode *SetCC = SetCCs[i];
5660 SmallVector<SDValue, 4> Ops;
5662 for (unsigned j = 0; j != 2; ++j) {
5663 SDValue SOp = SetCC->getOperand(j);
5665 Ops.push_back(ExtLoad);
5667 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5670 Ops.push_back(SetCC->getOperand(2));
5671 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5675 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5676 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5677 SDValue N0 = N->getOperand(0);
5678 EVT DstVT = N->getValueType(0);
5679 EVT SrcVT = N0.getValueType();
5681 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5682 N->getOpcode() == ISD::ZERO_EXTEND) &&
5683 "Unexpected node type (not an extend)!");
5685 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5686 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5687 // (v8i32 (sext (v8i16 (load x))))
5689 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5690 // (v4i32 (sextload (x + 16)))))
5691 // Where uses of the original load, i.e.:
5693 // are replaced with:
5695 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5696 // (v4i32 (sextload (x + 16)))))))
5698 // This combine is only applicable to illegal, but splittable, vectors.
5699 // All legal types, and illegal non-vector types, are handled elsewhere.
5700 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5702 if (N0->getOpcode() != ISD::LOAD)
5705 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5707 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5708 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5709 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5712 SmallVector<SDNode *, 4> SetCCs;
5713 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5716 ISD::LoadExtType ExtType =
5717 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5719 // Try to split the vector types to get down to legal types.
5720 EVT SplitSrcVT = SrcVT;
5721 EVT SplitDstVT = DstVT;
5722 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5723 SplitSrcVT.getVectorNumElements() > 1) {
5724 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5725 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5728 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5732 const unsigned NumSplits =
5733 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5734 const unsigned Stride = SplitSrcVT.getStoreSize();
5735 SmallVector<SDValue, 4> Loads;
5736 SmallVector<SDValue, 4> Chains;
5738 SDValue BasePtr = LN0->getBasePtr();
5739 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5740 const unsigned Offset = Idx * Stride;
5741 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5743 SDValue SplitLoad = DAG.getExtLoad(
5744 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5745 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5746 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5747 Align, LN0->getAAInfo());
5749 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5750 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5752 Loads.push_back(SplitLoad.getValue(0));
5753 Chains.push_back(SplitLoad.getValue(1));
5756 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5757 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5759 CombineTo(N, NewValue);
5761 // Replace uses of the original load (before extension)
5762 // with a truncate of the concatenated sextloaded vectors.
5764 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5765 CombineTo(N0.getNode(), Trunc, NewChain);
5766 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5767 (ISD::NodeType)N->getOpcode());
5768 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5771 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5772 SDValue N0 = N->getOperand(0);
5773 EVT VT = N->getValueType(0);
5775 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5777 return SDValue(Res, 0);
5779 // fold (sext (sext x)) -> (sext x)
5780 // fold (sext (aext x)) -> (sext x)
5781 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5782 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5785 if (N0.getOpcode() == ISD::TRUNCATE) {
5786 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5787 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5788 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5789 if (NarrowLoad.getNode()) {
5790 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5791 if (NarrowLoad.getNode() != N0.getNode()) {
5792 CombineTo(N0.getNode(), NarrowLoad);
5793 // CombineTo deleted the truncate, if needed, but not what's under it.
5796 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5799 // See if the value being truncated is already sign extended. If so, just
5800 // eliminate the trunc/sext pair.
5801 SDValue Op = N0.getOperand(0);
5802 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5803 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5804 unsigned DestBits = VT.getScalarType().getSizeInBits();
5805 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5807 if (OpBits == DestBits) {
5808 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5809 // bits, it is already ready.
5810 if (NumSignBits > DestBits-MidBits)
5812 } else if (OpBits < DestBits) {
5813 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5814 // bits, just sext from i32.
5815 if (NumSignBits > OpBits-MidBits)
5816 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5818 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5819 // bits, just truncate to i32.
5820 if (NumSignBits > OpBits-MidBits)
5821 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5824 // fold (sext (truncate x)) -> (sextinreg x).
5825 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5826 N0.getValueType())) {
5827 if (OpBits < DestBits)
5828 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5829 else if (OpBits > DestBits)
5830 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5831 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5832 DAG.getValueType(N0.getValueType()));
5836 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5837 // Only generate vector extloads when 1) they're legal, and 2) they are
5838 // deemed desirable by the target.
5839 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5840 ((!LegalOperations && !VT.isVector() &&
5841 !cast<LoadSDNode>(N0)->isVolatile()) ||
5842 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5843 bool DoXform = true;
5844 SmallVector<SDNode*, 4> SetCCs;
5845 if (!N0.hasOneUse())
5846 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5848 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5850 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5851 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5853 LN0->getBasePtr(), N0.getValueType(),
5854 LN0->getMemOperand());
5855 CombineTo(N, ExtLoad);
5856 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5857 N0.getValueType(), ExtLoad);
5858 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5859 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5861 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5865 // fold (sext (load x)) to multiple smaller sextloads.
5866 // Only on illegal but splittable vectors.
5867 if (SDValue ExtLoad = CombineExtLoad(N))
5870 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5871 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5872 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5873 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5874 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5875 EVT MemVT = LN0->getMemoryVT();
5876 if ((!LegalOperations && !LN0->isVolatile()) ||
5877 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5878 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5880 LN0->getBasePtr(), MemVT,
5881 LN0->getMemOperand());
5882 CombineTo(N, ExtLoad);
5883 CombineTo(N0.getNode(),
5884 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5885 N0.getValueType(), ExtLoad),
5886 ExtLoad.getValue(1));
5887 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5891 // fold (sext (and/or/xor (load x), cst)) ->
5892 // (and/or/xor (sextload x), (sext cst))
5893 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5894 N0.getOpcode() == ISD::XOR) &&
5895 isa<LoadSDNode>(N0.getOperand(0)) &&
5896 N0.getOperand(1).getOpcode() == ISD::Constant &&
5897 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5898 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5899 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5900 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5901 bool DoXform = true;
5902 SmallVector<SDNode*, 4> SetCCs;
5903 if (!N0.hasOneUse())
5904 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5907 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5908 LN0->getChain(), LN0->getBasePtr(),
5910 LN0->getMemOperand());
5911 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5912 Mask = Mask.sext(VT.getSizeInBits());
5914 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5915 ExtLoad, DAG.getConstant(Mask, DL, VT));
5916 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5917 SDLoc(N0.getOperand(0)),
5918 N0.getOperand(0).getValueType(), ExtLoad);
5920 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5921 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5923 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5928 if (N0.getOpcode() == ISD::SETCC) {
5929 EVT N0VT = N0.getOperand(0).getValueType();
5930 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5931 // Only do this before legalize for now.
5932 if (VT.isVector() && !LegalOperations &&
5933 TLI.getBooleanContents(N0VT) ==
5934 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5935 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5936 // of the same size as the compared operands. Only optimize sext(setcc())
5937 // if this is the case.
5938 EVT SVT = getSetCCResultType(N0VT);
5940 // We know that the # elements of the results is the same as the
5941 // # elements of the compare (and the # elements of the compare result
5942 // for that matter). Check to see that they are the same size. If so,
5943 // we know that the element size of the sext'd result matches the
5944 // element size of the compare operands.
5945 if (VT.getSizeInBits() == SVT.getSizeInBits())
5946 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5948 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5950 // If the desired elements are smaller or larger than the source
5951 // elements we can use a matching integer vector type and then
5952 // truncate/sign extend
5953 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5954 if (SVT == MatchingVectorType) {
5955 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5956 N0.getOperand(0), N0.getOperand(1),
5957 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5958 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5962 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5963 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5966 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5968 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5969 NegOne, DAG.getConstant(0, DL, VT),
5970 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5971 if (SCC.getNode()) return SCC;
5973 if (!VT.isVector()) {
5974 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5975 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5977 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5978 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5979 N0.getOperand(0), N0.getOperand(1), CC);
5980 return DAG.getSelect(DL, VT, SetCC,
5981 NegOne, DAG.getConstant(0, DL, VT));
5986 // fold (sext x) -> (zext x) if the sign bit is known zero.
5987 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5988 DAG.SignBitIsZero(N0))
5989 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5994 // isTruncateOf - If N is a truncate of some other value, return true, record
5995 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5996 // This function computes KnownZero to avoid a duplicated call to
5997 // computeKnownBits in the caller.
5998 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6001 if (N->getOpcode() == ISD::TRUNCATE) {
6002 Op = N->getOperand(0);
6003 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6007 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6008 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6011 SDValue Op0 = N->getOperand(0);
6012 SDValue Op1 = N->getOperand(1);
6013 assert(Op0.getValueType() == Op1.getValueType());
6015 if (isNullConstant(Op0))
6017 else if (isNullConstant(Op1))
6022 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6024 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6030 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6031 SDValue N0 = N->getOperand(0);
6032 EVT VT = N->getValueType(0);
6034 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6036 return SDValue(Res, 0);
6038 // fold (zext (zext x)) -> (zext x)
6039 // fold (zext (aext x)) -> (zext x)
6040 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6041 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6044 // fold (zext (truncate x)) -> (zext x) or
6045 // (zext (truncate x)) -> (truncate x)
6046 // This is valid when the truncated bits of x are already zero.
6047 // FIXME: We should extend this to work for vectors too.
6050 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6051 APInt TruncatedBits =
6052 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6053 APInt(Op.getValueSizeInBits(), 0) :
6054 APInt::getBitsSet(Op.getValueSizeInBits(),
6055 N0.getValueSizeInBits(),
6056 std::min(Op.getValueSizeInBits(),
6057 VT.getSizeInBits()));
6058 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6059 if (VT.bitsGT(Op.getValueType()))
6060 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6061 if (VT.bitsLT(Op.getValueType()))
6062 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6068 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6069 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6070 if (N0.getOpcode() == ISD::TRUNCATE) {
6071 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6072 if (NarrowLoad.getNode()) {
6073 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6074 if (NarrowLoad.getNode() != N0.getNode()) {
6075 CombineTo(N0.getNode(), NarrowLoad);
6076 // CombineTo deleted the truncate, if needed, but not what's under it.
6079 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6083 // fold (zext (truncate x)) -> (and x, mask)
6084 if (N0.getOpcode() == ISD::TRUNCATE &&
6085 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6087 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6088 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6089 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6090 if (NarrowLoad.getNode()) {
6091 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6092 if (NarrowLoad.getNode() != N0.getNode()) {
6093 CombineTo(N0.getNode(), NarrowLoad);
6094 // CombineTo deleted the truncate, if needed, but not what's under it.
6097 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6100 SDValue Op = N0.getOperand(0);
6101 if (Op.getValueType().bitsLT(VT)) {
6102 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6103 AddToWorklist(Op.getNode());
6104 } else if (Op.getValueType().bitsGT(VT)) {
6105 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6106 AddToWorklist(Op.getNode());
6108 return DAG.getZeroExtendInReg(Op, SDLoc(N),
6109 N0.getValueType().getScalarType());
6112 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6113 // if either of the casts is not free.
6114 if (N0.getOpcode() == ISD::AND &&
6115 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6116 N0.getOperand(1).getOpcode() == ISD::Constant &&
6117 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6118 N0.getValueType()) ||
6119 !TLI.isZExtFree(N0.getValueType(), VT))) {
6120 SDValue X = N0.getOperand(0).getOperand(0);
6121 if (X.getValueType().bitsLT(VT)) {
6122 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6123 } else if (X.getValueType().bitsGT(VT)) {
6124 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6126 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6127 Mask = Mask.zext(VT.getSizeInBits());
6129 return DAG.getNode(ISD::AND, DL, VT,
6130 X, DAG.getConstant(Mask, DL, VT));
6133 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6134 // Only generate vector extloads when 1) they're legal, and 2) they are
6135 // deemed desirable by the target.
6136 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6137 ((!LegalOperations && !VT.isVector() &&
6138 !cast<LoadSDNode>(N0)->isVolatile()) ||
6139 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6140 bool DoXform = true;
6141 SmallVector<SDNode*, 4> SetCCs;
6142 if (!N0.hasOneUse())
6143 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6145 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6147 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6148 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6150 LN0->getBasePtr(), N0.getValueType(),
6151 LN0->getMemOperand());
6152 CombineTo(N, ExtLoad);
6153 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6154 N0.getValueType(), ExtLoad);
6155 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6157 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6159 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6163 // fold (zext (load x)) to multiple smaller zextloads.
6164 // Only on illegal but splittable vectors.
6165 if (SDValue ExtLoad = CombineExtLoad(N))
6168 // fold (zext (and/or/xor (load x), cst)) ->
6169 // (and/or/xor (zextload x), (zext cst))
6170 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6171 N0.getOpcode() == ISD::XOR) &&
6172 isa<LoadSDNode>(N0.getOperand(0)) &&
6173 N0.getOperand(1).getOpcode() == ISD::Constant &&
6174 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6175 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6176 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6177 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6178 bool DoXform = true;
6179 SmallVector<SDNode*, 4> SetCCs;
6180 if (!N0.hasOneUse())
6181 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6184 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6185 LN0->getChain(), LN0->getBasePtr(),
6187 LN0->getMemOperand());
6188 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6189 Mask = Mask.zext(VT.getSizeInBits());
6191 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6192 ExtLoad, DAG.getConstant(Mask, DL, VT));
6193 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6194 SDLoc(N0.getOperand(0)),
6195 N0.getOperand(0).getValueType(), ExtLoad);
6197 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6198 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6200 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6205 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6206 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6207 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6208 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6209 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6210 EVT MemVT = LN0->getMemoryVT();
6211 if ((!LegalOperations && !LN0->isVolatile()) ||
6212 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6213 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6215 LN0->getBasePtr(), MemVT,
6216 LN0->getMemOperand());
6217 CombineTo(N, ExtLoad);
6218 CombineTo(N0.getNode(),
6219 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6221 ExtLoad.getValue(1));
6222 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6226 if (N0.getOpcode() == ISD::SETCC) {
6227 if (!LegalOperations && VT.isVector() &&
6228 N0.getValueType().getVectorElementType() == MVT::i1) {
6229 EVT N0VT = N0.getOperand(0).getValueType();
6230 if (getSetCCResultType(N0VT) == N0.getValueType())
6233 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6234 // Only do this before legalize for now.
6235 EVT EltVT = VT.getVectorElementType();
6237 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6238 DAG.getConstant(1, DL, EltVT));
6239 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6240 // We know that the # elements of the results is the same as the
6241 // # elements of the compare (and the # elements of the compare result
6242 // for that matter). Check to see that they are the same size. If so,
6243 // we know that the element size of the sext'd result matches the
6244 // element size of the compare operands.
6245 return DAG.getNode(ISD::AND, DL, VT,
6246 DAG.getSetCC(DL, VT, N0.getOperand(0),
6248 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6249 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6252 // If the desired elements are smaller or larger than the source
6253 // elements we can use a matching integer vector type and then
6254 // truncate/sign extend
6255 EVT MatchingElementType =
6256 EVT::getIntegerVT(*DAG.getContext(),
6257 N0VT.getScalarType().getSizeInBits());
6258 EVT MatchingVectorType =
6259 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6260 N0VT.getVectorNumElements());
6262 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6264 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6265 return DAG.getNode(ISD::AND, DL, VT,
6266 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6267 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6270 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6273 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6274 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6275 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6276 if (SCC.getNode()) return SCC;
6279 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6280 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6281 isa<ConstantSDNode>(N0.getOperand(1)) &&
6282 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6284 SDValue ShAmt = N0.getOperand(1);
6285 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6286 if (N0.getOpcode() == ISD::SHL) {
6287 SDValue InnerZExt = N0.getOperand(0);
6288 // If the original shl may be shifting out bits, do not perform this
6290 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6291 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6292 if (ShAmtVal > KnownZeroBits)
6298 // Ensure that the shift amount is wide enough for the shifted value.
6299 if (VT.getSizeInBits() >= 256)
6300 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6302 return DAG.getNode(N0.getOpcode(), DL, VT,
6303 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6310 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6311 SDValue N0 = N->getOperand(0);
6312 EVT VT = N->getValueType(0);
6314 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6316 return SDValue(Res, 0);
6318 // fold (aext (aext x)) -> (aext x)
6319 // fold (aext (zext x)) -> (zext x)
6320 // fold (aext (sext x)) -> (sext x)
6321 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6322 N0.getOpcode() == ISD::ZERO_EXTEND ||
6323 N0.getOpcode() == ISD::SIGN_EXTEND)
6324 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6326 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6327 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6328 if (N0.getOpcode() == ISD::TRUNCATE) {
6329 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6330 if (NarrowLoad.getNode()) {
6331 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6332 if (NarrowLoad.getNode() != N0.getNode()) {
6333 CombineTo(N0.getNode(), NarrowLoad);
6334 // CombineTo deleted the truncate, if needed, but not what's under it.
6337 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6341 // fold (aext (truncate x))
6342 if (N0.getOpcode() == ISD::TRUNCATE) {
6343 SDValue TruncOp = N0.getOperand(0);
6344 if (TruncOp.getValueType() == VT)
6345 return TruncOp; // x iff x size == zext size.
6346 if (TruncOp.getValueType().bitsGT(VT))
6347 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6348 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6351 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6352 // if the trunc is not free.
6353 if (N0.getOpcode() == ISD::AND &&
6354 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6355 N0.getOperand(1).getOpcode() == ISD::Constant &&
6356 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6357 N0.getValueType())) {
6358 SDValue X = N0.getOperand(0).getOperand(0);
6359 if (X.getValueType().bitsLT(VT)) {
6360 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6361 } else if (X.getValueType().bitsGT(VT)) {
6362 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6364 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6365 Mask = Mask.zext(VT.getSizeInBits());
6367 return DAG.getNode(ISD::AND, DL, VT,
6368 X, DAG.getConstant(Mask, DL, VT));
6371 // fold (aext (load x)) -> (aext (truncate (extload x)))
6372 // None of the supported targets knows how to perform load and any_ext
6373 // on vectors in one instruction. We only perform this transformation on
6375 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6376 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6377 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6378 bool DoXform = true;
6379 SmallVector<SDNode*, 4> SetCCs;
6380 if (!N0.hasOneUse())
6381 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6383 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6384 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6386 LN0->getBasePtr(), N0.getValueType(),
6387 LN0->getMemOperand());
6388 CombineTo(N, ExtLoad);
6389 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6390 N0.getValueType(), ExtLoad);
6391 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6392 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6394 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6398 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6399 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6400 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6401 if (N0.getOpcode() == ISD::LOAD &&
6402 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6404 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6405 ISD::LoadExtType ExtType = LN0->getExtensionType();
6406 EVT MemVT = LN0->getMemoryVT();
6407 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6408 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6409 VT, LN0->getChain(), LN0->getBasePtr(),
6410 MemVT, LN0->getMemOperand());
6411 CombineTo(N, ExtLoad);
6412 CombineTo(N0.getNode(),
6413 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6414 N0.getValueType(), ExtLoad),
6415 ExtLoad.getValue(1));
6416 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6420 if (N0.getOpcode() == ISD::SETCC) {
6422 // aext(setcc) -> vsetcc
6423 // aext(setcc) -> truncate(vsetcc)
6424 // aext(setcc) -> aext(vsetcc)
6425 // Only do this before legalize for now.
6426 if (VT.isVector() && !LegalOperations) {
6427 EVT N0VT = N0.getOperand(0).getValueType();
6428 // We know that the # elements of the results is the same as the
6429 // # elements of the compare (and the # elements of the compare result
6430 // for that matter). Check to see that they are the same size. If so,
6431 // we know that the element size of the sext'd result matches the
6432 // element size of the compare operands.
6433 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6434 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6436 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6437 // If the desired elements are smaller or larger than the source
6438 // elements we can use a matching integer vector type and then
6439 // truncate/any extend
6441 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6443 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6445 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6446 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6450 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6453 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6454 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6455 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6463 /// See if the specified operand can be simplified with the knowledge that only
6464 /// the bits specified by Mask are used. If so, return the simpler operand,
6465 /// otherwise return a null SDValue.
6466 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6467 switch (V.getOpcode()) {
6469 case ISD::Constant: {
6470 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6471 assert(CV && "Const value should be ConstSDNode.");
6472 const APInt &CVal = CV->getAPIntValue();
6473 APInt NewVal = CVal & Mask;
6475 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6480 // If the LHS or RHS don't contribute bits to the or, drop them.
6481 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6482 return V.getOperand(1);
6483 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6484 return V.getOperand(0);
6487 // Only look at single-use SRLs.
6488 if (!V.getNode()->hasOneUse())
6490 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6491 // See if we can recursively simplify the LHS.
6492 unsigned Amt = RHSC->getZExtValue();
6494 // Watch out for shift count overflow though.
6495 if (Amt >= Mask.getBitWidth()) break;
6496 APInt NewMask = Mask << Amt;
6497 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6498 if (SimplifyLHS.getNode())
6499 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6500 SimplifyLHS, V.getOperand(1));
6506 /// If the result of a wider load is shifted to right of N bits and then
6507 /// truncated to a narrower type and where N is a multiple of number of bits of
6508 /// the narrower type, transform it to a narrower load from address + N / num of
6509 /// bits of new type. If the result is to be extended, also fold the extension
6510 /// to form a extending load.
6511 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6512 unsigned Opc = N->getOpcode();
6514 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6515 SDValue N0 = N->getOperand(0);
6516 EVT VT = N->getValueType(0);
6519 // This transformation isn't valid for vector loads.
6523 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6525 if (Opc == ISD::SIGN_EXTEND_INREG) {
6526 ExtType = ISD::SEXTLOAD;
6527 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6528 } else if (Opc == ISD::SRL) {
6529 // Another special-case: SRL is basically zero-extending a narrower value.
6530 ExtType = ISD::ZEXTLOAD;
6532 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6533 if (!N01) return SDValue();
6534 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6535 VT.getSizeInBits() - N01->getZExtValue());
6537 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6540 unsigned EVTBits = ExtVT.getSizeInBits();
6542 // Do not generate loads of non-round integer types since these can
6543 // be expensive (and would be wrong if the type is not byte sized).
6544 if (!ExtVT.isRound())
6548 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6549 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6550 ShAmt = N01->getZExtValue();
6551 // Is the shift amount a multiple of size of VT?
6552 if ((ShAmt & (EVTBits-1)) == 0) {
6553 N0 = N0.getOperand(0);
6554 // Is the load width a multiple of size of VT?
6555 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6559 // At this point, we must have a load or else we can't do the transform.
6560 if (!isa<LoadSDNode>(N0)) return SDValue();
6562 // Because a SRL must be assumed to *need* to zero-extend the high bits
6563 // (as opposed to anyext the high bits), we can't combine the zextload
6564 // lowering of SRL and an sextload.
6565 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6568 // If the shift amount is larger than the input type then we're not
6569 // accessing any of the loaded bytes. If the load was a zextload/extload
6570 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6571 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6576 // If the load is shifted left (and the result isn't shifted back right),
6577 // we can fold the truncate through the shift.
6578 unsigned ShLeftAmt = 0;
6579 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6580 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6581 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6582 ShLeftAmt = N01->getZExtValue();
6583 N0 = N0.getOperand(0);
6587 // If we haven't found a load, we can't narrow it. Don't transform one with
6588 // multiple uses, this would require adding a new load.
6589 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6592 // Don't change the width of a volatile load.
6593 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6594 if (LN0->isVolatile())
6597 // Verify that we are actually reducing a load width here.
6598 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6601 // For the transform to be legal, the load must produce only two values
6602 // (the value loaded and the chain). Don't transform a pre-increment
6603 // load, for example, which produces an extra value. Otherwise the
6604 // transformation is not equivalent, and the downstream logic to replace
6605 // uses gets things wrong.
6606 if (LN0->getNumValues() > 2)
6609 // If the load that we're shrinking is an extload and we're not just
6610 // discarding the extension we can't simply shrink the load. Bail.
6611 // TODO: It would be possible to merge the extensions in some cases.
6612 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6613 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6616 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6619 EVT PtrType = N0.getOperand(1).getValueType();
6621 if (PtrType == MVT::Untyped || PtrType.isExtended())
6622 // It's not possible to generate a constant of extended or untyped type.
6625 // For big endian targets, we need to adjust the offset to the pointer to
6626 // load the correct bytes.
6627 if (TLI.isBigEndian()) {
6628 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6629 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6630 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6633 uint64_t PtrOff = ShAmt / 8;
6634 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6636 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6637 PtrType, LN0->getBasePtr(),
6638 DAG.getConstant(PtrOff, DL, PtrType));
6639 AddToWorklist(NewPtr.getNode());
6642 if (ExtType == ISD::NON_EXTLOAD)
6643 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6644 LN0->getPointerInfo().getWithOffset(PtrOff),
6645 LN0->isVolatile(), LN0->isNonTemporal(),
6646 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6648 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6649 LN0->getPointerInfo().getWithOffset(PtrOff),
6650 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6651 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6653 // Replace the old load's chain with the new load's chain.
6654 WorklistRemover DeadNodes(*this);
6655 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6657 // Shift the result left, if we've swallowed a left shift.
6658 SDValue Result = Load;
6659 if (ShLeftAmt != 0) {
6660 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6661 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6663 // If the shift amount is as large as the result size (but, presumably,
6664 // no larger than the source) then the useful bits of the result are
6665 // zero; we can't simply return the shortened shift, because the result
6666 // of that operation is undefined.
6668 if (ShLeftAmt >= VT.getSizeInBits())
6669 Result = DAG.getConstant(0, DL, VT);
6671 Result = DAG.getNode(ISD::SHL, DL, VT,
6672 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6675 // Return the new loaded value.
6679 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6680 SDValue N0 = N->getOperand(0);
6681 SDValue N1 = N->getOperand(1);
6682 EVT VT = N->getValueType(0);
6683 EVT EVT = cast<VTSDNode>(N1)->getVT();
6684 unsigned VTBits = VT.getScalarType().getSizeInBits();
6685 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6687 // fold (sext_in_reg c1) -> c1
6688 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6689 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6691 // If the input is already sign extended, just drop the extension.
6692 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6695 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6696 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6697 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6698 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6699 N0.getOperand(0), N1);
6701 // fold (sext_in_reg (sext x)) -> (sext x)
6702 // fold (sext_in_reg (aext x)) -> (sext x)
6703 // if x is small enough.
6704 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6705 SDValue N00 = N0.getOperand(0);
6706 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6707 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6708 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6711 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6712 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6713 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6715 // fold operands of sext_in_reg based on knowledge that the top bits are not
6717 if (SimplifyDemandedBits(SDValue(N, 0)))
6718 return SDValue(N, 0);
6720 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6721 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6722 SDValue NarrowLoad = ReduceLoadWidth(N);
6723 if (NarrowLoad.getNode())
6726 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6727 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6728 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6729 if (N0.getOpcode() == ISD::SRL) {
6730 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6731 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6732 // We can turn this into an SRA iff the input to the SRL is already sign
6734 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6735 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6736 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6737 N0.getOperand(0), N0.getOperand(1));
6741 // fold (sext_inreg (extload x)) -> (sextload x)
6742 if (ISD::isEXTLoad(N0.getNode()) &&
6743 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6744 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6745 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6746 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6747 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6748 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6750 LN0->getBasePtr(), EVT,
6751 LN0->getMemOperand());
6752 CombineTo(N, ExtLoad);
6753 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6754 AddToWorklist(ExtLoad.getNode());
6755 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6757 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6758 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6760 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6761 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6762 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6763 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6764 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6766 LN0->getBasePtr(), EVT,
6767 LN0->getMemOperand());
6768 CombineTo(N, ExtLoad);
6769 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6770 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6773 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6774 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6775 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6776 N0.getOperand(1), false);
6777 if (BSwap.getNode())
6778 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6782 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6783 // into a build_vector.
6784 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6785 SmallVector<SDValue, 8> Elts;
6786 unsigned NumElts = N0->getNumOperands();
6787 unsigned ShAmt = VTBits - EVTBits;
6789 for (unsigned i = 0; i != NumElts; ++i) {
6790 SDValue Op = N0->getOperand(i);
6791 if (Op->getOpcode() == ISD::UNDEF) {
6796 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6797 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6798 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6799 SDLoc(Op), Op.getValueType()));
6802 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6808 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6809 SDValue N0 = N->getOperand(0);
6810 EVT VT = N->getValueType(0);
6811 bool isLE = TLI.isLittleEndian();
6814 if (N0.getValueType() == N->getValueType(0))
6816 // fold (truncate c1) -> c1
6817 if (isConstantIntBuildVectorOrConstantInt(N0))
6818 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6819 // fold (truncate (truncate x)) -> (truncate x)
6820 if (N0.getOpcode() == ISD::TRUNCATE)
6821 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6822 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6823 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6824 N0.getOpcode() == ISD::SIGN_EXTEND ||
6825 N0.getOpcode() == ISD::ANY_EXTEND) {
6826 if (N0.getOperand(0).getValueType().bitsLT(VT))
6827 // if the source is smaller than the dest, we still need an extend
6828 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6830 if (N0.getOperand(0).getValueType().bitsGT(VT))
6831 // if the source is larger than the dest, than we just need the truncate
6832 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6833 // if the source and dest are the same type, we can drop both the extend
6834 // and the truncate.
6835 return N0.getOperand(0);
6838 // Fold extract-and-trunc into a narrow extract. For example:
6839 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6840 // i32 y = TRUNCATE(i64 x)
6842 // v16i8 b = BITCAST (v2i64 val)
6843 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6845 // Note: We only run this optimization after type legalization (which often
6846 // creates this pattern) and before operation legalization after which
6847 // we need to be more careful about the vector instructions that we generate.
6848 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6849 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6851 EVT VecTy = N0.getOperand(0).getValueType();
6852 EVT ExTy = N0.getValueType();
6853 EVT TrTy = N->getValueType(0);
6855 unsigned NumElem = VecTy.getVectorNumElements();
6856 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6858 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6859 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6861 SDValue EltNo = N0->getOperand(1);
6862 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6863 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6864 EVT IndexTy = TLI.getVectorIdxTy();
6865 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6867 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6868 NVT, N0.getOperand(0));
6871 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6873 DAG.getConstant(Index, DL, IndexTy));
6877 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6878 if (N0.getOpcode() == ISD::SELECT) {
6879 EVT SrcVT = N0.getValueType();
6880 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6881 TLI.isTruncateFree(SrcVT, VT)) {
6883 SDValue Cond = N0.getOperand(0);
6884 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6885 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6886 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6890 // Fold a series of buildvector, bitcast, and truncate if possible.
6892 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6893 // (2xi32 (buildvector x, y)).
6894 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6895 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6896 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6897 N0.getOperand(0).hasOneUse()) {
6899 SDValue BuildVect = N0.getOperand(0);
6900 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6901 EVT TruncVecEltTy = VT.getVectorElementType();
6903 // Check that the element types match.
6904 if (BuildVectEltTy == TruncVecEltTy) {
6905 // Now we only need to compute the offset of the truncated elements.
6906 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6907 unsigned TruncVecNumElts = VT.getVectorNumElements();
6908 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6910 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6911 "Invalid number of elements");
6913 SmallVector<SDValue, 8> Opnds;
6914 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6915 Opnds.push_back(BuildVect.getOperand(i));
6917 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6921 // See if we can simplify the input to this truncate through knowledge that
6922 // only the low bits are being used.
6923 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6924 // Currently we only perform this optimization on scalars because vectors
6925 // may have different active low bits.
6926 if (!VT.isVector()) {
6928 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6929 VT.getSizeInBits()));
6930 if (Shorter.getNode())
6931 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6933 // fold (truncate (load x)) -> (smaller load x)
6934 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6935 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6936 SDValue Reduced = ReduceLoadWidth(N);
6937 if (Reduced.getNode())
6939 // Handle the case where the load remains an extending load even
6940 // after truncation.
6941 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6942 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6943 if (!LN0->isVolatile() &&
6944 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6945 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6946 VT, LN0->getChain(), LN0->getBasePtr(),
6948 LN0->getMemOperand());
6949 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6954 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6955 // where ... are all 'undef'.
6956 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6957 SmallVector<EVT, 8> VTs;
6960 unsigned NumDefs = 0;
6962 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6963 SDValue X = N0.getOperand(i);
6964 if (X.getOpcode() != ISD::UNDEF) {
6969 // Stop if more than one members are non-undef.
6972 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6973 VT.getVectorElementType(),
6974 X.getValueType().getVectorNumElements()));
6978 return DAG.getUNDEF(VT);
6981 assert(V.getNode() && "The single defined operand is empty!");
6982 SmallVector<SDValue, 8> Opnds;
6983 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6985 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6988 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6989 AddToWorklist(NV.getNode());
6990 Opnds.push_back(NV);
6992 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6996 // Simplify the operands using demanded-bits information.
6997 if (!VT.isVector() &&
6998 SimplifyDemandedBits(SDValue(N, 0)))
6999 return SDValue(N, 0);
7004 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7005 SDValue Elt = N->getOperand(i);
7006 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7007 return Elt.getNode();
7008 return Elt.getOperand(Elt.getResNo()).getNode();
7011 /// build_pair (load, load) -> load
7012 /// if load locations are consecutive.
7013 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7014 assert(N->getOpcode() == ISD::BUILD_PAIR);
7016 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7017 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7018 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7019 LD1->getAddressSpace() != LD2->getAddressSpace())
7021 EVT LD1VT = LD1->getValueType(0);
7023 if (ISD::isNON_EXTLoad(LD2) &&
7025 // If both are volatile this would reduce the number of volatile loads.
7026 // If one is volatile it might be ok, but play conservative and bail out.
7027 !LD1->isVolatile() &&
7028 !LD2->isVolatile() &&
7029 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7030 unsigned Align = LD1->getAlignment();
7031 unsigned NewAlign = TLI.getDataLayout()->
7032 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7034 if (NewAlign <= Align &&
7035 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7036 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7037 LD1->getBasePtr(), LD1->getPointerInfo(),
7038 false, false, false, Align);
7044 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7045 SDValue N0 = N->getOperand(0);
7046 EVT VT = N->getValueType(0);
7048 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7049 // Only do this before legalize, since afterward the target may be depending
7050 // on the bitconvert.
7051 // First check to see if this is all constant.
7053 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7055 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7057 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7058 assert(!DestEltVT.isVector() &&
7059 "Element type of vector ValueType must not be vector!");
7061 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7064 // If the input is a constant, let getNode fold it.
7065 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7066 // If we can't allow illegal operations, we need to check that this is just
7067 // a fp -> int or int -> conversion and that the resulting operation will
7069 if (!LegalOperations ||
7070 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7071 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7072 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7073 TLI.isOperationLegal(ISD::Constant, VT)))
7074 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7077 // (conv (conv x, t1), t2) -> (conv x, t2)
7078 if (N0.getOpcode() == ISD::BITCAST)
7079 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7082 // fold (conv (load x)) -> (load (conv*)x)
7083 // If the resultant load doesn't need a higher alignment than the original!
7084 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7085 // Do not change the width of a volatile load.
7086 !cast<LoadSDNode>(N0)->isVolatile() &&
7087 // Do not remove the cast if the types differ in endian layout.
7088 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7089 TLI.hasBigEndianPartOrdering(VT) &&
7090 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7091 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7092 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7093 unsigned Align = TLI.getDataLayout()->
7094 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7095 unsigned OrigAlign = LN0->getAlignment();
7097 if (Align <= OrigAlign) {
7098 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7099 LN0->getBasePtr(), LN0->getPointerInfo(),
7100 LN0->isVolatile(), LN0->isNonTemporal(),
7101 LN0->isInvariant(), OrigAlign,
7103 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7108 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7109 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7110 // This often reduces constant pool loads.
7111 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7112 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7113 N0.getNode()->hasOneUse() && VT.isInteger() &&
7114 !VT.isVector() && !N0.getValueType().isVector()) {
7115 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7117 AddToWorklist(NewConv.getNode());
7120 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7121 if (N0.getOpcode() == ISD::FNEG)
7122 return DAG.getNode(ISD::XOR, DL, VT,
7123 NewConv, DAG.getConstant(SignBit, DL, VT));
7124 assert(N0.getOpcode() == ISD::FABS);
7125 return DAG.getNode(ISD::AND, DL, VT,
7126 NewConv, DAG.getConstant(~SignBit, DL, VT));
7129 // fold (bitconvert (fcopysign cst, x)) ->
7130 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7131 // Note that we don't handle (copysign x, cst) because this can always be
7132 // folded to an fneg or fabs.
7133 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7134 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7135 VT.isInteger() && !VT.isVector()) {
7136 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7137 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7138 if (isTypeLegal(IntXVT)) {
7139 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7140 IntXVT, N0.getOperand(1));
7141 AddToWorklist(X.getNode());
7143 // If X has a different width than the result/lhs, sext it or truncate it.
7144 unsigned VTWidth = VT.getSizeInBits();
7145 if (OrigXWidth < VTWidth) {
7146 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7147 AddToWorklist(X.getNode());
7148 } else if (OrigXWidth > VTWidth) {
7149 // To get the sign bit in the right place, we have to shift it right
7150 // before truncating.
7152 X = DAG.getNode(ISD::SRL, DL,
7153 X.getValueType(), X,
7154 DAG.getConstant(OrigXWidth-VTWidth, DL,
7156 AddToWorklist(X.getNode());
7157 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7158 AddToWorklist(X.getNode());
7161 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7162 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7163 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7164 AddToWorklist(X.getNode());
7166 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7167 VT, N0.getOperand(0));
7168 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7169 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7170 AddToWorklist(Cst.getNode());
7172 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7176 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7177 if (N0.getOpcode() == ISD::BUILD_PAIR) {
7178 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7179 if (CombineLD.getNode())
7183 // Remove double bitcasts from shuffles - this is often a legacy of
7184 // XformToShuffleWithZero being used to combine bitmaskings (of
7185 // float vectors bitcast to integer vectors) into shuffles.
7186 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7187 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7188 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7189 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7190 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7191 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7193 // If operands are a bitcast, peek through if it casts the original VT.
7194 // If operands are a UNDEF or constant, just bitcast back to original VT.
7195 auto PeekThroughBitcast = [&](SDValue Op) {
7196 if (Op.getOpcode() == ISD::BITCAST &&
7197 Op.getOperand(0)->getValueType(0) == VT)
7198 return SDValue(Op.getOperand(0));
7199 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7200 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7201 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7205 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7206 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7211 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7212 SmallVector<int, 8> NewMask;
7213 for (int M : SVN->getMask())
7214 for (int i = 0; i != MaskScale; ++i)
7215 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7217 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7219 std::swap(SV0, SV1);
7220 ShuffleVectorSDNode::commuteMask(NewMask);
7221 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7225 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7231 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7232 EVT VT = N->getValueType(0);
7233 return CombineConsecutiveLoads(N, VT);
7236 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7237 /// operands. DstEltVT indicates the destination element value type.
7238 SDValue DAGCombiner::
7239 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7240 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7242 // If this is already the right type, we're done.
7243 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7245 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7246 unsigned DstBitSize = DstEltVT.getSizeInBits();
7248 // If this is a conversion of N elements of one type to N elements of another
7249 // type, convert each element. This handles FP<->INT cases.
7250 if (SrcBitSize == DstBitSize) {
7251 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7252 BV->getValueType(0).getVectorNumElements());
7254 // Due to the FP element handling below calling this routine recursively,
7255 // we can end up with a scalar-to-vector node here.
7256 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7257 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7258 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7259 DstEltVT, BV->getOperand(0)));
7261 SmallVector<SDValue, 8> Ops;
7262 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7263 SDValue Op = BV->getOperand(i);
7264 // If the vector element type is not legal, the BUILD_VECTOR operands
7265 // are promoted and implicitly truncated. Make that explicit here.
7266 if (Op.getValueType() != SrcEltVT)
7267 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7268 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7270 AddToWorklist(Ops.back().getNode());
7272 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7275 // Otherwise, we're growing or shrinking the elements. To avoid having to
7276 // handle annoying details of growing/shrinking FP values, we convert them to
7278 if (SrcEltVT.isFloatingPoint()) {
7279 // Convert the input float vector to a int vector where the elements are the
7281 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7282 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7286 // Now we know the input is an integer vector. If the output is a FP type,
7287 // convert to integer first, then to FP of the right size.
7288 if (DstEltVT.isFloatingPoint()) {
7289 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7290 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7292 // Next, convert to FP elements of the same size.
7293 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7298 // Okay, we know the src/dst types are both integers of differing types.
7299 // Handling growing first.
7300 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7301 if (SrcBitSize < DstBitSize) {
7302 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7304 SmallVector<SDValue, 8> Ops;
7305 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7306 i += NumInputsPerOutput) {
7307 bool isLE = TLI.isLittleEndian();
7308 APInt NewBits = APInt(DstBitSize, 0);
7309 bool EltIsUndef = true;
7310 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7311 // Shift the previously computed bits over.
7312 NewBits <<= SrcBitSize;
7313 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7314 if (Op.getOpcode() == ISD::UNDEF) continue;
7317 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7318 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7322 Ops.push_back(DAG.getUNDEF(DstEltVT));
7324 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7327 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7328 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7331 // Finally, this must be the case where we are shrinking elements: each input
7332 // turns into multiple outputs.
7333 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7334 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7335 NumOutputsPerInput*BV->getNumOperands());
7336 SmallVector<SDValue, 8> Ops;
7338 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7339 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7340 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7344 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7345 getAPIntValue().zextOrTrunc(SrcBitSize);
7347 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7348 APInt ThisVal = OpVal.trunc(DstBitSize);
7349 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7350 OpVal = OpVal.lshr(DstBitSize);
7353 // For big endian targets, swap the order of the pieces of each element.
7354 if (TLI.isBigEndian())
7355 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7358 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7361 /// Try to perform FMA combining on a given FADD node.
7362 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7363 SDValue N0 = N->getOperand(0);
7364 SDValue N1 = N->getOperand(1);
7365 EVT VT = N->getValueType(0);
7368 const TargetOptions &Options = DAG.getTarget().Options;
7369 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7370 Options.UnsafeFPMath);
7372 // Floating-point multiply-add with intermediate rounding.
7373 bool HasFMAD = (LegalOperations &&
7374 TLI.isOperationLegal(ISD::FMAD, VT));
7376 // Floating-point multiply-add without intermediate rounding.
7377 bool HasFMA = ((!LegalOperations ||
7378 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7379 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7382 // No valid opcode, do not combine.
7383 if (!HasFMAD && !HasFMA)
7386 // Always prefer FMAD to FMA for precision.
7387 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7388 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7389 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7391 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7392 if (N0.getOpcode() == ISD::FMUL &&
7393 (Aggressive || N0->hasOneUse())) {
7394 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7395 N0.getOperand(0), N0.getOperand(1), N1);
7398 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7399 // Note: Commutes FADD operands.
7400 if (N1.getOpcode() == ISD::FMUL &&
7401 (Aggressive || N1->hasOneUse())) {
7402 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7403 N1.getOperand(0), N1.getOperand(1), N0);
7406 // Look through FP_EXTEND nodes to do more combining.
7407 if (UnsafeFPMath && LookThroughFPExt) {
7408 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7409 if (N0.getOpcode() == ISD::FP_EXTEND) {
7410 SDValue N00 = N0.getOperand(0);
7411 if (N00.getOpcode() == ISD::FMUL)
7412 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7413 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7415 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7416 N00.getOperand(1)), N1);
7419 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7420 // Note: Commutes FADD operands.
7421 if (N1.getOpcode() == ISD::FP_EXTEND) {
7422 SDValue N10 = N1.getOperand(0);
7423 if (N10.getOpcode() == ISD::FMUL)
7424 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7425 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7427 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7428 N10.getOperand(1)), N0);
7432 // More folding opportunities when target permits.
7433 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7434 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7435 if (N0.getOpcode() == PreferredFusedOpcode &&
7436 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7437 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7438 N0.getOperand(0), N0.getOperand(1),
7439 DAG.getNode(PreferredFusedOpcode, SL, VT,
7440 N0.getOperand(2).getOperand(0),
7441 N0.getOperand(2).getOperand(1),
7445 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7446 if (N1->getOpcode() == PreferredFusedOpcode &&
7447 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7448 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7449 N1.getOperand(0), N1.getOperand(1),
7450 DAG.getNode(PreferredFusedOpcode, SL, VT,
7451 N1.getOperand(2).getOperand(0),
7452 N1.getOperand(2).getOperand(1),
7456 if (UnsafeFPMath && LookThroughFPExt) {
7457 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7458 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7459 auto FoldFAddFMAFPExtFMul = [&] (
7460 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7461 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7462 DAG.getNode(PreferredFusedOpcode, SL, VT,
7463 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7464 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7467 if (N0.getOpcode() == PreferredFusedOpcode) {
7468 SDValue N02 = N0.getOperand(2);
7469 if (N02.getOpcode() == ISD::FP_EXTEND) {
7470 SDValue N020 = N02.getOperand(0);
7471 if (N020.getOpcode() == ISD::FMUL)
7472 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7473 N020.getOperand(0), N020.getOperand(1),
7478 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7479 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7480 // FIXME: This turns two single-precision and one double-precision
7481 // operation into two double-precision operations, which might not be
7482 // interesting for all targets, especially GPUs.
7483 auto FoldFAddFPExtFMAFMul = [&] (
7484 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7485 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7486 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7487 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7488 DAG.getNode(PreferredFusedOpcode, SL, VT,
7489 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7490 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7493 if (N0.getOpcode() == ISD::FP_EXTEND) {
7494 SDValue N00 = N0.getOperand(0);
7495 if (N00.getOpcode() == PreferredFusedOpcode) {
7496 SDValue N002 = N00.getOperand(2);
7497 if (N002.getOpcode() == ISD::FMUL)
7498 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7499 N002.getOperand(0), N002.getOperand(1),
7504 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7505 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7506 if (N1.getOpcode() == PreferredFusedOpcode) {
7507 SDValue N12 = N1.getOperand(2);
7508 if (N12.getOpcode() == ISD::FP_EXTEND) {
7509 SDValue N120 = N12.getOperand(0);
7510 if (N120.getOpcode() == ISD::FMUL)
7511 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7512 N120.getOperand(0), N120.getOperand(1),
7517 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7518 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7519 // FIXME: This turns two single-precision and one double-precision
7520 // operation into two double-precision operations, which might not be
7521 // interesting for all targets, especially GPUs.
7522 if (N1.getOpcode() == ISD::FP_EXTEND) {
7523 SDValue N10 = N1.getOperand(0);
7524 if (N10.getOpcode() == PreferredFusedOpcode) {
7525 SDValue N102 = N10.getOperand(2);
7526 if (N102.getOpcode() == ISD::FMUL)
7527 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7528 N102.getOperand(0), N102.getOperand(1),
7538 /// Try to perform FMA combining on a given FSUB node.
7539 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7540 SDValue N0 = N->getOperand(0);
7541 SDValue N1 = N->getOperand(1);
7542 EVT VT = N->getValueType(0);
7545 const TargetOptions &Options = DAG.getTarget().Options;
7546 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7547 Options.UnsafeFPMath);
7549 // Floating-point multiply-add with intermediate rounding.
7550 bool HasFMAD = (LegalOperations &&
7551 TLI.isOperationLegal(ISD::FMAD, VT));
7553 // Floating-point multiply-add without intermediate rounding.
7554 bool HasFMA = ((!LegalOperations ||
7555 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7556 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7559 // No valid opcode, do not combine.
7560 if (!HasFMAD && !HasFMA)
7563 // Always prefer FMAD to FMA for precision.
7564 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7565 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7566 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7568 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7569 if (N0.getOpcode() == ISD::FMUL &&
7570 (Aggressive || N0->hasOneUse())) {
7571 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7572 N0.getOperand(0), N0.getOperand(1),
7573 DAG.getNode(ISD::FNEG, SL, VT, N1));
7576 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7577 // Note: Commutes FSUB operands.
7578 if (N1.getOpcode() == ISD::FMUL &&
7579 (Aggressive || N1->hasOneUse()))
7580 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7581 DAG.getNode(ISD::FNEG, SL, VT,
7583 N1.getOperand(1), N0);
7585 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7586 if (N0.getOpcode() == ISD::FNEG &&
7587 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7588 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7589 SDValue N00 = N0.getOperand(0).getOperand(0);
7590 SDValue N01 = N0.getOperand(0).getOperand(1);
7591 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7592 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7593 DAG.getNode(ISD::FNEG, SL, VT, N1));
7596 // Look through FP_EXTEND nodes to do more combining.
7597 if (UnsafeFPMath && LookThroughFPExt) {
7598 // fold (fsub (fpext (fmul x, y)), z)
7599 // -> (fma (fpext x), (fpext y), (fneg z))
7600 if (N0.getOpcode() == ISD::FP_EXTEND) {
7601 SDValue N00 = N0.getOperand(0);
7602 if (N00.getOpcode() == ISD::FMUL)
7603 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7604 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7606 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7608 DAG.getNode(ISD::FNEG, SL, VT, N1));
7611 // fold (fsub x, (fpext (fmul y, z)))
7612 // -> (fma (fneg (fpext y)), (fpext z), x)
7613 // Note: Commutes FSUB operands.
7614 if (N1.getOpcode() == ISD::FP_EXTEND) {
7615 SDValue N10 = N1.getOperand(0);
7616 if (N10.getOpcode() == ISD::FMUL)
7617 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7618 DAG.getNode(ISD::FNEG, SL, VT,
7619 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7620 N10.getOperand(0))),
7621 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7626 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7627 // -> (fneg (fma (fpext x), (fpext y), z))
7628 // Note: This could be removed with appropriate canonicalization of the
7629 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7630 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7631 // from implementing the canonicalization in visitFSUB.
7632 if (N0.getOpcode() == ISD::FP_EXTEND) {
7633 SDValue N00 = N0.getOperand(0);
7634 if (N00.getOpcode() == ISD::FNEG) {
7635 SDValue N000 = N00.getOperand(0);
7636 if (N000.getOpcode() == ISD::FMUL) {
7637 return DAG.getNode(ISD::FNEG, SL, VT,
7638 DAG.getNode(PreferredFusedOpcode, SL, VT,
7639 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7640 N000.getOperand(0)),
7641 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7642 N000.getOperand(1)),
7648 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7649 // -> (fneg (fma (fpext x)), (fpext y), z)
7650 // Note: This could be removed with appropriate canonicalization of the
7651 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7652 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7653 // from implementing the canonicalization in visitFSUB.
7654 if (N0.getOpcode() == ISD::FNEG) {
7655 SDValue N00 = N0.getOperand(0);
7656 if (N00.getOpcode() == ISD::FP_EXTEND) {
7657 SDValue N000 = N00.getOperand(0);
7658 if (N000.getOpcode() == ISD::FMUL) {
7659 return DAG.getNode(ISD::FNEG, SL, VT,
7660 DAG.getNode(PreferredFusedOpcode, SL, VT,
7661 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7662 N000.getOperand(0)),
7663 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7664 N000.getOperand(1)),
7672 // More folding opportunities when target permits.
7673 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7674 // fold (fsub (fma x, y, (fmul u, v)), z)
7675 // -> (fma x, y (fma u, v, (fneg z)))
7676 if (N0.getOpcode() == PreferredFusedOpcode &&
7677 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7678 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7679 N0.getOperand(0), N0.getOperand(1),
7680 DAG.getNode(PreferredFusedOpcode, SL, VT,
7681 N0.getOperand(2).getOperand(0),
7682 N0.getOperand(2).getOperand(1),
7683 DAG.getNode(ISD::FNEG, SL, VT,
7687 // fold (fsub x, (fma y, z, (fmul u, v)))
7688 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7689 if (N1.getOpcode() == PreferredFusedOpcode &&
7690 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7691 SDValue N20 = N1.getOperand(2).getOperand(0);
7692 SDValue N21 = N1.getOperand(2).getOperand(1);
7693 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7694 DAG.getNode(ISD::FNEG, SL, VT,
7697 DAG.getNode(PreferredFusedOpcode, SL, VT,
7698 DAG.getNode(ISD::FNEG, SL, VT, N20),
7703 if (UnsafeFPMath && LookThroughFPExt) {
7704 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7705 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7706 if (N0.getOpcode() == PreferredFusedOpcode) {
7707 SDValue N02 = N0.getOperand(2);
7708 if (N02.getOpcode() == ISD::FP_EXTEND) {
7709 SDValue N020 = N02.getOperand(0);
7710 if (N020.getOpcode() == ISD::FMUL)
7711 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7712 N0.getOperand(0), N0.getOperand(1),
7713 DAG.getNode(PreferredFusedOpcode, SL, VT,
7714 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7715 N020.getOperand(0)),
7716 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7717 N020.getOperand(1)),
7718 DAG.getNode(ISD::FNEG, SL, VT,
7723 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7724 // -> (fma (fpext x), (fpext y),
7725 // (fma (fpext u), (fpext v), (fneg z)))
7726 // FIXME: This turns two single-precision and one double-precision
7727 // operation into two double-precision operations, which might not be
7728 // interesting for all targets, especially GPUs.
7729 if (N0.getOpcode() == ISD::FP_EXTEND) {
7730 SDValue N00 = N0.getOperand(0);
7731 if (N00.getOpcode() == PreferredFusedOpcode) {
7732 SDValue N002 = N00.getOperand(2);
7733 if (N002.getOpcode() == ISD::FMUL)
7734 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7735 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7737 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7739 DAG.getNode(PreferredFusedOpcode, SL, VT,
7740 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7741 N002.getOperand(0)),
7742 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7743 N002.getOperand(1)),
7744 DAG.getNode(ISD::FNEG, SL, VT,
7749 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7750 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7751 if (N1.getOpcode() == PreferredFusedOpcode &&
7752 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7753 SDValue N120 = N1.getOperand(2).getOperand(0);
7754 if (N120.getOpcode() == ISD::FMUL) {
7755 SDValue N1200 = N120.getOperand(0);
7756 SDValue N1201 = N120.getOperand(1);
7757 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7758 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7760 DAG.getNode(PreferredFusedOpcode, SL, VT,
7761 DAG.getNode(ISD::FNEG, SL, VT,
7762 DAG.getNode(ISD::FP_EXTEND, SL,
7764 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7770 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7771 // -> (fma (fneg (fpext y)), (fpext z),
7772 // (fma (fneg (fpext u)), (fpext v), x))
7773 // FIXME: This turns two single-precision and one double-precision
7774 // operation into two double-precision operations, which might not be
7775 // interesting for all targets, especially GPUs.
7776 if (N1.getOpcode() == ISD::FP_EXTEND &&
7777 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7778 SDValue N100 = N1.getOperand(0).getOperand(0);
7779 SDValue N101 = N1.getOperand(0).getOperand(1);
7780 SDValue N102 = N1.getOperand(0).getOperand(2);
7781 if (N102.getOpcode() == ISD::FMUL) {
7782 SDValue N1020 = N102.getOperand(0);
7783 SDValue N1021 = N102.getOperand(1);
7784 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7785 DAG.getNode(ISD::FNEG, SL, VT,
7786 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7788 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7789 DAG.getNode(PreferredFusedOpcode, SL, VT,
7790 DAG.getNode(ISD::FNEG, SL, VT,
7791 DAG.getNode(ISD::FP_EXTEND, SL,
7793 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7804 SDValue DAGCombiner::visitFADD(SDNode *N) {
7805 SDValue N0 = N->getOperand(0);
7806 SDValue N1 = N->getOperand(1);
7807 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7808 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7809 EVT VT = N->getValueType(0);
7811 const TargetOptions &Options = DAG.getTarget().Options;
7815 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7818 // fold (fadd c1, c2) -> c1 + c2
7820 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7822 // canonicalize constant to RHS
7823 if (N0CFP && !N1CFP)
7824 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7826 // fold (fadd A, (fneg B)) -> (fsub A, B)
7827 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7828 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7829 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7830 GetNegatedExpression(N1, DAG, LegalOperations));
7832 // fold (fadd (fneg A), B) -> (fsub B, A)
7833 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7834 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7835 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7836 GetNegatedExpression(N0, DAG, LegalOperations));
7838 // If 'unsafe math' is enabled, fold lots of things.
7839 if (Options.UnsafeFPMath) {
7840 // No FP constant should be created after legalization as Instruction
7841 // Selection pass has a hard time dealing with FP constants.
7842 bool AllowNewConst = (Level < AfterLegalizeDAG);
7844 // fold (fadd A, 0) -> A
7845 if (N1CFP && N1CFP->getValueAPF().isZero())
7848 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7849 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7850 isa<ConstantFPSDNode>(N0.getOperand(1)))
7851 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7852 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7854 // If allowed, fold (fadd (fneg x), x) -> 0.0
7855 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7856 return DAG.getConstantFP(0.0, DL, VT);
7858 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7859 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7860 return DAG.getConstantFP(0.0, DL, VT);
7862 // We can fold chains of FADD's of the same value into multiplications.
7863 // This transform is not safe in general because we are reducing the number
7864 // of rounding steps.
7865 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7866 if (N0.getOpcode() == ISD::FMUL) {
7867 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7868 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7870 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7871 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7872 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7873 DAG.getConstantFP(1.0, DL, VT));
7874 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7877 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7878 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7879 N1.getOperand(0) == N1.getOperand(1) &&
7880 N0.getOperand(0) == N1.getOperand(0)) {
7881 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7882 DAG.getConstantFP(2.0, DL, VT));
7883 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7887 if (N1.getOpcode() == ISD::FMUL) {
7888 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7889 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7891 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7892 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7893 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7894 DAG.getConstantFP(1.0, DL, VT));
7895 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7898 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7899 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7900 N0.getOperand(0) == N0.getOperand(1) &&
7901 N1.getOperand(0) == N0.getOperand(0)) {
7902 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7903 DAG.getConstantFP(2.0, DL, VT));
7904 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7908 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7909 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7910 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7911 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7912 (N0.getOperand(0) == N1)) {
7913 return DAG.getNode(ISD::FMUL, DL, VT,
7914 N1, DAG.getConstantFP(3.0, DL, VT));
7918 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7919 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7920 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7921 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7922 N1.getOperand(0) == N0) {
7923 return DAG.getNode(ISD::FMUL, DL, VT,
7924 N0, DAG.getConstantFP(3.0, DL, VT));
7928 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7929 if (AllowNewConst &&
7930 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7931 N0.getOperand(0) == N0.getOperand(1) &&
7932 N1.getOperand(0) == N1.getOperand(1) &&
7933 N0.getOperand(0) == N1.getOperand(0)) {
7934 return DAG.getNode(ISD::FMUL, DL, VT,
7935 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7938 } // enable-unsafe-fp-math
7940 // FADD -> FMA combines:
7941 SDValue Fused = visitFADDForFMACombine(N);
7943 AddToWorklist(Fused.getNode());
7950 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7951 SDValue N0 = N->getOperand(0);
7952 SDValue N1 = N->getOperand(1);
7953 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7954 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7955 EVT VT = N->getValueType(0);
7957 const TargetOptions &Options = DAG.getTarget().Options;
7961 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7964 // fold (fsub c1, c2) -> c1-c2
7966 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7968 // fold (fsub A, (fneg B)) -> (fadd A, B)
7969 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7970 return DAG.getNode(ISD::FADD, dl, VT, N0,
7971 GetNegatedExpression(N1, DAG, LegalOperations));
7973 // If 'unsafe math' is enabled, fold lots of things.
7974 if (Options.UnsafeFPMath) {
7976 if (N1CFP && N1CFP->getValueAPF().isZero())
7979 // (fsub 0, B) -> -B
7980 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7981 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7982 return GetNegatedExpression(N1, DAG, LegalOperations);
7983 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7984 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7987 // (fsub x, x) -> 0.0
7989 return DAG.getConstantFP(0.0f, dl, VT);
7991 // (fsub x, (fadd x, y)) -> (fneg y)
7992 // (fsub x, (fadd y, x)) -> (fneg y)
7993 if (N1.getOpcode() == ISD::FADD) {
7994 SDValue N10 = N1->getOperand(0);
7995 SDValue N11 = N1->getOperand(1);
7997 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7998 return GetNegatedExpression(N11, DAG, LegalOperations);
8000 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8001 return GetNegatedExpression(N10, DAG, LegalOperations);
8005 // FSUB -> FMA combines:
8006 SDValue Fused = visitFSUBForFMACombine(N);
8008 AddToWorklist(Fused.getNode());
8015 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8016 SDValue N0 = N->getOperand(0);
8017 SDValue N1 = N->getOperand(1);
8018 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8019 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8020 EVT VT = N->getValueType(0);
8022 const TargetOptions &Options = DAG.getTarget().Options;
8025 if (VT.isVector()) {
8026 // This just handles C1 * C2 for vectors. Other vector folds are below.
8027 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8031 // fold (fmul c1, c2) -> c1*c2
8033 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8035 // canonicalize constant to RHS
8036 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8037 !isConstantFPBuildVectorOrConstantFP(N1))
8038 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8040 // fold (fmul A, 1.0) -> A
8041 if (N1CFP && N1CFP->isExactlyValue(1.0))
8044 if (Options.UnsafeFPMath) {
8045 // fold (fmul A, 0) -> 0
8046 if (N1CFP && N1CFP->getValueAPF().isZero())
8049 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8050 if (N0.getOpcode() == ISD::FMUL) {
8051 // Fold scalars or any vector constants (not just splats).
8052 // This fold is done in general by InstCombine, but extra fmul insts
8053 // may have been generated during lowering.
8054 SDValue N00 = N0.getOperand(0);
8055 SDValue N01 = N0.getOperand(1);
8056 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8057 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8058 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8060 // Check 1: Make sure that the first operand of the inner multiply is NOT
8061 // a constant. Otherwise, we may induce infinite looping.
8062 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8063 // Check 2: Make sure that the second operand of the inner multiply and
8064 // the second operand of the outer multiply are constants.
8065 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8066 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8067 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8068 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8073 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8074 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8075 // during an early run of DAGCombiner can prevent folding with fmuls
8076 // inserted during lowering.
8077 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8078 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8079 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8080 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8084 // fold (fmul X, 2.0) -> (fadd X, X)
8085 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8086 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8088 // fold (fmul X, -1.0) -> (fneg X)
8089 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8090 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8091 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8093 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8094 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8095 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8096 // Both can be negated for free, check to see if at least one is cheaper
8098 if (LHSNeg == 2 || RHSNeg == 2)
8099 return DAG.getNode(ISD::FMUL, DL, VT,
8100 GetNegatedExpression(N0, DAG, LegalOperations),
8101 GetNegatedExpression(N1, DAG, LegalOperations));
8108 SDValue DAGCombiner::visitFMA(SDNode *N) {
8109 SDValue N0 = N->getOperand(0);
8110 SDValue N1 = N->getOperand(1);
8111 SDValue N2 = N->getOperand(2);
8112 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8113 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8114 EVT VT = N->getValueType(0);
8116 const TargetOptions &Options = DAG.getTarget().Options;
8118 // Constant fold FMA.
8119 if (isa<ConstantFPSDNode>(N0) &&
8120 isa<ConstantFPSDNode>(N1) &&
8121 isa<ConstantFPSDNode>(N2)) {
8122 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8125 if (Options.UnsafeFPMath) {
8126 if (N0CFP && N0CFP->isZero())
8128 if (N1CFP && N1CFP->isZero())
8131 if (N0CFP && N0CFP->isExactlyValue(1.0))
8132 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8133 if (N1CFP && N1CFP->isExactlyValue(1.0))
8134 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8136 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8137 if (N0CFP && !N1CFP)
8138 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8140 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8141 if (Options.UnsafeFPMath && N1CFP &&
8142 N2.getOpcode() == ISD::FMUL &&
8143 N0 == N2.getOperand(0) &&
8144 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8145 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8146 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8150 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8151 if (Options.UnsafeFPMath &&
8152 N0.getOpcode() == ISD::FMUL && N1CFP &&
8153 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8154 return DAG.getNode(ISD::FMA, dl, VT,
8156 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8160 // (fma x, 1, y) -> (fadd x, y)
8161 // (fma x, -1, y) -> (fadd (fneg x), y)
8163 if (N1CFP->isExactlyValue(1.0))
8164 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8166 if (N1CFP->isExactlyValue(-1.0) &&
8167 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8168 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8169 AddToWorklist(RHSNeg.getNode());
8170 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8174 // (fma x, c, x) -> (fmul x, (c+1))
8175 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8176 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8177 DAG.getNode(ISD::FADD, dl, VT,
8178 N1, DAG.getConstantFP(1.0, dl, VT)));
8180 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8181 if (Options.UnsafeFPMath && N1CFP &&
8182 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8183 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8184 DAG.getNode(ISD::FADD, dl, VT,
8185 N1, DAG.getConstantFP(-1.0, dl, VT)));
8191 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8192 SDValue N0 = N->getOperand(0);
8193 SDValue N1 = N->getOperand(1);
8194 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8195 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8196 EVT VT = N->getValueType(0);
8198 const TargetOptions &Options = DAG.getTarget().Options;
8202 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8205 // fold (fdiv c1, c2) -> c1/c2
8207 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8209 if (Options.UnsafeFPMath) {
8210 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8212 // Compute the reciprocal 1.0 / c2.
8213 APFloat N1APF = N1CFP->getValueAPF();
8214 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8215 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8216 // Only do the transform if the reciprocal is a legal fp immediate that
8217 // isn't too nasty (eg NaN, denormal, ...).
8218 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8219 (!LegalOperations ||
8220 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8221 // backend)... we should handle this gracefully after Legalize.
8222 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8223 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8224 TLI.isFPImmLegal(Recip, VT)))
8225 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8226 DAG.getConstantFP(Recip, DL, VT));
8229 // If this FDIV is part of a reciprocal square root, it may be folded
8230 // into a target-specific square root estimate instruction.
8231 if (N1.getOpcode() == ISD::FSQRT) {
8232 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8233 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8235 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8236 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8237 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8238 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8239 AddToWorklist(RV.getNode());
8240 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8242 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8243 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8244 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8245 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8246 AddToWorklist(RV.getNode());
8247 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8249 } else if (N1.getOpcode() == ISD::FMUL) {
8250 // Look through an FMUL. Even though this won't remove the FDIV directly,
8251 // it's still worthwhile to get rid of the FSQRT if possible.
8254 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8255 SqrtOp = N1.getOperand(0);
8256 OtherOp = N1.getOperand(1);
8257 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8258 SqrtOp = N1.getOperand(1);
8259 OtherOp = N1.getOperand(0);
8261 if (SqrtOp.getNode()) {
8262 // We found a FSQRT, so try to make this fold:
8263 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8264 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8265 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8266 AddToWorklist(RV.getNode());
8267 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8272 // Fold into a reciprocal estimate and multiply instead of a real divide.
8273 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8274 AddToWorklist(RV.getNode());
8275 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8279 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8280 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8281 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8282 // Both can be negated for free, check to see if at least one is cheaper
8284 if (LHSNeg == 2 || RHSNeg == 2)
8285 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8286 GetNegatedExpression(N0, DAG, LegalOperations),
8287 GetNegatedExpression(N1, DAG, LegalOperations));
8291 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8293 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8294 // Notice that this is not always beneficial. One reason is different target
8295 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8296 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8297 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8298 if (Options.UnsafeFPMath) {
8299 // Skip if current node is a reciprocal.
8300 if (N0CFP && N0CFP->isExactlyValue(1.0))
8303 SmallVector<SDNode *, 4> Users;
8304 // Find all FDIV users of the same divisor.
8305 for (auto *U : N1->uses()) {
8306 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8310 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8311 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8312 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8314 // Dividend / Divisor -> Dividend * Reciprocal
8315 for (auto *U : Users) {
8316 SDValue Dividend = U->getOperand(0);
8317 if (Dividend != FPOne) {
8318 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8320 DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8330 SDValue DAGCombiner::visitFREM(SDNode *N) {
8331 SDValue N0 = N->getOperand(0);
8332 SDValue N1 = N->getOperand(1);
8333 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8334 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8335 EVT VT = N->getValueType(0);
8337 // fold (frem c1, c2) -> fmod(c1,c2)
8339 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8344 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8345 if (DAG.getTarget().Options.UnsafeFPMath &&
8346 !TLI.isFsqrtCheap()) {
8347 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8348 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8349 EVT VT = RV.getValueType();
8351 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8352 AddToWorklist(RV.getNode());
8354 // Unfortunately, RV is now NaN if the input was exactly 0.
8355 // Select out this case and force the answer to 0.
8356 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8358 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8359 N->getOperand(0), Zero, ISD::SETEQ);
8360 AddToWorklist(ZeroCmp.getNode());
8361 AddToWorklist(RV.getNode());
8363 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8364 DL, VT, ZeroCmp, Zero, RV);
8371 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8372 SDValue N0 = N->getOperand(0);
8373 SDValue N1 = N->getOperand(1);
8374 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8375 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8376 EVT VT = N->getValueType(0);
8378 if (N0CFP && N1CFP) // Constant fold
8379 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8382 const APFloat& V = N1CFP->getValueAPF();
8383 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8384 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8385 if (!V.isNegative()) {
8386 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8387 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8389 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8390 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8391 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8395 // copysign(fabs(x), y) -> copysign(x, y)
8396 // copysign(fneg(x), y) -> copysign(x, y)
8397 // copysign(copysign(x,z), y) -> copysign(x, y)
8398 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8399 N0.getOpcode() == ISD::FCOPYSIGN)
8400 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8401 N0.getOperand(0), N1);
8403 // copysign(x, abs(y)) -> abs(x)
8404 if (N1.getOpcode() == ISD::FABS)
8405 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8407 // copysign(x, copysign(y,z)) -> copysign(x, z)
8408 if (N1.getOpcode() == ISD::FCOPYSIGN)
8409 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8410 N0, N1.getOperand(1));
8412 // copysign(x, fp_extend(y)) -> copysign(x, y)
8413 // copysign(x, fp_round(y)) -> copysign(x, y)
8414 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8415 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8416 N0, N1.getOperand(0));
8421 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8422 SDValue N0 = N->getOperand(0);
8423 EVT VT = N->getValueType(0);
8424 EVT OpVT = N0.getValueType();
8426 // fold (sint_to_fp c1) -> c1fp
8427 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8428 // ...but only if the target supports immediate floating-point values
8429 (!LegalOperations ||
8430 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8431 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8433 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8434 // but UINT_TO_FP is legal on this target, try to convert.
8435 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8436 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8437 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8438 if (DAG.SignBitIsZero(N0))
8439 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8442 // The next optimizations are desirable only if SELECT_CC can be lowered.
8443 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8444 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8445 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8447 (!LegalOperations ||
8448 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8451 { N0.getOperand(0), N0.getOperand(1),
8452 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8454 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8457 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8458 // (select_cc x, y, 1.0, 0.0,, cc)
8459 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8460 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8461 (!LegalOperations ||
8462 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8465 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8466 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8467 N0.getOperand(0).getOperand(2) };
8468 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8475 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8476 SDValue N0 = N->getOperand(0);
8477 EVT VT = N->getValueType(0);
8478 EVT OpVT = N0.getValueType();
8480 // fold (uint_to_fp c1) -> c1fp
8481 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8482 // ...but only if the target supports immediate floating-point values
8483 (!LegalOperations ||
8484 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8485 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8487 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8488 // but SINT_TO_FP is legal on this target, try to convert.
8489 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8490 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8491 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8492 if (DAG.SignBitIsZero(N0))
8493 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8496 // The next optimizations are desirable only if SELECT_CC can be lowered.
8497 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8498 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8500 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8501 (!LegalOperations ||
8502 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8505 { N0.getOperand(0), N0.getOperand(1),
8506 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8508 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8515 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8516 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8517 SDValue N0 = N->getOperand(0);
8518 EVT VT = N->getValueType(0);
8520 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8523 SDValue Src = N0.getOperand(0);
8524 EVT SrcVT = Src.getValueType();
8525 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8526 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8528 // We can safely assume the conversion won't overflow the output range,
8529 // because (for example) (uint8_t)18293.f is undefined behavior.
8531 // Since we can assume the conversion won't overflow, our decision as to
8532 // whether the input will fit in the float should depend on the minimum
8533 // of the input range and output range.
8535 // This means this is also safe for a signed input and unsigned output, since
8536 // a negative input would lead to undefined behavior.
8537 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8538 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8539 unsigned ActualSize = std::min(InputSize, OutputSize);
8540 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8542 // We can only fold away the float conversion if the input range can be
8543 // represented exactly in the float range.
8544 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8545 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8546 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8548 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8550 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8551 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8554 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8559 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8560 SDValue N0 = N->getOperand(0);
8561 EVT VT = N->getValueType(0);
8563 // fold (fp_to_sint c1fp) -> c1
8564 if (isConstantFPBuildVectorOrConstantFP(N0))
8565 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8567 return FoldIntToFPToInt(N, DAG);
8570 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8571 SDValue N0 = N->getOperand(0);
8572 EVT VT = N->getValueType(0);
8574 // fold (fp_to_uint c1fp) -> c1
8575 if (isConstantFPBuildVectorOrConstantFP(N0))
8576 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8578 return FoldIntToFPToInt(N, DAG);
8581 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8582 SDValue N0 = N->getOperand(0);
8583 SDValue N1 = N->getOperand(1);
8584 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8585 EVT VT = N->getValueType(0);
8587 // fold (fp_round c1fp) -> c1fp
8589 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8591 // fold (fp_round (fp_extend x)) -> x
8592 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8593 return N0.getOperand(0);
8595 // fold (fp_round (fp_round x)) -> (fp_round x)
8596 if (N0.getOpcode() == ISD::FP_ROUND) {
8597 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8598 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8599 // If the first fp_round isn't a value preserving truncation, it might
8600 // introduce a tie in the second fp_round, that wouldn't occur in the
8601 // single-step fp_round we want to fold to.
8602 // In other words, double rounding isn't the same as rounding.
8603 // Also, this is a value preserving truncation iff both fp_round's are.
8604 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8606 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8607 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8611 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8612 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8613 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8614 N0.getOperand(0), N1);
8615 AddToWorklist(Tmp.getNode());
8616 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8617 Tmp, N0.getOperand(1));
8623 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8624 SDValue N0 = N->getOperand(0);
8625 EVT VT = N->getValueType(0);
8626 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8627 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8629 // fold (fp_round_inreg c1fp) -> c1fp
8630 if (N0CFP && isTypeLegal(EVT)) {
8632 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8633 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8639 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8640 SDValue N0 = N->getOperand(0);
8641 EVT VT = N->getValueType(0);
8643 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8644 if (N->hasOneUse() &&
8645 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8648 // fold (fp_extend c1fp) -> c1fp
8649 if (isConstantFPBuildVectorOrConstantFP(N0))
8650 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8652 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8653 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8654 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8655 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8657 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8659 if (N0.getOpcode() == ISD::FP_ROUND
8660 && N0.getNode()->getConstantOperandVal(1) == 1) {
8661 SDValue In = N0.getOperand(0);
8662 if (In.getValueType() == VT) return In;
8663 if (VT.bitsLT(In.getValueType()))
8664 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8665 In, N0.getOperand(1));
8666 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8669 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8670 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8671 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8672 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8673 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8675 LN0->getBasePtr(), N0.getValueType(),
8676 LN0->getMemOperand());
8677 CombineTo(N, ExtLoad);
8678 CombineTo(N0.getNode(),
8679 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8680 N0.getValueType(), ExtLoad,
8681 DAG.getIntPtrConstant(1, SDLoc(N0))),
8682 ExtLoad.getValue(1));
8683 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8689 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8690 SDValue N0 = N->getOperand(0);
8691 EVT VT = N->getValueType(0);
8693 // fold (fceil c1) -> fceil(c1)
8694 if (isConstantFPBuildVectorOrConstantFP(N0))
8695 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8700 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8701 SDValue N0 = N->getOperand(0);
8702 EVT VT = N->getValueType(0);
8704 // fold (ftrunc c1) -> ftrunc(c1)
8705 if (isConstantFPBuildVectorOrConstantFP(N0))
8706 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8711 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8712 SDValue N0 = N->getOperand(0);
8713 EVT VT = N->getValueType(0);
8715 // fold (ffloor c1) -> ffloor(c1)
8716 if (isConstantFPBuildVectorOrConstantFP(N0))
8717 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8722 // FIXME: FNEG and FABS have a lot in common; refactor.
8723 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8724 SDValue N0 = N->getOperand(0);
8725 EVT VT = N->getValueType(0);
8727 // Constant fold FNEG.
8728 if (isConstantFPBuildVectorOrConstantFP(N0))
8729 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8731 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8732 &DAG.getTarget().Options))
8733 return GetNegatedExpression(N0, DAG, LegalOperations);
8735 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8736 // constant pool values.
8737 if (!TLI.isFNegFree(VT) &&
8738 N0.getOpcode() == ISD::BITCAST &&
8739 N0.getNode()->hasOneUse()) {
8740 SDValue Int = N0.getOperand(0);
8741 EVT IntVT = Int.getValueType();
8742 if (IntVT.isInteger() && !IntVT.isVector()) {
8744 if (N0.getValueType().isVector()) {
8745 // For a vector, get a mask such as 0x80... per scalar element
8747 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8748 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8750 // For a scalar, just generate 0x80...
8751 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8754 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8755 DAG.getConstant(SignMask, DL0, IntVT));
8756 AddToWorklist(Int.getNode());
8757 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8761 // (fneg (fmul c, x)) -> (fmul -c, x)
8762 if (N0.getOpcode() == ISD::FMUL) {
8763 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8765 APFloat CVal = CFP1->getValueAPF();
8767 if (Level >= AfterLegalizeDAG &&
8768 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8769 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8771 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8772 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8779 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8780 SDValue N0 = N->getOperand(0);
8781 SDValue N1 = N->getOperand(1);
8782 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8783 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8785 if (N0CFP && N1CFP) {
8786 const APFloat &C0 = N0CFP->getValueAPF();
8787 const APFloat &C1 = N1CFP->getValueAPF();
8788 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8792 EVT VT = N->getValueType(0);
8793 // Canonicalize to constant on RHS.
8794 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8800 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8801 SDValue N0 = N->getOperand(0);
8802 SDValue N1 = N->getOperand(1);
8803 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8804 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8806 if (N0CFP && N1CFP) {
8807 const APFloat &C0 = N0CFP->getValueAPF();
8808 const APFloat &C1 = N1CFP->getValueAPF();
8809 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8813 EVT VT = N->getValueType(0);
8814 // Canonicalize to constant on RHS.
8815 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8821 SDValue DAGCombiner::visitFABS(SDNode *N) {
8822 SDValue N0 = N->getOperand(0);
8823 EVT VT = N->getValueType(0);
8825 // fold (fabs c1) -> fabs(c1)
8826 if (isConstantFPBuildVectorOrConstantFP(N0))
8827 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8829 // fold (fabs (fabs x)) -> (fabs x)
8830 if (N0.getOpcode() == ISD::FABS)
8831 return N->getOperand(0);
8833 // fold (fabs (fneg x)) -> (fabs x)
8834 // fold (fabs (fcopysign x, y)) -> (fabs x)
8835 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8836 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8838 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8839 // constant pool values.
8840 if (!TLI.isFAbsFree(VT) &&
8841 N0.getOpcode() == ISD::BITCAST &&
8842 N0.getNode()->hasOneUse()) {
8843 SDValue Int = N0.getOperand(0);
8844 EVT IntVT = Int.getValueType();
8845 if (IntVT.isInteger() && !IntVT.isVector()) {
8847 if (N0.getValueType().isVector()) {
8848 // For a vector, get a mask such as 0x7f... per scalar element
8850 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8851 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8853 // For a scalar, just generate 0x7f...
8854 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8857 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8858 DAG.getConstant(SignMask, DL, IntVT));
8859 AddToWorklist(Int.getNode());
8860 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8867 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8868 SDValue Chain = N->getOperand(0);
8869 SDValue N1 = N->getOperand(1);
8870 SDValue N2 = N->getOperand(2);
8872 // If N is a constant we could fold this into a fallthrough or unconditional
8873 // branch. However that doesn't happen very often in normal code, because
8874 // Instcombine/SimplifyCFG should have handled the available opportunities.
8875 // If we did this folding here, it would be necessary to update the
8876 // MachineBasicBlock CFG, which is awkward.
8878 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8880 if (N1.getOpcode() == ISD::SETCC &&
8881 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8882 N1.getOperand(0).getValueType())) {
8883 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8884 Chain, N1.getOperand(2),
8885 N1.getOperand(0), N1.getOperand(1), N2);
8888 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8889 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8890 (N1.getOperand(0).hasOneUse() &&
8891 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8892 SDNode *Trunc = nullptr;
8893 if (N1.getOpcode() == ISD::TRUNCATE) {
8894 // Look pass the truncate.
8895 Trunc = N1.getNode();
8896 N1 = N1.getOperand(0);
8899 // Match this pattern so that we can generate simpler code:
8902 // %b = and i32 %a, 2
8903 // %c = srl i32 %b, 1
8904 // brcond i32 %c ...
8909 // %b = and i32 %a, 2
8910 // %c = setcc eq %b, 0
8913 // This applies only when the AND constant value has one bit set and the
8914 // SRL constant is equal to the log2 of the AND constant. The back-end is
8915 // smart enough to convert the result into a TEST/JMP sequence.
8916 SDValue Op0 = N1.getOperand(0);
8917 SDValue Op1 = N1.getOperand(1);
8919 if (Op0.getOpcode() == ISD::AND &&
8920 Op1.getOpcode() == ISD::Constant) {
8921 SDValue AndOp1 = Op0.getOperand(1);
8923 if (AndOp1.getOpcode() == ISD::Constant) {
8924 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8926 if (AndConst.isPowerOf2() &&
8927 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8931 getSetCCResultType(Op0.getValueType()),
8932 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8935 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8936 MVT::Other, Chain, SetCC, N2);
8937 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8938 // will convert it back to (X & C1) >> C2.
8939 CombineTo(N, NewBRCond, false);
8940 // Truncate is dead.
8942 deleteAndRecombine(Trunc);
8943 // Replace the uses of SRL with SETCC
8944 WorklistRemover DeadNodes(*this);
8945 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8946 deleteAndRecombine(N1.getNode());
8947 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8953 // Restore N1 if the above transformation doesn't match.
8954 N1 = N->getOperand(1);
8957 // Transform br(xor(x, y)) -> br(x != y)
8958 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8959 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8960 SDNode *TheXor = N1.getNode();
8961 SDValue Op0 = TheXor->getOperand(0);
8962 SDValue Op1 = TheXor->getOperand(1);
8963 if (Op0.getOpcode() == Op1.getOpcode()) {
8964 // Avoid missing important xor optimizations.
8965 SDValue Tmp = visitXOR(TheXor);
8966 if (Tmp.getNode()) {
8967 if (Tmp.getNode() != TheXor) {
8968 DEBUG(dbgs() << "\nReplacing.8 ";
8970 dbgs() << "\nWith: ";
8971 Tmp.getNode()->dump(&DAG);
8973 WorklistRemover DeadNodes(*this);
8974 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8975 deleteAndRecombine(TheXor);
8976 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8977 MVT::Other, Chain, Tmp, N2);
8980 // visitXOR has changed XOR's operands or replaced the XOR completely,
8982 return SDValue(N, 0);
8986 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8988 if (isOneConstant(Op0) && Op0.hasOneUse() &&
8989 Op0.getOpcode() == ISD::XOR) {
8990 TheXor = Op0.getNode();
8994 EVT SetCCVT = N1.getValueType();
8996 SetCCVT = getSetCCResultType(SetCCVT);
8997 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9000 Equal ? ISD::SETEQ : ISD::SETNE);
9001 // Replace the uses of XOR with SETCC
9002 WorklistRemover DeadNodes(*this);
9003 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9004 deleteAndRecombine(N1.getNode());
9005 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9006 MVT::Other, Chain, SetCC, N2);
9013 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9015 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9016 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9017 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9019 // If N is a constant we could fold this into a fallthrough or unconditional
9020 // branch. However that doesn't happen very often in normal code, because
9021 // Instcombine/SimplifyCFG should have handled the available opportunities.
9022 // If we did this folding here, it would be necessary to update the
9023 // MachineBasicBlock CFG, which is awkward.
9025 // Use SimplifySetCC to simplify SETCC's.
9026 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9027 CondLHS, CondRHS, CC->get(), SDLoc(N),
9029 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9031 // fold to a simpler setcc
9032 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9033 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9034 N->getOperand(0), Simp.getOperand(2),
9035 Simp.getOperand(0), Simp.getOperand(1),
9041 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9042 /// and that N may be folded in the load / store addressing mode.
9043 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9045 const TargetLowering &TLI) {
9047 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9048 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9050 VT = LD->getMemoryVT();
9051 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9052 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9054 VT = ST->getMemoryVT();
9058 TargetLowering::AddrMode AM;
9059 if (N->getOpcode() == ISD::ADD) {
9060 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9063 AM.BaseOffs = Offset->getSExtValue();
9067 } else if (N->getOpcode() == ISD::SUB) {
9068 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9071 AM.BaseOffs = -Offset->getSExtValue();
9078 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9081 /// Try turning a load/store into a pre-indexed load/store when the base
9082 /// pointer is an add or subtract and it has other uses besides the load/store.
9083 /// After the transformation, the new indexed load/store has effectively folded
9084 /// the add/subtract in and all of its other uses are redirected to the
9086 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9087 if (Level < AfterLegalizeDAG)
9093 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9094 if (LD->isIndexed())
9096 VT = LD->getMemoryVT();
9097 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9098 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9100 Ptr = LD->getBasePtr();
9101 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9102 if (ST->isIndexed())
9104 VT = ST->getMemoryVT();
9105 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9106 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9108 Ptr = ST->getBasePtr();
9114 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9115 // out. There is no reason to make this a preinc/predec.
9116 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9117 Ptr.getNode()->hasOneUse())
9120 // Ask the target to do addressing mode selection.
9123 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9124 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9127 // Backends without true r+i pre-indexed forms may need to pass a
9128 // constant base with a variable offset so that constant coercion
9129 // will work with the patterns in canonical form.
9130 bool Swapped = false;
9131 if (isa<ConstantSDNode>(BasePtr)) {
9132 std::swap(BasePtr, Offset);
9136 // Don't create a indexed load / store with zero offset.
9137 if (isNullConstant(Offset))
9140 // Try turning it into a pre-indexed load / store except when:
9141 // 1) The new base ptr is a frame index.
9142 // 2) If N is a store and the new base ptr is either the same as or is a
9143 // predecessor of the value being stored.
9144 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9145 // that would create a cycle.
9146 // 4) All uses are load / store ops that use it as old base ptr.
9148 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9149 // (plus the implicit offset) to a register to preinc anyway.
9150 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9155 SDValue Val = cast<StoreSDNode>(N)->getValue();
9156 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9160 // If the offset is a constant, there may be other adds of constants that
9161 // can be folded with this one. We should do this to avoid having to keep
9162 // a copy of the original base pointer.
9163 SmallVector<SDNode *, 16> OtherUses;
9164 if (isa<ConstantSDNode>(Offset))
9165 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9166 UE = BasePtr.getNode()->use_end();
9168 SDUse &Use = UI.getUse();
9169 // Skip the use that is Ptr and uses of other results from BasePtr's
9170 // node (important for nodes that return multiple results).
9171 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9174 if (Use.getUser()->isPredecessorOf(N))
9177 if (Use.getUser()->getOpcode() != ISD::ADD &&
9178 Use.getUser()->getOpcode() != ISD::SUB) {
9183 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9184 if (!isa<ConstantSDNode>(Op1)) {
9189 // FIXME: In some cases, we can be smarter about this.
9190 if (Op1.getValueType() != Offset.getValueType()) {
9195 OtherUses.push_back(Use.getUser());
9199 std::swap(BasePtr, Offset);
9201 // Now check for #3 and #4.
9202 bool RealUse = false;
9204 // Caches for hasPredecessorHelper
9205 SmallPtrSet<const SDNode *, 32> Visited;
9206 SmallVector<const SDNode *, 16> Worklist;
9208 for (SDNode *Use : Ptr.getNode()->uses()) {
9211 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9214 // If Ptr may be folded in addressing mode of other use, then it's
9215 // not profitable to do this transformation.
9216 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9225 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9226 BasePtr, Offset, AM);
9228 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9229 BasePtr, Offset, AM);
9232 DEBUG(dbgs() << "\nReplacing.4 ";
9234 dbgs() << "\nWith: ";
9235 Result.getNode()->dump(&DAG);
9237 WorklistRemover DeadNodes(*this);
9239 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9240 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9242 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9245 // Finally, since the node is now dead, remove it from the graph.
9246 deleteAndRecombine(N);
9249 std::swap(BasePtr, Offset);
9251 // Replace other uses of BasePtr that can be updated to use Ptr
9252 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9253 unsigned OffsetIdx = 1;
9254 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9256 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9257 BasePtr.getNode() && "Expected BasePtr operand");
9259 // We need to replace ptr0 in the following expression:
9260 // x0 * offset0 + y0 * ptr0 = t0
9262 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9264 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9265 // indexed load/store and the expresion that needs to be re-written.
9267 // Therefore, we have:
9268 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9270 ConstantSDNode *CN =
9271 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9273 APInt Offset0 = CN->getAPIntValue();
9274 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9276 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9277 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9278 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9279 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9281 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9283 APInt CNV = Offset0;
9284 if (X0 < 0) CNV = -CNV;
9285 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9286 else CNV = CNV - Offset1;
9288 SDLoc DL(OtherUses[i]);
9290 // We can now generate the new expression.
9291 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9292 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9294 SDValue NewUse = DAG.getNode(Opcode,
9296 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9297 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9298 deleteAndRecombine(OtherUses[i]);
9301 // Replace the uses of Ptr with uses of the updated base value.
9302 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9303 deleteAndRecombine(Ptr.getNode());
9308 /// Try to combine a load/store with a add/sub of the base pointer node into a
9309 /// post-indexed load/store. The transformation folded the add/subtract into the
9310 /// new indexed load/store effectively and all of its uses are redirected to the
9312 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9313 if (Level < AfterLegalizeDAG)
9319 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9320 if (LD->isIndexed())
9322 VT = LD->getMemoryVT();
9323 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9324 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9326 Ptr = LD->getBasePtr();
9327 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9328 if (ST->isIndexed())
9330 VT = ST->getMemoryVT();
9331 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9332 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9334 Ptr = ST->getBasePtr();
9340 if (Ptr.getNode()->hasOneUse())
9343 for (SDNode *Op : Ptr.getNode()->uses()) {
9345 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9350 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9351 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9352 // Don't create a indexed load / store with zero offset.
9353 if (isNullConstant(Offset))
9356 // Try turning it into a post-indexed load / store except when
9357 // 1) All uses are load / store ops that use it as base ptr (and
9358 // it may be folded as addressing mmode).
9359 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9360 // nor a successor of N. Otherwise, if Op is folded that would
9363 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9367 bool TryNext = false;
9368 for (SDNode *Use : BasePtr.getNode()->uses()) {
9369 if (Use == Ptr.getNode())
9372 // If all the uses are load / store addresses, then don't do the
9374 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9375 bool RealUse = false;
9376 for (SDNode *UseUse : Use->uses()) {
9377 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9392 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9393 SDValue Result = isLoad
9394 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9395 BasePtr, Offset, AM)
9396 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9397 BasePtr, Offset, AM);
9400 DEBUG(dbgs() << "\nReplacing.5 ";
9402 dbgs() << "\nWith: ";
9403 Result.getNode()->dump(&DAG);
9405 WorklistRemover DeadNodes(*this);
9407 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9408 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9410 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9413 // Finally, since the node is now dead, remove it from the graph.
9414 deleteAndRecombine(N);
9416 // Replace the uses of Use with uses of the updated base value.
9417 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9418 Result.getValue(isLoad ? 1 : 0));
9419 deleteAndRecombine(Op);
9428 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9429 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9430 ISD::MemIndexedMode AM = LD->getAddressingMode();
9431 assert(AM != ISD::UNINDEXED);
9432 SDValue BP = LD->getOperand(1);
9433 SDValue Inc = LD->getOperand(2);
9435 // Some backends use TargetConstants for load offsets, but don't expect
9436 // TargetConstants in general ADD nodes. We can convert these constants into
9437 // regular Constants (if the constant is not opaque).
9438 assert((Inc.getOpcode() != ISD::TargetConstant ||
9439 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9440 "Cannot split out indexing using opaque target constants");
9441 if (Inc.getOpcode() == ISD::TargetConstant) {
9442 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9443 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9444 ConstInc->getValueType(0));
9448 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9449 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9452 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9453 LoadSDNode *LD = cast<LoadSDNode>(N);
9454 SDValue Chain = LD->getChain();
9455 SDValue Ptr = LD->getBasePtr();
9457 // If load is not volatile and there are no uses of the loaded value (and
9458 // the updated indexed value in case of indexed loads), change uses of the
9459 // chain value into uses of the chain input (i.e. delete the dead load).
9460 if (!LD->isVolatile()) {
9461 if (N->getValueType(1) == MVT::Other) {
9463 if (!N->hasAnyUseOfValue(0)) {
9464 // It's not safe to use the two value CombineTo variant here. e.g.
9465 // v1, chain2 = load chain1, loc
9466 // v2, chain3 = load chain2, loc
9468 // Now we replace use of chain2 with chain1. This makes the second load
9469 // isomorphic to the one we are deleting, and thus makes this load live.
9470 DEBUG(dbgs() << "\nReplacing.6 ";
9472 dbgs() << "\nWith chain: ";
9473 Chain.getNode()->dump(&DAG);
9475 WorklistRemover DeadNodes(*this);
9476 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9479 deleteAndRecombine(N);
9481 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9485 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9487 // If this load has an opaque TargetConstant offset, then we cannot split
9488 // the indexing into an add/sub directly (that TargetConstant may not be
9489 // valid for a different type of node, and we cannot convert an opaque
9490 // target constant into a regular constant).
9491 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9492 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9494 if (!N->hasAnyUseOfValue(0) &&
9495 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9496 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9498 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9499 Index = SplitIndexingFromLoad(LD);
9500 // Try to fold the base pointer arithmetic into subsequent loads and
9502 AddUsersToWorklist(N);
9504 Index = DAG.getUNDEF(N->getValueType(1));
9505 DEBUG(dbgs() << "\nReplacing.7 ";
9507 dbgs() << "\nWith: ";
9508 Undef.getNode()->dump(&DAG);
9509 dbgs() << " and 2 other values\n");
9510 WorklistRemover DeadNodes(*this);
9511 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9512 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9513 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9514 deleteAndRecombine(N);
9515 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9520 // If this load is directly stored, replace the load value with the stored
9522 // TODO: Handle store large -> read small portion.
9523 // TODO: Handle TRUNCSTORE/LOADEXT
9524 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9525 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9526 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9527 if (PrevST->getBasePtr() == Ptr &&
9528 PrevST->getValue().getValueType() == N->getValueType(0))
9529 return CombineTo(N, Chain.getOperand(1), Chain);
9533 // Try to infer better alignment information than the load already has.
9534 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9535 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9536 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9538 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9539 LD->getValueType(0),
9540 Chain, Ptr, LD->getPointerInfo(),
9542 LD->isVolatile(), LD->isNonTemporal(),
9543 LD->isInvariant(), Align, LD->getAAInfo());
9544 if (NewLoad.getNode() != N)
9545 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9550 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9551 : DAG.getSubtarget().useAA();
9553 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9554 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9557 if (UseAA && LD->isUnindexed()) {
9558 // Walk up chain skipping non-aliasing memory nodes.
9559 SDValue BetterChain = FindBetterChain(N, Chain);
9561 // If there is a better chain.
9562 if (Chain != BetterChain) {
9565 // Replace the chain to void dependency.
9566 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9567 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9568 BetterChain, Ptr, LD->getMemOperand());
9570 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9571 LD->getValueType(0),
9572 BetterChain, Ptr, LD->getMemoryVT(),
9573 LD->getMemOperand());
9576 // Create token factor to keep old chain connected.
9577 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9578 MVT::Other, Chain, ReplLoad.getValue(1));
9580 // Make sure the new and old chains are cleaned up.
9581 AddToWorklist(Token.getNode());
9583 // Replace uses with load result and token factor. Don't add users
9585 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9589 // Try transforming N to an indexed load.
9590 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9591 return SDValue(N, 0);
9593 // Try to slice up N to more direct loads if the slices are mapped to
9594 // different register banks or pairing can take place.
9596 return SDValue(N, 0);
9602 /// \brief Helper structure used to slice a load in smaller loads.
9603 /// Basically a slice is obtained from the following sequence:
9604 /// Origin = load Ty1, Base
9605 /// Shift = srl Ty1 Origin, CstTy Amount
9606 /// Inst = trunc Shift to Ty2
9608 /// Then, it will be rewriten into:
9609 /// Slice = load SliceTy, Base + SliceOffset
9610 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9612 /// SliceTy is deduced from the number of bits that are actually used to
9614 struct LoadedSlice {
9615 /// \brief Helper structure used to compute the cost of a slice.
9617 /// Are we optimizing for code size.
9622 unsigned CrossRegisterBanksCopies;
9626 Cost(bool ForCodeSize = false)
9627 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9628 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9630 /// \brief Get the cost of one isolated slice.
9631 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9632 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9633 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9634 EVT TruncType = LS.Inst->getValueType(0);
9635 EVT LoadedType = LS.getLoadedType();
9636 if (TruncType != LoadedType &&
9637 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9641 /// \brief Account for slicing gain in the current cost.
9642 /// Slicing provide a few gains like removing a shift or a
9643 /// truncate. This method allows to grow the cost of the original
9644 /// load with the gain from this slice.
9645 void addSliceGain(const LoadedSlice &LS) {
9646 // Each slice saves a truncate.
9647 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9648 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9649 LS.Inst->getOperand(0).getValueType()))
9651 // If there is a shift amount, this slice gets rid of it.
9654 // If this slice can merge a cross register bank copy, account for it.
9655 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9656 ++CrossRegisterBanksCopies;
9659 Cost &operator+=(const Cost &RHS) {
9661 Truncates += RHS.Truncates;
9662 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9668 bool operator==(const Cost &RHS) const {
9669 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9670 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9671 ZExts == RHS.ZExts && Shift == RHS.Shift;
9674 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9676 bool operator<(const Cost &RHS) const {
9677 // Assume cross register banks copies are as expensive as loads.
9678 // FIXME: Do we want some more target hooks?
9679 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9680 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9681 // Unless we are optimizing for code size, consider the
9682 // expensive operation first.
9683 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9684 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9685 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9686 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9689 bool operator>(const Cost &RHS) const { return RHS < *this; }
9691 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9693 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9695 // The last instruction that represent the slice. This should be a
9696 // truncate instruction.
9698 // The original load instruction.
9700 // The right shift amount in bits from the original load.
9702 // The DAG from which Origin came from.
9703 // This is used to get some contextual information about legal types, etc.
9706 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9707 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9708 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9710 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9711 /// \return Result is \p BitWidth and has used bits set to 1 and
9712 /// not used bits set to 0.
9713 APInt getUsedBits() const {
9714 // Reproduce the trunc(lshr) sequence:
9715 // - Start from the truncated value.
9716 // - Zero extend to the desired bit width.
9718 assert(Origin && "No original load to compare against.");
9719 unsigned BitWidth = Origin->getValueSizeInBits(0);
9720 assert(Inst && "This slice is not bound to an instruction");
9721 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9722 "Extracted slice is bigger than the whole type!");
9723 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9724 UsedBits.setAllBits();
9725 UsedBits = UsedBits.zext(BitWidth);
9730 /// \brief Get the size of the slice to be loaded in bytes.
9731 unsigned getLoadedSize() const {
9732 unsigned SliceSize = getUsedBits().countPopulation();
9733 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9734 return SliceSize / 8;
9737 /// \brief Get the type that will be loaded for this slice.
9738 /// Note: This may not be the final type for the slice.
9739 EVT getLoadedType() const {
9740 assert(DAG && "Missing context");
9741 LLVMContext &Ctxt = *DAG->getContext();
9742 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9745 /// \brief Get the alignment of the load used for this slice.
9746 unsigned getAlignment() const {
9747 unsigned Alignment = Origin->getAlignment();
9748 unsigned Offset = getOffsetFromBase();
9750 Alignment = MinAlign(Alignment, Alignment + Offset);
9754 /// \brief Check if this slice can be rewritten with legal operations.
9755 bool isLegal() const {
9756 // An invalid slice is not legal.
9757 if (!Origin || !Inst || !DAG)
9760 // Offsets are for indexed load only, we do not handle that.
9761 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9764 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9766 // Check that the type is legal.
9767 EVT SliceType = getLoadedType();
9768 if (!TLI.isTypeLegal(SliceType))
9771 // Check that the load is legal for this type.
9772 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9775 // Check that the offset can be computed.
9776 // 1. Check its type.
9777 EVT PtrType = Origin->getBasePtr().getValueType();
9778 if (PtrType == MVT::Untyped || PtrType.isExtended())
9781 // 2. Check that it fits in the immediate.
9782 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9785 // 3. Check that the computation is legal.
9786 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9789 // Check that the zext is legal if it needs one.
9790 EVT TruncateType = Inst->getValueType(0);
9791 if (TruncateType != SliceType &&
9792 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9798 /// \brief Get the offset in bytes of this slice in the original chunk of
9800 /// \pre DAG != nullptr.
9801 uint64_t getOffsetFromBase() const {
9802 assert(DAG && "Missing context.");
9804 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9805 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9806 uint64_t Offset = Shift / 8;
9807 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9808 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9809 "The size of the original loaded type is not a multiple of a"
9811 // If Offset is bigger than TySizeInBytes, it means we are loading all
9812 // zeros. This should have been optimized before in the process.
9813 assert(TySizeInBytes > Offset &&
9814 "Invalid shift amount for given loaded size");
9816 Offset = TySizeInBytes - Offset - getLoadedSize();
9820 /// \brief Generate the sequence of instructions to load the slice
9821 /// represented by this object and redirect the uses of this slice to
9822 /// this new sequence of instructions.
9823 /// \pre this->Inst && this->Origin are valid Instructions and this
9824 /// object passed the legal check: LoadedSlice::isLegal returned true.
9825 /// \return The last instruction of the sequence used to load the slice.
9826 SDValue loadSlice() const {
9827 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9828 const SDValue &OldBaseAddr = Origin->getBasePtr();
9829 SDValue BaseAddr = OldBaseAddr;
9830 // Get the offset in that chunk of bytes w.r.t. the endianess.
9831 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9832 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9834 // BaseAddr = BaseAddr + Offset.
9835 EVT ArithType = BaseAddr.getValueType();
9837 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9838 DAG->getConstant(Offset, DL, ArithType));
9841 // Create the type of the loaded slice according to its size.
9842 EVT SliceType = getLoadedType();
9844 // Create the load for the slice.
9845 SDValue LastInst = DAG->getLoad(
9846 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9847 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9848 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9849 // If the final type is not the same as the loaded type, this means that
9850 // we have to pad with zero. Create a zero extend for that.
9851 EVT FinalType = Inst->getValueType(0);
9852 if (SliceType != FinalType)
9854 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9858 /// \brief Check if this slice can be merged with an expensive cross register
9859 /// bank copy. E.g.,
9861 /// f = bitcast i32 i to float
9862 bool canMergeExpensiveCrossRegisterBankCopy() const {
9863 if (!Inst || !Inst->hasOneUse())
9865 SDNode *Use = *Inst->use_begin();
9866 if (Use->getOpcode() != ISD::BITCAST)
9868 assert(DAG && "Missing context");
9869 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9870 EVT ResVT = Use->getValueType(0);
9871 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9872 const TargetRegisterClass *ArgRC =
9873 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9874 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9877 // At this point, we know that we perform a cross-register-bank copy.
9878 // Check if it is expensive.
9879 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9880 // Assume bitcasts are cheap, unless both register classes do not
9881 // explicitly share a common sub class.
9882 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9885 // Check if it will be merged with the load.
9886 // 1. Check the alignment constraint.
9887 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9888 ResVT.getTypeForEVT(*DAG->getContext()));
9890 if (RequiredAlignment > getAlignment())
9893 // 2. Check that the load is a legal operation for that type.
9894 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9897 // 3. Check that we do not have a zext in the way.
9898 if (Inst->getValueType(0) != getLoadedType())
9906 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9907 /// \p UsedBits looks like 0..0 1..1 0..0.
9908 static bool areUsedBitsDense(const APInt &UsedBits) {
9909 // If all the bits are one, this is dense!
9910 if (UsedBits.isAllOnesValue())
9913 // Get rid of the unused bits on the right.
9914 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9915 // Get rid of the unused bits on the left.
9916 if (NarrowedUsedBits.countLeadingZeros())
9917 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9918 // Check that the chunk of bits is completely used.
9919 return NarrowedUsedBits.isAllOnesValue();
9922 /// \brief Check whether or not \p First and \p Second are next to each other
9923 /// in memory. This means that there is no hole between the bits loaded
9924 /// by \p First and the bits loaded by \p Second.
9925 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9926 const LoadedSlice &Second) {
9927 assert(First.Origin == Second.Origin && First.Origin &&
9928 "Unable to match different memory origins.");
9929 APInt UsedBits = First.getUsedBits();
9930 assert((UsedBits & Second.getUsedBits()) == 0 &&
9931 "Slices are not supposed to overlap.");
9932 UsedBits |= Second.getUsedBits();
9933 return areUsedBitsDense(UsedBits);
9936 /// \brief Adjust the \p GlobalLSCost according to the target
9937 /// paring capabilities and the layout of the slices.
9938 /// \pre \p GlobalLSCost should account for at least as many loads as
9939 /// there is in the slices in \p LoadedSlices.
9940 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9941 LoadedSlice::Cost &GlobalLSCost) {
9942 unsigned NumberOfSlices = LoadedSlices.size();
9943 // If there is less than 2 elements, no pairing is possible.
9944 if (NumberOfSlices < 2)
9947 // Sort the slices so that elements that are likely to be next to each
9948 // other in memory are next to each other in the list.
9949 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9950 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9951 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9952 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9954 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9955 // First (resp. Second) is the first (resp. Second) potentially candidate
9956 // to be placed in a paired load.
9957 const LoadedSlice *First = nullptr;
9958 const LoadedSlice *Second = nullptr;
9959 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9960 // Set the beginning of the pair.
9963 Second = &LoadedSlices[CurrSlice];
9965 // If First is NULL, it means we start a new pair.
9966 // Get to the next slice.
9970 EVT LoadedType = First->getLoadedType();
9972 // If the types of the slices are different, we cannot pair them.
9973 if (LoadedType != Second->getLoadedType())
9976 // Check if the target supplies paired loads for this type.
9977 unsigned RequiredAlignment = 0;
9978 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9979 // move to the next pair, this type is hopeless.
9983 // Check if we meet the alignment requirement.
9984 if (RequiredAlignment > First->getAlignment())
9987 // Check that both loads are next to each other in memory.
9988 if (!areSlicesNextToEachOther(*First, *Second))
9991 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9992 --GlobalLSCost.Loads;
9993 // Move to the next pair.
9998 /// \brief Check the profitability of all involved LoadedSlice.
9999 /// Currently, it is considered profitable if there is exactly two
10000 /// involved slices (1) which are (2) next to each other in memory, and
10001 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10003 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10004 /// the elements themselves.
10006 /// FIXME: When the cost model will be mature enough, we can relax
10007 /// constraints (1) and (2).
10008 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10009 const APInt &UsedBits, bool ForCodeSize) {
10010 unsigned NumberOfSlices = LoadedSlices.size();
10011 if (StressLoadSlicing)
10012 return NumberOfSlices > 1;
10015 if (NumberOfSlices != 2)
10019 if (!areUsedBitsDense(UsedBits))
10023 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10024 // The original code has one big load.
10025 OrigCost.Loads = 1;
10026 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10027 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10028 // Accumulate the cost of all the slices.
10029 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10030 GlobalSlicingCost += SliceCost;
10032 // Account as cost in the original configuration the gain obtained
10033 // with the current slices.
10034 OrigCost.addSliceGain(LS);
10037 // If the target supports paired load, adjust the cost accordingly.
10038 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10039 return OrigCost > GlobalSlicingCost;
10042 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10043 /// operations, split it in the various pieces being extracted.
10045 /// This sort of thing is introduced by SROA.
10046 /// This slicing takes care not to insert overlapping loads.
10047 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10048 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10049 if (Level < AfterLegalizeDAG)
10052 LoadSDNode *LD = cast<LoadSDNode>(N);
10053 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10054 !LD->getValueType(0).isInteger())
10057 // Keep track of already used bits to detect overlapping values.
10058 // In that case, we will just abort the transformation.
10059 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10061 SmallVector<LoadedSlice, 4> LoadedSlices;
10063 // Check if this load is used as several smaller chunks of bits.
10064 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10065 // of computation for each trunc.
10066 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10067 UI != UIEnd; ++UI) {
10068 // Skip the uses of the chain.
10069 if (UI.getUse().getResNo() != 0)
10072 SDNode *User = *UI;
10073 unsigned Shift = 0;
10075 // Check if this is a trunc(lshr).
10076 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10077 isa<ConstantSDNode>(User->getOperand(1))) {
10078 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10079 User = *User->use_begin();
10082 // At this point, User is a Truncate, iff we encountered, trunc or
10084 if (User->getOpcode() != ISD::TRUNCATE)
10087 // The width of the type must be a power of 2 and greater than 8-bits.
10088 // Otherwise the load cannot be represented in LLVM IR.
10089 // Moreover, if we shifted with a non-8-bits multiple, the slice
10090 // will be across several bytes. We do not support that.
10091 unsigned Width = User->getValueSizeInBits(0);
10092 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10095 // Build the slice for this chain of computations.
10096 LoadedSlice LS(User, LD, Shift, &DAG);
10097 APInt CurrentUsedBits = LS.getUsedBits();
10099 // Check if this slice overlaps with another.
10100 if ((CurrentUsedBits & UsedBits) != 0)
10102 // Update the bits used globally.
10103 UsedBits |= CurrentUsedBits;
10105 // Check if the new slice would be legal.
10109 // Record the slice.
10110 LoadedSlices.push_back(LS);
10113 // Abort slicing if it does not seem to be profitable.
10114 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10119 // Rewrite each chain to use an independent load.
10120 // By construction, each chain can be represented by a unique load.
10122 // Prepare the argument for the new token factor for all the slices.
10123 SmallVector<SDValue, 8> ArgChains;
10124 for (SmallVectorImpl<LoadedSlice>::const_iterator
10125 LSIt = LoadedSlices.begin(),
10126 LSItEnd = LoadedSlices.end();
10127 LSIt != LSItEnd; ++LSIt) {
10128 SDValue SliceInst = LSIt->loadSlice();
10129 CombineTo(LSIt->Inst, SliceInst, true);
10130 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10131 SliceInst = SliceInst.getOperand(0);
10132 assert(SliceInst->getOpcode() == ISD::LOAD &&
10133 "It takes more than a zext to get to the loaded slice!!");
10134 ArgChains.push_back(SliceInst.getValue(1));
10137 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10139 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10143 /// Check to see if V is (and load (ptr), imm), where the load is having
10144 /// specific bytes cleared out. If so, return the byte size being masked out
10145 /// and the shift amount.
10146 static std::pair<unsigned, unsigned>
10147 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10148 std::pair<unsigned, unsigned> Result(0, 0);
10150 // Check for the structure we're looking for.
10151 if (V->getOpcode() != ISD::AND ||
10152 !isa<ConstantSDNode>(V->getOperand(1)) ||
10153 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10156 // Check the chain and pointer.
10157 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10158 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10160 // The store should be chained directly to the load or be an operand of a
10162 if (LD == Chain.getNode())
10164 else if (Chain->getOpcode() != ISD::TokenFactor)
10165 return Result; // Fail.
10168 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10169 if (Chain->getOperand(i).getNode() == LD) {
10173 if (!isOk) return Result;
10176 // This only handles simple types.
10177 if (V.getValueType() != MVT::i16 &&
10178 V.getValueType() != MVT::i32 &&
10179 V.getValueType() != MVT::i64)
10182 // Check the constant mask. Invert it so that the bits being masked out are
10183 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10184 // follow the sign bit for uniformity.
10185 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10186 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10187 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10188 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10189 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10190 if (NotMaskLZ == 64) return Result; // All zero mask.
10192 // See if we have a continuous run of bits. If so, we have 0*1+0*
10193 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10196 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10197 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10198 NotMaskLZ -= 64-V.getValueSizeInBits();
10200 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10201 switch (MaskedBytes) {
10205 default: return Result; // All one mask, or 5-byte mask.
10208 // Verify that the first bit starts at a multiple of mask so that the access
10209 // is aligned the same as the access width.
10210 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10212 Result.first = MaskedBytes;
10213 Result.second = NotMaskTZ/8;
10218 /// Check to see if IVal is something that provides a value as specified by
10219 /// MaskInfo. If so, replace the specified store with a narrower store of
10220 /// truncated IVal.
10222 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10223 SDValue IVal, StoreSDNode *St,
10225 unsigned NumBytes = MaskInfo.first;
10226 unsigned ByteShift = MaskInfo.second;
10227 SelectionDAG &DAG = DC->getDAG();
10229 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10230 // that uses this. If not, this is not a replacement.
10231 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10232 ByteShift*8, (ByteShift+NumBytes)*8);
10233 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10235 // Check that it is legal on the target to do this. It is legal if the new
10236 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10238 MVT VT = MVT::getIntegerVT(NumBytes*8);
10239 if (!DC->isTypeLegal(VT))
10242 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10243 // shifted by ByteShift and truncated down to NumBytes.
10246 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10247 DAG.getConstant(ByteShift*8, DL,
10248 DC->getShiftAmountTy(IVal.getValueType())));
10251 // Figure out the offset for the store and the alignment of the access.
10253 unsigned NewAlign = St->getAlignment();
10255 if (DAG.getTargetLoweringInfo().isLittleEndian())
10256 StOffset = ByteShift;
10258 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10260 SDValue Ptr = St->getBasePtr();
10263 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10264 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10265 NewAlign = MinAlign(NewAlign, StOffset);
10268 // Truncate down to the new size.
10269 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10272 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10273 St->getPointerInfo().getWithOffset(StOffset),
10274 false, false, NewAlign).getNode();
10278 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10279 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10280 /// narrowing the load and store if it would end up being a win for performance
10282 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10283 StoreSDNode *ST = cast<StoreSDNode>(N);
10284 if (ST->isVolatile())
10287 SDValue Chain = ST->getChain();
10288 SDValue Value = ST->getValue();
10289 SDValue Ptr = ST->getBasePtr();
10290 EVT VT = Value.getValueType();
10292 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10295 unsigned Opc = Value.getOpcode();
10297 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10298 // is a byte mask indicating a consecutive number of bytes, check to see if
10299 // Y is known to provide just those bytes. If so, we try to replace the
10300 // load + replace + store sequence with a single (narrower) store, which makes
10302 if (Opc == ISD::OR) {
10303 std::pair<unsigned, unsigned> MaskedLoad;
10304 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10305 if (MaskedLoad.first)
10306 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10307 Value.getOperand(1), ST,this))
10308 return SDValue(NewST, 0);
10310 // Or is commutative, so try swapping X and Y.
10311 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10312 if (MaskedLoad.first)
10313 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10314 Value.getOperand(0), ST,this))
10315 return SDValue(NewST, 0);
10318 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10319 Value.getOperand(1).getOpcode() != ISD::Constant)
10322 SDValue N0 = Value.getOperand(0);
10323 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10324 Chain == SDValue(N0.getNode(), 1)) {
10325 LoadSDNode *LD = cast<LoadSDNode>(N0);
10326 if (LD->getBasePtr() != Ptr ||
10327 LD->getPointerInfo().getAddrSpace() !=
10328 ST->getPointerInfo().getAddrSpace())
10331 // Find the type to narrow it the load / op / store to.
10332 SDValue N1 = Value.getOperand(1);
10333 unsigned BitWidth = N1.getValueSizeInBits();
10334 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10335 if (Opc == ISD::AND)
10336 Imm ^= APInt::getAllOnesValue(BitWidth);
10337 if (Imm == 0 || Imm.isAllOnesValue())
10339 unsigned ShAmt = Imm.countTrailingZeros();
10340 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10341 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10342 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10343 // The narrowing should be profitable, the load/store operation should be
10344 // legal (or custom) and the store size should be equal to the NewVT width.
10345 while (NewBW < BitWidth &&
10346 (NewVT.getStoreSizeInBits() != NewBW ||
10347 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10348 !TLI.isNarrowingProfitable(VT, NewVT))) {
10349 NewBW = NextPowerOf2(NewBW);
10350 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10352 if (NewBW >= BitWidth)
10355 // If the lsb changed does not start at the type bitwidth boundary,
10356 // start at the previous one.
10358 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10359 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10360 std::min(BitWidth, ShAmt + NewBW));
10361 if ((Imm & Mask) == Imm) {
10362 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10363 if (Opc == ISD::AND)
10364 NewImm ^= APInt::getAllOnesValue(NewBW);
10365 uint64_t PtrOff = ShAmt / 8;
10366 // For big endian targets, we need to adjust the offset to the pointer to
10367 // load the correct bytes.
10368 if (TLI.isBigEndian())
10369 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10371 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10372 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10373 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10376 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10377 Ptr.getValueType(), Ptr,
10378 DAG.getConstant(PtrOff, SDLoc(LD),
10379 Ptr.getValueType()));
10380 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10381 LD->getChain(), NewPtr,
10382 LD->getPointerInfo().getWithOffset(PtrOff),
10383 LD->isVolatile(), LD->isNonTemporal(),
10384 LD->isInvariant(), NewAlign,
10386 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10387 DAG.getConstant(NewImm, SDLoc(Value),
10389 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10391 ST->getPointerInfo().getWithOffset(PtrOff),
10392 false, false, NewAlign);
10394 AddToWorklist(NewPtr.getNode());
10395 AddToWorklist(NewLD.getNode());
10396 AddToWorklist(NewVal.getNode());
10397 WorklistRemover DeadNodes(*this);
10398 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10407 /// For a given floating point load / store pair, if the load value isn't used
10408 /// by any other operations, then consider transforming the pair to integer
10409 /// load / store operations if the target deems the transformation profitable.
10410 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10411 StoreSDNode *ST = cast<StoreSDNode>(N);
10412 SDValue Chain = ST->getChain();
10413 SDValue Value = ST->getValue();
10414 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10415 Value.hasOneUse() &&
10416 Chain == SDValue(Value.getNode(), 1)) {
10417 LoadSDNode *LD = cast<LoadSDNode>(Value);
10418 EVT VT = LD->getMemoryVT();
10419 if (!VT.isFloatingPoint() ||
10420 VT != ST->getMemoryVT() ||
10421 LD->isNonTemporal() ||
10422 ST->isNonTemporal() ||
10423 LD->getPointerInfo().getAddrSpace() != 0 ||
10424 ST->getPointerInfo().getAddrSpace() != 0)
10427 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10428 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10429 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10430 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10431 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10434 unsigned LDAlign = LD->getAlignment();
10435 unsigned STAlign = ST->getAlignment();
10436 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10437 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10438 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10441 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10442 LD->getChain(), LD->getBasePtr(),
10443 LD->getPointerInfo(),
10444 false, false, false, LDAlign);
10446 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10447 NewLD, ST->getBasePtr(),
10448 ST->getPointerInfo(),
10449 false, false, STAlign);
10451 AddToWorklist(NewLD.getNode());
10452 AddToWorklist(NewST.getNode());
10453 WorklistRemover DeadNodes(*this);
10454 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10463 /// Helper struct to parse and store a memory address as base + index + offset.
10464 /// We ignore sign extensions when it is safe to do so.
10465 /// The following two expressions are not equivalent. To differentiate we need
10466 /// to store whether there was a sign extension involved in the index
10468 /// (load (i64 add (i64 copyfromreg %c)
10469 /// (i64 signextend (add (i8 load %index)
10473 /// (load (i64 add (i64 copyfromreg %c)
10474 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10476 struct BaseIndexOffset {
10480 bool IsIndexSignExt;
10482 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10484 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10485 bool IsIndexSignExt) :
10486 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10488 bool equalBaseIndex(const BaseIndexOffset &Other) {
10489 return Other.Base == Base && Other.Index == Index &&
10490 Other.IsIndexSignExt == IsIndexSignExt;
10493 /// Parses tree in Ptr for base, index, offset addresses.
10494 static BaseIndexOffset match(SDValue Ptr) {
10495 bool IsIndexSignExt = false;
10497 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10498 // instruction, then it could be just the BASE or everything else we don't
10499 // know how to handle. Just use Ptr as BASE and give up.
10500 if (Ptr->getOpcode() != ISD::ADD)
10501 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10503 // We know that we have at least an ADD instruction. Try to pattern match
10504 // the simple case of BASE + OFFSET.
10505 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10506 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10507 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10511 // Inside a loop the current BASE pointer is calculated using an ADD and a
10512 // MUL instruction. In this case Ptr is the actual BASE pointer.
10513 // (i64 add (i64 %array_ptr)
10514 // (i64 mul (i64 %induction_var)
10515 // (i64 %element_size)))
10516 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10517 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10519 // Look at Base + Index + Offset cases.
10520 SDValue Base = Ptr->getOperand(0);
10521 SDValue IndexOffset = Ptr->getOperand(1);
10523 // Skip signextends.
10524 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10525 IndexOffset = IndexOffset->getOperand(0);
10526 IsIndexSignExt = true;
10529 // Either the case of Base + Index (no offset) or something else.
10530 if (IndexOffset->getOpcode() != ISD::ADD)
10531 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10533 // Now we have the case of Base + Index + offset.
10534 SDValue Index = IndexOffset->getOperand(0);
10535 SDValue Offset = IndexOffset->getOperand(1);
10537 if (!isa<ConstantSDNode>(Offset))
10538 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10540 // Ignore signextends.
10541 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10542 Index = Index->getOperand(0);
10543 IsIndexSignExt = true;
10544 } else IsIndexSignExt = false;
10546 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10547 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10552 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10553 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10554 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10555 // Make sure we have something to merge.
10559 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10560 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10561 unsigned LatestNodeUsed = 0;
10563 for (unsigned i=0; i < NumElem; ++i) {
10564 // Find a chain for the new wide-store operand. Notice that some
10565 // of the store nodes that we found may not be selected for inclusion
10566 // in the wide store. The chain we use needs to be the chain of the
10567 // latest store node which is *used* and replaced by the wide store.
10568 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10569 LatestNodeUsed = i;
10572 // The latest Node in the DAG.
10573 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10574 SDLoc DL(StoreNodes[0].MemNode);
10578 // Find a legal type for the vector store.
10579 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10580 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10581 if (IsConstantSrc) {
10582 // A vector store with a constant source implies that the constant is
10583 // zero; we only handle merging stores of constant zeros because the zero
10584 // can be materialized without a load.
10585 // It may be beneficial to loosen this restriction to allow non-zero
10587 StoredVal = DAG.getConstant(0, DL, Ty);
10589 SmallVector<SDValue, 8> Ops;
10590 for (unsigned i = 0; i < NumElem ; ++i) {
10591 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10592 SDValue Val = St->getValue();
10593 // All of the operands of a BUILD_VECTOR must have the same type.
10594 if (Val.getValueType() != MemVT)
10596 Ops.push_back(Val);
10599 // Build the extracted vector elements back into a vector.
10600 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10603 // We should always use a vector store when merging extracted vector
10604 // elements, so this path implies a store of constants.
10605 assert(IsConstantSrc && "Merged vector elements should use vector store");
10607 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10608 APInt StoreInt(StoreBW, 0);
10610 // Construct a single integer constant which is made of the smaller
10611 // constant inputs.
10612 bool IsLE = TLI.isLittleEndian();
10613 for (unsigned i = 0; i < NumElem ; ++i) {
10614 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10615 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10616 SDValue Val = St->getValue();
10617 StoreInt <<= ElementSizeBytes*8;
10618 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10619 StoreInt |= C->getAPIntValue().zext(StoreBW);
10620 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10621 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10623 llvm_unreachable("Invalid constant element type");
10627 // Create the new Load and Store operations.
10628 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10629 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10632 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10633 FirstInChain->getBasePtr(),
10634 FirstInChain->getPointerInfo(),
10636 FirstInChain->getAlignment());
10638 // Replace the last store with the new store
10639 CombineTo(LatestOp, NewStore);
10640 // Erase all other stores.
10641 for (unsigned i = 0; i < NumElem ; ++i) {
10642 if (StoreNodes[i].MemNode == LatestOp)
10644 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10645 // ReplaceAllUsesWith will replace all uses that existed when it was
10646 // called, but graph optimizations may cause new ones to appear. For
10647 // example, the case in pr14333 looks like
10649 // St's chain -> St -> another store -> X
10651 // And the only difference from St to the other store is the chain.
10652 // When we change it's chain to be St's chain they become identical,
10653 // get CSEed and the net result is that X is now a use of St.
10654 // Since we know that St is redundant, just iterate.
10655 while (!St->use_empty())
10656 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10657 deleteAndRecombine(St);
10663 static bool allowableAlignment(const SelectionDAG &DAG,
10664 const TargetLowering &TLI, EVT EVTTy,
10665 unsigned AS, unsigned Align) {
10666 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10669 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10670 unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10671 return (Align >= ABIAlignment);
10674 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10675 if (OptLevel == CodeGenOpt::None)
10678 EVT MemVT = St->getMemoryVT();
10679 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10680 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10681 Attribute::NoImplicitFloat);
10683 // This function cannot currently deal with non-byte-sized memory sizes.
10684 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10687 // Don't merge vectors into wider inputs.
10688 if (MemVT.isVector() || !MemVT.isSimple())
10691 // Perform an early exit check. Do not bother looking at stored values that
10692 // are not constants, loads, or extracted vector elements.
10693 SDValue StoredVal = St->getValue();
10694 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10695 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10696 isa<ConstantFPSDNode>(StoredVal);
10697 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10699 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10702 // Only look at ends of store sequences.
10703 SDValue Chain = SDValue(St, 0);
10704 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10707 // This holds the base pointer, index, and the offset in bytes from the base
10709 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10711 // We must have a base and an offset.
10712 if (!BasePtr.Base.getNode())
10715 // Do not handle stores to undef base pointers.
10716 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10719 // Save the LoadSDNodes that we find in the chain.
10720 // We need to make sure that these nodes do not interfere with
10721 // any of the store nodes.
10722 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10724 // Save the StoreSDNodes that we find in the chain.
10725 SmallVector<MemOpLink, 8> StoreNodes;
10727 // Walk up the chain and look for nodes with offsets from the same
10728 // base pointer. Stop when reaching an instruction with a different kind
10729 // or instruction which has a different base pointer.
10731 StoreSDNode *Index = St;
10733 // If the chain has more than one use, then we can't reorder the mem ops.
10734 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10737 // Find the base pointer and offset for this memory node.
10738 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10740 // Check that the base pointer is the same as the original one.
10741 if (!Ptr.equalBaseIndex(BasePtr))
10744 // The memory operands must not be volatile.
10745 if (Index->isVolatile() || Index->isIndexed())
10749 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10750 if (St->isTruncatingStore())
10753 // The stored memory type must be the same.
10754 if (Index->getMemoryVT() != MemVT)
10757 // We found a potential memory operand to merge.
10758 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10760 // Find the next memory operand in the chain. If the next operand in the
10761 // chain is a store then move up and continue the scan with the next
10762 // memory operand. If the next operand is a load save it and use alias
10763 // information to check if it interferes with anything.
10764 SDNode *NextInChain = Index->getChain().getNode();
10766 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10767 // We found a store node. Use it for the next iteration.
10770 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10771 if (Ldn->isVolatile()) {
10776 // Save the load node for later. Continue the scan.
10777 AliasLoadNodes.push_back(Ldn);
10778 NextInChain = Ldn->getChain().getNode();
10787 // Check if there is anything to merge.
10788 if (StoreNodes.size() < 2)
10791 // Sort the memory operands according to their distance from the base pointer.
10792 std::sort(StoreNodes.begin(), StoreNodes.end(),
10793 [](MemOpLink LHS, MemOpLink RHS) {
10794 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10795 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10796 LHS.SequenceNum > RHS.SequenceNum);
10799 // Scan the memory operations on the chain and find the first non-consecutive
10800 // store memory address.
10801 unsigned LastConsecutiveStore = 0;
10802 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10803 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10805 // Check that the addresses are consecutive starting from the second
10806 // element in the list of stores.
10808 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10809 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10813 bool Alias = false;
10814 // Check if this store interferes with any of the loads that we found.
10815 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10816 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10820 // We found a load that alias with this store. Stop the sequence.
10824 // Mark this node as useful.
10825 LastConsecutiveStore = i;
10828 // The node with the lowest store address.
10829 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10830 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10831 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10833 // Store the constants into memory as one consecutive store.
10834 if (IsConstantSrc) {
10835 unsigned LastLegalType = 0;
10836 unsigned LastLegalVectorType = 0;
10837 bool NonZero = false;
10838 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10839 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10840 SDValue StoredVal = St->getValue();
10842 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10843 NonZero |= !C->isNullValue();
10844 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10845 NonZero |= !C->getConstantFPValue()->isNullValue();
10851 // Find a legal type for the constant store.
10852 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10853 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10854 if (TLI.isTypeLegal(StoreTy) &&
10855 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10856 FirstStoreAlign)) {
10857 LastLegalType = i+1;
10858 // Or check whether a truncstore is legal.
10859 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10860 TargetLowering::TypePromoteInteger) {
10861 EVT LegalizedStoredValueTy =
10862 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10863 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10864 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10865 FirstStoreAlign)) {
10866 LastLegalType = i + 1;
10870 // Find a legal type for the vector store.
10871 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10872 if (TLI.isTypeLegal(Ty) &&
10873 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10874 LastLegalVectorType = i + 1;
10878 // We only use vectors if the constant is known to be zero and the
10879 // function is not marked with the noimplicitfloat attribute.
10880 if (NonZero || NoVectors)
10881 LastLegalVectorType = 0;
10883 // Check if we found a legal integer type to store.
10884 if (LastLegalType == 0 && LastLegalVectorType == 0)
10887 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10888 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10890 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10894 // When extracting multiple vector elements, try to store them
10895 // in one vector store rather than a sequence of scalar stores.
10896 if (IsExtractVecEltSrc) {
10897 unsigned NumElem = 0;
10898 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10899 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10900 SDValue StoredVal = St->getValue();
10901 // This restriction could be loosened.
10902 // Bail out if any stored values are not elements extracted from a vector.
10903 // It should be possible to handle mixed sources, but load sources need
10904 // more careful handling (see the block of code below that handles
10905 // consecutive loads).
10906 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10909 // Find a legal type for the vector store.
10910 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10911 if (TLI.isTypeLegal(Ty) &&
10912 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10916 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10920 // Below we handle the case of multiple consecutive stores that
10921 // come from multiple consecutive loads. We merge them into a single
10922 // wide load and a single wide store.
10924 // Look for load nodes which are used by the stored values.
10925 SmallVector<MemOpLink, 8> LoadNodes;
10927 // Find acceptable loads. Loads need to have the same chain (token factor),
10928 // must not be zext, volatile, indexed, and they must be consecutive.
10929 BaseIndexOffset LdBasePtr;
10930 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10931 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10932 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10935 // Loads must only have one use.
10936 if (!Ld->hasNUsesOfValue(1, 0))
10939 // The memory operands must not be volatile.
10940 if (Ld->isVolatile() || Ld->isIndexed())
10943 // We do not accept ext loads.
10944 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10947 // The stored memory type must be the same.
10948 if (Ld->getMemoryVT() != MemVT)
10951 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10952 // If this is not the first ptr that we check.
10953 if (LdBasePtr.Base.getNode()) {
10954 // The base ptr must be the same.
10955 if (!LdPtr.equalBaseIndex(LdBasePtr))
10958 // Check that all other base pointers are the same as this one.
10962 // We found a potential memory operand to merge.
10963 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10966 if (LoadNodes.size() < 2)
10969 // If we have load/store pair instructions and we only have two values,
10971 unsigned RequiredAlignment;
10972 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10973 St->getAlignment() >= RequiredAlignment)
10976 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10977 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
10978 unsigned FirstLoadAlign = FirstLoad->getAlignment();
10980 // Scan the memory operations on the chain and find the first non-consecutive
10981 // load memory address. These variables hold the index in the store node
10983 unsigned LastConsecutiveLoad = 0;
10984 // This variable refers to the size and not index in the array.
10985 unsigned LastLegalVectorType = 0;
10986 unsigned LastLegalIntegerType = 0;
10987 StartAddress = LoadNodes[0].OffsetFromBase;
10988 SDValue FirstChain = FirstLoad->getChain();
10989 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10990 // All loads much share the same chain.
10991 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10994 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10995 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10997 LastConsecutiveLoad = i;
10999 // Find a legal type for the vector store.
11000 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11001 if (TLI.isTypeLegal(StoreTy) &&
11002 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11003 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11004 LastLegalVectorType = i + 1;
11007 // Find a legal type for the integer store.
11008 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
11009 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11010 if (TLI.isTypeLegal(StoreTy) &&
11011 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11012 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11013 LastLegalIntegerType = i + 1;
11014 // Or check whether a truncstore and extload is legal.
11015 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11016 TargetLowering::TypePromoteInteger) {
11017 EVT LegalizedStoredValueTy =
11018 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11019 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11020 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11021 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11022 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11023 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11024 FirstStoreAlign) &&
11025 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11027 LastLegalIntegerType = i+1;
11031 // Only use vector types if the vector type is larger than the integer type.
11032 // If they are the same, use integers.
11033 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11034 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11036 // We add +1 here because the LastXXX variables refer to location while
11037 // the NumElem refers to array/index size.
11038 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11039 NumElem = std::min(LastLegalType, NumElem);
11044 // The latest Node in the DAG.
11045 unsigned LatestNodeUsed = 0;
11046 for (unsigned i=1; i<NumElem; ++i) {
11047 // Find a chain for the new wide-store operand. Notice that some
11048 // of the store nodes that we found may not be selected for inclusion
11049 // in the wide store. The chain we use needs to be the chain of the
11050 // latest store node which is *used* and replaced by the wide store.
11051 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11052 LatestNodeUsed = i;
11055 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11057 // Find if it is better to use vectors or integers to load and store
11061 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11063 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11064 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11067 SDLoc LoadDL(LoadNodes[0].MemNode);
11068 SDLoc StoreDL(StoreNodes[0].MemNode);
11070 SDValue NewLoad = DAG.getLoad(
11071 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11072 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11074 SDValue NewStore = DAG.getStore(
11075 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11076 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11078 // Replace one of the loads with the new load.
11079 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11080 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11081 SDValue(NewLoad.getNode(), 1));
11083 // Remove the rest of the load chains.
11084 for (unsigned i = 1; i < NumElem ; ++i) {
11085 // Replace all chain users of the old load nodes with the chain of the new
11087 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11088 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11091 // Replace the last store with the new store.
11092 CombineTo(LatestOp, NewStore);
11093 // Erase all other stores.
11094 for (unsigned i = 0; i < NumElem ; ++i) {
11095 // Remove all Store nodes.
11096 if (StoreNodes[i].MemNode == LatestOp)
11098 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11099 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11100 deleteAndRecombine(St);
11106 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11107 StoreSDNode *ST = cast<StoreSDNode>(N);
11108 SDValue Chain = ST->getChain();
11109 SDValue Value = ST->getValue();
11110 SDValue Ptr = ST->getBasePtr();
11112 // If this is a store of a bit convert, store the input value if the
11113 // resultant store does not need a higher alignment than the original.
11114 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11115 ST->isUnindexed()) {
11116 unsigned OrigAlign = ST->getAlignment();
11117 EVT SVT = Value.getOperand(0).getValueType();
11118 unsigned Align = TLI.getDataLayout()->
11119 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11120 if (Align <= OrigAlign &&
11121 ((!LegalOperations && !ST->isVolatile()) ||
11122 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11123 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11124 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11125 ST->isNonTemporal(), OrigAlign,
11129 // Turn 'store undef, Ptr' -> nothing.
11130 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11133 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11134 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11135 // NOTE: If the original store is volatile, this transform must not increase
11136 // the number of stores. For example, on x86-32 an f64 can be stored in one
11137 // processor operation but an i64 (which is not legal) requires two. So the
11138 // transform should not be done in this case.
11139 if (Value.getOpcode() != ISD::TargetConstantFP) {
11141 switch (CFP->getSimpleValueType(0).SimpleTy) {
11142 default: llvm_unreachable("Unknown FP type");
11143 case MVT::f16: // We don't do this for these yet.
11149 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11150 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11152 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11153 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11155 return DAG.getStore(Chain, SDLoc(N), Tmp,
11156 Ptr, ST->getMemOperand());
11160 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11161 !ST->isVolatile()) ||
11162 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11164 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11165 getZExtValue(), SDLoc(CFP), MVT::i64);
11166 return DAG.getStore(Chain, SDLoc(N), Tmp,
11167 Ptr, ST->getMemOperand());
11170 if (!ST->isVolatile() &&
11171 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11172 // Many FP stores are not made apparent until after legalize, e.g. for
11173 // argument passing. Since this is so common, custom legalize the
11174 // 64-bit integer store into two 32-bit stores.
11175 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11176 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11177 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11178 if (TLI.isBigEndian()) std::swap(Lo, Hi);
11180 unsigned Alignment = ST->getAlignment();
11181 bool isVolatile = ST->isVolatile();
11182 bool isNonTemporal = ST->isNonTemporal();
11183 AAMDNodes AAInfo = ST->getAAInfo();
11187 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11188 Ptr, ST->getPointerInfo(),
11189 isVolatile, isNonTemporal,
11190 ST->getAlignment(), AAInfo);
11191 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11192 DAG.getConstant(4, DL, Ptr.getValueType()));
11193 Alignment = MinAlign(Alignment, 4U);
11194 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11195 Ptr, ST->getPointerInfo().getWithOffset(4),
11196 isVolatile, isNonTemporal,
11197 Alignment, AAInfo);
11198 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11207 // Try to infer better alignment information than the store already has.
11208 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11209 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11210 if (Align > ST->getAlignment()) {
11212 DAG.getTruncStore(Chain, SDLoc(N), Value,
11213 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11214 ST->isVolatile(), ST->isNonTemporal(), Align,
11216 if (NewStore.getNode() != N)
11217 return CombineTo(ST, NewStore, true);
11222 // Try transforming a pair floating point load / store ops to integer
11223 // load / store ops.
11224 SDValue NewST = TransformFPLoadStorePair(N);
11225 if (NewST.getNode())
11228 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11229 : DAG.getSubtarget().useAA();
11231 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11232 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11235 if (UseAA && ST->isUnindexed()) {
11236 // Walk up chain skipping non-aliasing memory nodes.
11237 SDValue BetterChain = FindBetterChain(N, Chain);
11239 // If there is a better chain.
11240 if (Chain != BetterChain) {
11243 // Replace the chain to avoid dependency.
11244 if (ST->isTruncatingStore()) {
11245 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11246 ST->getMemoryVT(), ST->getMemOperand());
11248 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11249 ST->getMemOperand());
11252 // Create token to keep both nodes around.
11253 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11254 MVT::Other, Chain, ReplStore);
11256 // Make sure the new and old chains are cleaned up.
11257 AddToWorklist(Token.getNode());
11259 // Don't add users to work list.
11260 return CombineTo(N, Token, false);
11264 // Try transforming N to an indexed store.
11265 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11266 return SDValue(N, 0);
11268 // FIXME: is there such a thing as a truncating indexed store?
11269 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11270 Value.getValueType().isInteger()) {
11271 // See if we can simplify the input to this truncstore with knowledge that
11272 // only the low bits are being used. For example:
11273 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11275 GetDemandedBits(Value,
11276 APInt::getLowBitsSet(
11277 Value.getValueType().getScalarType().getSizeInBits(),
11278 ST->getMemoryVT().getScalarType().getSizeInBits()));
11279 AddToWorklist(Value.getNode());
11280 if (Shorter.getNode())
11281 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11282 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11284 // Otherwise, see if we can simplify the operation with
11285 // SimplifyDemandedBits, which only works if the value has a single use.
11286 if (SimplifyDemandedBits(Value,
11287 APInt::getLowBitsSet(
11288 Value.getValueType().getScalarType().getSizeInBits(),
11289 ST->getMemoryVT().getScalarType().getSizeInBits())))
11290 return SDValue(N, 0);
11293 // If this is a load followed by a store to the same location, then the store
11295 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11296 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11297 ST->isUnindexed() && !ST->isVolatile() &&
11298 // There can't be any side effects between the load and store, such as
11299 // a call or store.
11300 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11301 // The store is dead, remove it.
11306 // If this is a store followed by a store with the same value to the same
11307 // location, then the store is dead/noop.
11308 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11309 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11310 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11311 ST1->isUnindexed() && !ST1->isVolatile()) {
11312 // The store is dead, remove it.
11317 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11318 // truncating store. We can do this even if this is already a truncstore.
11319 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11320 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11321 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11322 ST->getMemoryVT())) {
11323 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11324 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11327 // Only perform this optimization before the types are legal, because we
11328 // don't want to perform this optimization on every DAGCombine invocation.
11330 bool EverChanged = false;
11333 // There can be multiple store sequences on the same chain.
11334 // Keep trying to merge store sequences until we are unable to do so
11335 // or until we merge the last store on the chain.
11336 bool Changed = MergeConsecutiveStores(ST);
11337 EverChanged |= Changed;
11338 if (!Changed) break;
11339 } while (ST->getOpcode() != ISD::DELETED_NODE);
11342 return SDValue(N, 0);
11345 return ReduceLoadOpStoreWidth(N);
11348 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11349 SDValue InVec = N->getOperand(0);
11350 SDValue InVal = N->getOperand(1);
11351 SDValue EltNo = N->getOperand(2);
11354 // If the inserted element is an UNDEF, just use the input vector.
11355 if (InVal.getOpcode() == ISD::UNDEF)
11358 EVT VT = InVec.getValueType();
11360 // If we can't generate a legal BUILD_VECTOR, exit
11361 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11364 // Check that we know which element is being inserted
11365 if (!isa<ConstantSDNode>(EltNo))
11367 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11369 // Canonicalize insert_vector_elt dag nodes.
11371 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11372 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11374 // Do this only if the child insert_vector node has one use; also
11375 // do this only if indices are both constants and Idx1 < Idx0.
11376 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11377 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11378 unsigned OtherElt =
11379 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11380 if (Elt < OtherElt) {
11382 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11383 InVec.getOperand(0), InVal, EltNo);
11384 AddToWorklist(NewOp.getNode());
11385 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11386 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11390 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11391 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11392 // vector elements.
11393 SmallVector<SDValue, 8> Ops;
11394 // Do not combine these two vectors if the output vector will not replace
11395 // the input vector.
11396 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11397 Ops.append(InVec.getNode()->op_begin(),
11398 InVec.getNode()->op_end());
11399 } else if (InVec.getOpcode() == ISD::UNDEF) {
11400 unsigned NElts = VT.getVectorNumElements();
11401 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11406 // Insert the element
11407 if (Elt < Ops.size()) {
11408 // All the operands of BUILD_VECTOR must have the same type;
11409 // we enforce that here.
11410 EVT OpVT = Ops[0].getValueType();
11411 if (InVal.getValueType() != OpVT)
11412 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11413 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11414 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11418 // Return the new vector
11419 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11422 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11423 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11424 EVT ResultVT = EVE->getValueType(0);
11425 EVT VecEltVT = InVecVT.getVectorElementType();
11426 unsigned Align = OriginalLoad->getAlignment();
11427 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11428 VecEltVT.getTypeForEVT(*DAG.getContext()));
11430 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11435 SDValue NewPtr = OriginalLoad->getBasePtr();
11437 EVT PtrType = NewPtr.getValueType();
11438 MachinePointerInfo MPI;
11440 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11441 int Elt = ConstEltNo->getZExtValue();
11442 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11443 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11444 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11446 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11447 Offset = DAG.getNode(
11448 ISD::MUL, DL, PtrType, Offset,
11449 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11450 MPI = OriginalLoad->getPointerInfo();
11452 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11454 // The replacement we need to do here is a little tricky: we need to
11455 // replace an extractelement of a load with a load.
11456 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11457 // Note that this replacement assumes that the extractvalue is the only
11458 // use of the load; that's okay because we don't want to perform this
11459 // transformation in other cases anyway.
11462 if (ResultVT.bitsGT(VecEltVT)) {
11463 // If the result type of vextract is wider than the load, then issue an
11464 // extending load instead.
11465 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11469 Load = DAG.getExtLoad(
11470 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11471 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11472 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11473 Chain = Load.getValue(1);
11475 Load = DAG.getLoad(
11476 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11477 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11478 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11479 Chain = Load.getValue(1);
11480 if (ResultVT.bitsLT(VecEltVT))
11481 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11483 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11485 WorklistRemover DeadNodes(*this);
11486 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11487 SDValue To[] = { Load, Chain };
11488 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11489 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11490 // worklist explicitly as well.
11491 AddToWorklist(Load.getNode());
11492 AddUsersToWorklist(Load.getNode()); // Add users too
11493 // Make sure to revisit this node to clean it up; it will usually be dead.
11494 AddToWorklist(EVE);
11496 return SDValue(EVE, 0);
11499 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11500 // (vextract (scalar_to_vector val, 0) -> val
11501 SDValue InVec = N->getOperand(0);
11502 EVT VT = InVec.getValueType();
11503 EVT NVT = N->getValueType(0);
11505 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11506 // Check if the result type doesn't match the inserted element type. A
11507 // SCALAR_TO_VECTOR may truncate the inserted element and the
11508 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11509 SDValue InOp = InVec.getOperand(0);
11510 if (InOp.getValueType() != NVT) {
11511 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11512 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11517 SDValue EltNo = N->getOperand(1);
11518 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11520 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11521 // We only perform this optimization before the op legalization phase because
11522 // we may introduce new vector instructions which are not backed by TD
11523 // patterns. For example on AVX, extracting elements from a wide vector
11524 // without using extract_subvector. However, if we can find an underlying
11525 // scalar value, then we can always use that.
11526 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11528 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11529 int NumElem = VT.getVectorNumElements();
11530 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11531 // Find the new index to extract from.
11532 int OrigElt = SVOp->getMaskElt(Elt);
11534 // Extracting an undef index is undef.
11536 return DAG.getUNDEF(NVT);
11538 // Select the right vector half to extract from.
11540 if (OrigElt < NumElem) {
11541 SVInVec = InVec->getOperand(0);
11543 SVInVec = InVec->getOperand(1);
11544 OrigElt -= NumElem;
11547 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11548 SDValue InOp = SVInVec.getOperand(OrigElt);
11549 if (InOp.getValueType() != NVT) {
11550 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11551 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11557 // FIXME: We should handle recursing on other vector shuffles and
11558 // scalar_to_vector here as well.
11560 if (!LegalOperations) {
11561 EVT IndexTy = TLI.getVectorIdxTy();
11562 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11563 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11567 bool BCNumEltsChanged = false;
11568 EVT ExtVT = VT.getVectorElementType();
11571 // If the result of load has to be truncated, then it's not necessarily
11573 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11576 if (InVec.getOpcode() == ISD::BITCAST) {
11577 // Don't duplicate a load with other uses.
11578 if (!InVec.hasOneUse())
11581 EVT BCVT = InVec.getOperand(0).getValueType();
11582 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11584 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11585 BCNumEltsChanged = true;
11586 InVec = InVec.getOperand(0);
11587 ExtVT = BCVT.getVectorElementType();
11590 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11591 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11592 ISD::isNormalLoad(InVec.getNode()) &&
11593 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11594 SDValue Index = N->getOperand(1);
11595 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11596 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11600 // Perform only after legalization to ensure build_vector / vector_shuffle
11601 // optimizations have already been done.
11602 if (!LegalOperations) return SDValue();
11604 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11605 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11606 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11609 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11611 LoadSDNode *LN0 = nullptr;
11612 const ShuffleVectorSDNode *SVN = nullptr;
11613 if (ISD::isNormalLoad(InVec.getNode())) {
11614 LN0 = cast<LoadSDNode>(InVec);
11615 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11616 InVec.getOperand(0).getValueType() == ExtVT &&
11617 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11618 // Don't duplicate a load with other uses.
11619 if (!InVec.hasOneUse())
11622 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11623 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11624 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11626 // (load $addr+1*size)
11628 // Don't duplicate a load with other uses.
11629 if (!InVec.hasOneUse())
11632 // If the bit convert changed the number of elements, it is unsafe
11633 // to examine the mask.
11634 if (BCNumEltsChanged)
11637 // Select the input vector, guarding against out of range extract vector.
11638 unsigned NumElems = VT.getVectorNumElements();
11639 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11640 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11642 if (InVec.getOpcode() == ISD::BITCAST) {
11643 // Don't duplicate a load with other uses.
11644 if (!InVec.hasOneUse())
11647 InVec = InVec.getOperand(0);
11649 if (ISD::isNormalLoad(InVec.getNode())) {
11650 LN0 = cast<LoadSDNode>(InVec);
11651 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11652 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11656 // Make sure we found a non-volatile load and the extractelement is
11658 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11661 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11663 return DAG.getUNDEF(LVT);
11665 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11671 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11672 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11673 // We perform this optimization post type-legalization because
11674 // the type-legalizer often scalarizes integer-promoted vectors.
11675 // Performing this optimization before may create bit-casts which
11676 // will be type-legalized to complex code sequences.
11677 // We perform this optimization only before the operation legalizer because we
11678 // may introduce illegal operations.
11679 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11682 unsigned NumInScalars = N->getNumOperands();
11684 EVT VT = N->getValueType(0);
11686 // Check to see if this is a BUILD_VECTOR of a bunch of values
11687 // which come from any_extend or zero_extend nodes. If so, we can create
11688 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11689 // optimizations. We do not handle sign-extend because we can't fill the sign
11691 EVT SourceType = MVT::Other;
11692 bool AllAnyExt = true;
11694 for (unsigned i = 0; i != NumInScalars; ++i) {
11695 SDValue In = N->getOperand(i);
11696 // Ignore undef inputs.
11697 if (In.getOpcode() == ISD::UNDEF) continue;
11699 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11700 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11702 // Abort if the element is not an extension.
11703 if (!ZeroExt && !AnyExt) {
11704 SourceType = MVT::Other;
11708 // The input is a ZeroExt or AnyExt. Check the original type.
11709 EVT InTy = In.getOperand(0).getValueType();
11711 // Check that all of the widened source types are the same.
11712 if (SourceType == MVT::Other)
11715 else if (InTy != SourceType) {
11716 // Multiple income types. Abort.
11717 SourceType = MVT::Other;
11721 // Check if all of the extends are ANY_EXTENDs.
11722 AllAnyExt &= AnyExt;
11725 // In order to have valid types, all of the inputs must be extended from the
11726 // same source type and all of the inputs must be any or zero extend.
11727 // Scalar sizes must be a power of two.
11728 EVT OutScalarTy = VT.getScalarType();
11729 bool ValidTypes = SourceType != MVT::Other &&
11730 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11731 isPowerOf2_32(SourceType.getSizeInBits());
11733 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11734 // turn into a single shuffle instruction.
11738 bool isLE = TLI.isLittleEndian();
11739 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11740 assert(ElemRatio > 1 && "Invalid element size ratio");
11741 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11742 DAG.getConstant(0, SDLoc(N), SourceType);
11744 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11745 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11747 // Populate the new build_vector
11748 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11749 SDValue Cast = N->getOperand(i);
11750 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11751 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11752 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11754 if (Cast.getOpcode() == ISD::UNDEF)
11755 In = DAG.getUNDEF(SourceType);
11757 In = Cast->getOperand(0);
11758 unsigned Index = isLE ? (i * ElemRatio) :
11759 (i * ElemRatio + (ElemRatio - 1));
11761 assert(Index < Ops.size() && "Invalid index");
11765 // The type of the new BUILD_VECTOR node.
11766 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11767 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11768 "Invalid vector size");
11769 // Check if the new vector type is legal.
11770 if (!isTypeLegal(VecVT)) return SDValue();
11772 // Make the new BUILD_VECTOR.
11773 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11775 // The new BUILD_VECTOR node has the potential to be further optimized.
11776 AddToWorklist(BV.getNode());
11777 // Bitcast to the desired type.
11778 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11781 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11782 EVT VT = N->getValueType(0);
11784 unsigned NumInScalars = N->getNumOperands();
11787 EVT SrcVT = MVT::Other;
11788 unsigned Opcode = ISD::DELETED_NODE;
11789 unsigned NumDefs = 0;
11791 for (unsigned i = 0; i != NumInScalars; ++i) {
11792 SDValue In = N->getOperand(i);
11793 unsigned Opc = In.getOpcode();
11795 if (Opc == ISD::UNDEF)
11798 // If all scalar values are floats and converted from integers.
11799 if (Opcode == ISD::DELETED_NODE &&
11800 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11807 EVT InVT = In.getOperand(0).getValueType();
11809 // If all scalar values are typed differently, bail out. It's chosen to
11810 // simplify BUILD_VECTOR of integer types.
11811 if (SrcVT == MVT::Other)
11818 // If the vector has just one element defined, it's not worth to fold it into
11819 // a vectorized one.
11823 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11824 && "Should only handle conversion from integer to float.");
11825 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11827 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11829 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11832 // Just because the floating-point vector type is legal does not necessarily
11833 // mean that the corresponding integer vector type is.
11834 if (!isTypeLegal(NVT))
11837 SmallVector<SDValue, 8> Opnds;
11838 for (unsigned i = 0; i != NumInScalars; ++i) {
11839 SDValue In = N->getOperand(i);
11841 if (In.getOpcode() == ISD::UNDEF)
11842 Opnds.push_back(DAG.getUNDEF(SrcVT));
11844 Opnds.push_back(In.getOperand(0));
11846 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11847 AddToWorklist(BV.getNode());
11849 return DAG.getNode(Opcode, dl, VT, BV);
11852 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11853 unsigned NumInScalars = N->getNumOperands();
11855 EVT VT = N->getValueType(0);
11857 // A vector built entirely of undefs is undef.
11858 if (ISD::allOperandsUndef(N))
11859 return DAG.getUNDEF(VT);
11861 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11864 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11867 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11868 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11869 // at most two distinct vectors, turn this into a shuffle node.
11871 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11872 if (!isTypeLegal(VT))
11875 // May only combine to shuffle after legalize if shuffle is legal.
11876 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11879 SDValue VecIn1, VecIn2;
11880 bool UsesZeroVector = false;
11881 for (unsigned i = 0; i != NumInScalars; ++i) {
11882 SDValue Op = N->getOperand(i);
11883 // Ignore undef inputs.
11884 if (Op.getOpcode() == ISD::UNDEF) continue;
11886 // See if we can combine this build_vector into a blend with a zero vector.
11887 if (!VecIn2.getNode() && (isNullConstant(Op) ||
11888 (Op.getOpcode() == ISD::ConstantFP &&
11889 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11890 UsesZeroVector = true;
11894 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11895 // constant index, bail out.
11896 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11897 !isa<ConstantSDNode>(Op.getOperand(1))) {
11898 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11902 // We allow up to two distinct input vectors.
11903 SDValue ExtractedFromVec = Op.getOperand(0);
11904 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11907 if (!VecIn1.getNode()) {
11908 VecIn1 = ExtractedFromVec;
11909 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11910 VecIn2 = ExtractedFromVec;
11912 // Too many inputs.
11913 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11918 // If everything is good, we can make a shuffle operation.
11919 if (VecIn1.getNode()) {
11920 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11921 SmallVector<int, 8> Mask;
11922 for (unsigned i = 0; i != NumInScalars; ++i) {
11923 unsigned Opcode = N->getOperand(i).getOpcode();
11924 if (Opcode == ISD::UNDEF) {
11925 Mask.push_back(-1);
11929 // Operands can also be zero.
11930 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11931 assert(UsesZeroVector &&
11932 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11933 "Unexpected node found!");
11934 Mask.push_back(NumInScalars+i);
11938 // If extracting from the first vector, just use the index directly.
11939 SDValue Extract = N->getOperand(i);
11940 SDValue ExtVal = Extract.getOperand(1);
11941 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11942 if (Extract.getOperand(0) == VecIn1) {
11943 Mask.push_back(ExtIndex);
11947 // Otherwise, use InIdx + InputVecSize
11948 Mask.push_back(InNumElements + ExtIndex);
11951 // Avoid introducing illegal shuffles with zero.
11952 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11955 // We can't generate a shuffle node with mismatched input and output types.
11956 // Attempt to transform a single input vector to the correct type.
11957 if ((VT != VecIn1.getValueType())) {
11958 // If the input vector type has a different base type to the output
11959 // vector type, bail out.
11960 EVT VTElemType = VT.getVectorElementType();
11961 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11962 (VecIn2.getNode() &&
11963 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11966 // If the input vector is too small, widen it.
11967 // We only support widening of vectors which are half the size of the
11968 // output registers. For example XMM->YMM widening on X86 with AVX.
11969 EVT VecInT = VecIn1.getValueType();
11970 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11971 // If we only have one small input, widen it by adding undef values.
11972 if (!VecIn2.getNode())
11973 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11974 DAG.getUNDEF(VecIn1.getValueType()));
11975 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11976 // If we have two small inputs of the same type, try to concat them.
11977 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11978 VecIn2 = SDValue(nullptr, 0);
11981 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11982 // If the input vector is too large, try to split it.
11983 // We don't support having two input vectors that are too large.
11984 // If the zero vector was used, we can not split the vector,
11985 // since we'd need 3 inputs.
11986 if (UsesZeroVector || VecIn2.getNode())
11989 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11992 // Try to replace VecIn1 with two extract_subvectors
11993 // No need to update the masks, they should still be correct.
11994 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11995 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11996 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11997 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
12002 if (UsesZeroVector)
12003 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12004 DAG.getConstantFP(0.0, dl, VT);
12006 // If VecIn2 is unused then change it to undef.
12007 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12009 // Check that we were able to transform all incoming values to the same
12011 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12012 VecIn1.getValueType() != VT)
12015 // Return the new VECTOR_SHUFFLE node.
12019 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12025 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12026 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12027 EVT OpVT = N->getOperand(0).getValueType();
12029 // If the operands are legal vectors, leave them alone.
12030 if (TLI.isTypeLegal(OpVT))
12034 EVT VT = N->getValueType(0);
12035 SmallVector<SDValue, 8> Ops;
12037 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12038 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12040 // Keep track of what we encounter.
12041 bool AnyInteger = false;
12042 bool AnyFP = false;
12043 for (const SDValue &Op : N->ops()) {
12044 if (ISD::BITCAST == Op.getOpcode() &&
12045 !Op.getOperand(0).getValueType().isVector())
12046 Ops.push_back(Op.getOperand(0));
12047 else if (ISD::UNDEF == Op.getOpcode())
12048 Ops.push_back(ScalarUndef);
12052 // Note whether we encounter an integer or floating point scalar.
12053 // If it's neither, bail out, it could be something weird like x86mmx.
12054 EVT LastOpVT = Ops.back().getValueType();
12055 if (LastOpVT.isFloatingPoint())
12057 else if (LastOpVT.isInteger())
12063 // If any of the operands is a floating point scalar bitcast to a vector,
12064 // use floating point types throughout, and bitcast everything.
12065 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12067 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12068 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12070 for (SDValue &Op : Ops) {
12071 if (Op.getValueType() == SVT)
12073 if (Op.getOpcode() == ISD::UNDEF)
12076 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12081 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12082 VT.getSizeInBits() / SVT.getSizeInBits());
12083 return DAG.getNode(ISD::BITCAST, DL, VT,
12084 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12087 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12088 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12089 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12090 // inputs come from at most two distinct vectors, turn this into a shuffle
12093 // If we only have one input vector, we don't need to do any concatenation.
12094 if (N->getNumOperands() == 1)
12095 return N->getOperand(0);
12097 // Check if all of the operands are undefs.
12098 EVT VT = N->getValueType(0);
12099 if (ISD::allOperandsUndef(N))
12100 return DAG.getUNDEF(VT);
12102 // Optimize concat_vectors where all but the first of the vectors are undef.
12103 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12104 return Op.getOpcode() == ISD::UNDEF;
12106 SDValue In = N->getOperand(0);
12107 assert(In.getValueType().isVector() && "Must concat vectors");
12109 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12110 if (In->getOpcode() == ISD::BITCAST &&
12111 !In->getOperand(0)->getValueType(0).isVector()) {
12112 SDValue Scalar = In->getOperand(0);
12114 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12115 // look through the trunc so we can still do the transform:
12116 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12117 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12118 !TLI.isTypeLegal(Scalar.getValueType()) &&
12119 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12120 Scalar = Scalar->getOperand(0);
12122 EVT SclTy = Scalar->getValueType(0);
12124 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12127 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12128 VT.getSizeInBits() / SclTy.getSizeInBits());
12129 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12132 SDLoc dl = SDLoc(N);
12133 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12134 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12138 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12139 // We have already tested above for an UNDEF only concatenation.
12140 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12141 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12142 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12143 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12145 bool AllBuildVectorsOrUndefs =
12146 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12147 if (AllBuildVectorsOrUndefs) {
12148 SmallVector<SDValue, 8> Opnds;
12149 EVT SVT = VT.getScalarType();
12152 if (!SVT.isFloatingPoint()) {
12153 // If BUILD_VECTOR are from built from integer, they may have different
12154 // operand types. Get the smallest type and truncate all operands to it.
12155 bool FoundMinVT = false;
12156 for (const SDValue &Op : N->ops())
12157 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12158 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12159 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12162 assert(FoundMinVT && "Concat vector type mismatch");
12165 for (const SDValue &Op : N->ops()) {
12166 EVT OpVT = Op.getValueType();
12167 unsigned NumElts = OpVT.getVectorNumElements();
12169 if (ISD::UNDEF == Op.getOpcode())
12170 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12172 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12173 if (SVT.isFloatingPoint()) {
12174 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12175 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12177 for (unsigned i = 0; i != NumElts; ++i)
12179 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12184 assert(VT.getVectorNumElements() == Opnds.size() &&
12185 "Concat vector type mismatch");
12186 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12189 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12190 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12193 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12194 // nodes often generate nop CONCAT_VECTOR nodes.
12195 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12196 // place the incoming vectors at the exact same location.
12197 SDValue SingleSource = SDValue();
12198 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12200 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12201 SDValue Op = N->getOperand(i);
12203 if (Op.getOpcode() == ISD::UNDEF)
12206 // Check if this is the identity extract:
12207 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12210 // Find the single incoming vector for the extract_subvector.
12211 if (SingleSource.getNode()) {
12212 if (Op.getOperand(0) != SingleSource)
12215 SingleSource = Op.getOperand(0);
12217 // Check the source type is the same as the type of the result.
12218 // If not, this concat may extend the vector, so we can not
12219 // optimize it away.
12220 if (SingleSource.getValueType() != N->getValueType(0))
12224 unsigned IdentityIndex = i * PartNumElem;
12225 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12226 // The extract index must be constant.
12230 // Check that we are reading from the identity index.
12231 if (CS->getZExtValue() != IdentityIndex)
12235 if (SingleSource.getNode())
12236 return SingleSource;
12241 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12242 EVT NVT = N->getValueType(0);
12243 SDValue V = N->getOperand(0);
12245 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12247 // (extract_subvec (concat V1, V2, ...), i)
12250 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12252 if (V->getOperand(0).getValueType() != NVT)
12254 unsigned Idx = N->getConstantOperandVal(1);
12255 unsigned NumElems = NVT.getVectorNumElements();
12256 assert((Idx % NumElems) == 0 &&
12257 "IDX in concat is not a multiple of the result vector length.");
12258 return V->getOperand(Idx / NumElems);
12262 if (V->getOpcode() == ISD::BITCAST)
12263 V = V.getOperand(0);
12265 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12267 // Handle only simple case where vector being inserted and vector
12268 // being extracted are of same type, and are half size of larger vectors.
12269 EVT BigVT = V->getOperand(0).getValueType();
12270 EVT SmallVT = V->getOperand(1).getValueType();
12271 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12274 // Only handle cases where both indexes are constants with the same type.
12275 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12276 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12278 if (InsIdx && ExtIdx &&
12279 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12280 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12282 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12284 // indices are equal or bit offsets are equal => V1
12285 // otherwise => (extract_subvec V1, ExtIdx)
12286 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12287 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12288 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12289 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12290 DAG.getNode(ISD::BITCAST, dl,
12291 N->getOperand(0).getValueType(),
12292 V->getOperand(0)), N->getOperand(1));
12299 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12300 SDValue V, SelectionDAG &DAG) {
12302 EVT VT = V.getValueType();
12304 switch (V.getOpcode()) {
12308 case ISD::CONCAT_VECTORS: {
12309 EVT OpVT = V->getOperand(0).getValueType();
12310 int OpSize = OpVT.getVectorNumElements();
12311 SmallBitVector OpUsedElements(OpSize, false);
12312 bool FoundSimplification = false;
12313 SmallVector<SDValue, 4> NewOps;
12314 NewOps.reserve(V->getNumOperands());
12315 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12316 SDValue Op = V->getOperand(i);
12317 bool OpUsed = false;
12318 for (int j = 0; j < OpSize; ++j)
12319 if (UsedElements[i * OpSize + j]) {
12320 OpUsedElements[j] = true;
12324 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12325 : DAG.getUNDEF(OpVT));
12326 FoundSimplification |= Op == NewOps.back();
12327 OpUsedElements.reset();
12329 if (FoundSimplification)
12330 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12334 case ISD::INSERT_SUBVECTOR: {
12335 SDValue BaseV = V->getOperand(0);
12336 SDValue SubV = V->getOperand(1);
12337 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12341 int SubSize = SubV.getValueType().getVectorNumElements();
12342 int Idx = IdxN->getZExtValue();
12343 bool SubVectorUsed = false;
12344 SmallBitVector SubUsedElements(SubSize, false);
12345 for (int i = 0; i < SubSize; ++i)
12346 if (UsedElements[i + Idx]) {
12347 SubVectorUsed = true;
12348 SubUsedElements[i] = true;
12349 UsedElements[i + Idx] = false;
12352 // Now recurse on both the base and sub vectors.
12353 SDValue SimplifiedSubV =
12355 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12356 : DAG.getUNDEF(SubV.getValueType());
12357 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12358 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12359 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12360 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12366 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12367 SDValue N1, SelectionDAG &DAG) {
12368 EVT VT = SVN->getValueType(0);
12369 int NumElts = VT.getVectorNumElements();
12370 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12371 for (int M : SVN->getMask())
12372 if (M >= 0 && M < NumElts)
12373 N0UsedElements[M] = true;
12374 else if (M >= NumElts)
12375 N1UsedElements[M - NumElts] = true;
12377 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12378 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12379 if (S0 == N0 && S1 == N1)
12382 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12385 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12386 // or turn a shuffle of a single concat into simpler shuffle then concat.
12387 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12388 EVT VT = N->getValueType(0);
12389 unsigned NumElts = VT.getVectorNumElements();
12391 SDValue N0 = N->getOperand(0);
12392 SDValue N1 = N->getOperand(1);
12393 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12395 SmallVector<SDValue, 4> Ops;
12396 EVT ConcatVT = N0.getOperand(0).getValueType();
12397 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12398 unsigned NumConcats = NumElts / NumElemsPerConcat;
12400 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12401 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12402 // half vector elements.
12403 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12404 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12405 SVN->getMask().end(), [](int i) { return i == -1; })) {
12406 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12407 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12408 N1 = DAG.getUNDEF(ConcatVT);
12409 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12412 // Look at every vector that's inserted. We're looking for exact
12413 // subvector-sized copies from a concatenated vector
12414 for (unsigned I = 0; I != NumConcats; ++I) {
12415 // Make sure we're dealing with a copy.
12416 unsigned Begin = I * NumElemsPerConcat;
12417 bool AllUndef = true, NoUndef = true;
12418 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12419 if (SVN->getMaskElt(J) >= 0)
12426 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12429 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12430 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12433 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12434 if (FirstElt < N0.getNumOperands())
12435 Ops.push_back(N0.getOperand(FirstElt));
12437 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12439 } else if (AllUndef) {
12440 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12441 } else { // Mixed with general masks and undefs, can't do optimization.
12446 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12449 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12450 EVT VT = N->getValueType(0);
12451 unsigned NumElts = VT.getVectorNumElements();
12453 SDValue N0 = N->getOperand(0);
12454 SDValue N1 = N->getOperand(1);
12456 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12458 // Canonicalize shuffle undef, undef -> undef
12459 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12460 return DAG.getUNDEF(VT);
12462 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12464 // Canonicalize shuffle v, v -> v, undef
12466 SmallVector<int, 8> NewMask;
12467 for (unsigned i = 0; i != NumElts; ++i) {
12468 int Idx = SVN->getMaskElt(i);
12469 if (Idx >= (int)NumElts) Idx -= NumElts;
12470 NewMask.push_back(Idx);
12472 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12476 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12477 if (N0.getOpcode() == ISD::UNDEF) {
12478 SmallVector<int, 8> NewMask;
12479 for (unsigned i = 0; i != NumElts; ++i) {
12480 int Idx = SVN->getMaskElt(i);
12482 if (Idx >= (int)NumElts)
12485 Idx = -1; // remove reference to lhs
12487 NewMask.push_back(Idx);
12489 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12493 // Remove references to rhs if it is undef
12494 if (N1.getOpcode() == ISD::UNDEF) {
12495 bool Changed = false;
12496 SmallVector<int, 8> NewMask;
12497 for (unsigned i = 0; i != NumElts; ++i) {
12498 int Idx = SVN->getMaskElt(i);
12499 if (Idx >= (int)NumElts) {
12503 NewMask.push_back(Idx);
12506 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12509 // If it is a splat, check if the argument vector is another splat or a
12511 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12512 SDNode *V = N0.getNode();
12514 // If this is a bit convert that changes the element type of the vector but
12515 // not the number of vector elements, look through it. Be careful not to
12516 // look though conversions that change things like v4f32 to v2f64.
12517 if (V->getOpcode() == ISD::BITCAST) {
12518 SDValue ConvInput = V->getOperand(0);
12519 if (ConvInput.getValueType().isVector() &&
12520 ConvInput.getValueType().getVectorNumElements() == NumElts)
12521 V = ConvInput.getNode();
12524 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12525 assert(V->getNumOperands() == NumElts &&
12526 "BUILD_VECTOR has wrong number of operands");
12528 bool AllSame = true;
12529 for (unsigned i = 0; i != NumElts; ++i) {
12530 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12531 Base = V->getOperand(i);
12535 // Splat of <u, u, u, u>, return <u, u, u, u>
12536 if (!Base.getNode())
12538 for (unsigned i = 0; i != NumElts; ++i) {
12539 if (V->getOperand(i) != Base) {
12544 // Splat of <x, x, x, x>, return <x, x, x, x>
12548 // Canonicalize any other splat as a build_vector.
12549 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12550 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12551 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12552 V->getValueType(0), Ops);
12554 // We may have jumped through bitcasts, so the type of the
12555 // BUILD_VECTOR may not match the type of the shuffle.
12556 if (V->getValueType(0) != VT)
12557 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12562 // There are various patterns used to build up a vector from smaller vectors,
12563 // subvectors, or elements. Scan chains of these and replace unused insertions
12564 // or components with undef.
12565 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12568 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12569 Level < AfterLegalizeVectorOps &&
12570 (N1.getOpcode() == ISD::UNDEF ||
12571 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12572 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12573 SDValue V = partitionShuffleOfConcats(N, DAG);
12579 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12580 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12581 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12582 SmallVector<SDValue, 8> Ops;
12583 for (int M : SVN->getMask()) {
12584 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12586 int Idx = M % NumElts;
12587 SDValue &S = (M < (int)NumElts ? N0 : N1);
12588 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12589 Op = S.getOperand(Idx);
12590 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12592 Op = S.getOperand(0);
12594 // Operand can't be combined - bail out.
12600 if (Ops.size() == VT.getVectorNumElements()) {
12601 // BUILD_VECTOR requires all inputs to be of the same type, find the
12602 // maximum type and extend them all.
12603 EVT SVT = VT.getScalarType();
12604 if (SVT.isInteger())
12605 for (SDValue &Op : Ops)
12606 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12607 if (SVT != VT.getScalarType())
12608 for (SDValue &Op : Ops)
12609 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12610 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12611 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12612 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12616 // If this shuffle only has a single input that is a bitcasted shuffle,
12617 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12618 // back to their original types.
12619 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12620 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12621 TLI.isTypeLegal(VT)) {
12623 // Peek through the bitcast only if there is one user.
12625 while (BC0.getOpcode() == ISD::BITCAST) {
12626 if (!BC0.hasOneUse())
12628 BC0 = BC0.getOperand(0);
12631 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12633 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12635 SmallVector<int, 8> NewMask;
12637 for (int s = 0; s != Scale; ++s)
12638 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12642 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12643 EVT SVT = VT.getScalarType();
12644 EVT InnerVT = BC0->getValueType(0);
12645 EVT InnerSVT = InnerVT.getScalarType();
12647 // Determine which shuffle works with the smaller scalar type.
12648 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12649 EVT ScaleSVT = ScaleVT.getScalarType();
12651 if (TLI.isTypeLegal(ScaleVT) &&
12652 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12653 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12655 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12656 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12658 // Scale the shuffle masks to the smaller scalar type.
12659 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12660 SmallVector<int, 8> InnerMask =
12661 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12662 SmallVector<int, 8> OuterMask =
12663 ScaleShuffleMask(SVN->getMask(), OuterScale);
12665 // Merge the shuffle masks.
12666 SmallVector<int, 8> NewMask;
12667 for (int M : OuterMask)
12668 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12670 // Test for shuffle mask legality over both commutations.
12671 SDValue SV0 = BC0->getOperand(0);
12672 SDValue SV1 = BC0->getOperand(1);
12673 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12675 std::swap(SV0, SV1);
12676 ShuffleVectorSDNode::commuteMask(NewMask);
12677 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12681 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12682 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12683 return DAG.getNode(
12684 ISD::BITCAST, SDLoc(N), VT,
12685 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12691 // Canonicalize shuffles according to rules:
12692 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12693 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12694 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12695 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12696 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12697 TLI.isTypeLegal(VT)) {
12698 // The incoming shuffle must be of the same type as the result of the
12699 // current shuffle.
12700 assert(N1->getOperand(0).getValueType() == VT &&
12701 "Shuffle types don't match");
12703 SDValue SV0 = N1->getOperand(0);
12704 SDValue SV1 = N1->getOperand(1);
12705 bool HasSameOp0 = N0 == SV0;
12706 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12707 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12708 // Commute the operands of this shuffle so that next rule
12710 return DAG.getCommutedVectorShuffle(*SVN);
12713 // Try to fold according to rules:
12714 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12715 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12716 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12717 // Don't try to fold shuffles with illegal type.
12718 // Only fold if this shuffle is the only user of the other shuffle.
12719 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12720 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12721 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12723 // The incoming shuffle must be of the same type as the result of the
12724 // current shuffle.
12725 assert(OtherSV->getOperand(0).getValueType() == VT &&
12726 "Shuffle types don't match");
12729 SmallVector<int, 4> Mask;
12730 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12731 // operand, and SV1 as the second operand.
12732 for (unsigned i = 0; i != NumElts; ++i) {
12733 int Idx = SVN->getMaskElt(i);
12735 // Propagate Undef.
12736 Mask.push_back(Idx);
12740 SDValue CurrentVec;
12741 if (Idx < (int)NumElts) {
12742 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12743 // shuffle mask to identify which vector is actually referenced.
12744 Idx = OtherSV->getMaskElt(Idx);
12746 // Propagate Undef.
12747 Mask.push_back(Idx);
12751 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12752 : OtherSV->getOperand(1);
12754 // This shuffle index references an element within N1.
12758 // Simple case where 'CurrentVec' is UNDEF.
12759 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12760 Mask.push_back(-1);
12764 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12765 // will be the first or second operand of the combined shuffle.
12766 Idx = Idx % NumElts;
12767 if (!SV0.getNode() || SV0 == CurrentVec) {
12768 // Ok. CurrentVec is the left hand side.
12769 // Update the mask accordingly.
12771 Mask.push_back(Idx);
12775 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12776 if (SV1.getNode() && SV1 != CurrentVec)
12779 // Ok. CurrentVec is the right hand side.
12780 // Update the mask accordingly.
12782 Mask.push_back(Idx + NumElts);
12785 // Check if all indices in Mask are Undef. In case, propagate Undef.
12786 bool isUndefMask = true;
12787 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12788 isUndefMask &= Mask[i] < 0;
12791 return DAG.getUNDEF(VT);
12793 if (!SV0.getNode())
12794 SV0 = DAG.getUNDEF(VT);
12795 if (!SV1.getNode())
12796 SV1 = DAG.getUNDEF(VT);
12798 // Avoid introducing shuffles with illegal mask.
12799 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12800 ShuffleVectorSDNode::commuteMask(Mask);
12802 if (!TLI.isShuffleMaskLegal(Mask, VT))
12805 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12806 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12807 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12808 std::swap(SV0, SV1);
12811 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12812 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12813 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12814 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12820 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12821 SDValue InVal = N->getOperand(0);
12822 EVT VT = N->getValueType(0);
12824 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12825 // with a VECTOR_SHUFFLE.
12826 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12827 SDValue InVec = InVal->getOperand(0);
12828 SDValue EltNo = InVal->getOperand(1);
12830 // FIXME: We could support implicit truncation if the shuffle can be
12831 // scaled to a smaller vector scalar type.
12832 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12833 if (C0 && VT == InVec.getValueType() &&
12834 VT.getScalarType() == InVal.getValueType()) {
12835 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12836 int Elt = C0->getZExtValue();
12839 if (TLI.isShuffleMaskLegal(NewMask, VT))
12840 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12848 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12849 SDValue N0 = N->getOperand(0);
12850 SDValue N2 = N->getOperand(2);
12852 // If the input vector is a concatenation, and the insert replaces
12853 // one of the halves, we can optimize into a single concat_vectors.
12854 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12855 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12856 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12857 EVT VT = N->getValueType(0);
12859 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12860 // (concat_vectors Z, Y)
12862 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12863 N->getOperand(1), N0.getOperand(1));
12865 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12866 // (concat_vectors X, Z)
12867 if (InsIdx == VT.getVectorNumElements()/2)
12868 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12869 N0.getOperand(0), N->getOperand(1));
12875 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12876 SDValue N0 = N->getOperand(0);
12878 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12879 if (N0->getOpcode() == ISD::FP16_TO_FP)
12880 return N0->getOperand(0);
12885 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12886 /// with the destination vector and a zero vector.
12887 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12888 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12889 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12890 EVT VT = N->getValueType(0);
12891 SDValue LHS = N->getOperand(0);
12892 SDValue RHS = N->getOperand(1);
12895 // Make sure we're not running after operation legalization where it
12896 // may have custom lowered the vector shuffles.
12897 if (LegalOperations)
12900 if (N->getOpcode() != ISD::AND)
12903 if (RHS.getOpcode() == ISD::BITCAST)
12904 RHS = RHS.getOperand(0);
12906 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12907 SmallVector<int, 8> Indices;
12908 unsigned NumElts = RHS.getNumOperands();
12910 for (unsigned i = 0; i != NumElts; ++i) {
12911 SDValue Elt = RHS.getOperand(i);
12912 if (isAllOnesConstant(Elt))
12913 Indices.push_back(i);
12914 else if (isNullConstant(Elt))
12915 Indices.push_back(NumElts+i);
12920 // Let's see if the target supports this vector_shuffle.
12921 EVT RVT = RHS.getValueType();
12922 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12925 // Return the new VECTOR_SHUFFLE node.
12926 EVT EltVT = RVT.getVectorElementType();
12927 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12928 DAG.getConstant(0, dl, EltVT));
12929 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12930 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12931 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12932 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12938 /// Visit a binary vector operation, like ADD.
12939 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12940 assert(N->getValueType(0).isVector() &&
12941 "SimplifyVBinOp only works on vectors!");
12943 SDValue LHS = N->getOperand(0);
12944 SDValue RHS = N->getOperand(1);
12946 if (SDValue Shuffle = XformToShuffleWithZero(N))
12949 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12951 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12952 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12953 // Check if both vectors are constants. If not bail out.
12954 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12955 cast<BuildVectorSDNode>(RHS)->isConstant()))
12958 SmallVector<SDValue, 8> Ops;
12959 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12960 SDValue LHSOp = LHS.getOperand(i);
12961 SDValue RHSOp = RHS.getOperand(i);
12963 // Can't fold divide by zero.
12964 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12965 N->getOpcode() == ISD::FDIV) {
12966 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
12967 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12971 EVT VT = LHSOp.getValueType();
12972 EVT RVT = RHSOp.getValueType();
12974 // Integer BUILD_VECTOR operands may have types larger than the element
12975 // size (e.g., when the element type is not legal). Prior to type
12976 // legalization, the types may not match between the two BUILD_VECTORS.
12977 // Truncate one of the operands to make them match.
12978 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12979 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12981 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12985 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12987 if (FoldOp.getOpcode() != ISD::UNDEF &&
12988 FoldOp.getOpcode() != ISD::Constant &&
12989 FoldOp.getOpcode() != ISD::ConstantFP)
12991 Ops.push_back(FoldOp);
12992 AddToWorklist(FoldOp.getNode());
12995 if (Ops.size() == LHS.getNumOperands())
12996 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12999 // Type legalization might introduce new shuffles in the DAG.
13000 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13001 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13002 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13003 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13004 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13005 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13006 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13007 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13009 if (SVN0->getMask().equals(SVN1->getMask())) {
13010 EVT VT = N->getValueType(0);
13011 SDValue UndefVector = LHS.getOperand(1);
13012 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13013 LHS.getOperand(0), RHS.getOperand(0));
13014 AddUsersToWorklist(N);
13015 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13016 &SVN0->getMask()[0]);
13023 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13024 SDValue N1, SDValue N2){
13025 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13027 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13028 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13030 // If we got a simplified select_cc node back from SimplifySelectCC, then
13031 // break it down into a new SETCC node, and a new SELECT node, and then return
13032 // the SELECT node, since we were called with a SELECT node.
13033 if (SCC.getNode()) {
13034 // Check to see if we got a select_cc back (to turn into setcc/select).
13035 // Otherwise, just return whatever node we got back, like fabs.
13036 if (SCC.getOpcode() == ISD::SELECT_CC) {
13037 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13039 SCC.getOperand(0), SCC.getOperand(1),
13040 SCC.getOperand(4));
13041 AddToWorklist(SETCC.getNode());
13042 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13043 SCC.getOperand(2), SCC.getOperand(3));
13051 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13052 /// being selected between, see if we can simplify the select. Callers of this
13053 /// should assume that TheSelect is deleted if this returns true. As such, they
13054 /// should return the appropriate thing (e.g. the node) back to the top-level of
13055 /// the DAG combiner loop to avoid it being looked at.
13056 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13059 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13060 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13061 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13062 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13063 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13064 SDValue Sqrt = RHS;
13067 const ConstantFPSDNode *NegZero = nullptr;
13069 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13070 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13071 CmpLHS = TheSelect->getOperand(0);
13072 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13074 // SELECT or VSELECT
13075 SDValue Cmp = TheSelect->getOperand(0);
13076 if (Cmp.getOpcode() == ISD::SETCC) {
13077 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13078 CmpLHS = Cmp.getOperand(0);
13079 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13082 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13083 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13084 CC == ISD::SETULT || CC == ISD::SETLT)) {
13085 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13086 CombineTo(TheSelect, Sqrt);
13091 // Cannot simplify select with vector condition
13092 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13094 // If this is a select from two identical things, try to pull the operation
13095 // through the select.
13096 if (LHS.getOpcode() != RHS.getOpcode() ||
13097 !LHS.hasOneUse() || !RHS.hasOneUse())
13100 // If this is a load and the token chain is identical, replace the select
13101 // of two loads with a load through a select of the address to load from.
13102 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13103 // constants have been dropped into the constant pool.
13104 if (LHS.getOpcode() == ISD::LOAD) {
13105 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13106 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13108 // Token chains must be identical.
13109 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13110 // Do not let this transformation reduce the number of volatile loads.
13111 LLD->isVolatile() || RLD->isVolatile() ||
13112 // FIXME: If either is a pre/post inc/dec load,
13113 // we'd need to split out the address adjustment.
13114 LLD->isIndexed() || RLD->isIndexed() ||
13115 // If this is an EXTLOAD, the VT's must match.
13116 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13117 // If this is an EXTLOAD, the kind of extension must match.
13118 (LLD->getExtensionType() != RLD->getExtensionType() &&
13119 // The only exception is if one of the extensions is anyext.
13120 LLD->getExtensionType() != ISD::EXTLOAD &&
13121 RLD->getExtensionType() != ISD::EXTLOAD) ||
13122 // FIXME: this discards src value information. This is
13123 // over-conservative. It would be beneficial to be able to remember
13124 // both potential memory locations. Since we are discarding
13125 // src value info, don't do the transformation if the memory
13126 // locations are not in the default address space.
13127 LLD->getPointerInfo().getAddrSpace() != 0 ||
13128 RLD->getPointerInfo().getAddrSpace() != 0 ||
13129 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13130 LLD->getBasePtr().getValueType()))
13133 // Check that the select condition doesn't reach either load. If so,
13134 // folding this will induce a cycle into the DAG. If not, this is safe to
13135 // xform, so create a select of the addresses.
13137 if (TheSelect->getOpcode() == ISD::SELECT) {
13138 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13139 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13140 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13142 // The loads must not depend on one another.
13143 if (LLD->isPredecessorOf(RLD) ||
13144 RLD->isPredecessorOf(LLD))
13146 Addr = DAG.getSelect(SDLoc(TheSelect),
13147 LLD->getBasePtr().getValueType(),
13148 TheSelect->getOperand(0), LLD->getBasePtr(),
13149 RLD->getBasePtr());
13150 } else { // Otherwise SELECT_CC
13151 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13152 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13154 if ((LLD->hasAnyUseOfValue(1) &&
13155 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13156 (RLD->hasAnyUseOfValue(1) &&
13157 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13160 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13161 LLD->getBasePtr().getValueType(),
13162 TheSelect->getOperand(0),
13163 TheSelect->getOperand(1),
13164 LLD->getBasePtr(), RLD->getBasePtr(),
13165 TheSelect->getOperand(4));
13169 // It is safe to replace the two loads if they have different alignments,
13170 // but the new load must be the minimum (most restrictive) alignment of the
13172 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13173 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13174 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13175 Load = DAG.getLoad(TheSelect->getValueType(0),
13177 // FIXME: Discards pointer and AA info.
13178 LLD->getChain(), Addr, MachinePointerInfo(),
13179 LLD->isVolatile(), LLD->isNonTemporal(),
13180 isInvariant, Alignment);
13182 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13183 RLD->getExtensionType() : LLD->getExtensionType(),
13185 TheSelect->getValueType(0),
13186 // FIXME: Discards pointer and AA info.
13187 LLD->getChain(), Addr, MachinePointerInfo(),
13188 LLD->getMemoryVT(), LLD->isVolatile(),
13189 LLD->isNonTemporal(), isInvariant, Alignment);
13192 // Users of the select now use the result of the load.
13193 CombineTo(TheSelect, Load);
13195 // Users of the old loads now use the new load's chain. We know the
13196 // old-load value is dead now.
13197 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13198 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13205 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13206 /// where 'cond' is the comparison specified by CC.
13207 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13208 SDValue N2, SDValue N3,
13209 ISD::CondCode CC, bool NotExtCompare) {
13210 // (x ? y : y) -> y.
13211 if (N2 == N3) return N2;
13213 EVT VT = N2.getValueType();
13214 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13215 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13217 // Determine if the condition we're dealing with is constant
13218 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13219 N0, N1, CC, DL, false);
13220 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13222 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13223 // fold select_cc true, x, y -> x
13224 // fold select_cc false, x, y -> y
13225 return !SCCC->isNullValue() ? N2 : N3;
13228 // Check to see if we can simplify the select into an fabs node
13229 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13230 // Allow either -0.0 or 0.0
13231 if (CFP->getValueAPF().isZero()) {
13232 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13233 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13234 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13235 N2 == N3.getOperand(0))
13236 return DAG.getNode(ISD::FABS, DL, VT, N0);
13238 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13239 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13240 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13241 N2.getOperand(0) == N3)
13242 return DAG.getNode(ISD::FABS, DL, VT, N3);
13246 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13247 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13248 // in it. This is a win when the constant is not otherwise available because
13249 // it replaces two constant pool loads with one. We only do this if the FP
13250 // type is known to be legal, because if it isn't, then we are before legalize
13251 // types an we want the other legalization to happen first (e.g. to avoid
13252 // messing with soft float) and if the ConstantFP is not legal, because if
13253 // it is legal, we may not need to store the FP constant in a constant pool.
13254 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13255 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13256 if (TLI.isTypeLegal(N2.getValueType()) &&
13257 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13258 TargetLowering::Legal &&
13259 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13260 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13261 // If both constants have multiple uses, then we won't need to do an
13262 // extra load, they are likely around in registers for other users.
13263 (TV->hasOneUse() || FV->hasOneUse())) {
13264 Constant *Elts[] = {
13265 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13266 const_cast<ConstantFP*>(TV->getConstantFPValue())
13268 Type *FPTy = Elts[0]->getType();
13269 const DataLayout &TD = *TLI.getDataLayout();
13271 // Create a ConstantArray of the two constants.
13272 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13273 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13274 TD.getPrefTypeAlignment(FPTy));
13275 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13277 // Get the offsets to the 0 and 1 element of the array so that we can
13278 // select between them.
13279 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13280 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13281 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13283 SDValue Cond = DAG.getSetCC(DL,
13284 getSetCCResultType(N0.getValueType()),
13286 AddToWorklist(Cond.getNode());
13287 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13289 AddToWorklist(CstOffset.getNode());
13290 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13292 AddToWorklist(CPIdx.getNode());
13293 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13294 MachinePointerInfo::getConstantPool(), false,
13295 false, false, Alignment);
13299 // Check to see if we can perform the "gzip trick", transforming
13300 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13301 if (isNullConstant(N3) && CC == ISD::SETLT &&
13302 (isNullConstant(N1) || // (a < 0) ? b : 0
13303 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13304 EVT XType = N0.getValueType();
13305 EVT AType = N2.getValueType();
13306 if (XType.bitsGE(AType)) {
13307 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13308 // single-bit constant.
13309 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13310 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13311 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13312 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13313 getShiftAmountTy(N0.getValueType()));
13314 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13316 AddToWorklist(Shift.getNode());
13318 if (XType.bitsGT(AType)) {
13319 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13320 AddToWorklist(Shift.getNode());
13323 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13326 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13328 DAG.getConstant(XType.getSizeInBits() - 1,
13330 getShiftAmountTy(N0.getValueType())));
13331 AddToWorklist(Shift.getNode());
13333 if (XType.bitsGT(AType)) {
13334 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13335 AddToWorklist(Shift.getNode());
13338 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13342 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13343 // where y is has a single bit set.
13344 // A plaintext description would be, we can turn the SELECT_CC into an AND
13345 // when the condition can be materialized as an all-ones register. Any
13346 // single bit-test can be materialized as an all-ones register with
13347 // shift-left and shift-right-arith.
13348 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13349 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13350 SDValue AndLHS = N0->getOperand(0);
13351 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13352 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13353 // Shift the tested bit over the sign bit.
13354 APInt AndMask = ConstAndRHS->getAPIntValue();
13356 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13357 getShiftAmountTy(AndLHS.getValueType()));
13358 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13360 // Now arithmetic right shift it all the way over, so the result is either
13361 // all-ones, or zero.
13363 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13364 getShiftAmountTy(Shl.getValueType()));
13365 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13367 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13371 // fold select C, 16, 0 -> shl C, 4
13372 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13373 TLI.getBooleanContents(N0.getValueType()) ==
13374 TargetLowering::ZeroOrOneBooleanContent) {
13376 // If the caller doesn't want us to simplify this into a zext of a compare,
13378 if (NotExtCompare && N2C->isOne())
13381 // Get a SetCC of the condition
13382 // NOTE: Don't create a SETCC if it's not legal on this target.
13383 if (!LegalOperations ||
13384 TLI.isOperationLegal(ISD::SETCC,
13385 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13387 // cast from setcc result type to select result type
13389 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13391 if (N2.getValueType().bitsLT(SCC.getValueType()))
13392 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13393 N2.getValueType());
13395 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13396 N2.getValueType(), SCC);
13398 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13399 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13400 N2.getValueType(), SCC);
13403 AddToWorklist(SCC.getNode());
13404 AddToWorklist(Temp.getNode());
13409 // shl setcc result by log2 n2c
13410 return DAG.getNode(
13411 ISD::SHL, DL, N2.getValueType(), Temp,
13412 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13413 getShiftAmountTy(Temp.getValueType())));
13417 // Check to see if this is the equivalent of setcc
13418 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13419 // otherwise, go ahead with the folds.
13420 if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13421 EVT XType = N0.getValueType();
13422 if (!LegalOperations ||
13423 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13424 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13425 if (Res.getValueType() != VT)
13426 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13430 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13431 if (isNullConstant(N1) && CC == ISD::SETEQ &&
13432 (!LegalOperations ||
13433 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13434 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13435 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13436 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13438 getShiftAmountTy(Ctlz.getValueType())));
13440 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13441 if (isNullConstant(N1) && CC == ISD::SETGT) {
13443 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13444 XType, DAG.getConstant(0, DL, XType), N0);
13445 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13446 return DAG.getNode(ISD::SRL, DL, XType,
13447 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13448 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13449 getShiftAmountTy(XType)));
13451 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13452 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13454 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13455 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13456 getShiftAmountTy(N0.getValueType())));
13457 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13462 // Check to see if this is an integer abs.
13463 // select_cc setg[te] X, 0, X, -X ->
13464 // select_cc setgt X, -1, X, -X ->
13465 // select_cc setl[te] X, 0, -X, X ->
13466 // select_cc setlt X, 1, -X, X ->
13467 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13469 ConstantSDNode *SubC = nullptr;
13470 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13471 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13472 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13473 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13474 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13475 (N1C->isOne() && CC == ISD::SETLT)) &&
13476 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13477 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13479 EVT XType = N0.getValueType();
13480 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13482 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13484 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13485 getShiftAmountTy(N0.getValueType())));
13486 SDValue Add = DAG.getNode(ISD::ADD, DL,
13488 AddToWorklist(Shift.getNode());
13489 AddToWorklist(Add.getNode());
13490 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13497 /// This is a stub for TargetLowering::SimplifySetCC.
13498 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13499 SDValue N1, ISD::CondCode Cond,
13500 SDLoc DL, bool foldBooleans) {
13501 TargetLowering::DAGCombinerInfo
13502 DagCombineInfo(DAG, Level, false, this);
13503 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13506 /// Given an ISD::SDIV node expressing a divide by constant, return
13507 /// a DAG expression to select that will generate the same value by multiplying
13508 /// by a magic number.
13509 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13510 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13511 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13515 // Avoid division by zero.
13516 if (C->isNullValue())
13519 std::vector<SDNode*> Built;
13521 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13523 for (SDNode *N : Built)
13528 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13529 /// DAG expression that will generate the same value by right shifting.
13530 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13531 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13535 // Avoid division by zero.
13536 if (C->isNullValue())
13539 std::vector<SDNode *> Built;
13540 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13542 for (SDNode *N : Built)
13547 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13548 /// expression that will generate the same value by multiplying by a magic
13550 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13551 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13552 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13556 // Avoid division by zero.
13557 if (C->isNullValue())
13560 std::vector<SDNode*> Built;
13562 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13564 for (SDNode *N : Built)
13569 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13570 if (Level >= AfterLegalizeDAG)
13573 // Expose the DAG combiner to the target combiner implementations.
13574 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13576 unsigned Iterations = 0;
13577 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13579 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13580 // For the reciprocal, we need to find the zero of the function:
13581 // F(X) = A X - 1 [which has a zero at X = 1/A]
13583 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13584 // does not require additional intermediate precision]
13585 EVT VT = Op.getValueType();
13587 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13589 AddToWorklist(Est.getNode());
13591 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13592 for (unsigned i = 0; i < Iterations; ++i) {
13593 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13594 AddToWorklist(NewEst.getNode());
13596 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13597 AddToWorklist(NewEst.getNode());
13599 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13600 AddToWorklist(NewEst.getNode());
13602 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13603 AddToWorklist(Est.getNode());
13612 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13613 /// For the reciprocal sqrt, we need to find the zero of the function:
13614 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13616 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13617 /// As a result, we precompute A/2 prior to the iteration loop.
13618 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13619 unsigned Iterations) {
13620 EVT VT = Arg.getValueType();
13622 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13624 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13625 // this entire sequence requires only one FP constant.
13626 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13627 AddToWorklist(HalfArg.getNode());
13629 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13630 AddToWorklist(HalfArg.getNode());
13632 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13633 for (unsigned i = 0; i < Iterations; ++i) {
13634 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13635 AddToWorklist(NewEst.getNode());
13637 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13638 AddToWorklist(NewEst.getNode());
13640 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13641 AddToWorklist(NewEst.getNode());
13643 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13644 AddToWorklist(Est.getNode());
13649 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13650 /// For the reciprocal sqrt, we need to find the zero of the function:
13651 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13653 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13654 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13655 unsigned Iterations) {
13656 EVT VT = Arg.getValueType();
13658 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13659 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13661 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13662 for (unsigned i = 0; i < Iterations; ++i) {
13663 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13664 AddToWorklist(HalfEst.getNode());
13666 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13667 AddToWorklist(Est.getNode());
13669 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13670 AddToWorklist(Est.getNode());
13672 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13673 AddToWorklist(Est.getNode());
13675 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13676 AddToWorklist(Est.getNode());
13681 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13682 if (Level >= AfterLegalizeDAG)
13685 // Expose the DAG combiner to the target combiner implementations.
13686 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13687 unsigned Iterations = 0;
13688 bool UseOneConstNR = false;
13689 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13690 AddToWorklist(Est.getNode());
13692 Est = UseOneConstNR ?
13693 BuildRsqrtNROneConst(Op, Est, Iterations) :
13694 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13702 /// Return true if base is a frame index, which is known not to alias with
13703 /// anything but itself. Provides base object and offset as results.
13704 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13705 const GlobalValue *&GV, const void *&CV) {
13706 // Assume it is a primitive operation.
13707 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13709 // If it's an adding a simple constant then integrate the offset.
13710 if (Base.getOpcode() == ISD::ADD) {
13711 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13712 Base = Base.getOperand(0);
13713 Offset += C->getZExtValue();
13717 // Return the underlying GlobalValue, and update the Offset. Return false
13718 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13719 // by multiple nodes with different offsets.
13720 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13721 GV = G->getGlobal();
13722 Offset += G->getOffset();
13726 // Return the underlying Constant value, and update the Offset. Return false
13727 // for ConstantSDNodes since the same constant pool entry may be represented
13728 // by multiple nodes with different offsets.
13729 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13730 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13731 : (const void *)C->getConstVal();
13732 Offset += C->getOffset();
13735 // If it's any of the following then it can't alias with anything but itself.
13736 return isa<FrameIndexSDNode>(Base);
13739 /// Return true if there is any possibility that the two addresses overlap.
13740 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13741 // If they are the same then they must be aliases.
13742 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13744 // If they are both volatile then they cannot be reordered.
13745 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13747 // Gather base node and offset information.
13748 SDValue Base1, Base2;
13749 int64_t Offset1, Offset2;
13750 const GlobalValue *GV1, *GV2;
13751 const void *CV1, *CV2;
13752 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13753 Base1, Offset1, GV1, CV1);
13754 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13755 Base2, Offset2, GV2, CV2);
13757 // If they have a same base address then check to see if they overlap.
13758 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13759 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13760 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13762 // It is possible for different frame indices to alias each other, mostly
13763 // when tail call optimization reuses return address slots for arguments.
13764 // To catch this case, look up the actual index of frame indices to compute
13765 // the real alias relationship.
13766 if (isFrameIndex1 && isFrameIndex2) {
13767 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13768 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13769 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13770 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13771 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13774 // Otherwise, if we know what the bases are, and they aren't identical, then
13775 // we know they cannot alias.
13776 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13779 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13780 // compared to the size and offset of the access, we may be able to prove they
13781 // do not alias. This check is conservative for now to catch cases created by
13782 // splitting vector types.
13783 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13784 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13785 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13786 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13787 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13788 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13789 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13791 // There is no overlap between these relatively aligned accesses of similar
13792 // size, return no alias.
13793 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13794 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13798 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13800 : DAG.getSubtarget().useAA();
13802 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13803 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13807 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13808 // Use alias analysis information.
13809 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13810 Op1->getSrcValueOffset());
13811 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13812 Op0->getSrcValueOffset() - MinOffset;
13813 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13814 Op1->getSrcValueOffset() - MinOffset;
13815 AliasAnalysis::AliasResult AAResult =
13816 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13818 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13819 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13821 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13822 if (AAResult == AliasAnalysis::NoAlias)
13826 // Otherwise we have to assume they alias.
13830 /// Walk up chain skipping non-aliasing memory nodes,
13831 /// looking for aliasing nodes and adding them to the Aliases vector.
13832 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13833 SmallVectorImpl<SDValue> &Aliases) {
13834 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13835 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13837 // Get alias information for node.
13838 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13841 Chains.push_back(OriginalChain);
13842 unsigned Depth = 0;
13844 // Look at each chain and determine if it is an alias. If so, add it to the
13845 // aliases list. If not, then continue up the chain looking for the next
13847 while (!Chains.empty()) {
13848 SDValue Chain = Chains.back();
13851 // For TokenFactor nodes, look at each operand and only continue up the
13852 // chain until we find two aliases. If we've seen two aliases, assume we'll
13853 // find more and revert to original chain since the xform is unlikely to be
13856 // FIXME: The depth check could be made to return the last non-aliasing
13857 // chain we found before we hit a tokenfactor rather than the original
13859 if (Depth > 6 || Aliases.size() == 2) {
13861 Aliases.push_back(OriginalChain);
13865 // Don't bother if we've been before.
13866 if (!Visited.insert(Chain.getNode()).second)
13869 switch (Chain.getOpcode()) {
13870 case ISD::EntryToken:
13871 // Entry token is ideal chain operand, but handled in FindBetterChain.
13876 // Get alias information for Chain.
13877 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13878 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13880 // If chain is alias then stop here.
13881 if (!(IsLoad && IsOpLoad) &&
13882 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13883 Aliases.push_back(Chain);
13885 // Look further up the chain.
13886 Chains.push_back(Chain.getOperand(0));
13892 case ISD::TokenFactor:
13893 // We have to check each of the operands of the token factor for "small"
13894 // token factors, so we queue them up. Adding the operands to the queue
13895 // (stack) in reverse order maintains the original order and increases the
13896 // likelihood that getNode will find a matching token factor (CSE.)
13897 if (Chain.getNumOperands() > 16) {
13898 Aliases.push_back(Chain);
13901 for (unsigned n = Chain.getNumOperands(); n;)
13902 Chains.push_back(Chain.getOperand(--n));
13907 // For all other instructions we will just have to take what we can get.
13908 Aliases.push_back(Chain);
13913 // We need to be careful here to also search for aliases through the
13914 // value operand of a store, etc. Consider the following situation:
13916 // L1 = load Token1, %52
13917 // S1 = store Token1, L1, %51
13918 // L2 = load Token1, %52+8
13919 // S2 = store Token1, L2, %51+8
13920 // Token2 = Token(S1, S2)
13921 // L3 = load Token2, %53
13922 // S3 = store Token2, L3, %52
13923 // L4 = load Token2, %53+8
13924 // S4 = store Token2, L4, %52+8
13925 // If we search for aliases of S3 (which loads address %52), and we look
13926 // only through the chain, then we'll miss the trivial dependence on L1
13927 // (which also loads from %52). We then might change all loads and
13928 // stores to use Token1 as their chain operand, which could result in
13929 // copying %53 into %52 before copying %52 into %51 (which should
13932 // The problem is, however, that searching for such data dependencies
13933 // can become expensive, and the cost is not directly related to the
13934 // chain depth. Instead, we'll rule out such configurations here by
13935 // insisting that we've visited all chain users (except for users
13936 // of the original chain, which is not necessary). When doing this,
13937 // we need to look through nodes we don't care about (otherwise, things
13938 // like register copies will interfere with trivial cases).
13940 SmallVector<const SDNode *, 16> Worklist;
13941 for (const SDNode *N : Visited)
13942 if (N != OriginalChain.getNode())
13943 Worklist.push_back(N);
13945 while (!Worklist.empty()) {
13946 const SDNode *M = Worklist.pop_back_val();
13948 // We have already visited M, and want to make sure we've visited any uses
13949 // of M that we care about. For uses that we've not visisted, and don't
13950 // care about, queue them to the worklist.
13952 for (SDNode::use_iterator UI = M->use_begin(),
13953 UIE = M->use_end(); UI != UIE; ++UI)
13954 if (UI.getUse().getValueType() == MVT::Other &&
13955 Visited.insert(*UI).second) {
13956 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13957 // We've not visited this use, and we care about it (it could have an
13958 // ordering dependency with the original node).
13960 Aliases.push_back(OriginalChain);
13964 // We've not visited this use, but we don't care about it. Mark it as
13965 // visited and enqueue it to the worklist.
13966 Worklist.push_back(*UI);
13971 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13972 /// (aliasing node.)
13973 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13974 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13976 // Accumulate all the aliases to this node.
13977 GatherAllAliases(N, OldChain, Aliases);
13979 // If no operands then chain to entry token.
13980 if (Aliases.size() == 0)
13981 return DAG.getEntryNode();
13983 // If a single operand then chain to it. We don't need to revisit it.
13984 if (Aliases.size() == 1)
13987 // Construct a custom tailored token factor.
13988 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13991 /// This is the entry point for the file.
13992 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13993 CodeGenOpt::Level OptLevel) {
13994 /// This is the main entry point to this class.
13995 DAGCombiner(*this, AA, OptLevel).Run(Level);