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 SDValue DAGCombiner::visitADD(SDNode *N) {
1594 SDValue N0 = N->getOperand(0);
1595 SDValue N1 = N->getOperand(1);
1596 EVT VT = N0.getValueType();
1599 if (VT.isVector()) {
1600 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1603 // fold (add x, 0) -> x, vector edition
1604 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1606 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1610 // fold (add x, undef) -> undef
1611 if (N0.getOpcode() == ISD::UNDEF)
1613 if (N1.getOpcode() == ISD::UNDEF)
1615 // fold (add c1, c2) -> c1+c2
1616 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1617 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1619 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1620 // canonicalize constant to RHS
1621 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1622 !isConstantIntBuildVectorOrConstantInt(N1))
1623 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1624 // fold (add x, 0) -> x
1625 if (isNullConstant(N1))
1627 // fold (add Sym, c) -> Sym+c
1628 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1629 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1630 GA->getOpcode() == ISD::GlobalAddress)
1631 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1633 (uint64_t)N1C->getSExtValue());
1634 // fold ((c1-A)+c2) -> (c1+c2)-A
1635 if (N1C && N0.getOpcode() == ISD::SUB)
1636 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1638 return DAG.getNode(ISD::SUB, DL, VT,
1639 DAG.getConstant(N1C->getAPIntValue()+
1640 N0C->getAPIntValue(), DL, VT),
1644 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1646 // fold ((0-A) + B) -> B-A
1647 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1648 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1649 // fold (A + (0-B)) -> A-B
1650 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1651 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1652 // fold (A+(B-A)) -> B
1653 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1654 return N1.getOperand(0);
1655 // fold ((B-A)+A) -> B
1656 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1657 return N0.getOperand(0);
1658 // fold (A+(B-(A+C))) to (B-C)
1659 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1660 N0 == N1.getOperand(1).getOperand(0))
1661 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1662 N1.getOperand(1).getOperand(1));
1663 // fold (A+(B-(C+A))) to (B-C)
1664 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1665 N0 == N1.getOperand(1).getOperand(1))
1666 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1667 N1.getOperand(1).getOperand(0));
1668 // fold (A+((B-A)+or-C)) to (B+or-C)
1669 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1670 N1.getOperand(0).getOpcode() == ISD::SUB &&
1671 N0 == N1.getOperand(0).getOperand(1))
1672 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1673 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1675 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1676 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1677 SDValue N00 = N0.getOperand(0);
1678 SDValue N01 = N0.getOperand(1);
1679 SDValue N10 = N1.getOperand(0);
1680 SDValue N11 = N1.getOperand(1);
1682 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1683 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1684 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1685 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1688 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1689 return SDValue(N, 0);
1691 // fold (a+b) -> (a|b) iff a and b share no bits.
1692 if (VT.isInteger() && !VT.isVector()) {
1693 APInt LHSZero, LHSOne;
1694 APInt RHSZero, RHSOne;
1695 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1697 if (LHSZero.getBoolValue()) {
1698 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1700 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1701 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1702 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1703 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1704 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1709 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1710 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1711 isNullConstant(N1.getOperand(0).getOperand(0)))
1712 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1713 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1714 N1.getOperand(0).getOperand(1),
1716 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1717 isNullConstant(N0.getOperand(0).getOperand(0)))
1718 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1719 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1720 N0.getOperand(0).getOperand(1),
1723 if (N1.getOpcode() == ISD::AND) {
1724 SDValue AndOp0 = N1.getOperand(0);
1725 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1726 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1727 unsigned DestBits = VT.getScalarType().getSizeInBits();
1729 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1730 // and similar xforms where the inner op is either ~0 or 0.
1731 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1733 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1737 // add (sext i1), X -> sub X, (zext i1)
1738 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1739 N0.getOperand(0).getValueType() == MVT::i1 &&
1740 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1742 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1743 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1746 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1747 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1748 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1749 if (TN->getVT() == MVT::i1) {
1751 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1752 DAG.getConstant(1, DL, VT));
1753 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1760 SDValue DAGCombiner::visitADDC(SDNode *N) {
1761 SDValue N0 = N->getOperand(0);
1762 SDValue N1 = N->getOperand(1);
1763 EVT VT = N0.getValueType();
1765 // If the flag result is dead, turn this into an ADD.
1766 if (!N->hasAnyUseOfValue(1))
1767 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1768 DAG.getNode(ISD::CARRY_FALSE,
1769 SDLoc(N), MVT::Glue));
1771 // canonicalize constant to RHS.
1772 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1773 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1775 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1777 // fold (addc x, 0) -> x + no carry out
1778 if (isNullConstant(N1))
1779 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1780 SDLoc(N), MVT::Glue));
1782 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1783 APInt LHSZero, LHSOne;
1784 APInt RHSZero, RHSOne;
1785 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1787 if (LHSZero.getBoolValue()) {
1788 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1790 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1791 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1792 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1793 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1794 DAG.getNode(ISD::CARRY_FALSE,
1795 SDLoc(N), MVT::Glue));
1801 SDValue DAGCombiner::visitADDE(SDNode *N) {
1802 SDValue N0 = N->getOperand(0);
1803 SDValue N1 = N->getOperand(1);
1804 SDValue CarryIn = N->getOperand(2);
1806 // canonicalize constant to RHS
1807 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1808 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1810 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1813 // fold (adde x, y, false) -> (addc x, y)
1814 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1815 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1820 // Since it may not be valid to emit a fold to zero for vector initializers
1821 // check if we can before folding.
1822 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1824 bool LegalOperations, bool LegalTypes) {
1826 return DAG.getConstant(0, DL, VT);
1827 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1828 return DAG.getConstant(0, DL, VT);
1832 SDValue DAGCombiner::visitSUB(SDNode *N) {
1833 SDValue N0 = N->getOperand(0);
1834 SDValue N1 = N->getOperand(1);
1835 EVT VT = N0.getValueType();
1838 if (VT.isVector()) {
1839 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1842 // fold (sub x, 0) -> x, vector edition
1843 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1847 // fold (sub x, x) -> 0
1848 // FIXME: Refactor this and xor and other similar operations together.
1850 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1851 // fold (sub c1, c2) -> c1-c2
1852 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1853 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1855 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1856 // fold (sub x, c) -> (add x, -c)
1859 return DAG.getNode(ISD::ADD, DL, VT, N0,
1860 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1862 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1863 if (isAllOnesConstant(N0))
1864 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1865 // fold A-(A-B) -> B
1866 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1867 return N1.getOperand(1);
1868 // fold (A+B)-A -> B
1869 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1870 return N0.getOperand(1);
1871 // fold (A+B)-B -> A
1872 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1873 return N0.getOperand(0);
1874 // fold C2-(A+C1) -> (C2-C1)-A
1875 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1876 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1877 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1879 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1881 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1884 // fold ((A+(B+or-C))-B) -> A+or-C
1885 if (N0.getOpcode() == ISD::ADD &&
1886 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1887 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1888 N0.getOperand(1).getOperand(0) == N1)
1889 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1890 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1891 // fold ((A+(C+B))-B) -> A+C
1892 if (N0.getOpcode() == ISD::ADD &&
1893 N0.getOperand(1).getOpcode() == ISD::ADD &&
1894 N0.getOperand(1).getOperand(1) == N1)
1895 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1896 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1897 // fold ((A-(B-C))-C) -> A-B
1898 if (N0.getOpcode() == ISD::SUB &&
1899 N0.getOperand(1).getOpcode() == ISD::SUB &&
1900 N0.getOperand(1).getOperand(1) == N1)
1901 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1902 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1904 // If either operand of a sub is undef, the result is undef
1905 if (N0.getOpcode() == ISD::UNDEF)
1907 if (N1.getOpcode() == ISD::UNDEF)
1910 // If the relocation model supports it, consider symbol offsets.
1911 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1912 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1913 // fold (sub Sym, c) -> Sym-c
1914 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1915 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1917 (uint64_t)N1C->getSExtValue());
1918 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1919 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1920 if (GA->getGlobal() == GB->getGlobal())
1921 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1925 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1926 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1927 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1928 if (TN->getVT() == MVT::i1) {
1930 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1931 DAG.getConstant(1, DL, VT));
1932 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1939 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1940 SDValue N0 = N->getOperand(0);
1941 SDValue N1 = N->getOperand(1);
1942 EVT VT = N0.getValueType();
1944 // If the flag result is dead, turn this into an SUB.
1945 if (!N->hasAnyUseOfValue(1))
1946 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1947 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1950 // fold (subc x, x) -> 0 + no borrow
1953 return CombineTo(N, DAG.getConstant(0, DL, VT),
1954 DAG.getNode(ISD::CARRY_FALSE, DL,
1958 // fold (subc x, 0) -> x + no borrow
1959 if (isNullConstant(N1))
1960 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1963 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1964 if (isAllOnesConstant(N0))
1965 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1966 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1972 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1973 SDValue N0 = N->getOperand(0);
1974 SDValue N1 = N->getOperand(1);
1975 SDValue CarryIn = N->getOperand(2);
1977 // fold (sube x, y, false) -> (subc x, y)
1978 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1979 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1984 SDValue DAGCombiner::visitMUL(SDNode *N) {
1985 SDValue N0 = N->getOperand(0);
1986 SDValue N1 = N->getOperand(1);
1987 EVT VT = N0.getValueType();
1989 // fold (mul x, undef) -> 0
1990 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1991 return DAG.getConstant(0, SDLoc(N), VT);
1993 bool N0IsConst = false;
1994 bool N1IsConst = false;
1995 APInt ConstValue0, ConstValue1;
1997 if (VT.isVector()) {
1998 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2001 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2002 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2004 N0IsConst = isa<ConstantSDNode>(N0);
2006 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2007 N1IsConst = isa<ConstantSDNode>(N1);
2009 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2012 // fold (mul c1, c2) -> c1*c2
2013 if (N0IsConst && N1IsConst)
2014 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2015 N0.getNode(), N1.getNode());
2017 // canonicalize constant to RHS (vector doesn't have to splat)
2018 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2019 !isConstantIntBuildVectorOrConstantInt(N1))
2020 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2021 // fold (mul x, 0) -> 0
2022 if (N1IsConst && ConstValue1 == 0)
2024 // We require a splat of the entire scalar bit width for non-contiguous
2027 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2028 // fold (mul x, 1) -> x
2029 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2031 // fold (mul x, -1) -> 0-x
2032 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2034 return DAG.getNode(ISD::SUB, DL, VT,
2035 DAG.getConstant(0, DL, VT), N0);
2037 // fold (mul x, (1 << c)) -> x << c
2038 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2040 return DAG.getNode(ISD::SHL, DL, VT, N0,
2041 DAG.getConstant(ConstValue1.logBase2(), DL,
2042 getShiftAmountTy(N0.getValueType())));
2044 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2045 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2046 unsigned Log2Val = (-ConstValue1).logBase2();
2048 // FIXME: If the input is something that is easily negated (e.g. a
2049 // single-use add), we should put the negate there.
2050 return DAG.getNode(ISD::SUB, DL, VT,
2051 DAG.getConstant(0, DL, VT),
2052 DAG.getNode(ISD::SHL, DL, VT, N0,
2053 DAG.getConstant(Log2Val, DL,
2054 getShiftAmountTy(N0.getValueType()))));
2058 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2059 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2060 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2061 isa<ConstantSDNode>(N0.getOperand(1)))) {
2062 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2063 N1, N0.getOperand(1));
2064 AddToWorklist(C3.getNode());
2065 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2066 N0.getOperand(0), C3);
2069 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2072 SDValue Sh(nullptr,0), Y(nullptr,0);
2073 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2074 if (N0.getOpcode() == ISD::SHL &&
2075 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2076 isa<ConstantSDNode>(N0.getOperand(1))) &&
2077 N0.getNode()->hasOneUse()) {
2079 } else if (N1.getOpcode() == ISD::SHL &&
2080 isa<ConstantSDNode>(N1.getOperand(1)) &&
2081 N1.getNode()->hasOneUse()) {
2086 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2087 Sh.getOperand(0), Y);
2088 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2089 Mul, Sh.getOperand(1));
2093 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2094 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2095 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2096 isa<ConstantSDNode>(N0.getOperand(1))))
2097 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2098 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2099 N0.getOperand(0), N1),
2100 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2101 N0.getOperand(1), N1));
2104 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2110 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2111 SDValue N0 = N->getOperand(0);
2112 SDValue N1 = N->getOperand(1);
2113 EVT VT = N->getValueType(0);
2117 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2120 // fold (sdiv c1, c2) -> c1/c2
2121 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2122 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2123 if (N0C && N1C && !N1C->isNullValue())
2124 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2125 // fold (sdiv X, 1) -> X
2126 if (N1C && N1C->getAPIntValue() == 1LL)
2128 // fold (sdiv X, -1) -> 0-X
2129 if (N1C && N1C->isAllOnesValue()) {
2131 return DAG.getNode(ISD::SUB, DL, VT,
2132 DAG.getConstant(0, DL, VT), N0);
2134 // If we know the sign bits of both operands are zero, strength reduce to a
2135 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2136 if (!VT.isVector()) {
2137 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2138 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2142 // fold (sdiv X, pow2) -> simple ops after legalize
2143 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2144 (-N1C->getAPIntValue()).isPowerOf2())) {
2145 // If dividing by powers of two is cheap, then don't perform the following
2147 if (TLI.isPow2SDivCheap())
2150 // Target-specific implementation of sdiv x, pow2.
2151 SDValue Res = BuildSDIVPow2(N);
2155 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2158 // Splat the sign bit into the register
2160 DAG.getNode(ISD::SRA, DL, VT, N0,
2161 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2162 getShiftAmountTy(N0.getValueType())));
2163 AddToWorklist(SGN.getNode());
2165 // Add (N0 < 0) ? abs2 - 1 : 0;
2167 DAG.getNode(ISD::SRL, DL, VT, SGN,
2168 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2169 getShiftAmountTy(SGN.getValueType())));
2170 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2171 AddToWorklist(SRL.getNode());
2172 AddToWorklist(ADD.getNode()); // Divide by pow2
2173 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2174 DAG.getConstant(lg2, DL,
2175 getShiftAmountTy(ADD.getValueType())));
2177 // If we're dividing by a positive value, we're done. Otherwise, we must
2178 // negate the result.
2179 if (N1C->getAPIntValue().isNonNegative())
2182 AddToWorklist(SRA.getNode());
2183 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2186 // If integer divide is expensive and we satisfy the requirements, emit an
2187 // alternate sequence.
2188 if (N1C && !TLI.isIntDivCheap()) {
2189 SDValue Op = BuildSDIV(N);
2190 if (Op.getNode()) return Op;
2194 if (N0.getOpcode() == ISD::UNDEF)
2195 return DAG.getConstant(0, SDLoc(N), VT);
2196 // X / undef -> undef
2197 if (N1.getOpcode() == ISD::UNDEF)
2203 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2204 SDValue N0 = N->getOperand(0);
2205 SDValue N1 = N->getOperand(1);
2206 EVT VT = N->getValueType(0);
2210 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2213 // fold (udiv c1, c2) -> c1/c2
2214 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2215 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2216 if (N0C && N1C && !N1C->isNullValue())
2217 return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2218 // fold (udiv x, (1 << c)) -> x >>u c
2219 if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2221 return DAG.getNode(ISD::SRL, DL, VT, N0,
2222 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2223 getShiftAmountTy(N0.getValueType())));
2225 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2226 if (N1.getOpcode() == ISD::SHL) {
2227 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2228 if (SHC->getAPIntValue().isPowerOf2()) {
2229 EVT ADDVT = N1.getOperand(1).getValueType();
2231 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2233 DAG.getConstant(SHC->getAPIntValue()
2236 AddToWorklist(Add.getNode());
2237 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2241 // fold (udiv x, c) -> alternate
2242 if (N1C && !TLI.isIntDivCheap()) {
2243 SDValue Op = BuildUDIV(N);
2244 if (Op.getNode()) return Op;
2248 if (N0.getOpcode() == ISD::UNDEF)
2249 return DAG.getConstant(0, SDLoc(N), VT);
2250 // X / undef -> undef
2251 if (N1.getOpcode() == ISD::UNDEF)
2257 SDValue DAGCombiner::visitSREM(SDNode *N) {
2258 SDValue N0 = N->getOperand(0);
2259 SDValue N1 = N->getOperand(1);
2260 EVT VT = N->getValueType(0);
2262 // fold (srem c1, c2) -> c1%c2
2263 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2264 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2265 if (N0C && N1C && !N1C->isNullValue())
2266 return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2267 // If we know the sign bits of both operands are zero, strength reduce to a
2268 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2269 if (!VT.isVector()) {
2270 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2271 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2274 // If X/C can be simplified by the division-by-constant logic, lower
2275 // X%C to the equivalent of X-X/C*C.
2276 if (N1C && !N1C->isNullValue()) {
2277 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2278 AddToWorklist(Div.getNode());
2279 SDValue OptimizedDiv = combine(Div.getNode());
2280 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2281 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2283 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2284 AddToWorklist(Mul.getNode());
2290 if (N0.getOpcode() == ISD::UNDEF)
2291 return DAG.getConstant(0, SDLoc(N), VT);
2292 // X % undef -> undef
2293 if (N1.getOpcode() == ISD::UNDEF)
2299 SDValue DAGCombiner::visitUREM(SDNode *N) {
2300 SDValue N0 = N->getOperand(0);
2301 SDValue N1 = N->getOperand(1);
2302 EVT VT = N->getValueType(0);
2304 // fold (urem c1, c2) -> c1%c2
2305 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2306 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2307 if (N0C && N1C && !N1C->isNullValue())
2308 return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2309 // fold (urem x, pow2) -> (and x, pow2-1)
2310 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2312 return DAG.getNode(ISD::AND, DL, VT, N0,
2313 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2315 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2316 if (N1.getOpcode() == ISD::SHL) {
2317 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2318 if (SHC->getAPIntValue().isPowerOf2()) {
2321 DAG.getNode(ISD::ADD, DL, VT, N1,
2322 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2324 AddToWorklist(Add.getNode());
2325 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2330 // If X/C can be simplified by the division-by-constant logic, lower
2331 // X%C to the equivalent of X-X/C*C.
2332 if (N1C && !N1C->isNullValue()) {
2333 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2334 AddToWorklist(Div.getNode());
2335 SDValue OptimizedDiv = combine(Div.getNode());
2336 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2337 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2339 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2340 AddToWorklist(Mul.getNode());
2346 if (N0.getOpcode() == ISD::UNDEF)
2347 return DAG.getConstant(0, SDLoc(N), VT);
2348 // X % undef -> undef
2349 if (N1.getOpcode() == ISD::UNDEF)
2355 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2356 SDValue N0 = N->getOperand(0);
2357 SDValue N1 = N->getOperand(1);
2358 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2359 EVT VT = N->getValueType(0);
2362 // fold (mulhs x, 0) -> 0
2363 if (isNullConstant(N1))
2365 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2366 if (N1C && N1C->getAPIntValue() == 1) {
2368 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2369 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2371 getShiftAmountTy(N0.getValueType())));
2373 // fold (mulhs x, undef) -> 0
2374 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2375 return DAG.getConstant(0, SDLoc(N), VT);
2377 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2379 if (VT.isSimple() && !VT.isVector()) {
2380 MVT Simple = VT.getSimpleVT();
2381 unsigned SimpleSize = Simple.getSizeInBits();
2382 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2383 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2384 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2385 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2386 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2387 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2388 DAG.getConstant(SimpleSize, DL,
2389 getShiftAmountTy(N1.getValueType())));
2390 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2397 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2398 SDValue N0 = N->getOperand(0);
2399 SDValue N1 = N->getOperand(1);
2400 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2401 EVT VT = N->getValueType(0);
2404 // fold (mulhu x, 0) -> 0
2405 if (isNullConstant(N1))
2407 // fold (mulhu x, 1) -> 0
2408 if (N1C && N1C->getAPIntValue() == 1)
2409 return DAG.getConstant(0, DL, N0.getValueType());
2410 // fold (mulhu x, undef) -> 0
2411 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2412 return DAG.getConstant(0, DL, VT);
2414 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2416 if (VT.isSimple() && !VT.isVector()) {
2417 MVT Simple = VT.getSimpleVT();
2418 unsigned SimpleSize = Simple.getSizeInBits();
2419 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2420 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2421 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2422 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2423 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2424 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2425 DAG.getConstant(SimpleSize, DL,
2426 getShiftAmountTy(N1.getValueType())));
2427 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2434 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2435 /// give the opcodes for the two computations that are being performed. Return
2436 /// true if a simplification was made.
2437 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2439 // If the high half is not needed, just compute the low half.
2440 bool HiExists = N->hasAnyUseOfValue(1);
2442 (!LegalOperations ||
2443 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2444 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2445 return CombineTo(N, Res, Res);
2448 // If the low half is not needed, just compute the high half.
2449 bool LoExists = N->hasAnyUseOfValue(0);
2451 (!LegalOperations ||
2452 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2453 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2454 return CombineTo(N, Res, Res);
2457 // If both halves are used, return as it is.
2458 if (LoExists && HiExists)
2461 // If the two computed results can be simplified separately, separate them.
2463 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2464 AddToWorklist(Lo.getNode());
2465 SDValue LoOpt = combine(Lo.getNode());
2466 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2467 (!LegalOperations ||
2468 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2469 return CombineTo(N, LoOpt, LoOpt);
2473 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2474 AddToWorklist(Hi.getNode());
2475 SDValue HiOpt = combine(Hi.getNode());
2476 if (HiOpt.getNode() && HiOpt != Hi &&
2477 (!LegalOperations ||
2478 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2479 return CombineTo(N, HiOpt, HiOpt);
2485 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2486 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2487 if (Res.getNode()) return Res;
2489 EVT VT = N->getValueType(0);
2492 // If the type is twice as wide is legal, transform the mulhu to a wider
2493 // multiply plus a shift.
2494 if (VT.isSimple() && !VT.isVector()) {
2495 MVT Simple = VT.getSimpleVT();
2496 unsigned SimpleSize = Simple.getSizeInBits();
2497 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2498 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2499 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2500 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2501 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2502 // Compute the high part as N1.
2503 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2504 DAG.getConstant(SimpleSize, DL,
2505 getShiftAmountTy(Lo.getValueType())));
2506 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2507 // Compute the low part as N0.
2508 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2509 return CombineTo(N, Lo, Hi);
2516 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2517 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2518 if (Res.getNode()) return Res;
2520 EVT VT = N->getValueType(0);
2523 // If the type is twice as wide is legal, transform the mulhu to a wider
2524 // multiply plus a shift.
2525 if (VT.isSimple() && !VT.isVector()) {
2526 MVT Simple = VT.getSimpleVT();
2527 unsigned SimpleSize = Simple.getSizeInBits();
2528 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2529 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2530 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2531 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2532 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2533 // Compute the high part as N1.
2534 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2535 DAG.getConstant(SimpleSize, DL,
2536 getShiftAmountTy(Lo.getValueType())));
2537 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2538 // Compute the low part as N0.
2539 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2540 return CombineTo(N, Lo, Hi);
2547 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2548 // (smulo x, 2) -> (saddo x, x)
2549 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2550 if (C2->getAPIntValue() == 2)
2551 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2552 N->getOperand(0), N->getOperand(0));
2557 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2558 // (umulo x, 2) -> (uaddo x, x)
2559 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2560 if (C2->getAPIntValue() == 2)
2561 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2562 N->getOperand(0), N->getOperand(0));
2567 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2568 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2569 if (Res.getNode()) return Res;
2574 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2575 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2576 if (Res.getNode()) return Res;
2581 /// If this is a binary operator with two operands of the same opcode, try to
2583 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2584 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2585 EVT VT = N0.getValueType();
2586 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2588 // Bail early if none of these transforms apply.
2589 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2591 // For each of OP in AND/OR/XOR:
2592 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2593 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2594 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2595 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2596 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2598 // do not sink logical op inside of a vector extend, since it may combine
2600 EVT Op0VT = N0.getOperand(0).getValueType();
2601 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2602 N0.getOpcode() == ISD::SIGN_EXTEND ||
2603 N0.getOpcode() == ISD::BSWAP ||
2604 // Avoid infinite looping with PromoteIntBinOp.
2605 (N0.getOpcode() == ISD::ANY_EXTEND &&
2606 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2607 (N0.getOpcode() == ISD::TRUNCATE &&
2608 (!TLI.isZExtFree(VT, Op0VT) ||
2609 !TLI.isTruncateFree(Op0VT, VT)) &&
2610 TLI.isTypeLegal(Op0VT))) &&
2612 Op0VT == N1.getOperand(0).getValueType() &&
2613 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2614 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2615 N0.getOperand(0).getValueType(),
2616 N0.getOperand(0), N1.getOperand(0));
2617 AddToWorklist(ORNode.getNode());
2618 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2621 // For each of OP in SHL/SRL/SRA/AND...
2622 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2623 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2624 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2625 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2626 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2627 N0.getOperand(1) == N1.getOperand(1)) {
2628 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2629 N0.getOperand(0).getValueType(),
2630 N0.getOperand(0), N1.getOperand(0));
2631 AddToWorklist(ORNode.getNode());
2632 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2633 ORNode, N0.getOperand(1));
2636 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2637 // Only perform this optimization after type legalization and before
2638 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2639 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2640 // we don't want to undo this promotion.
2641 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2643 if ((N0.getOpcode() == ISD::BITCAST ||
2644 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2645 Level == AfterLegalizeTypes) {
2646 SDValue In0 = N0.getOperand(0);
2647 SDValue In1 = N1.getOperand(0);
2648 EVT In0Ty = In0.getValueType();
2649 EVT In1Ty = In1.getValueType();
2651 // If both incoming values are integers, and the original types are the
2653 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2654 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2655 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2656 AddToWorklist(Op.getNode());
2661 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2662 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2663 // If both shuffles use the same mask, and both shuffle within a single
2664 // vector, then it is worthwhile to move the swizzle after the operation.
2665 // The type-legalizer generates this pattern when loading illegal
2666 // vector types from memory. In many cases this allows additional shuffle
2668 // There are other cases where moving the shuffle after the xor/and/or
2669 // is profitable even if shuffles don't perform a swizzle.
2670 // If both shuffles use the same mask, and both shuffles have the same first
2671 // or second operand, then it might still be profitable to move the shuffle
2672 // after the xor/and/or operation.
2673 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2674 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2675 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2677 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2678 "Inputs to shuffles are not the same type");
2680 // Check that both shuffles use the same mask. The masks are known to be of
2681 // the same length because the result vector type is the same.
2682 // Check also that shuffles have only one use to avoid introducing extra
2684 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2685 SVN0->getMask().equals(SVN1->getMask())) {
2686 SDValue ShOp = N0->getOperand(1);
2688 // Don't try to fold this node if it requires introducing a
2689 // build vector of all zeros that might be illegal at this stage.
2690 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2692 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2697 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2698 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2699 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2700 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2701 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2702 N0->getOperand(0), N1->getOperand(0));
2703 AddToWorklist(NewNode.getNode());
2704 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2705 &SVN0->getMask()[0]);
2708 // Don't try to fold this node if it requires introducing a
2709 // build vector of all zeros that might be illegal at this stage.
2710 ShOp = N0->getOperand(0);
2711 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2713 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2718 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2719 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2720 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2721 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2722 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2723 N0->getOperand(1), N1->getOperand(1));
2724 AddToWorklist(NewNode.getNode());
2725 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2726 &SVN0->getMask()[0]);
2734 /// This contains all DAGCombine rules which reduce two values combined by
2735 /// an And operation to a single value. This makes them reusable in the context
2736 /// of visitSELECT(). Rules involving constants are not included as
2737 /// visitSELECT() already handles those cases.
2738 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2739 SDNode *LocReference) {
2740 EVT VT = N1.getValueType();
2742 // fold (and x, undef) -> 0
2743 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2744 return DAG.getConstant(0, SDLoc(LocReference), VT);
2745 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2746 SDValue LL, LR, RL, RR, CC0, CC1;
2747 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2748 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2749 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2751 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2752 LL.getValueType().isInteger()) {
2753 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2754 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2755 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2756 LR.getValueType(), LL, RL);
2757 AddToWorklist(ORNode.getNode());
2758 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2760 if (isAllOnesConstant(LR)) {
2761 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2762 if (Op1 == ISD::SETEQ) {
2763 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2764 LR.getValueType(), LL, RL);
2765 AddToWorklist(ANDNode.getNode());
2766 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2768 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2769 if (Op1 == ISD::SETGT) {
2770 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2771 LR.getValueType(), LL, RL);
2772 AddToWorklist(ORNode.getNode());
2773 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2777 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2778 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2779 Op0 == Op1 && LL.getValueType().isInteger() &&
2780 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2781 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2783 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2784 LL, DAG.getConstant(1, DL,
2785 LL.getValueType()));
2786 AddToWorklist(ADDNode.getNode());
2787 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2788 DAG.getConstant(2, DL, LL.getValueType()),
2791 // canonicalize equivalent to ll == rl
2792 if (LL == RR && LR == RL) {
2793 Op1 = ISD::getSetCCSwappedOperands(Op1);
2796 if (LL == RL && LR == RR) {
2797 bool isInteger = LL.getValueType().isInteger();
2798 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2799 if (Result != ISD::SETCC_INVALID &&
2800 (!LegalOperations ||
2801 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2802 TLI.isOperationLegal(ISD::SETCC,
2803 getSetCCResultType(N0.getSimpleValueType())))))
2804 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2809 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2810 VT.getSizeInBits() <= 64) {
2811 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2812 APInt ADDC = ADDI->getAPIntValue();
2813 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2814 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2815 // immediate for an add, but it is legal if its top c2 bits are set,
2816 // transform the ADD so the immediate doesn't need to be materialized
2818 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2819 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2820 SRLI->getZExtValue());
2821 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2823 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2826 DAG.getNode(ISD::ADD, DL, VT,
2827 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2828 CombineTo(N0.getNode(), NewAdd);
2829 // Return N so it doesn't get rechecked!
2830 return SDValue(LocReference, 0);
2841 SDValue DAGCombiner::visitAND(SDNode *N) {
2842 SDValue N0 = N->getOperand(0);
2843 SDValue N1 = N->getOperand(1);
2844 EVT VT = N1.getValueType();
2847 if (VT.isVector()) {
2848 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2851 // fold (and x, 0) -> 0, vector edition
2852 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2853 // do not return N0, because undef node may exist in N0
2854 return DAG.getConstant(
2855 APInt::getNullValue(
2856 N0.getValueType().getScalarType().getSizeInBits()),
2857 SDLoc(N), N0.getValueType());
2858 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2859 // do not return N1, because undef node may exist in N1
2860 return DAG.getConstant(
2861 APInt::getNullValue(
2862 N1.getValueType().getScalarType().getSizeInBits()),
2863 SDLoc(N), N1.getValueType());
2865 // fold (and x, -1) -> x, vector edition
2866 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2868 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2872 // fold (and c1, c2) -> c1&c2
2873 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2874 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2876 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2877 // canonicalize constant to RHS
2878 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2879 !isConstantIntBuildVectorOrConstantInt(N1))
2880 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2881 // fold (and x, -1) -> x
2882 if (isAllOnesConstant(N1))
2884 // if (and x, c) is known to be zero, return 0
2885 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2886 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2887 APInt::getAllOnesValue(BitWidth)))
2888 return DAG.getConstant(0, SDLoc(N), VT);
2890 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2892 // fold (and (or x, C), D) -> D if (C & D) == D
2893 if (N1C && N0.getOpcode() == ISD::OR)
2894 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2895 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2897 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2898 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2899 SDValue N0Op0 = N0.getOperand(0);
2900 APInt Mask = ~N1C->getAPIntValue();
2901 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2902 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2903 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2904 N0.getValueType(), N0Op0);
2906 // Replace uses of the AND with uses of the Zero extend node.
2909 // We actually want to replace all uses of the any_extend with the
2910 // zero_extend, to avoid duplicating things. This will later cause this
2911 // AND to be folded.
2912 CombineTo(N0.getNode(), Zext);
2913 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2916 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2917 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2918 // already be zero by virtue of the width of the base type of the load.
2920 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2922 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2923 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2924 N0.getOpcode() == ISD::LOAD) {
2925 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2926 N0 : N0.getOperand(0) );
2928 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2929 // This can be a pure constant or a vector splat, in which case we treat the
2930 // vector as a scalar and use the splat value.
2931 APInt Constant = APInt::getNullValue(1);
2932 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2933 Constant = C->getAPIntValue();
2934 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2935 APInt SplatValue, SplatUndef;
2936 unsigned SplatBitSize;
2938 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2939 SplatBitSize, HasAnyUndefs);
2941 // Undef bits can contribute to a possible optimisation if set, so
2943 SplatValue |= SplatUndef;
2945 // The splat value may be something like "0x00FFFFFF", which means 0 for
2946 // the first vector value and FF for the rest, repeating. We need a mask
2947 // that will apply equally to all members of the vector, so AND all the
2948 // lanes of the constant together.
2949 EVT VT = Vector->getValueType(0);
2950 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2952 // If the splat value has been compressed to a bitlength lower
2953 // than the size of the vector lane, we need to re-expand it to
2955 if (BitWidth > SplatBitSize)
2956 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2957 SplatBitSize < BitWidth;
2958 SplatBitSize = SplatBitSize * 2)
2959 SplatValue |= SplatValue.shl(SplatBitSize);
2961 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2962 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2963 if (SplatBitSize % BitWidth == 0) {
2964 Constant = APInt::getAllOnesValue(BitWidth);
2965 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2966 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2971 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2972 // actually legal and isn't going to get expanded, else this is a false
2974 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2975 Load->getValueType(0),
2976 Load->getMemoryVT());
2978 // Resize the constant to the same size as the original memory access before
2979 // extension. If it is still the AllOnesValue then this AND is completely
2982 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2985 switch (Load->getExtensionType()) {
2986 default: B = false; break;
2987 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2989 case ISD::NON_EXTLOAD: B = true; break;
2992 if (B && Constant.isAllOnesValue()) {
2993 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2994 // preserve semantics once we get rid of the AND.
2995 SDValue NewLoad(Load, 0);
2996 if (Load->getExtensionType() == ISD::EXTLOAD) {
2997 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2998 Load->getValueType(0), SDLoc(Load),
2999 Load->getChain(), Load->getBasePtr(),
3000 Load->getOffset(), Load->getMemoryVT(),
3001 Load->getMemOperand());
3002 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3003 if (Load->getNumValues() == 3) {
3004 // PRE/POST_INC loads have 3 values.
3005 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3006 NewLoad.getValue(2) };
3007 CombineTo(Load, To, 3, true);
3009 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3013 // Fold the AND away, taking care not to fold to the old load node if we
3015 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3017 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3021 // fold (and (load x), 255) -> (zextload x, i8)
3022 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3023 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3024 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3025 (N0.getOpcode() == ISD::ANY_EXTEND &&
3026 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3027 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3028 LoadSDNode *LN0 = HasAnyExt
3029 ? cast<LoadSDNode>(N0.getOperand(0))
3030 : cast<LoadSDNode>(N0);
3031 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3032 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3033 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3034 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3035 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3036 EVT LoadedVT = LN0->getMemoryVT();
3037 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3039 if (ExtVT == LoadedVT &&
3040 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3044 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3045 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3046 LN0->getMemOperand());
3048 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3049 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3052 // Do not change the width of a volatile load.
3053 // Do not generate loads of non-round integer types since these can
3054 // be expensive (and would be wrong if the type is not byte sized).
3055 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3056 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3058 EVT PtrType = LN0->getOperand(1).getValueType();
3060 unsigned Alignment = LN0->getAlignment();
3061 SDValue NewPtr = LN0->getBasePtr();
3063 // For big endian targets, we need to add an offset to the pointer
3064 // to load the correct bytes. For little endian systems, we merely
3065 // need to read fewer bytes from the same pointer.
3066 if (TLI.isBigEndian()) {
3067 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3068 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3069 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3071 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3072 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3073 Alignment = MinAlign(Alignment, PtrOff);
3076 AddToWorklist(NewPtr.getNode());
3079 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3080 LN0->getChain(), NewPtr,
3081 LN0->getPointerInfo(),
3082 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3083 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3085 CombineTo(LN0, Load, Load.getValue(1));
3086 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3092 if (SDValue Combined = visitANDLike(N0, N1, N))
3095 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3096 if (N0.getOpcode() == N1.getOpcode()) {
3097 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3098 if (Tmp.getNode()) return Tmp;
3101 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3102 // fold (and (sra)) -> (and (srl)) when possible.
3103 if (!VT.isVector() &&
3104 SimplifyDemandedBits(SDValue(N, 0)))
3105 return SDValue(N, 0);
3107 // fold (zext_inreg (extload x)) -> (zextload x)
3108 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3109 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3110 EVT MemVT = LN0->getMemoryVT();
3111 // If we zero all the possible extended bits, then we can turn this into
3112 // a zextload if we are running before legalize or the operation is legal.
3113 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3114 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3115 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3116 ((!LegalOperations && !LN0->isVolatile()) ||
3117 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3118 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3119 LN0->getChain(), LN0->getBasePtr(),
3120 MemVT, LN0->getMemOperand());
3122 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3123 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3126 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3127 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3129 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3130 EVT MemVT = LN0->getMemoryVT();
3131 // If we zero all the possible extended bits, then we can turn this into
3132 // a zextload if we are running before legalize or the operation is legal.
3133 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3134 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3135 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3136 ((!LegalOperations && !LN0->isVolatile()) ||
3137 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3138 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3139 LN0->getChain(), LN0->getBasePtr(),
3140 MemVT, LN0->getMemOperand());
3142 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3143 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3146 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3147 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3148 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3149 N0.getOperand(1), false);
3150 if (BSwap.getNode())
3157 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3158 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3159 bool DemandHighBits) {
3160 if (!LegalOperations)
3163 EVT VT = N->getValueType(0);
3164 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3166 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3169 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3170 bool LookPassAnd0 = false;
3171 bool LookPassAnd1 = false;
3172 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3174 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3176 if (N0.getOpcode() == ISD::AND) {
3177 if (!N0.getNode()->hasOneUse())
3179 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3180 if (!N01C || N01C->getZExtValue() != 0xFF00)
3182 N0 = N0.getOperand(0);
3183 LookPassAnd0 = true;
3186 if (N1.getOpcode() == ISD::AND) {
3187 if (!N1.getNode()->hasOneUse())
3189 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3190 if (!N11C || N11C->getZExtValue() != 0xFF)
3192 N1 = N1.getOperand(0);
3193 LookPassAnd1 = true;
3196 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3198 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3200 if (!N0.getNode()->hasOneUse() ||
3201 !N1.getNode()->hasOneUse())
3204 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3208 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3211 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3212 SDValue N00 = N0->getOperand(0);
3213 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3214 if (!N00.getNode()->hasOneUse())
3216 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3217 if (!N001C || N001C->getZExtValue() != 0xFF)
3219 N00 = N00.getOperand(0);
3220 LookPassAnd0 = true;
3223 SDValue N10 = N1->getOperand(0);
3224 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3225 if (!N10.getNode()->hasOneUse())
3227 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3228 if (!N101C || N101C->getZExtValue() != 0xFF00)
3230 N10 = N10.getOperand(0);
3231 LookPassAnd1 = true;
3237 // Make sure everything beyond the low halfword gets set to zero since the SRL
3238 // 16 will clear the top bits.
3239 unsigned OpSizeInBits = VT.getSizeInBits();
3240 if (DemandHighBits && OpSizeInBits > 16) {
3241 // If the left-shift isn't masked out then the only way this is a bswap is
3242 // if all bits beyond the low 8 are 0. In that case the entire pattern
3243 // reduces to a left shift anyway: leave it for other parts of the combiner.
3247 // However, if the right shift isn't masked out then it might be because
3248 // it's not needed. See if we can spot that too.
3249 if (!LookPassAnd1 &&
3250 !DAG.MaskedValueIsZero(
3251 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3255 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3256 if (OpSizeInBits > 16) {
3258 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3259 DAG.getConstant(OpSizeInBits - 16, DL,
3260 getShiftAmountTy(VT)));
3265 /// Return true if the specified node is an element that makes up a 32-bit
3266 /// packed halfword byteswap.
3267 /// ((x & 0x000000ff) << 8) |
3268 /// ((x & 0x0000ff00) >> 8) |
3269 /// ((x & 0x00ff0000) << 8) |
3270 /// ((x & 0xff000000) >> 8)
3271 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3272 if (!N.getNode()->hasOneUse())
3275 unsigned Opc = N.getOpcode();
3276 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3279 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3284 switch (N1C->getZExtValue()) {
3287 case 0xFF: Num = 0; break;
3288 case 0xFF00: Num = 1; break;
3289 case 0xFF0000: Num = 2; break;
3290 case 0xFF000000: Num = 3; break;
3293 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3294 SDValue N0 = N.getOperand(0);
3295 if (Opc == ISD::AND) {
3296 if (Num == 0 || Num == 2) {
3298 // (x >> 8) & 0xff0000
3299 if (N0.getOpcode() != ISD::SRL)
3301 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3302 if (!C || C->getZExtValue() != 8)
3305 // (x << 8) & 0xff00
3306 // (x << 8) & 0xff000000
3307 if (N0.getOpcode() != ISD::SHL)
3309 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3310 if (!C || C->getZExtValue() != 8)
3313 } else if (Opc == ISD::SHL) {
3315 // (x & 0xff0000) << 8
3316 if (Num != 0 && Num != 2)
3318 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3319 if (!C || C->getZExtValue() != 8)
3321 } else { // Opc == ISD::SRL
3322 // (x & 0xff00) >> 8
3323 // (x & 0xff000000) >> 8
3324 if (Num != 1 && Num != 3)
3326 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3327 if (!C || C->getZExtValue() != 8)
3334 Parts[Num] = N0.getOperand(0).getNode();
3338 /// Match a 32-bit packed halfword bswap. That is
3339 /// ((x & 0x000000ff) << 8) |
3340 /// ((x & 0x0000ff00) >> 8) |
3341 /// ((x & 0x00ff0000) << 8) |
3342 /// ((x & 0xff000000) >> 8)
3343 /// => (rotl (bswap x), 16)
3344 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3345 if (!LegalOperations)
3348 EVT VT = N->getValueType(0);
3351 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3355 // (or (or (and), (and)), (or (and), (and)))
3356 // (or (or (or (and), (and)), (and)), (and))
3357 if (N0.getOpcode() != ISD::OR)
3359 SDValue N00 = N0.getOperand(0);
3360 SDValue N01 = N0.getOperand(1);
3361 SDNode *Parts[4] = {};
3363 if (N1.getOpcode() == ISD::OR &&
3364 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3365 // (or (or (and), (and)), (or (and), (and)))
3366 SDValue N000 = N00.getOperand(0);
3367 if (!isBSwapHWordElement(N000, Parts))
3370 SDValue N001 = N00.getOperand(1);
3371 if (!isBSwapHWordElement(N001, Parts))
3373 SDValue N010 = N01.getOperand(0);
3374 if (!isBSwapHWordElement(N010, Parts))
3376 SDValue N011 = N01.getOperand(1);
3377 if (!isBSwapHWordElement(N011, Parts))
3380 // (or (or (or (and), (and)), (and)), (and))
3381 if (!isBSwapHWordElement(N1, Parts))
3383 if (!isBSwapHWordElement(N01, Parts))
3385 if (N00.getOpcode() != ISD::OR)
3387 SDValue N000 = N00.getOperand(0);
3388 if (!isBSwapHWordElement(N000, Parts))
3390 SDValue N001 = N00.getOperand(1);
3391 if (!isBSwapHWordElement(N001, Parts))
3395 // Make sure the parts are all coming from the same node.
3396 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3400 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3401 SDValue(Parts[0], 0));
3403 // Result of the bswap should be rotated by 16. If it's not legal, then
3404 // do (x << 16) | (x >> 16).
3405 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3406 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3407 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3408 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3409 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3410 return DAG.getNode(ISD::OR, DL, VT,
3411 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3412 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3415 /// This contains all DAGCombine rules which reduce two values combined by
3416 /// an Or operation to a single value \see visitANDLike().
3417 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3418 EVT VT = N1.getValueType();
3419 // fold (or x, undef) -> -1
3420 if (!LegalOperations &&
3421 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3422 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3423 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3424 SDLoc(LocReference), VT);
3426 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3427 SDValue LL, LR, RL, RR, CC0, CC1;
3428 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3429 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3430 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3432 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3433 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3434 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3435 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3436 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3437 LR.getValueType(), LL, RL);
3438 AddToWorklist(ORNode.getNode());
3439 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3441 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3442 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3443 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3444 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3445 LR.getValueType(), LL, RL);
3446 AddToWorklist(ANDNode.getNode());
3447 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3450 // canonicalize equivalent to ll == rl
3451 if (LL == RR && LR == RL) {
3452 Op1 = ISD::getSetCCSwappedOperands(Op1);
3455 if (LL == RL && LR == RR) {
3456 bool isInteger = LL.getValueType().isInteger();
3457 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3458 if (Result != ISD::SETCC_INVALID &&
3459 (!LegalOperations ||
3460 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3461 TLI.isOperationLegal(ISD::SETCC,
3462 getSetCCResultType(N0.getValueType())))))
3463 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3468 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3469 if (N0.getOpcode() == ISD::AND &&
3470 N1.getOpcode() == ISD::AND &&
3471 N0.getOperand(1).getOpcode() == ISD::Constant &&
3472 N1.getOperand(1).getOpcode() == ISD::Constant &&
3473 // Don't increase # computations.
3474 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3475 // We can only do this xform if we know that bits from X that are set in C2
3476 // but not in C1 are already zero. Likewise for Y.
3477 const APInt &LHSMask =
3478 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3479 const APInt &RHSMask =
3480 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3482 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3483 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3484 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3485 N0.getOperand(0), N1.getOperand(0));
3486 SDLoc DL(LocReference);
3487 return DAG.getNode(ISD::AND, DL, VT, X,
3488 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3492 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3493 if (N0.getOpcode() == ISD::AND &&
3494 N1.getOpcode() == ISD::AND &&
3495 N0.getOperand(0) == N1.getOperand(0) &&
3496 // Don't increase # computations.
3497 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3498 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3499 N0.getOperand(1), N1.getOperand(1));
3500 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3506 SDValue DAGCombiner::visitOR(SDNode *N) {
3507 SDValue N0 = N->getOperand(0);
3508 SDValue N1 = N->getOperand(1);
3509 EVT VT = N1.getValueType();
3512 if (VT.isVector()) {
3513 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3516 // fold (or x, 0) -> x, vector edition
3517 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3519 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3522 // fold (or x, -1) -> -1, vector edition
3523 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3524 // do not return N0, because undef node may exist in N0
3525 return DAG.getConstant(
3526 APInt::getAllOnesValue(
3527 N0.getValueType().getScalarType().getSizeInBits()),
3528 SDLoc(N), N0.getValueType());
3529 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3530 // do not return N1, because undef node may exist in N1
3531 return DAG.getConstant(
3532 APInt::getAllOnesValue(
3533 N1.getValueType().getScalarType().getSizeInBits()),
3534 SDLoc(N), N1.getValueType());
3536 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3537 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3538 // Do this only if the resulting shuffle is legal.
3539 if (isa<ShuffleVectorSDNode>(N0) &&
3540 isa<ShuffleVectorSDNode>(N1) &&
3541 // Avoid folding a node with illegal type.
3542 TLI.isTypeLegal(VT) &&
3543 N0->getOperand(1) == N1->getOperand(1) &&
3544 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3545 bool CanFold = true;
3546 unsigned NumElts = VT.getVectorNumElements();
3547 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3548 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3549 // We construct two shuffle masks:
3550 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3551 // and N1 as the second operand.
3552 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3553 // and N0 as the second operand.
3554 // We do this because OR is commutable and therefore there might be
3555 // two ways to fold this node into a shuffle.
3556 SmallVector<int,4> Mask1;
3557 SmallVector<int,4> Mask2;
3559 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3560 int M0 = SV0->getMaskElt(i);
3561 int M1 = SV1->getMaskElt(i);
3563 // Both shuffle indexes are undef. Propagate Undef.
3564 if (M0 < 0 && M1 < 0) {
3565 Mask1.push_back(M0);
3566 Mask2.push_back(M0);
3570 if (M0 < 0 || M1 < 0 ||
3571 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3572 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3577 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3578 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3582 // Fold this sequence only if the resulting shuffle is 'legal'.
3583 if (TLI.isShuffleMaskLegal(Mask1, VT))
3584 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3585 N1->getOperand(0), &Mask1[0]);
3586 if (TLI.isShuffleMaskLegal(Mask2, VT))
3587 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3588 N0->getOperand(0), &Mask2[0]);
3593 // fold (or c1, c2) -> c1|c2
3594 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3595 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3597 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3598 // canonicalize constant to RHS
3599 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3600 !isConstantIntBuildVectorOrConstantInt(N1))
3601 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3602 // fold (or x, 0) -> x
3603 if (isNullConstant(N1))
3605 // fold (or x, -1) -> -1
3606 if (isAllOnesConstant(N1))
3608 // fold (or x, c) -> c iff (x & ~c) == 0
3609 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3612 if (SDValue Combined = visitORLike(N0, N1, N))
3615 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3616 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3617 if (BSwap.getNode())
3619 BSwap = MatchBSwapHWordLow(N, N0, N1);
3620 if (BSwap.getNode())
3624 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3626 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3627 // iff (c1 & c2) == 0.
3628 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3629 isa<ConstantSDNode>(N0.getOperand(1))) {
3630 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3631 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3632 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3635 ISD::AND, SDLoc(N), VT,
3636 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3640 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3641 if (N0.getOpcode() == N1.getOpcode()) {
3642 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3643 if (Tmp.getNode()) return Tmp;
3646 // See if this is some rotate idiom.
3647 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3648 return SDValue(Rot, 0);
3650 // Simplify the operands using demanded-bits information.
3651 if (!VT.isVector() &&
3652 SimplifyDemandedBits(SDValue(N, 0)))
3653 return SDValue(N, 0);
3658 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3659 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3660 if (Op.getOpcode() == ISD::AND) {
3661 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3662 Mask = Op.getOperand(1);
3663 Op = Op.getOperand(0);
3669 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3677 // Return true if we can prove that, whenever Neg and Pos are both in the
3678 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3679 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3681 // (or (shift1 X, Neg), (shift2 X, Pos))
3683 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3684 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3685 // to consider shift amounts with defined behavior.
3686 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3687 // If OpSize is a power of 2 then:
3689 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3690 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3692 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3693 // for the stronger condition:
3695 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3697 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3698 // we can just replace Neg with Neg' for the rest of the function.
3700 // In other cases we check for the even stronger condition:
3702 // Neg == OpSize - Pos [B]
3704 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3705 // behavior if Pos == 0 (and consequently Neg == OpSize).
3707 // We could actually use [A] whenever OpSize is a power of 2, but the
3708 // only extra cases that it would match are those uninteresting ones
3709 // where Neg and Pos are never in range at the same time. E.g. for
3710 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3711 // as well as (sub 32, Pos), but:
3713 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3715 // always invokes undefined behavior for 32-bit X.
3717 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3718 unsigned MaskLoBits = 0;
3719 if (Neg.getOpcode() == ISD::AND &&
3720 isPowerOf2_64(OpSize) &&
3721 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3722 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3723 Neg = Neg.getOperand(0);
3724 MaskLoBits = Log2_64(OpSize);
3727 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3728 if (Neg.getOpcode() != ISD::SUB)
3730 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3733 SDValue NegOp1 = Neg.getOperand(1);
3735 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3736 // Pos'. The truncation is redundant for the purpose of the equality.
3738 Pos.getOpcode() == ISD::AND &&
3739 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3740 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3741 Pos = Pos.getOperand(0);
3743 // The condition we need is now:
3745 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3747 // If NegOp1 == Pos then we need:
3749 // OpSize & Mask == NegC & Mask
3751 // (because "x & Mask" is a truncation and distributes through subtraction).
3754 Width = NegC->getAPIntValue();
3755 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3756 // Then the condition we want to prove becomes:
3758 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3760 // which, again because "x & Mask" is a truncation, becomes:
3762 // NegC & Mask == (OpSize - PosC) & Mask
3763 // OpSize & Mask == (NegC + PosC) & Mask
3764 else if (Pos.getOpcode() == ISD::ADD &&
3765 Pos.getOperand(0) == NegOp1 &&
3766 Pos.getOperand(1).getOpcode() == ISD::Constant)
3767 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3768 NegC->getAPIntValue());
3772 // Now we just need to check that OpSize & Mask == Width & Mask.
3774 // Opsize & Mask is 0 since Mask is Opsize - 1.
3775 return Width.getLoBits(MaskLoBits) == 0;
3776 return Width == OpSize;
3779 // A subroutine of MatchRotate used once we have found an OR of two opposite
3780 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3781 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3782 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3783 // Neg with outer conversions stripped away.
3784 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3785 SDValue Neg, SDValue InnerPos,
3786 SDValue InnerNeg, unsigned PosOpcode,
3787 unsigned NegOpcode, SDLoc DL) {
3788 // fold (or (shl x, (*ext y)),
3789 // (srl x, (*ext (sub 32, y)))) ->
3790 // (rotl x, y) or (rotr x, (sub 32, y))
3792 // fold (or (shl x, (*ext (sub 32, y))),
3793 // (srl x, (*ext y))) ->
3794 // (rotr x, y) or (rotl x, (sub 32, y))
3795 EVT VT = Shifted.getValueType();
3796 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3797 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3798 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3799 HasPos ? Pos : Neg).getNode();
3805 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3806 // idioms for rotate, and if the target supports rotation instructions, generate
3808 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3809 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3810 EVT VT = LHS.getValueType();
3811 if (!TLI.isTypeLegal(VT)) return nullptr;
3813 // The target must have at least one rotate flavor.
3814 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3815 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3816 if (!HasROTL && !HasROTR) return nullptr;
3818 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3819 SDValue LHSShift; // The shift.
3820 SDValue LHSMask; // AND value if any.
3821 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3822 return nullptr; // Not part of a rotate.
3824 SDValue RHSShift; // The shift.
3825 SDValue RHSMask; // AND value if any.
3826 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3827 return nullptr; // Not part of a rotate.
3829 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3830 return nullptr; // Not shifting the same value.
3832 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3833 return nullptr; // Shifts must disagree.
3835 // Canonicalize shl to left side in a shl/srl pair.
3836 if (RHSShift.getOpcode() == ISD::SHL) {
3837 std::swap(LHS, RHS);
3838 std::swap(LHSShift, RHSShift);
3839 std::swap(LHSMask , RHSMask );
3842 unsigned OpSizeInBits = VT.getSizeInBits();
3843 SDValue LHSShiftArg = LHSShift.getOperand(0);
3844 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3845 SDValue RHSShiftArg = RHSShift.getOperand(0);
3846 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3848 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3849 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3850 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3851 RHSShiftAmt.getOpcode() == ISD::Constant) {
3852 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3853 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3854 if ((LShVal + RShVal) != OpSizeInBits)
3857 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3858 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3860 // If there is an AND of either shifted operand, apply it to the result.
3861 if (LHSMask.getNode() || RHSMask.getNode()) {
3862 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3864 if (LHSMask.getNode()) {
3865 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3866 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3868 if (RHSMask.getNode()) {
3869 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3870 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3873 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3876 return Rot.getNode();
3879 // If there is a mask here, and we have a variable shift, we can't be sure
3880 // that we're masking out the right stuff.
3881 if (LHSMask.getNode() || RHSMask.getNode())
3884 // If the shift amount is sign/zext/any-extended just peel it off.
3885 SDValue LExtOp0 = LHSShiftAmt;
3886 SDValue RExtOp0 = RHSShiftAmt;
3887 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3888 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3889 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3890 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3891 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3892 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3893 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3894 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3895 LExtOp0 = LHSShiftAmt.getOperand(0);
3896 RExtOp0 = RHSShiftAmt.getOperand(0);
3899 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3900 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3904 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3905 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3912 SDValue DAGCombiner::visitXOR(SDNode *N) {
3913 SDValue N0 = N->getOperand(0);
3914 SDValue N1 = N->getOperand(1);
3915 EVT VT = N0.getValueType();
3918 if (VT.isVector()) {
3919 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3922 // fold (xor x, 0) -> x, vector edition
3923 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3925 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3929 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3930 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3931 return DAG.getConstant(0, SDLoc(N), VT);
3932 // fold (xor x, undef) -> undef
3933 if (N0.getOpcode() == ISD::UNDEF)
3935 if (N1.getOpcode() == ISD::UNDEF)
3937 // fold (xor c1, c2) -> c1^c2
3938 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3939 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3941 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3942 // canonicalize constant to RHS
3943 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3944 !isConstantIntBuildVectorOrConstantInt(N1))
3945 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3946 // fold (xor x, 0) -> x
3947 if (isNullConstant(N1))
3950 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3953 // fold !(x cc y) -> (x !cc y)
3954 SDValue LHS, RHS, CC;
3955 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3956 bool isInt = LHS.getValueType().isInteger();
3957 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3960 if (!LegalOperations ||
3961 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3962 switch (N0.getOpcode()) {
3964 llvm_unreachable("Unhandled SetCC Equivalent!");
3966 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3967 case ISD::SELECT_CC:
3968 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3969 N0.getOperand(3), NotCC);
3974 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3975 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3976 N0.getNode()->hasOneUse() &&
3977 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3978 SDValue V = N0.getOperand(0);
3980 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3981 DAG.getConstant(1, DL, V.getValueType()));
3982 AddToWorklist(V.getNode());
3983 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3986 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3987 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3988 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3989 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3990 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3991 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3992 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3993 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3994 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3995 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3998 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3999 if (isAllOnesConstant(N1) &&
4000 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4001 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4002 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4003 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4004 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4005 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4006 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4007 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4010 // fold (xor (and x, y), y) -> (and (not x), y)
4011 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4012 N0->getOperand(1) == N1) {
4013 SDValue X = N0->getOperand(0);
4014 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4015 AddToWorklist(NotX.getNode());
4016 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4018 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4019 if (N1C && N0.getOpcode() == ISD::XOR) {
4020 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4021 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4024 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4025 DAG.getConstant(N1C->getAPIntValue() ^
4026 N00C->getAPIntValue(), DL, VT));
4030 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4031 DAG.getConstant(N1C->getAPIntValue() ^
4032 N01C->getAPIntValue(), DL, VT));
4035 // fold (xor x, x) -> 0
4037 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4039 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4040 // Here is a concrete example of this equivalence:
4042 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4043 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4047 // i16 ~1 == 0b1111111111111110
4048 // i16 rol(~1, 14) == 0b1011111111111111
4050 // Some additional tips to help conceptualize this transform:
4051 // - Try to see the operation as placing a single zero in a value of all ones.
4052 // - There exists no value for x which would allow the result to contain zero.
4053 // - Values of x larger than the bitwidth are undefined and do not require a
4054 // consistent result.
4055 // - Pushing the zero left requires shifting one bits in from the right.
4056 // A rotate left of ~1 is a nice way of achieving the desired result.
4057 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4058 if (N0.getOpcode() == ISD::SHL)
4059 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4060 if (isAllOnesConstant(N1) && ShlLHS->isOne()) {
4062 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4066 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4067 if (N0.getOpcode() == N1.getOpcode()) {
4068 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4069 if (Tmp.getNode()) return Tmp;
4072 // Simplify the expression using non-local knowledge.
4073 if (!VT.isVector() &&
4074 SimplifyDemandedBits(SDValue(N, 0)))
4075 return SDValue(N, 0);
4080 /// Handle transforms common to the three shifts, when the shift amount is a
4082 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4083 // We can't and shouldn't fold opaque constants.
4084 if (Amt->isOpaque())
4087 SDNode *LHS = N->getOperand(0).getNode();
4088 if (!LHS->hasOneUse()) return SDValue();
4090 // We want to pull some binops through shifts, so that we have (and (shift))
4091 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4092 // thing happens with address calculations, so it's important to canonicalize
4094 bool HighBitSet = false; // Can we transform this if the high bit is set?
4096 switch (LHS->getOpcode()) {
4097 default: return SDValue();
4100 HighBitSet = false; // We can only transform sra if the high bit is clear.
4103 HighBitSet = true; // We can only transform sra if the high bit is set.
4106 if (N->getOpcode() != ISD::SHL)
4107 return SDValue(); // only shl(add) not sr[al](add).
4108 HighBitSet = false; // We can only transform sra if the high bit is clear.
4112 // We require the RHS of the binop to be a constant and not opaque as well.
4113 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4114 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4116 // FIXME: disable this unless the input to the binop is a shift by a constant.
4117 // If it is not a shift, it pessimizes some common cases like:
4119 // void foo(int *X, int i) { X[i & 1235] = 1; }
4120 // int bar(int *X, int i) { return X[i & 255]; }
4121 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4122 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4123 BinOpLHSVal->getOpcode() != ISD::SRA &&
4124 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4125 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4128 EVT VT = N->getValueType(0);
4130 // If this is a signed shift right, and the high bit is modified by the
4131 // logical operation, do not perform the transformation. The highBitSet
4132 // boolean indicates the value of the high bit of the constant which would
4133 // cause it to be modified for this operation.
4134 if (N->getOpcode() == ISD::SRA) {
4135 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4136 if (BinOpRHSSignSet != HighBitSet)
4140 if (!TLI.isDesirableToCommuteWithShift(LHS))
4143 // Fold the constants, shifting the binop RHS by the shift amount.
4144 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4146 LHS->getOperand(1), N->getOperand(1));
4147 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4149 // Create the new shift.
4150 SDValue NewShift = DAG.getNode(N->getOpcode(),
4151 SDLoc(LHS->getOperand(0)),
4152 VT, LHS->getOperand(0), N->getOperand(1));
4154 // Create the new binop.
4155 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4158 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4159 assert(N->getOpcode() == ISD::TRUNCATE);
4160 assert(N->getOperand(0).getOpcode() == ISD::AND);
4162 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4163 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4164 SDValue N01 = N->getOperand(0).getOperand(1);
4166 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4167 EVT TruncVT = N->getValueType(0);
4168 SDValue N00 = N->getOperand(0).getOperand(0);
4169 APInt TruncC = N01C->getAPIntValue();
4170 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4173 return DAG.getNode(ISD::AND, DL, TruncVT,
4174 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4175 DAG.getConstant(TruncC, DL, TruncVT));
4182 SDValue DAGCombiner::visitRotate(SDNode *N) {
4183 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4184 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4185 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4186 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4187 if (NewOp1.getNode())
4188 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4189 N->getOperand(0), NewOp1);
4194 SDValue DAGCombiner::visitSHL(SDNode *N) {
4195 SDValue N0 = N->getOperand(0);
4196 SDValue N1 = N->getOperand(1);
4197 EVT VT = N0.getValueType();
4198 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4201 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4202 if (VT.isVector()) {
4203 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4206 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4207 // If setcc produces all-one true value then:
4208 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4209 if (N1CV && N1CV->isConstant()) {
4210 if (N0.getOpcode() == ISD::AND) {
4211 SDValue N00 = N0->getOperand(0);
4212 SDValue N01 = N0->getOperand(1);
4213 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4215 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4216 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4217 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4218 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4220 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4223 N1C = isConstOrConstSplat(N1);
4228 // fold (shl c1, c2) -> c1<<c2
4229 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4231 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4232 // fold (shl 0, x) -> 0
4233 if (isNullConstant(N0))
4235 // fold (shl x, c >= size(x)) -> undef
4236 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4237 return DAG.getUNDEF(VT);
4238 // fold (shl x, 0) -> x
4239 if (N1C && N1C->isNullValue())
4241 // fold (shl undef, x) -> 0
4242 if (N0.getOpcode() == ISD::UNDEF)
4243 return DAG.getConstant(0, SDLoc(N), VT);
4244 // if (shl x, c) is known to be zero, return 0
4245 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4246 APInt::getAllOnesValue(OpSizeInBits)))
4247 return DAG.getConstant(0, SDLoc(N), VT);
4248 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4249 if (N1.getOpcode() == ISD::TRUNCATE &&
4250 N1.getOperand(0).getOpcode() == ISD::AND) {
4251 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4252 if (NewOp1.getNode())
4253 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4256 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4257 return SDValue(N, 0);
4259 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4260 if (N1C && N0.getOpcode() == ISD::SHL) {
4261 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4262 uint64_t c1 = N0C1->getZExtValue();
4263 uint64_t c2 = N1C->getZExtValue();
4265 if (c1 + c2 >= OpSizeInBits)
4266 return DAG.getConstant(0, DL, VT);
4267 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4268 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4272 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4273 // For this to be valid, the second form must not preserve any of the bits
4274 // that are shifted out by the inner shift in the first form. This means
4275 // the outer shift size must be >= the number of bits added by the ext.
4276 // As a corollary, we don't care what kind of ext it is.
4277 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4278 N0.getOpcode() == ISD::ANY_EXTEND ||
4279 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4280 N0.getOperand(0).getOpcode() == ISD::SHL) {
4281 SDValue N0Op0 = N0.getOperand(0);
4282 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4283 uint64_t c1 = N0Op0C1->getZExtValue();
4284 uint64_t c2 = N1C->getZExtValue();
4285 EVT InnerShiftVT = N0Op0.getValueType();
4286 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4287 if (c2 >= OpSizeInBits - InnerShiftSize) {
4289 if (c1 + c2 >= OpSizeInBits)
4290 return DAG.getConstant(0, DL, VT);
4291 return DAG.getNode(ISD::SHL, DL, VT,
4292 DAG.getNode(N0.getOpcode(), DL, VT,
4293 N0Op0->getOperand(0)),
4294 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4299 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4300 // Only fold this if the inner zext has no other uses to avoid increasing
4301 // the total number of instructions.
4302 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4303 N0.getOperand(0).getOpcode() == ISD::SRL) {
4304 SDValue N0Op0 = N0.getOperand(0);
4305 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4306 uint64_t c1 = N0Op0C1->getZExtValue();
4307 if (c1 < VT.getScalarSizeInBits()) {
4308 uint64_t c2 = N1C->getZExtValue();
4310 SDValue NewOp0 = N0.getOperand(0);
4311 EVT CountVT = NewOp0.getOperand(1).getValueType();
4313 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4315 DAG.getConstant(c2, DL, CountVT));
4316 AddToWorklist(NewSHL.getNode());
4317 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4323 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4324 // (and (srl x, (sub c1, c2), MASK)
4325 // Only fold this if the inner shift has no other uses -- if it does, folding
4326 // this will increase the total number of instructions.
4327 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4328 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4329 uint64_t c1 = N0C1->getZExtValue();
4330 if (c1 < OpSizeInBits) {
4331 uint64_t c2 = N1C->getZExtValue();
4332 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4335 Mask = Mask.shl(c2 - c1);
4337 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4338 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4340 Mask = Mask.lshr(c1 - c2);
4342 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4343 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4346 return DAG.getNode(ISD::AND, DL, VT, Shift,
4347 DAG.getConstant(Mask, DL, VT));
4351 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4352 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4353 unsigned BitSize = VT.getScalarSizeInBits();
4355 SDValue HiBitsMask =
4356 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4357 BitSize - N1C->getZExtValue()),
4359 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4363 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4364 // Variant of version done on multiply, except mul by a power of 2 is turned
4367 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4368 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4369 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4370 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4371 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4372 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4376 SDValue NewSHL = visitShiftByConstant(N, N1C);
4377 if (NewSHL.getNode())
4384 SDValue DAGCombiner::visitSRA(SDNode *N) {
4385 SDValue N0 = N->getOperand(0);
4386 SDValue N1 = N->getOperand(1);
4387 EVT VT = N0.getValueType();
4388 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4391 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4392 if (VT.isVector()) {
4393 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4396 N1C = isConstOrConstSplat(N1);
4399 // fold (sra c1, c2) -> (sra c1, c2)
4400 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4402 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4403 // fold (sra 0, x) -> 0
4404 if (isNullConstant(N0))
4406 // fold (sra -1, x) -> -1
4407 if (isAllOnesConstant(N0))
4409 // fold (sra x, (setge c, size(x))) -> undef
4410 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4411 return DAG.getUNDEF(VT);
4412 // fold (sra x, 0) -> x
4413 if (N1C && N1C->isNullValue())
4415 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4417 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4418 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4419 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4421 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4422 ExtVT, VT.getVectorNumElements());
4423 if ((!LegalOperations ||
4424 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4425 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4426 N0.getOperand(0), DAG.getValueType(ExtVT));
4429 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4430 if (N1C && N0.getOpcode() == ISD::SRA) {
4431 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4432 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4433 if (Sum >= OpSizeInBits)
4434 Sum = OpSizeInBits - 1;
4436 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4437 DAG.getConstant(Sum, DL, N1.getValueType()));
4441 // fold (sra (shl X, m), (sub result_size, n))
4442 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4443 // result_size - n != m.
4444 // If truncate is free for the target sext(shl) is likely to result in better
4446 if (N0.getOpcode() == ISD::SHL && N1C) {
4447 // Get the two constanst of the shifts, CN0 = m, CN = n.
4448 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4450 LLVMContext &Ctx = *DAG.getContext();
4451 // Determine what the truncate's result bitsize and type would be.
4452 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4455 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4457 // Determine the residual right-shift amount.
4458 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4460 // If the shift is not a no-op (in which case this should be just a sign
4461 // extend already), the truncated to type is legal, sign_extend is legal
4462 // on that type, and the truncate to that type is both legal and free,
4463 // perform the transform.
4464 if ((ShiftAmt > 0) &&
4465 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4466 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4467 TLI.isTruncateFree(VT, TruncVT)) {
4470 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4471 getShiftAmountTy(N0.getOperand(0).getValueType()));
4472 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4473 N0.getOperand(0), Amt);
4474 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4476 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4477 N->getValueType(0), Trunc);
4482 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4483 if (N1.getOpcode() == ISD::TRUNCATE &&
4484 N1.getOperand(0).getOpcode() == ISD::AND) {
4485 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4486 if (NewOp1.getNode())
4487 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4490 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4491 // if c1 is equal to the number of bits the trunc removes
4492 if (N0.getOpcode() == ISD::TRUNCATE &&
4493 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4494 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4495 N0.getOperand(0).hasOneUse() &&
4496 N0.getOperand(0).getOperand(1).hasOneUse() &&
4498 SDValue N0Op0 = N0.getOperand(0);
4499 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4500 unsigned LargeShiftVal = LargeShift->getZExtValue();
4501 EVT LargeVT = N0Op0.getValueType();
4503 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4506 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4507 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4508 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4509 N0Op0.getOperand(0), Amt);
4510 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4515 // Simplify, based on bits shifted out of the LHS.
4516 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4517 return SDValue(N, 0);
4520 // If the sign bit is known to be zero, switch this to a SRL.
4521 if (DAG.SignBitIsZero(N0))
4522 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4525 SDValue NewSRA = visitShiftByConstant(N, N1C);
4526 if (NewSRA.getNode())
4533 SDValue DAGCombiner::visitSRL(SDNode *N) {
4534 SDValue N0 = N->getOperand(0);
4535 SDValue N1 = N->getOperand(1);
4536 EVT VT = N0.getValueType();
4537 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4540 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4541 if (VT.isVector()) {
4542 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4545 N1C = isConstOrConstSplat(N1);
4548 // fold (srl c1, c2) -> c1 >>u c2
4549 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4551 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4552 // fold (srl 0, x) -> 0
4553 if (isNullConstant(N0))
4555 // fold (srl x, c >= size(x)) -> undef
4556 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4557 return DAG.getUNDEF(VT);
4558 // fold (srl x, 0) -> x
4559 if (N1C && N1C->isNullValue())
4561 // if (srl x, c) is known to be zero, return 0
4562 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4563 APInt::getAllOnesValue(OpSizeInBits)))
4564 return DAG.getConstant(0, SDLoc(N), VT);
4566 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4567 if (N1C && N0.getOpcode() == ISD::SRL) {
4568 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4569 uint64_t c1 = N01C->getZExtValue();
4570 uint64_t c2 = N1C->getZExtValue();
4572 if (c1 + c2 >= OpSizeInBits)
4573 return DAG.getConstant(0, DL, VT);
4574 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4575 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4579 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4580 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4581 N0.getOperand(0).getOpcode() == ISD::SRL &&
4582 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4584 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4585 uint64_t c2 = N1C->getZExtValue();
4586 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4587 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4588 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4589 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4590 if (c1 + OpSizeInBits == InnerShiftSize) {
4592 if (c1 + c2 >= InnerShiftSize)
4593 return DAG.getConstant(0, DL, VT);
4594 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4595 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4596 N0.getOperand(0)->getOperand(0),
4597 DAG.getConstant(c1 + c2, DL,
4602 // fold (srl (shl x, c), c) -> (and x, cst2)
4603 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4604 unsigned BitSize = N0.getScalarValueSizeInBits();
4605 if (BitSize <= 64) {
4606 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4608 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4609 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4613 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4614 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4615 // Shifting in all undef bits?
4616 EVT SmallVT = N0.getOperand(0).getValueType();
4617 unsigned BitSize = SmallVT.getScalarSizeInBits();
4618 if (N1C->getZExtValue() >= BitSize)
4619 return DAG.getUNDEF(VT);
4621 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4622 uint64_t ShiftAmt = N1C->getZExtValue();
4624 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4626 DAG.getConstant(ShiftAmt, DL0,
4627 getShiftAmountTy(SmallVT)));
4628 AddToWorklist(SmallShift.getNode());
4629 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4631 return DAG.getNode(ISD::AND, DL, VT,
4632 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4633 DAG.getConstant(Mask, DL, VT));
4637 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4638 // bit, which is unmodified by sra.
4639 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4640 if (N0.getOpcode() == ISD::SRA)
4641 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4644 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4645 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4646 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4647 APInt KnownZero, KnownOne;
4648 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4650 // If any of the input bits are KnownOne, then the input couldn't be all
4651 // zeros, thus the result of the srl will always be zero.
4652 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4654 // If all of the bits input the to ctlz node are known to be zero, then
4655 // the result of the ctlz is "32" and the result of the shift is one.
4656 APInt UnknownBits = ~KnownZero;
4657 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4659 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4660 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4661 // Okay, we know that only that the single bit specified by UnknownBits
4662 // could be set on input to the CTLZ node. If this bit is set, the SRL
4663 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4664 // to an SRL/XOR pair, which is likely to simplify more.
4665 unsigned ShAmt = UnknownBits.countTrailingZeros();
4666 SDValue Op = N0.getOperand(0);
4670 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4671 DAG.getConstant(ShAmt, DL,
4672 getShiftAmountTy(Op.getValueType())));
4673 AddToWorklist(Op.getNode());
4677 return DAG.getNode(ISD::XOR, DL, VT,
4678 Op, DAG.getConstant(1, DL, VT));
4682 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4683 if (N1.getOpcode() == ISD::TRUNCATE &&
4684 N1.getOperand(0).getOpcode() == ISD::AND) {
4685 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4686 if (NewOp1.getNode())
4687 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4690 // fold operands of srl based on knowledge that the low bits are not
4692 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4693 return SDValue(N, 0);
4696 SDValue NewSRL = visitShiftByConstant(N, N1C);
4697 if (NewSRL.getNode())
4701 // Attempt to convert a srl of a load into a narrower zero-extending load.
4702 SDValue NarrowLoad = ReduceLoadWidth(N);
4703 if (NarrowLoad.getNode())
4706 // Here is a common situation. We want to optimize:
4709 // %b = and i32 %a, 2
4710 // %c = srl i32 %b, 1
4711 // brcond i32 %c ...
4717 // %c = setcc eq %b, 0
4720 // However when after the source operand of SRL is optimized into AND, the SRL
4721 // itself may not be optimized further. Look for it and add the BRCOND into
4723 if (N->hasOneUse()) {
4724 SDNode *Use = *N->use_begin();
4725 if (Use->getOpcode() == ISD::BRCOND)
4727 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4728 // Also look pass the truncate.
4729 Use = *Use->use_begin();
4730 if (Use->getOpcode() == ISD::BRCOND)
4738 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4739 SDValue N0 = N->getOperand(0);
4740 EVT VT = N->getValueType(0);
4742 // fold (ctlz c1) -> c2
4743 if (isa<ConstantSDNode>(N0))
4744 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4748 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4749 SDValue N0 = N->getOperand(0);
4750 EVT VT = N->getValueType(0);
4752 // fold (ctlz_zero_undef c1) -> c2
4753 if (isa<ConstantSDNode>(N0))
4754 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4758 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4759 SDValue N0 = N->getOperand(0);
4760 EVT VT = N->getValueType(0);
4762 // fold (cttz c1) -> c2
4763 if (isa<ConstantSDNode>(N0))
4764 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4768 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4769 SDValue N0 = N->getOperand(0);
4770 EVT VT = N->getValueType(0);
4772 // fold (cttz_zero_undef c1) -> c2
4773 if (isa<ConstantSDNode>(N0))
4774 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4778 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4779 SDValue N0 = N->getOperand(0);
4780 EVT VT = N->getValueType(0);
4782 // fold (ctpop c1) -> c2
4783 if (isa<ConstantSDNode>(N0))
4784 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4789 /// \brief Generate Min/Max node
4790 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4791 SDValue True, SDValue False,
4792 ISD::CondCode CC, const TargetLowering &TLI,
4793 SelectionDAG &DAG) {
4794 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4804 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4805 if (TLI.isOperationLegal(Opcode, VT))
4806 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4815 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4816 if (TLI.isOperationLegal(Opcode, VT))
4817 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4825 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4826 SDValue N0 = N->getOperand(0);
4827 SDValue N1 = N->getOperand(1);
4828 SDValue N2 = N->getOperand(2);
4829 EVT VT = N->getValueType(0);
4830 EVT VT0 = N0.getValueType();
4832 // fold (select C, X, X) -> X
4835 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4836 // fold (select true, X, Y) -> X
4837 // fold (select false, X, Y) -> Y
4838 return !N0C->isNullValue() ? N1 : N2;
4840 // fold (select C, 1, X) -> (or C, X)
4841 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4842 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4843 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4844 // fold (select C, 0, 1) -> (xor C, 1)
4845 // We can't do this reliably if integer based booleans have different contents
4846 // to floating point based booleans. This is because we can't tell whether we
4847 // have an integer-based boolean or a floating-point-based boolean unless we
4848 // can find the SETCC that produced it and inspect its operands. This is
4849 // fairly easy if C is the SETCC node, but it can potentially be
4850 // undiscoverable (or not reasonably discoverable). For example, it could be
4851 // in another basic block or it could require searching a complicated
4853 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4854 if (VT.isInteger() &&
4855 (VT0 == MVT::i1 || (VT0.isInteger() &&
4856 TLI.getBooleanContents(false, false) ==
4857 TLI.getBooleanContents(false, true) &&
4858 TLI.getBooleanContents(false, false) ==
4859 TargetLowering::ZeroOrOneBooleanContent)) &&
4860 isNullConstant(N1) && N2C && N2C->isOne()) {
4864 return DAG.getNode(ISD::XOR, DL, VT0,
4865 N0, DAG.getConstant(1, DL, VT0));
4868 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4869 N0, DAG.getConstant(1, DL0, VT0));
4870 AddToWorklist(XORNode.getNode());
4872 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4873 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4875 // fold (select C, 0, X) -> (and (not C), X)
4876 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4877 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4878 AddToWorklist(NOTNode.getNode());
4879 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4881 // fold (select C, X, 1) -> (or (not C), X)
4882 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4883 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4884 AddToWorklist(NOTNode.getNode());
4885 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4887 // fold (select C, X, 0) -> (and C, X)
4888 if (VT == MVT::i1 && isNullConstant(N2))
4889 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4890 // fold (select X, X, Y) -> (or X, Y)
4891 // fold (select X, 1, Y) -> (or X, Y)
4892 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4893 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4894 // fold (select X, Y, X) -> (and X, Y)
4895 // fold (select X, Y, 0) -> (and X, Y)
4896 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4897 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4899 // If we can fold this based on the true/false value, do so.
4900 if (SimplifySelectOps(N, N1, N2))
4901 return SDValue(N, 0); // Don't revisit N.
4903 // fold selects based on a setcc into other things, such as min/max/abs
4904 if (N0.getOpcode() == ISD::SETCC) {
4905 // select x, y (fcmp lt x, y) -> fminnum x, y
4906 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4908 // This is OK if we don't care about what happens if either operand is a
4912 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4913 // no signed zeros as well as no nans.
4914 const TargetOptions &Options = DAG.getTarget().Options;
4915 if (Options.UnsafeFPMath &&
4916 VT.isFloatingPoint() && N0.hasOneUse() &&
4917 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4918 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4921 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4922 N1, N2, CC, TLI, DAG);
4927 if ((!LegalOperations &&
4928 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4929 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4930 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4931 N0.getOperand(0), N0.getOperand(1),
4932 N1, N2, N0.getOperand(2));
4933 return SimplifySelect(SDLoc(N), N0, N1, N2);
4936 if (VT0 == MVT::i1) {
4937 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4938 // select (and Cond0, Cond1), X, Y
4939 // -> select Cond0, (select Cond1, X, Y), Y
4940 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4941 SDValue Cond0 = N0->getOperand(0);
4942 SDValue Cond1 = N0->getOperand(1);
4943 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4944 N1.getValueType(), Cond1, N1, N2);
4945 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4948 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4949 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4950 SDValue Cond0 = N0->getOperand(0);
4951 SDValue Cond1 = N0->getOperand(1);
4952 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4953 N1.getValueType(), Cond1, N1, N2);
4954 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4959 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4960 if (N1->getOpcode() == ISD::SELECT) {
4961 SDValue N1_0 = N1->getOperand(0);
4962 SDValue N1_1 = N1->getOperand(1);
4963 SDValue N1_2 = N1->getOperand(2);
4964 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4965 // Create the actual and node if we can generate good code for it.
4966 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4967 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4969 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4972 // Otherwise see if we can optimize the "and" to a better pattern.
4973 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4974 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4978 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4979 if (N2->getOpcode() == ISD::SELECT) {
4980 SDValue N2_0 = N2->getOperand(0);
4981 SDValue N2_1 = N2->getOperand(1);
4982 SDValue N2_2 = N2->getOperand(2);
4983 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4984 // Create the actual or node if we can generate good code for it.
4985 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4986 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4988 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4991 // Otherwise see if we can optimize to a better pattern.
4992 if (SDValue Combined = visitORLike(N0, N2_0, N))
4993 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5003 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5006 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5008 // Split the inputs.
5009 SDValue Lo, Hi, LL, LH, RL, RH;
5010 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5011 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5013 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5014 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5016 return std::make_pair(Lo, Hi);
5019 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5020 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5021 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5023 SDValue Cond = N->getOperand(0);
5024 SDValue LHS = N->getOperand(1);
5025 SDValue RHS = N->getOperand(2);
5026 EVT VT = N->getValueType(0);
5027 int NumElems = VT.getVectorNumElements();
5028 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5029 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5030 Cond.getOpcode() == ISD::BUILD_VECTOR);
5032 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5033 // binary ones here.
5034 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5037 // We're sure we have an even number of elements due to the
5038 // concat_vectors we have as arguments to vselect.
5039 // Skip BV elements until we find one that's not an UNDEF
5040 // After we find an UNDEF element, keep looping until we get to half the
5041 // length of the BV and see if all the non-undef nodes are the same.
5042 ConstantSDNode *BottomHalf = nullptr;
5043 for (int i = 0; i < NumElems / 2; ++i) {
5044 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5047 if (BottomHalf == nullptr)
5048 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5049 else if (Cond->getOperand(i).getNode() != BottomHalf)
5053 // Do the same for the second half of the BuildVector
5054 ConstantSDNode *TopHalf = nullptr;
5055 for (int i = NumElems / 2; i < NumElems; ++i) {
5056 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5059 if (TopHalf == nullptr)
5060 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5061 else if (Cond->getOperand(i).getNode() != TopHalf)
5065 assert(TopHalf && BottomHalf &&
5066 "One half of the selector was all UNDEFs and the other was all the "
5067 "same value. This should have been addressed before this function.");
5069 ISD::CONCAT_VECTORS, dl, VT,
5070 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5071 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5074 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5076 if (Level >= AfterLegalizeTypes)
5079 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5080 SDValue Mask = MSC->getMask();
5081 SDValue Data = MSC->getValue();
5084 // If the MSCATTER data type requires splitting and the mask is provided by a
5085 // SETCC, then split both nodes and its operands before legalization. This
5086 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5087 // and enables future optimizations (e.g. min/max pattern matching on X86).
5088 if (Mask.getOpcode() != ISD::SETCC)
5091 // Check if any splitting is required.
5092 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5093 TargetLowering::TypeSplitVector)
5095 SDValue MaskLo, MaskHi, Lo, Hi;
5096 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5099 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5101 SDValue Chain = MSC->getChain();
5103 EVT MemoryVT = MSC->getMemoryVT();
5104 unsigned Alignment = MSC->getOriginalAlignment();
5106 EVT LoMemVT, HiMemVT;
5107 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5109 SDValue DataLo, DataHi;
5110 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5112 SDValue BasePtr = MSC->getBasePtr();
5113 SDValue IndexLo, IndexHi;
5114 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5116 MachineMemOperand *MMO = DAG.getMachineFunction().
5117 getMachineMemOperand(MSC->getPointerInfo(),
5118 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5119 Alignment, MSC->getAAInfo(), MSC->getRanges());
5121 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5122 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5125 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5126 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5129 AddToWorklist(Lo.getNode());
5130 AddToWorklist(Hi.getNode());
5132 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5135 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5137 if (Level >= AfterLegalizeTypes)
5140 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5141 SDValue Mask = MST->getMask();
5142 SDValue Data = MST->getValue();
5145 // If the MSTORE data type requires splitting and the mask is provided by a
5146 // SETCC, then split both nodes and its operands before legalization. This
5147 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5148 // and enables future optimizations (e.g. min/max pattern matching on X86).
5149 if (Mask.getOpcode() == ISD::SETCC) {
5151 // Check if any splitting is required.
5152 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5153 TargetLowering::TypeSplitVector)
5156 SDValue MaskLo, MaskHi, Lo, Hi;
5157 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5160 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5162 SDValue Chain = MST->getChain();
5163 SDValue Ptr = MST->getBasePtr();
5165 EVT MemoryVT = MST->getMemoryVT();
5166 unsigned Alignment = MST->getOriginalAlignment();
5168 // if Alignment is equal to the vector size,
5169 // take the half of it for the second part
5170 unsigned SecondHalfAlignment =
5171 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5172 Alignment/2 : Alignment;
5174 EVT LoMemVT, HiMemVT;
5175 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5177 SDValue DataLo, DataHi;
5178 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5180 MachineMemOperand *MMO = DAG.getMachineFunction().
5181 getMachineMemOperand(MST->getPointerInfo(),
5182 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5183 Alignment, MST->getAAInfo(), MST->getRanges());
5185 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5186 MST->isTruncatingStore());
5188 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5189 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5190 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5192 MMO = DAG.getMachineFunction().
5193 getMachineMemOperand(MST->getPointerInfo(),
5194 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5195 SecondHalfAlignment, MST->getAAInfo(),
5198 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5199 MST->isTruncatingStore());
5201 AddToWorklist(Lo.getNode());
5202 AddToWorklist(Hi.getNode());
5204 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5209 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5211 if (Level >= AfterLegalizeTypes)
5214 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5215 SDValue Mask = MGT->getMask();
5218 // If the MGATHER result requires splitting and the mask is provided by a
5219 // SETCC, then split both nodes and its operands before legalization. This
5220 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5221 // and enables future optimizations (e.g. min/max pattern matching on X86).
5223 if (Mask.getOpcode() != ISD::SETCC)
5226 EVT VT = N->getValueType(0);
5228 // Check if any splitting is required.
5229 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5230 TargetLowering::TypeSplitVector)
5233 SDValue MaskLo, MaskHi, Lo, Hi;
5234 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5236 SDValue Src0 = MGT->getValue();
5237 SDValue Src0Lo, Src0Hi;
5238 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5241 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5243 SDValue Chain = MGT->getChain();
5244 EVT MemoryVT = MGT->getMemoryVT();
5245 unsigned Alignment = MGT->getOriginalAlignment();
5247 EVT LoMemVT, HiMemVT;
5248 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5250 SDValue BasePtr = MGT->getBasePtr();
5251 SDValue Index = MGT->getIndex();
5252 SDValue IndexLo, IndexHi;
5253 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5255 MachineMemOperand *MMO = DAG.getMachineFunction().
5256 getMachineMemOperand(MGT->getPointerInfo(),
5257 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5258 Alignment, MGT->getAAInfo(), MGT->getRanges());
5260 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5261 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5264 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5265 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5268 AddToWorklist(Lo.getNode());
5269 AddToWorklist(Hi.getNode());
5271 // Build a factor node to remember that this load is independent of the
5273 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5276 // Legalized the chain result - switch anything that used the old chain to
5278 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5280 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5282 SDValue RetOps[] = { GatherRes, Chain };
5283 return DAG.getMergeValues(RetOps, DL);
5286 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5288 if (Level >= AfterLegalizeTypes)
5291 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5292 SDValue Mask = MLD->getMask();
5295 // If the MLOAD result requires splitting and the mask is provided by a
5296 // SETCC, then split both nodes and its operands before legalization. This
5297 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5298 // and enables future optimizations (e.g. min/max pattern matching on X86).
5300 if (Mask.getOpcode() == ISD::SETCC) {
5301 EVT VT = N->getValueType(0);
5303 // Check if any splitting is required.
5304 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5305 TargetLowering::TypeSplitVector)
5308 SDValue MaskLo, MaskHi, Lo, Hi;
5309 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5311 SDValue Src0 = MLD->getSrc0();
5312 SDValue Src0Lo, Src0Hi;
5313 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5316 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5318 SDValue Chain = MLD->getChain();
5319 SDValue Ptr = MLD->getBasePtr();
5320 EVT MemoryVT = MLD->getMemoryVT();
5321 unsigned Alignment = MLD->getOriginalAlignment();
5323 // if Alignment is equal to the vector size,
5324 // take the half of it for the second part
5325 unsigned SecondHalfAlignment =
5326 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5327 Alignment/2 : Alignment;
5329 EVT LoMemVT, HiMemVT;
5330 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5332 MachineMemOperand *MMO = DAG.getMachineFunction().
5333 getMachineMemOperand(MLD->getPointerInfo(),
5334 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5335 Alignment, MLD->getAAInfo(), MLD->getRanges());
5337 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5340 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5341 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5342 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5344 MMO = DAG.getMachineFunction().
5345 getMachineMemOperand(MLD->getPointerInfo(),
5346 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5347 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5349 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5352 AddToWorklist(Lo.getNode());
5353 AddToWorklist(Hi.getNode());
5355 // Build a factor node to remember that this load is independent of the
5357 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5360 // Legalized the chain result - switch anything that used the old chain to
5362 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5364 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5366 SDValue RetOps[] = { LoadRes, Chain };
5367 return DAG.getMergeValues(RetOps, DL);
5372 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5373 SDValue N0 = N->getOperand(0);
5374 SDValue N1 = N->getOperand(1);
5375 SDValue N2 = N->getOperand(2);
5378 // Canonicalize integer abs.
5379 // vselect (setg[te] X, 0), X, -X ->
5380 // vselect (setgt X, -1), X, -X ->
5381 // vselect (setl[te] X, 0), -X, X ->
5382 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5383 if (N0.getOpcode() == ISD::SETCC) {
5384 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5385 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5387 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5389 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5390 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5391 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5392 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5393 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5394 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5395 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5398 EVT VT = LHS.getValueType();
5399 SDValue Shift = DAG.getNode(
5400 ISD::SRA, DL, VT, LHS,
5401 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5402 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5403 AddToWorklist(Shift.getNode());
5404 AddToWorklist(Add.getNode());
5405 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5409 if (SimplifySelectOps(N, N1, N2))
5410 return SDValue(N, 0); // Don't revisit N.
5412 // If the VSELECT result requires splitting and the mask is provided by a
5413 // SETCC, then split both nodes and its operands before legalization. This
5414 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5415 // and enables future optimizations (e.g. min/max pattern matching on X86).
5416 if (N0.getOpcode() == ISD::SETCC) {
5417 EVT VT = N->getValueType(0);
5419 // Check if any splitting is required.
5420 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5421 TargetLowering::TypeSplitVector)
5424 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5425 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5426 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5427 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5429 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5430 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5432 // Add the new VSELECT nodes to the work list in case they need to be split
5434 AddToWorklist(Lo.getNode());
5435 AddToWorklist(Hi.getNode());
5437 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5440 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5441 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5443 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5444 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5447 // The ConvertSelectToConcatVector function is assuming both the above
5448 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5450 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5451 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5452 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5453 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5461 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5462 SDValue N0 = N->getOperand(0);
5463 SDValue N1 = N->getOperand(1);
5464 SDValue N2 = N->getOperand(2);
5465 SDValue N3 = N->getOperand(3);
5466 SDValue N4 = N->getOperand(4);
5467 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5469 // fold select_cc lhs, rhs, x, x, cc -> x
5473 // Determine if the condition we're dealing with is constant
5474 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5475 N0, N1, CC, SDLoc(N), false);
5476 if (SCC.getNode()) {
5477 AddToWorklist(SCC.getNode());
5479 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5480 if (!SCCC->isNullValue())
5481 return N2; // cond always true -> true val
5483 return N3; // cond always false -> false val
5484 } else if (SCC->getOpcode() == ISD::UNDEF) {
5485 // When the condition is UNDEF, just return the first operand. This is
5486 // coherent the DAG creation, no setcc node is created in this case
5488 } else if (SCC.getOpcode() == ISD::SETCC) {
5489 // Fold to a simpler select_cc
5490 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5491 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5496 // If we can fold this based on the true/false value, do so.
5497 if (SimplifySelectOps(N, N2, N3))
5498 return SDValue(N, 0); // Don't revisit N.
5500 // fold select_cc into other things, such as min/max/abs
5501 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5504 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5505 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5506 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5510 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5511 // dag node into a ConstantSDNode or a build_vector of constants.
5512 // This function is called by the DAGCombiner when visiting sext/zext/aext
5513 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5514 // Vector extends are not folded if operations are legal; this is to
5515 // avoid introducing illegal build_vector dag nodes.
5516 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5517 SelectionDAG &DAG, bool LegalTypes,
5518 bool LegalOperations) {
5519 unsigned Opcode = N->getOpcode();
5520 SDValue N0 = N->getOperand(0);
5521 EVT VT = N->getValueType(0);
5523 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5524 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5526 // fold (sext c1) -> c1
5527 // fold (zext c1) -> c1
5528 // fold (aext c1) -> c1
5529 if (isa<ConstantSDNode>(N0))
5530 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5532 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5533 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5534 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5535 EVT SVT = VT.getScalarType();
5536 if (!(VT.isVector() &&
5537 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5538 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5541 // We can fold this node into a build_vector.
5542 unsigned VTBits = SVT.getSizeInBits();
5543 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5544 unsigned ShAmt = VTBits - EVTBits;
5545 SmallVector<SDValue, 8> Elts;
5546 unsigned NumElts = N0->getNumOperands();
5549 for (unsigned i=0; i != NumElts; ++i) {
5550 SDValue Op = N0->getOperand(i);
5551 if (Op->getOpcode() == ISD::UNDEF) {
5552 Elts.push_back(DAG.getUNDEF(SVT));
5557 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5558 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5559 if (Opcode == ISD::SIGN_EXTEND)
5560 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5563 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5567 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5570 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5571 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5572 // transformation. Returns true if extension are possible and the above
5573 // mentioned transformation is profitable.
5574 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5576 SmallVectorImpl<SDNode *> &ExtendNodes,
5577 const TargetLowering &TLI) {
5578 bool HasCopyToRegUses = false;
5579 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5580 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5581 UE = N0.getNode()->use_end();
5586 if (UI.getUse().getResNo() != N0.getResNo())
5588 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5589 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5590 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5591 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5592 // Sign bits will be lost after a zext.
5595 for (unsigned i = 0; i != 2; ++i) {
5596 SDValue UseOp = User->getOperand(i);
5599 if (!isa<ConstantSDNode>(UseOp))
5604 ExtendNodes.push_back(User);
5607 // If truncates aren't free and there are users we can't
5608 // extend, it isn't worthwhile.
5611 // Remember if this value is live-out.
5612 if (User->getOpcode() == ISD::CopyToReg)
5613 HasCopyToRegUses = true;
5616 if (HasCopyToRegUses) {
5617 bool BothLiveOut = false;
5618 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5620 SDUse &Use = UI.getUse();
5621 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5627 // Both unextended and extended values are live out. There had better be
5628 // a good reason for the transformation.
5629 return ExtendNodes.size();
5634 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5635 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5636 ISD::NodeType ExtType) {
5637 // Extend SetCC uses if necessary.
5638 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5639 SDNode *SetCC = SetCCs[i];
5640 SmallVector<SDValue, 4> Ops;
5642 for (unsigned j = 0; j != 2; ++j) {
5643 SDValue SOp = SetCC->getOperand(j);
5645 Ops.push_back(ExtLoad);
5647 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5650 Ops.push_back(SetCC->getOperand(2));
5651 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5655 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5656 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5657 SDValue N0 = N->getOperand(0);
5658 EVT DstVT = N->getValueType(0);
5659 EVT SrcVT = N0.getValueType();
5661 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5662 N->getOpcode() == ISD::ZERO_EXTEND) &&
5663 "Unexpected node type (not an extend)!");
5665 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5666 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5667 // (v8i32 (sext (v8i16 (load x))))
5669 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5670 // (v4i32 (sextload (x + 16)))))
5671 // Where uses of the original load, i.e.:
5673 // are replaced with:
5675 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5676 // (v4i32 (sextload (x + 16)))))))
5678 // This combine is only applicable to illegal, but splittable, vectors.
5679 // All legal types, and illegal non-vector types, are handled elsewhere.
5680 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5682 if (N0->getOpcode() != ISD::LOAD)
5685 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5687 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5688 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5689 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5692 SmallVector<SDNode *, 4> SetCCs;
5693 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5696 ISD::LoadExtType ExtType =
5697 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5699 // Try to split the vector types to get down to legal types.
5700 EVT SplitSrcVT = SrcVT;
5701 EVT SplitDstVT = DstVT;
5702 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5703 SplitSrcVT.getVectorNumElements() > 1) {
5704 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5705 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5708 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5712 const unsigned NumSplits =
5713 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5714 const unsigned Stride = SplitSrcVT.getStoreSize();
5715 SmallVector<SDValue, 4> Loads;
5716 SmallVector<SDValue, 4> Chains;
5718 SDValue BasePtr = LN0->getBasePtr();
5719 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5720 const unsigned Offset = Idx * Stride;
5721 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5723 SDValue SplitLoad = DAG.getExtLoad(
5724 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5725 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5726 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5727 Align, LN0->getAAInfo());
5729 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5730 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5732 Loads.push_back(SplitLoad.getValue(0));
5733 Chains.push_back(SplitLoad.getValue(1));
5736 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5737 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5739 CombineTo(N, NewValue);
5741 // Replace uses of the original load (before extension)
5742 // with a truncate of the concatenated sextloaded vectors.
5744 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5745 CombineTo(N0.getNode(), Trunc, NewChain);
5746 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5747 (ISD::NodeType)N->getOpcode());
5748 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5751 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5752 SDValue N0 = N->getOperand(0);
5753 EVT VT = N->getValueType(0);
5755 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5757 return SDValue(Res, 0);
5759 // fold (sext (sext x)) -> (sext x)
5760 // fold (sext (aext x)) -> (sext x)
5761 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5762 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5765 if (N0.getOpcode() == ISD::TRUNCATE) {
5766 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5767 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5768 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5769 if (NarrowLoad.getNode()) {
5770 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5771 if (NarrowLoad.getNode() != N0.getNode()) {
5772 CombineTo(N0.getNode(), NarrowLoad);
5773 // CombineTo deleted the truncate, if needed, but not what's under it.
5776 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5779 // See if the value being truncated is already sign extended. If so, just
5780 // eliminate the trunc/sext pair.
5781 SDValue Op = N0.getOperand(0);
5782 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5783 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5784 unsigned DestBits = VT.getScalarType().getSizeInBits();
5785 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5787 if (OpBits == DestBits) {
5788 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5789 // bits, it is already ready.
5790 if (NumSignBits > DestBits-MidBits)
5792 } else if (OpBits < DestBits) {
5793 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5794 // bits, just sext from i32.
5795 if (NumSignBits > OpBits-MidBits)
5796 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5798 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5799 // bits, just truncate to i32.
5800 if (NumSignBits > OpBits-MidBits)
5801 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5804 // fold (sext (truncate x)) -> (sextinreg x).
5805 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5806 N0.getValueType())) {
5807 if (OpBits < DestBits)
5808 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5809 else if (OpBits > DestBits)
5810 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5811 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5812 DAG.getValueType(N0.getValueType()));
5816 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5817 // Only generate vector extloads when 1) they're legal, and 2) they are
5818 // deemed desirable by the target.
5819 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5820 ((!LegalOperations && !VT.isVector() &&
5821 !cast<LoadSDNode>(N0)->isVolatile()) ||
5822 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5823 bool DoXform = true;
5824 SmallVector<SDNode*, 4> SetCCs;
5825 if (!N0.hasOneUse())
5826 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5828 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5830 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5831 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5833 LN0->getBasePtr(), N0.getValueType(),
5834 LN0->getMemOperand());
5835 CombineTo(N, ExtLoad);
5836 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5837 N0.getValueType(), ExtLoad);
5838 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5839 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5841 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5845 // fold (sext (load x)) to multiple smaller sextloads.
5846 // Only on illegal but splittable vectors.
5847 if (SDValue ExtLoad = CombineExtLoad(N))
5850 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5851 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5852 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5853 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5854 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5855 EVT MemVT = LN0->getMemoryVT();
5856 if ((!LegalOperations && !LN0->isVolatile()) ||
5857 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5858 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5860 LN0->getBasePtr(), MemVT,
5861 LN0->getMemOperand());
5862 CombineTo(N, ExtLoad);
5863 CombineTo(N0.getNode(),
5864 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5865 N0.getValueType(), ExtLoad),
5866 ExtLoad.getValue(1));
5867 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5871 // fold (sext (and/or/xor (load x), cst)) ->
5872 // (and/or/xor (sextload x), (sext cst))
5873 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5874 N0.getOpcode() == ISD::XOR) &&
5875 isa<LoadSDNode>(N0.getOperand(0)) &&
5876 N0.getOperand(1).getOpcode() == ISD::Constant &&
5877 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5878 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5879 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5880 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5881 bool DoXform = true;
5882 SmallVector<SDNode*, 4> SetCCs;
5883 if (!N0.hasOneUse())
5884 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5887 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5888 LN0->getChain(), LN0->getBasePtr(),
5890 LN0->getMemOperand());
5891 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5892 Mask = Mask.sext(VT.getSizeInBits());
5894 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5895 ExtLoad, DAG.getConstant(Mask, DL, VT));
5896 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5897 SDLoc(N0.getOperand(0)),
5898 N0.getOperand(0).getValueType(), ExtLoad);
5900 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5901 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5903 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5908 if (N0.getOpcode() == ISD::SETCC) {
5909 EVT N0VT = N0.getOperand(0).getValueType();
5910 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5911 // Only do this before legalize for now.
5912 if (VT.isVector() && !LegalOperations &&
5913 TLI.getBooleanContents(N0VT) ==
5914 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5915 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5916 // of the same size as the compared operands. Only optimize sext(setcc())
5917 // if this is the case.
5918 EVT SVT = getSetCCResultType(N0VT);
5920 // We know that the # elements of the results is the same as the
5921 // # elements of the compare (and the # elements of the compare result
5922 // for that matter). Check to see that they are the same size. If so,
5923 // we know that the element size of the sext'd result matches the
5924 // element size of the compare operands.
5925 if (VT.getSizeInBits() == SVT.getSizeInBits())
5926 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5928 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5930 // If the desired elements are smaller or larger than the source
5931 // elements we can use a matching integer vector type and then
5932 // truncate/sign extend
5933 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5934 if (SVT == MatchingVectorType) {
5935 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5936 N0.getOperand(0), N0.getOperand(1),
5937 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5938 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5942 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5943 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5946 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5948 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5949 NegOne, DAG.getConstant(0, DL, VT),
5950 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5951 if (SCC.getNode()) return SCC;
5953 if (!VT.isVector()) {
5954 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5955 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5957 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5958 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5959 N0.getOperand(0), N0.getOperand(1), CC);
5960 return DAG.getSelect(DL, VT, SetCC,
5961 NegOne, DAG.getConstant(0, DL, VT));
5966 // fold (sext x) -> (zext x) if the sign bit is known zero.
5967 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5968 DAG.SignBitIsZero(N0))
5969 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5974 // isTruncateOf - If N is a truncate of some other value, return true, record
5975 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5976 // This function computes KnownZero to avoid a duplicated call to
5977 // computeKnownBits in the caller.
5978 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5981 if (N->getOpcode() == ISD::TRUNCATE) {
5982 Op = N->getOperand(0);
5983 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5987 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5988 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5991 SDValue Op0 = N->getOperand(0);
5992 SDValue Op1 = N->getOperand(1);
5993 assert(Op0.getValueType() == Op1.getValueType());
5995 if (isNullConstant(Op0))
5997 else if (isNullConstant(Op1))
6002 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6004 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6010 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6011 SDValue N0 = N->getOperand(0);
6012 EVT VT = N->getValueType(0);
6014 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6016 return SDValue(Res, 0);
6018 // fold (zext (zext x)) -> (zext x)
6019 // fold (zext (aext x)) -> (zext x)
6020 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6021 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6024 // fold (zext (truncate x)) -> (zext x) or
6025 // (zext (truncate x)) -> (truncate x)
6026 // This is valid when the truncated bits of x are already zero.
6027 // FIXME: We should extend this to work for vectors too.
6030 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6031 APInt TruncatedBits =
6032 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6033 APInt(Op.getValueSizeInBits(), 0) :
6034 APInt::getBitsSet(Op.getValueSizeInBits(),
6035 N0.getValueSizeInBits(),
6036 std::min(Op.getValueSizeInBits(),
6037 VT.getSizeInBits()));
6038 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6039 if (VT.bitsGT(Op.getValueType()))
6040 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6041 if (VT.bitsLT(Op.getValueType()))
6042 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6048 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6049 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6050 if (N0.getOpcode() == ISD::TRUNCATE) {
6051 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6052 if (NarrowLoad.getNode()) {
6053 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6054 if (NarrowLoad.getNode() != N0.getNode()) {
6055 CombineTo(N0.getNode(), NarrowLoad);
6056 // CombineTo deleted the truncate, if needed, but not what's under it.
6059 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6063 // fold (zext (truncate x)) -> (and x, mask)
6064 if (N0.getOpcode() == ISD::TRUNCATE &&
6065 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6067 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6068 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6069 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6070 if (NarrowLoad.getNode()) {
6071 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6072 if (NarrowLoad.getNode() != N0.getNode()) {
6073 CombineTo(N0.getNode(), NarrowLoad);
6074 // CombineTo deleted the truncate, if needed, but not what's under it.
6077 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6080 SDValue Op = N0.getOperand(0);
6081 if (Op.getValueType().bitsLT(VT)) {
6082 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6083 AddToWorklist(Op.getNode());
6084 } else if (Op.getValueType().bitsGT(VT)) {
6085 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6086 AddToWorklist(Op.getNode());
6088 return DAG.getZeroExtendInReg(Op, SDLoc(N),
6089 N0.getValueType().getScalarType());
6092 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6093 // if either of the casts is not free.
6094 if (N0.getOpcode() == ISD::AND &&
6095 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6096 N0.getOperand(1).getOpcode() == ISD::Constant &&
6097 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6098 N0.getValueType()) ||
6099 !TLI.isZExtFree(N0.getValueType(), VT))) {
6100 SDValue X = N0.getOperand(0).getOperand(0);
6101 if (X.getValueType().bitsLT(VT)) {
6102 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6103 } else if (X.getValueType().bitsGT(VT)) {
6104 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6106 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6107 Mask = Mask.zext(VT.getSizeInBits());
6109 return DAG.getNode(ISD::AND, DL, VT,
6110 X, DAG.getConstant(Mask, DL, VT));
6113 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6114 // Only generate vector extloads when 1) they're legal, and 2) they are
6115 // deemed desirable by the target.
6116 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6117 ((!LegalOperations && !VT.isVector() &&
6118 !cast<LoadSDNode>(N0)->isVolatile()) ||
6119 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6120 bool DoXform = true;
6121 SmallVector<SDNode*, 4> SetCCs;
6122 if (!N0.hasOneUse())
6123 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6125 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6127 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6128 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6130 LN0->getBasePtr(), N0.getValueType(),
6131 LN0->getMemOperand());
6132 CombineTo(N, ExtLoad);
6133 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6134 N0.getValueType(), ExtLoad);
6135 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6137 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6139 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6143 // fold (zext (load x)) to multiple smaller zextloads.
6144 // Only on illegal but splittable vectors.
6145 if (SDValue ExtLoad = CombineExtLoad(N))
6148 // fold (zext (and/or/xor (load x), cst)) ->
6149 // (and/or/xor (zextload x), (zext cst))
6150 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6151 N0.getOpcode() == ISD::XOR) &&
6152 isa<LoadSDNode>(N0.getOperand(0)) &&
6153 N0.getOperand(1).getOpcode() == ISD::Constant &&
6154 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6155 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6156 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6157 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6158 bool DoXform = true;
6159 SmallVector<SDNode*, 4> SetCCs;
6160 if (!N0.hasOneUse())
6161 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6164 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6165 LN0->getChain(), LN0->getBasePtr(),
6167 LN0->getMemOperand());
6168 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6169 Mask = Mask.zext(VT.getSizeInBits());
6171 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6172 ExtLoad, DAG.getConstant(Mask, DL, VT));
6173 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6174 SDLoc(N0.getOperand(0)),
6175 N0.getOperand(0).getValueType(), ExtLoad);
6177 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6178 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6180 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6185 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6186 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6187 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6188 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6189 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6190 EVT MemVT = LN0->getMemoryVT();
6191 if ((!LegalOperations && !LN0->isVolatile()) ||
6192 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6193 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6195 LN0->getBasePtr(), MemVT,
6196 LN0->getMemOperand());
6197 CombineTo(N, ExtLoad);
6198 CombineTo(N0.getNode(),
6199 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6201 ExtLoad.getValue(1));
6202 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6206 if (N0.getOpcode() == ISD::SETCC) {
6207 if (!LegalOperations && VT.isVector() &&
6208 N0.getValueType().getVectorElementType() == MVT::i1) {
6209 EVT N0VT = N0.getOperand(0).getValueType();
6210 if (getSetCCResultType(N0VT) == N0.getValueType())
6213 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6214 // Only do this before legalize for now.
6215 EVT EltVT = VT.getVectorElementType();
6217 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6218 DAG.getConstant(1, DL, EltVT));
6219 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6220 // We know that the # elements of the results is the same as the
6221 // # elements of the compare (and the # elements of the compare result
6222 // for that matter). Check to see that they are the same size. If so,
6223 // we know that the element size of the sext'd result matches the
6224 // element size of the compare operands.
6225 return DAG.getNode(ISD::AND, DL, VT,
6226 DAG.getSetCC(DL, VT, N0.getOperand(0),
6228 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6229 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6232 // If the desired elements are smaller or larger than the source
6233 // elements we can use a matching integer vector type and then
6234 // truncate/sign extend
6235 EVT MatchingElementType =
6236 EVT::getIntegerVT(*DAG.getContext(),
6237 N0VT.getScalarType().getSizeInBits());
6238 EVT MatchingVectorType =
6239 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6240 N0VT.getVectorNumElements());
6242 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6244 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6245 return DAG.getNode(ISD::AND, DL, VT,
6246 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6247 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6250 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6253 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6254 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6255 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6256 if (SCC.getNode()) return SCC;
6259 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6260 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6261 isa<ConstantSDNode>(N0.getOperand(1)) &&
6262 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6264 SDValue ShAmt = N0.getOperand(1);
6265 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6266 if (N0.getOpcode() == ISD::SHL) {
6267 SDValue InnerZExt = N0.getOperand(0);
6268 // If the original shl may be shifting out bits, do not perform this
6270 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6271 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6272 if (ShAmtVal > KnownZeroBits)
6278 // Ensure that the shift amount is wide enough for the shifted value.
6279 if (VT.getSizeInBits() >= 256)
6280 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6282 return DAG.getNode(N0.getOpcode(), DL, VT,
6283 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6290 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6291 SDValue N0 = N->getOperand(0);
6292 EVT VT = N->getValueType(0);
6294 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6296 return SDValue(Res, 0);
6298 // fold (aext (aext x)) -> (aext x)
6299 // fold (aext (zext x)) -> (zext x)
6300 // fold (aext (sext x)) -> (sext x)
6301 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6302 N0.getOpcode() == ISD::ZERO_EXTEND ||
6303 N0.getOpcode() == ISD::SIGN_EXTEND)
6304 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6306 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6307 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6308 if (N0.getOpcode() == ISD::TRUNCATE) {
6309 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6310 if (NarrowLoad.getNode()) {
6311 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6312 if (NarrowLoad.getNode() != N0.getNode()) {
6313 CombineTo(N0.getNode(), NarrowLoad);
6314 // CombineTo deleted the truncate, if needed, but not what's under it.
6317 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6321 // fold (aext (truncate x))
6322 if (N0.getOpcode() == ISD::TRUNCATE) {
6323 SDValue TruncOp = N0.getOperand(0);
6324 if (TruncOp.getValueType() == VT)
6325 return TruncOp; // x iff x size == zext size.
6326 if (TruncOp.getValueType().bitsGT(VT))
6327 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6328 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6331 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6332 // if the trunc is not free.
6333 if (N0.getOpcode() == ISD::AND &&
6334 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6335 N0.getOperand(1).getOpcode() == ISD::Constant &&
6336 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6337 N0.getValueType())) {
6338 SDValue X = N0.getOperand(0).getOperand(0);
6339 if (X.getValueType().bitsLT(VT)) {
6340 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6341 } else if (X.getValueType().bitsGT(VT)) {
6342 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6344 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6345 Mask = Mask.zext(VT.getSizeInBits());
6347 return DAG.getNode(ISD::AND, DL, VT,
6348 X, DAG.getConstant(Mask, DL, VT));
6351 // fold (aext (load x)) -> (aext (truncate (extload x)))
6352 // None of the supported targets knows how to perform load and any_ext
6353 // on vectors in one instruction. We only perform this transformation on
6355 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6356 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6357 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6358 bool DoXform = true;
6359 SmallVector<SDNode*, 4> SetCCs;
6360 if (!N0.hasOneUse())
6361 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6363 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6364 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6366 LN0->getBasePtr(), N0.getValueType(),
6367 LN0->getMemOperand());
6368 CombineTo(N, ExtLoad);
6369 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6370 N0.getValueType(), ExtLoad);
6371 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6372 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6374 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6378 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6379 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6380 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6381 if (N0.getOpcode() == ISD::LOAD &&
6382 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6384 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6385 ISD::LoadExtType ExtType = LN0->getExtensionType();
6386 EVT MemVT = LN0->getMemoryVT();
6387 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6388 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6389 VT, LN0->getChain(), LN0->getBasePtr(),
6390 MemVT, LN0->getMemOperand());
6391 CombineTo(N, ExtLoad);
6392 CombineTo(N0.getNode(),
6393 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6394 N0.getValueType(), ExtLoad),
6395 ExtLoad.getValue(1));
6396 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6400 if (N0.getOpcode() == ISD::SETCC) {
6402 // aext(setcc) -> vsetcc
6403 // aext(setcc) -> truncate(vsetcc)
6404 // aext(setcc) -> aext(vsetcc)
6405 // Only do this before legalize for now.
6406 if (VT.isVector() && !LegalOperations) {
6407 EVT N0VT = N0.getOperand(0).getValueType();
6408 // We know that the # elements of the results is the same as the
6409 // # elements of the compare (and the # elements of the compare result
6410 // for that matter). Check to see that they are the same size. If so,
6411 // we know that the element size of the sext'd result matches the
6412 // element size of the compare operands.
6413 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6414 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6416 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6417 // If the desired elements are smaller or larger than the source
6418 // elements we can use a matching integer vector type and then
6419 // truncate/any extend
6421 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6423 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6425 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6426 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6430 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6433 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6434 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6435 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6443 /// See if the specified operand can be simplified with the knowledge that only
6444 /// the bits specified by Mask are used. If so, return the simpler operand,
6445 /// otherwise return a null SDValue.
6446 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6447 switch (V.getOpcode()) {
6449 case ISD::Constant: {
6450 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6451 assert(CV && "Const value should be ConstSDNode.");
6452 const APInt &CVal = CV->getAPIntValue();
6453 APInt NewVal = CVal & Mask;
6455 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6460 // If the LHS or RHS don't contribute bits to the or, drop them.
6461 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6462 return V.getOperand(1);
6463 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6464 return V.getOperand(0);
6467 // Only look at single-use SRLs.
6468 if (!V.getNode()->hasOneUse())
6470 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6471 // See if we can recursively simplify the LHS.
6472 unsigned Amt = RHSC->getZExtValue();
6474 // Watch out for shift count overflow though.
6475 if (Amt >= Mask.getBitWidth()) break;
6476 APInt NewMask = Mask << Amt;
6477 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6478 if (SimplifyLHS.getNode())
6479 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6480 SimplifyLHS, V.getOperand(1));
6486 /// If the result of a wider load is shifted to right of N bits and then
6487 /// truncated to a narrower type and where N is a multiple of number of bits of
6488 /// the narrower type, transform it to a narrower load from address + N / num of
6489 /// bits of new type. If the result is to be extended, also fold the extension
6490 /// to form a extending load.
6491 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6492 unsigned Opc = N->getOpcode();
6494 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6495 SDValue N0 = N->getOperand(0);
6496 EVT VT = N->getValueType(0);
6499 // This transformation isn't valid for vector loads.
6503 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6505 if (Opc == ISD::SIGN_EXTEND_INREG) {
6506 ExtType = ISD::SEXTLOAD;
6507 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6508 } else if (Opc == ISD::SRL) {
6509 // Another special-case: SRL is basically zero-extending a narrower value.
6510 ExtType = ISD::ZEXTLOAD;
6512 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6513 if (!N01) return SDValue();
6514 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6515 VT.getSizeInBits() - N01->getZExtValue());
6517 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6520 unsigned EVTBits = ExtVT.getSizeInBits();
6522 // Do not generate loads of non-round integer types since these can
6523 // be expensive (and would be wrong if the type is not byte sized).
6524 if (!ExtVT.isRound())
6528 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6529 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6530 ShAmt = N01->getZExtValue();
6531 // Is the shift amount a multiple of size of VT?
6532 if ((ShAmt & (EVTBits-1)) == 0) {
6533 N0 = N0.getOperand(0);
6534 // Is the load width a multiple of size of VT?
6535 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6539 // At this point, we must have a load or else we can't do the transform.
6540 if (!isa<LoadSDNode>(N0)) return SDValue();
6542 // Because a SRL must be assumed to *need* to zero-extend the high bits
6543 // (as opposed to anyext the high bits), we can't combine the zextload
6544 // lowering of SRL and an sextload.
6545 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6548 // If the shift amount is larger than the input type then we're not
6549 // accessing any of the loaded bytes. If the load was a zextload/extload
6550 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6551 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6556 // If the load is shifted left (and the result isn't shifted back right),
6557 // we can fold the truncate through the shift.
6558 unsigned ShLeftAmt = 0;
6559 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6560 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6561 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6562 ShLeftAmt = N01->getZExtValue();
6563 N0 = N0.getOperand(0);
6567 // If we haven't found a load, we can't narrow it. Don't transform one with
6568 // multiple uses, this would require adding a new load.
6569 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6572 // Don't change the width of a volatile load.
6573 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6574 if (LN0->isVolatile())
6577 // Verify that we are actually reducing a load width here.
6578 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6581 // For the transform to be legal, the load must produce only two values
6582 // (the value loaded and the chain). Don't transform a pre-increment
6583 // load, for example, which produces an extra value. Otherwise the
6584 // transformation is not equivalent, and the downstream logic to replace
6585 // uses gets things wrong.
6586 if (LN0->getNumValues() > 2)
6589 // If the load that we're shrinking is an extload and we're not just
6590 // discarding the extension we can't simply shrink the load. Bail.
6591 // TODO: It would be possible to merge the extensions in some cases.
6592 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6593 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6596 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6599 EVT PtrType = N0.getOperand(1).getValueType();
6601 if (PtrType == MVT::Untyped || PtrType.isExtended())
6602 // It's not possible to generate a constant of extended or untyped type.
6605 // For big endian targets, we need to adjust the offset to the pointer to
6606 // load the correct bytes.
6607 if (TLI.isBigEndian()) {
6608 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6609 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6610 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6613 uint64_t PtrOff = ShAmt / 8;
6614 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6616 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6617 PtrType, LN0->getBasePtr(),
6618 DAG.getConstant(PtrOff, DL, PtrType));
6619 AddToWorklist(NewPtr.getNode());
6622 if (ExtType == ISD::NON_EXTLOAD)
6623 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6624 LN0->getPointerInfo().getWithOffset(PtrOff),
6625 LN0->isVolatile(), LN0->isNonTemporal(),
6626 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6628 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6629 LN0->getPointerInfo().getWithOffset(PtrOff),
6630 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6631 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6633 // Replace the old load's chain with the new load's chain.
6634 WorklistRemover DeadNodes(*this);
6635 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6637 // Shift the result left, if we've swallowed a left shift.
6638 SDValue Result = Load;
6639 if (ShLeftAmt != 0) {
6640 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6641 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6643 // If the shift amount is as large as the result size (but, presumably,
6644 // no larger than the source) then the useful bits of the result are
6645 // zero; we can't simply return the shortened shift, because the result
6646 // of that operation is undefined.
6648 if (ShLeftAmt >= VT.getSizeInBits())
6649 Result = DAG.getConstant(0, DL, VT);
6651 Result = DAG.getNode(ISD::SHL, DL, VT,
6652 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6655 // Return the new loaded value.
6659 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6660 SDValue N0 = N->getOperand(0);
6661 SDValue N1 = N->getOperand(1);
6662 EVT VT = N->getValueType(0);
6663 EVT EVT = cast<VTSDNode>(N1)->getVT();
6664 unsigned VTBits = VT.getScalarType().getSizeInBits();
6665 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6667 // fold (sext_in_reg c1) -> c1
6668 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6669 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6671 // If the input is already sign extended, just drop the extension.
6672 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6675 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6676 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6677 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6678 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6679 N0.getOperand(0), N1);
6681 // fold (sext_in_reg (sext x)) -> (sext x)
6682 // fold (sext_in_reg (aext x)) -> (sext x)
6683 // if x is small enough.
6684 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6685 SDValue N00 = N0.getOperand(0);
6686 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6687 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6688 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6691 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6692 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6693 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6695 // fold operands of sext_in_reg based on knowledge that the top bits are not
6697 if (SimplifyDemandedBits(SDValue(N, 0)))
6698 return SDValue(N, 0);
6700 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6701 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6702 SDValue NarrowLoad = ReduceLoadWidth(N);
6703 if (NarrowLoad.getNode())
6706 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6707 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6708 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6709 if (N0.getOpcode() == ISD::SRL) {
6710 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6711 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6712 // We can turn this into an SRA iff the input to the SRL is already sign
6714 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6715 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6716 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6717 N0.getOperand(0), N0.getOperand(1));
6721 // fold (sext_inreg (extload x)) -> (sextload x)
6722 if (ISD::isEXTLoad(N0.getNode()) &&
6723 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6724 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6725 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6726 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6727 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6728 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6730 LN0->getBasePtr(), EVT,
6731 LN0->getMemOperand());
6732 CombineTo(N, ExtLoad);
6733 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6734 AddToWorklist(ExtLoad.getNode());
6735 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6737 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6738 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6740 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6741 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6742 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6743 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6744 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6746 LN0->getBasePtr(), EVT,
6747 LN0->getMemOperand());
6748 CombineTo(N, ExtLoad);
6749 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6750 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6753 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6754 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6755 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6756 N0.getOperand(1), false);
6757 if (BSwap.getNode())
6758 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6762 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6763 // into a build_vector.
6764 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6765 SmallVector<SDValue, 8> Elts;
6766 unsigned NumElts = N0->getNumOperands();
6767 unsigned ShAmt = VTBits - EVTBits;
6769 for (unsigned i = 0; i != NumElts; ++i) {
6770 SDValue Op = N0->getOperand(i);
6771 if (Op->getOpcode() == ISD::UNDEF) {
6776 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6777 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6778 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6779 SDLoc(Op), Op.getValueType()));
6782 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6788 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6789 SDValue N0 = N->getOperand(0);
6790 EVT VT = N->getValueType(0);
6791 bool isLE = TLI.isLittleEndian();
6794 if (N0.getValueType() == N->getValueType(0))
6796 // fold (truncate c1) -> c1
6797 if (isConstantIntBuildVectorOrConstantInt(N0))
6798 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6799 // fold (truncate (truncate x)) -> (truncate x)
6800 if (N0.getOpcode() == ISD::TRUNCATE)
6801 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6802 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6803 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6804 N0.getOpcode() == ISD::SIGN_EXTEND ||
6805 N0.getOpcode() == ISD::ANY_EXTEND) {
6806 if (N0.getOperand(0).getValueType().bitsLT(VT))
6807 // if the source is smaller than the dest, we still need an extend
6808 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6810 if (N0.getOperand(0).getValueType().bitsGT(VT))
6811 // if the source is larger than the dest, than we just need the truncate
6812 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6813 // if the source and dest are the same type, we can drop both the extend
6814 // and the truncate.
6815 return N0.getOperand(0);
6818 // Fold extract-and-trunc into a narrow extract. For example:
6819 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6820 // i32 y = TRUNCATE(i64 x)
6822 // v16i8 b = BITCAST (v2i64 val)
6823 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6825 // Note: We only run this optimization after type legalization (which often
6826 // creates this pattern) and before operation legalization after which
6827 // we need to be more careful about the vector instructions that we generate.
6828 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6829 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6831 EVT VecTy = N0.getOperand(0).getValueType();
6832 EVT ExTy = N0.getValueType();
6833 EVT TrTy = N->getValueType(0);
6835 unsigned NumElem = VecTy.getVectorNumElements();
6836 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6838 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6839 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6841 SDValue EltNo = N0->getOperand(1);
6842 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6843 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6844 EVT IndexTy = TLI.getVectorIdxTy();
6845 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6847 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6848 NVT, N0.getOperand(0));
6851 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6853 DAG.getConstant(Index, DL, IndexTy));
6857 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6858 if (N0.getOpcode() == ISD::SELECT) {
6859 EVT SrcVT = N0.getValueType();
6860 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6861 TLI.isTruncateFree(SrcVT, VT)) {
6863 SDValue Cond = N0.getOperand(0);
6864 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6865 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6866 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6870 // Fold a series of buildvector, bitcast, and truncate if possible.
6872 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6873 // (2xi32 (buildvector x, y)).
6874 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6875 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6876 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6877 N0.getOperand(0).hasOneUse()) {
6879 SDValue BuildVect = N0.getOperand(0);
6880 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6881 EVT TruncVecEltTy = VT.getVectorElementType();
6883 // Check that the element types match.
6884 if (BuildVectEltTy == TruncVecEltTy) {
6885 // Now we only need to compute the offset of the truncated elements.
6886 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6887 unsigned TruncVecNumElts = VT.getVectorNumElements();
6888 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6890 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6891 "Invalid number of elements");
6893 SmallVector<SDValue, 8> Opnds;
6894 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6895 Opnds.push_back(BuildVect.getOperand(i));
6897 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6901 // See if we can simplify the input to this truncate through knowledge that
6902 // only the low bits are being used.
6903 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6904 // Currently we only perform this optimization on scalars because vectors
6905 // may have different active low bits.
6906 if (!VT.isVector()) {
6908 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6909 VT.getSizeInBits()));
6910 if (Shorter.getNode())
6911 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6913 // fold (truncate (load x)) -> (smaller load x)
6914 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6915 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6916 SDValue Reduced = ReduceLoadWidth(N);
6917 if (Reduced.getNode())
6919 // Handle the case where the load remains an extending load even
6920 // after truncation.
6921 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6922 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6923 if (!LN0->isVolatile() &&
6924 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6925 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6926 VT, LN0->getChain(), LN0->getBasePtr(),
6928 LN0->getMemOperand());
6929 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6934 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6935 // where ... are all 'undef'.
6936 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6937 SmallVector<EVT, 8> VTs;
6940 unsigned NumDefs = 0;
6942 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6943 SDValue X = N0.getOperand(i);
6944 if (X.getOpcode() != ISD::UNDEF) {
6949 // Stop if more than one members are non-undef.
6952 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6953 VT.getVectorElementType(),
6954 X.getValueType().getVectorNumElements()));
6958 return DAG.getUNDEF(VT);
6961 assert(V.getNode() && "The single defined operand is empty!");
6962 SmallVector<SDValue, 8> Opnds;
6963 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6965 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6968 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6969 AddToWorklist(NV.getNode());
6970 Opnds.push_back(NV);
6972 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6976 // Simplify the operands using demanded-bits information.
6977 if (!VT.isVector() &&
6978 SimplifyDemandedBits(SDValue(N, 0)))
6979 return SDValue(N, 0);
6984 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6985 SDValue Elt = N->getOperand(i);
6986 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6987 return Elt.getNode();
6988 return Elt.getOperand(Elt.getResNo()).getNode();
6991 /// build_pair (load, load) -> load
6992 /// if load locations are consecutive.
6993 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6994 assert(N->getOpcode() == ISD::BUILD_PAIR);
6996 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6997 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6998 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6999 LD1->getAddressSpace() != LD2->getAddressSpace())
7001 EVT LD1VT = LD1->getValueType(0);
7003 if (ISD::isNON_EXTLoad(LD2) &&
7005 // If both are volatile this would reduce the number of volatile loads.
7006 // If one is volatile it might be ok, but play conservative and bail out.
7007 !LD1->isVolatile() &&
7008 !LD2->isVolatile() &&
7009 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7010 unsigned Align = LD1->getAlignment();
7011 unsigned NewAlign = TLI.getDataLayout()->
7012 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7014 if (NewAlign <= Align &&
7015 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7016 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7017 LD1->getBasePtr(), LD1->getPointerInfo(),
7018 false, false, false, Align);
7024 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7025 SDValue N0 = N->getOperand(0);
7026 EVT VT = N->getValueType(0);
7028 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7029 // Only do this before legalize, since afterward the target may be depending
7030 // on the bitconvert.
7031 // First check to see if this is all constant.
7033 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7035 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7037 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7038 assert(!DestEltVT.isVector() &&
7039 "Element type of vector ValueType must not be vector!");
7041 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7044 // If the input is a constant, let getNode fold it.
7045 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7046 // If we can't allow illegal operations, we need to check that this is just
7047 // a fp -> int or int -> conversion and that the resulting operation will
7049 if (!LegalOperations ||
7050 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7051 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7052 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7053 TLI.isOperationLegal(ISD::Constant, VT)))
7054 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7057 // (conv (conv x, t1), t2) -> (conv x, t2)
7058 if (N0.getOpcode() == ISD::BITCAST)
7059 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7062 // fold (conv (load x)) -> (load (conv*)x)
7063 // If the resultant load doesn't need a higher alignment than the original!
7064 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7065 // Do not change the width of a volatile load.
7066 !cast<LoadSDNode>(N0)->isVolatile() &&
7067 // Do not remove the cast if the types differ in endian layout.
7068 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7069 TLI.hasBigEndianPartOrdering(VT) &&
7070 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7071 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7072 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7073 unsigned Align = TLI.getDataLayout()->
7074 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7075 unsigned OrigAlign = LN0->getAlignment();
7077 if (Align <= OrigAlign) {
7078 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7079 LN0->getBasePtr(), LN0->getPointerInfo(),
7080 LN0->isVolatile(), LN0->isNonTemporal(),
7081 LN0->isInvariant(), OrigAlign,
7083 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7088 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7089 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7090 // This often reduces constant pool loads.
7091 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7092 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7093 N0.getNode()->hasOneUse() && VT.isInteger() &&
7094 !VT.isVector() && !N0.getValueType().isVector()) {
7095 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7097 AddToWorklist(NewConv.getNode());
7100 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7101 if (N0.getOpcode() == ISD::FNEG)
7102 return DAG.getNode(ISD::XOR, DL, VT,
7103 NewConv, DAG.getConstant(SignBit, DL, VT));
7104 assert(N0.getOpcode() == ISD::FABS);
7105 return DAG.getNode(ISD::AND, DL, VT,
7106 NewConv, DAG.getConstant(~SignBit, DL, VT));
7109 // fold (bitconvert (fcopysign cst, x)) ->
7110 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7111 // Note that we don't handle (copysign x, cst) because this can always be
7112 // folded to an fneg or fabs.
7113 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7114 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7115 VT.isInteger() && !VT.isVector()) {
7116 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7117 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7118 if (isTypeLegal(IntXVT)) {
7119 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7120 IntXVT, N0.getOperand(1));
7121 AddToWorklist(X.getNode());
7123 // If X has a different width than the result/lhs, sext it or truncate it.
7124 unsigned VTWidth = VT.getSizeInBits();
7125 if (OrigXWidth < VTWidth) {
7126 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7127 AddToWorklist(X.getNode());
7128 } else if (OrigXWidth > VTWidth) {
7129 // To get the sign bit in the right place, we have to shift it right
7130 // before truncating.
7132 X = DAG.getNode(ISD::SRL, DL,
7133 X.getValueType(), X,
7134 DAG.getConstant(OrigXWidth-VTWidth, DL,
7136 AddToWorklist(X.getNode());
7137 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7138 AddToWorklist(X.getNode());
7141 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7142 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7143 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7144 AddToWorklist(X.getNode());
7146 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7147 VT, N0.getOperand(0));
7148 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7149 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7150 AddToWorklist(Cst.getNode());
7152 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7156 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7157 if (N0.getOpcode() == ISD::BUILD_PAIR) {
7158 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7159 if (CombineLD.getNode())
7163 // Remove double bitcasts from shuffles - this is often a legacy of
7164 // XformToShuffleWithZero being used to combine bitmaskings (of
7165 // float vectors bitcast to integer vectors) into shuffles.
7166 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7167 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7168 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7169 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7170 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7171 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7173 // If operands are a bitcast, peek through if it casts the original VT.
7174 // If operands are a UNDEF or constant, just bitcast back to original VT.
7175 auto PeekThroughBitcast = [&](SDValue Op) {
7176 if (Op.getOpcode() == ISD::BITCAST &&
7177 Op.getOperand(0)->getValueType(0) == VT)
7178 return SDValue(Op.getOperand(0));
7179 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7180 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7181 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7185 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7186 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7191 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7192 SmallVector<int, 8> NewMask;
7193 for (int M : SVN->getMask())
7194 for (int i = 0; i != MaskScale; ++i)
7195 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7197 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7199 std::swap(SV0, SV1);
7200 ShuffleVectorSDNode::commuteMask(NewMask);
7201 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7205 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7211 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7212 EVT VT = N->getValueType(0);
7213 return CombineConsecutiveLoads(N, VT);
7216 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7217 /// operands. DstEltVT indicates the destination element value type.
7218 SDValue DAGCombiner::
7219 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7220 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7222 // If this is already the right type, we're done.
7223 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7225 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7226 unsigned DstBitSize = DstEltVT.getSizeInBits();
7228 // If this is a conversion of N elements of one type to N elements of another
7229 // type, convert each element. This handles FP<->INT cases.
7230 if (SrcBitSize == DstBitSize) {
7231 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7232 BV->getValueType(0).getVectorNumElements());
7234 // Due to the FP element handling below calling this routine recursively,
7235 // we can end up with a scalar-to-vector node here.
7236 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7237 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7238 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7239 DstEltVT, BV->getOperand(0)));
7241 SmallVector<SDValue, 8> Ops;
7242 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7243 SDValue Op = BV->getOperand(i);
7244 // If the vector element type is not legal, the BUILD_VECTOR operands
7245 // are promoted and implicitly truncated. Make that explicit here.
7246 if (Op.getValueType() != SrcEltVT)
7247 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7248 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7250 AddToWorklist(Ops.back().getNode());
7252 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7255 // Otherwise, we're growing or shrinking the elements. To avoid having to
7256 // handle annoying details of growing/shrinking FP values, we convert them to
7258 if (SrcEltVT.isFloatingPoint()) {
7259 // Convert the input float vector to a int vector where the elements are the
7261 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7262 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7266 // Now we know the input is an integer vector. If the output is a FP type,
7267 // convert to integer first, then to FP of the right size.
7268 if (DstEltVT.isFloatingPoint()) {
7269 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7270 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7272 // Next, convert to FP elements of the same size.
7273 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7278 // Okay, we know the src/dst types are both integers of differing types.
7279 // Handling growing first.
7280 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7281 if (SrcBitSize < DstBitSize) {
7282 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7284 SmallVector<SDValue, 8> Ops;
7285 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7286 i += NumInputsPerOutput) {
7287 bool isLE = TLI.isLittleEndian();
7288 APInt NewBits = APInt(DstBitSize, 0);
7289 bool EltIsUndef = true;
7290 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7291 // Shift the previously computed bits over.
7292 NewBits <<= SrcBitSize;
7293 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7294 if (Op.getOpcode() == ISD::UNDEF) continue;
7297 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7298 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7302 Ops.push_back(DAG.getUNDEF(DstEltVT));
7304 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7307 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7308 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7311 // Finally, this must be the case where we are shrinking elements: each input
7312 // turns into multiple outputs.
7313 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7314 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7315 NumOutputsPerInput*BV->getNumOperands());
7316 SmallVector<SDValue, 8> Ops;
7318 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7319 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7320 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7324 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7325 getAPIntValue().zextOrTrunc(SrcBitSize);
7327 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7328 APInt ThisVal = OpVal.trunc(DstBitSize);
7329 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7330 OpVal = OpVal.lshr(DstBitSize);
7333 // For big endian targets, swap the order of the pieces of each element.
7334 if (TLI.isBigEndian())
7335 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7338 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7341 /// Try to perform FMA combining on a given FADD node.
7342 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7343 SDValue N0 = N->getOperand(0);
7344 SDValue N1 = N->getOperand(1);
7345 EVT VT = N->getValueType(0);
7348 const TargetOptions &Options = DAG.getTarget().Options;
7349 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7350 Options.UnsafeFPMath);
7352 // Floating-point multiply-add with intermediate rounding.
7353 bool HasFMAD = (LegalOperations &&
7354 TLI.isOperationLegal(ISD::FMAD, VT));
7356 // Floating-point multiply-add without intermediate rounding.
7357 bool HasFMA = ((!LegalOperations ||
7358 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7359 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7362 // No valid opcode, do not combine.
7363 if (!HasFMAD && !HasFMA)
7366 // Always prefer FMAD to FMA for precision.
7367 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7368 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7369 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7371 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7372 if (N0.getOpcode() == ISD::FMUL &&
7373 (Aggressive || N0->hasOneUse())) {
7374 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7375 N0.getOperand(0), N0.getOperand(1), N1);
7378 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7379 // Note: Commutes FADD operands.
7380 if (N1.getOpcode() == ISD::FMUL &&
7381 (Aggressive || N1->hasOneUse())) {
7382 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7383 N1.getOperand(0), N1.getOperand(1), N0);
7386 // Look through FP_EXTEND nodes to do more combining.
7387 if (UnsafeFPMath && LookThroughFPExt) {
7388 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7389 if (N0.getOpcode() == ISD::FP_EXTEND) {
7390 SDValue N00 = N0.getOperand(0);
7391 if (N00.getOpcode() == ISD::FMUL)
7392 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7393 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7395 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7396 N00.getOperand(1)), N1);
7399 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7400 // Note: Commutes FADD operands.
7401 if (N1.getOpcode() == ISD::FP_EXTEND) {
7402 SDValue N10 = N1.getOperand(0);
7403 if (N10.getOpcode() == ISD::FMUL)
7404 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7405 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7407 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7408 N10.getOperand(1)), N0);
7412 // More folding opportunities when target permits.
7413 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7414 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7415 if (N0.getOpcode() == PreferredFusedOpcode &&
7416 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7417 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7418 N0.getOperand(0), N0.getOperand(1),
7419 DAG.getNode(PreferredFusedOpcode, SL, VT,
7420 N0.getOperand(2).getOperand(0),
7421 N0.getOperand(2).getOperand(1),
7425 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7426 if (N1->getOpcode() == PreferredFusedOpcode &&
7427 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7428 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7429 N1.getOperand(0), N1.getOperand(1),
7430 DAG.getNode(PreferredFusedOpcode, SL, VT,
7431 N1.getOperand(2).getOperand(0),
7432 N1.getOperand(2).getOperand(1),
7436 if (UnsafeFPMath && LookThroughFPExt) {
7437 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7438 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7439 auto FoldFAddFMAFPExtFMul = [&] (
7440 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7441 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7442 DAG.getNode(PreferredFusedOpcode, SL, VT,
7443 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7444 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7447 if (N0.getOpcode() == PreferredFusedOpcode) {
7448 SDValue N02 = N0.getOperand(2);
7449 if (N02.getOpcode() == ISD::FP_EXTEND) {
7450 SDValue N020 = N02.getOperand(0);
7451 if (N020.getOpcode() == ISD::FMUL)
7452 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7453 N020.getOperand(0), N020.getOperand(1),
7458 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7459 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7460 // FIXME: This turns two single-precision and one double-precision
7461 // operation into two double-precision operations, which might not be
7462 // interesting for all targets, especially GPUs.
7463 auto FoldFAddFPExtFMAFMul = [&] (
7464 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7465 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7466 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7467 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7468 DAG.getNode(PreferredFusedOpcode, SL, VT,
7469 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7470 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7473 if (N0.getOpcode() == ISD::FP_EXTEND) {
7474 SDValue N00 = N0.getOperand(0);
7475 if (N00.getOpcode() == PreferredFusedOpcode) {
7476 SDValue N002 = N00.getOperand(2);
7477 if (N002.getOpcode() == ISD::FMUL)
7478 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7479 N002.getOperand(0), N002.getOperand(1),
7484 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7485 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7486 if (N1.getOpcode() == PreferredFusedOpcode) {
7487 SDValue N12 = N1.getOperand(2);
7488 if (N12.getOpcode() == ISD::FP_EXTEND) {
7489 SDValue N120 = N12.getOperand(0);
7490 if (N120.getOpcode() == ISD::FMUL)
7491 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7492 N120.getOperand(0), N120.getOperand(1),
7497 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7498 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7499 // FIXME: This turns two single-precision and one double-precision
7500 // operation into two double-precision operations, which might not be
7501 // interesting for all targets, especially GPUs.
7502 if (N1.getOpcode() == ISD::FP_EXTEND) {
7503 SDValue N10 = N1.getOperand(0);
7504 if (N10.getOpcode() == PreferredFusedOpcode) {
7505 SDValue N102 = N10.getOperand(2);
7506 if (N102.getOpcode() == ISD::FMUL)
7507 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7508 N102.getOperand(0), N102.getOperand(1),
7518 /// Try to perform FMA combining on a given FSUB node.
7519 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7520 SDValue N0 = N->getOperand(0);
7521 SDValue N1 = N->getOperand(1);
7522 EVT VT = N->getValueType(0);
7525 const TargetOptions &Options = DAG.getTarget().Options;
7526 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7527 Options.UnsafeFPMath);
7529 // Floating-point multiply-add with intermediate rounding.
7530 bool HasFMAD = (LegalOperations &&
7531 TLI.isOperationLegal(ISD::FMAD, VT));
7533 // Floating-point multiply-add without intermediate rounding.
7534 bool HasFMA = ((!LegalOperations ||
7535 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7536 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7539 // No valid opcode, do not combine.
7540 if (!HasFMAD && !HasFMA)
7543 // Always prefer FMAD to FMA for precision.
7544 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7545 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7546 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7548 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7549 if (N0.getOpcode() == ISD::FMUL &&
7550 (Aggressive || N0->hasOneUse())) {
7551 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7552 N0.getOperand(0), N0.getOperand(1),
7553 DAG.getNode(ISD::FNEG, SL, VT, N1));
7556 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7557 // Note: Commutes FSUB operands.
7558 if (N1.getOpcode() == ISD::FMUL &&
7559 (Aggressive || N1->hasOneUse()))
7560 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7561 DAG.getNode(ISD::FNEG, SL, VT,
7563 N1.getOperand(1), N0);
7565 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7566 if (N0.getOpcode() == ISD::FNEG &&
7567 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7568 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7569 SDValue N00 = N0.getOperand(0).getOperand(0);
7570 SDValue N01 = N0.getOperand(0).getOperand(1);
7571 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7572 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7573 DAG.getNode(ISD::FNEG, SL, VT, N1));
7576 // Look through FP_EXTEND nodes to do more combining.
7577 if (UnsafeFPMath && LookThroughFPExt) {
7578 // fold (fsub (fpext (fmul x, y)), z)
7579 // -> (fma (fpext x), (fpext y), (fneg z))
7580 if (N0.getOpcode() == ISD::FP_EXTEND) {
7581 SDValue N00 = N0.getOperand(0);
7582 if (N00.getOpcode() == ISD::FMUL)
7583 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7584 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7586 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7588 DAG.getNode(ISD::FNEG, SL, VT, N1));
7591 // fold (fsub x, (fpext (fmul y, z)))
7592 // -> (fma (fneg (fpext y)), (fpext z), x)
7593 // Note: Commutes FSUB operands.
7594 if (N1.getOpcode() == ISD::FP_EXTEND) {
7595 SDValue N10 = N1.getOperand(0);
7596 if (N10.getOpcode() == ISD::FMUL)
7597 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7598 DAG.getNode(ISD::FNEG, SL, VT,
7599 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7600 N10.getOperand(0))),
7601 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7606 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7607 // -> (fneg (fma (fpext x), (fpext y), z))
7608 // Note: This could be removed with appropriate canonicalization of the
7609 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7610 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7611 // from implementing the canonicalization in visitFSUB.
7612 if (N0.getOpcode() == ISD::FP_EXTEND) {
7613 SDValue N00 = N0.getOperand(0);
7614 if (N00.getOpcode() == ISD::FNEG) {
7615 SDValue N000 = N00.getOperand(0);
7616 if (N000.getOpcode() == ISD::FMUL) {
7617 return DAG.getNode(ISD::FNEG, SL, VT,
7618 DAG.getNode(PreferredFusedOpcode, SL, VT,
7619 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7620 N000.getOperand(0)),
7621 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7622 N000.getOperand(1)),
7628 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7629 // -> (fneg (fma (fpext x)), (fpext y), z)
7630 // Note: This could be removed with appropriate canonicalization of the
7631 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7632 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7633 // from implementing the canonicalization in visitFSUB.
7634 if (N0.getOpcode() == ISD::FNEG) {
7635 SDValue N00 = N0.getOperand(0);
7636 if (N00.getOpcode() == ISD::FP_EXTEND) {
7637 SDValue N000 = N00.getOperand(0);
7638 if (N000.getOpcode() == ISD::FMUL) {
7639 return DAG.getNode(ISD::FNEG, SL, VT,
7640 DAG.getNode(PreferredFusedOpcode, SL, VT,
7641 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7642 N000.getOperand(0)),
7643 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7644 N000.getOperand(1)),
7652 // More folding opportunities when target permits.
7653 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7654 // fold (fsub (fma x, y, (fmul u, v)), z)
7655 // -> (fma x, y (fma u, v, (fneg z)))
7656 if (N0.getOpcode() == PreferredFusedOpcode &&
7657 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7658 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7659 N0.getOperand(0), N0.getOperand(1),
7660 DAG.getNode(PreferredFusedOpcode, SL, VT,
7661 N0.getOperand(2).getOperand(0),
7662 N0.getOperand(2).getOperand(1),
7663 DAG.getNode(ISD::FNEG, SL, VT,
7667 // fold (fsub x, (fma y, z, (fmul u, v)))
7668 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7669 if (N1.getOpcode() == PreferredFusedOpcode &&
7670 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7671 SDValue N20 = N1.getOperand(2).getOperand(0);
7672 SDValue N21 = N1.getOperand(2).getOperand(1);
7673 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7674 DAG.getNode(ISD::FNEG, SL, VT,
7677 DAG.getNode(PreferredFusedOpcode, SL, VT,
7678 DAG.getNode(ISD::FNEG, SL, VT, N20),
7683 if (UnsafeFPMath && LookThroughFPExt) {
7684 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7685 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7686 if (N0.getOpcode() == PreferredFusedOpcode) {
7687 SDValue N02 = N0.getOperand(2);
7688 if (N02.getOpcode() == ISD::FP_EXTEND) {
7689 SDValue N020 = N02.getOperand(0);
7690 if (N020.getOpcode() == ISD::FMUL)
7691 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7692 N0.getOperand(0), N0.getOperand(1),
7693 DAG.getNode(PreferredFusedOpcode, SL, VT,
7694 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7695 N020.getOperand(0)),
7696 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7697 N020.getOperand(1)),
7698 DAG.getNode(ISD::FNEG, SL, VT,
7703 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7704 // -> (fma (fpext x), (fpext y),
7705 // (fma (fpext u), (fpext v), (fneg z)))
7706 // FIXME: This turns two single-precision and one double-precision
7707 // operation into two double-precision operations, which might not be
7708 // interesting for all targets, especially GPUs.
7709 if (N0.getOpcode() == ISD::FP_EXTEND) {
7710 SDValue N00 = N0.getOperand(0);
7711 if (N00.getOpcode() == PreferredFusedOpcode) {
7712 SDValue N002 = N00.getOperand(2);
7713 if (N002.getOpcode() == ISD::FMUL)
7714 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7715 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7717 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7719 DAG.getNode(PreferredFusedOpcode, SL, VT,
7720 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7721 N002.getOperand(0)),
7722 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7723 N002.getOperand(1)),
7724 DAG.getNode(ISD::FNEG, SL, VT,
7729 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7730 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7731 if (N1.getOpcode() == PreferredFusedOpcode &&
7732 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7733 SDValue N120 = N1.getOperand(2).getOperand(0);
7734 if (N120.getOpcode() == ISD::FMUL) {
7735 SDValue N1200 = N120.getOperand(0);
7736 SDValue N1201 = N120.getOperand(1);
7737 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7738 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7740 DAG.getNode(PreferredFusedOpcode, SL, VT,
7741 DAG.getNode(ISD::FNEG, SL, VT,
7742 DAG.getNode(ISD::FP_EXTEND, SL,
7744 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7750 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7751 // -> (fma (fneg (fpext y)), (fpext z),
7752 // (fma (fneg (fpext u)), (fpext v), x))
7753 // FIXME: This turns two single-precision and one double-precision
7754 // operation into two double-precision operations, which might not be
7755 // interesting for all targets, especially GPUs.
7756 if (N1.getOpcode() == ISD::FP_EXTEND &&
7757 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7758 SDValue N100 = N1.getOperand(0).getOperand(0);
7759 SDValue N101 = N1.getOperand(0).getOperand(1);
7760 SDValue N102 = N1.getOperand(0).getOperand(2);
7761 if (N102.getOpcode() == ISD::FMUL) {
7762 SDValue N1020 = N102.getOperand(0);
7763 SDValue N1021 = N102.getOperand(1);
7764 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7765 DAG.getNode(ISD::FNEG, SL, VT,
7766 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7768 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7769 DAG.getNode(PreferredFusedOpcode, SL, VT,
7770 DAG.getNode(ISD::FNEG, SL, VT,
7771 DAG.getNode(ISD::FP_EXTEND, SL,
7773 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7784 SDValue DAGCombiner::visitFADD(SDNode *N) {
7785 SDValue N0 = N->getOperand(0);
7786 SDValue N1 = N->getOperand(1);
7787 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7788 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7789 EVT VT = N->getValueType(0);
7791 const TargetOptions &Options = DAG.getTarget().Options;
7795 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7798 // fold (fadd c1, c2) -> c1 + c2
7800 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7802 // canonicalize constant to RHS
7803 if (N0CFP && !N1CFP)
7804 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7806 // fold (fadd A, (fneg B)) -> (fsub A, B)
7807 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7808 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7809 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7810 GetNegatedExpression(N1, DAG, LegalOperations));
7812 // fold (fadd (fneg A), B) -> (fsub B, A)
7813 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7814 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7815 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7816 GetNegatedExpression(N0, DAG, LegalOperations));
7818 // If 'unsafe math' is enabled, fold lots of things.
7819 if (Options.UnsafeFPMath) {
7820 // No FP constant should be created after legalization as Instruction
7821 // Selection pass has a hard time dealing with FP constants.
7822 bool AllowNewConst = (Level < AfterLegalizeDAG);
7824 // fold (fadd A, 0) -> A
7825 if (N1CFP && N1CFP->getValueAPF().isZero())
7828 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7829 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7830 isa<ConstantFPSDNode>(N0.getOperand(1)))
7831 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7832 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7834 // If allowed, fold (fadd (fneg x), x) -> 0.0
7835 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7836 return DAG.getConstantFP(0.0, DL, VT);
7838 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7839 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7840 return DAG.getConstantFP(0.0, DL, VT);
7842 // We can fold chains of FADD's of the same value into multiplications.
7843 // This transform is not safe in general because we are reducing the number
7844 // of rounding steps.
7845 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7846 if (N0.getOpcode() == ISD::FMUL) {
7847 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7848 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7850 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7851 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7852 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7853 DAG.getConstantFP(1.0, DL, VT));
7854 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7857 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7858 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7859 N1.getOperand(0) == N1.getOperand(1) &&
7860 N0.getOperand(0) == N1.getOperand(0)) {
7861 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7862 DAG.getConstantFP(2.0, DL, VT));
7863 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7867 if (N1.getOpcode() == ISD::FMUL) {
7868 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7869 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7871 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7872 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7873 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7874 DAG.getConstantFP(1.0, DL, VT));
7875 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7878 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7879 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7880 N0.getOperand(0) == N0.getOperand(1) &&
7881 N1.getOperand(0) == N0.getOperand(0)) {
7882 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7883 DAG.getConstantFP(2.0, DL, VT));
7884 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7888 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7889 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7890 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7891 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7892 (N0.getOperand(0) == N1)) {
7893 return DAG.getNode(ISD::FMUL, DL, VT,
7894 N1, DAG.getConstantFP(3.0, DL, VT));
7898 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7899 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7900 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7901 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7902 N1.getOperand(0) == N0) {
7903 return DAG.getNode(ISD::FMUL, DL, VT,
7904 N0, DAG.getConstantFP(3.0, DL, VT));
7908 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7909 if (AllowNewConst &&
7910 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7911 N0.getOperand(0) == N0.getOperand(1) &&
7912 N1.getOperand(0) == N1.getOperand(1) &&
7913 N0.getOperand(0) == N1.getOperand(0)) {
7914 return DAG.getNode(ISD::FMUL, DL, VT,
7915 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7918 } // enable-unsafe-fp-math
7920 // FADD -> FMA combines:
7921 SDValue Fused = visitFADDForFMACombine(N);
7923 AddToWorklist(Fused.getNode());
7930 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7931 SDValue N0 = N->getOperand(0);
7932 SDValue N1 = N->getOperand(1);
7933 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7934 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7935 EVT VT = N->getValueType(0);
7937 const TargetOptions &Options = DAG.getTarget().Options;
7941 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7944 // fold (fsub c1, c2) -> c1-c2
7946 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7948 // fold (fsub A, (fneg B)) -> (fadd A, B)
7949 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7950 return DAG.getNode(ISD::FADD, dl, VT, N0,
7951 GetNegatedExpression(N1, DAG, LegalOperations));
7953 // If 'unsafe math' is enabled, fold lots of things.
7954 if (Options.UnsafeFPMath) {
7956 if (N1CFP && N1CFP->getValueAPF().isZero())
7959 // (fsub 0, B) -> -B
7960 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7961 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7962 return GetNegatedExpression(N1, DAG, LegalOperations);
7963 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7964 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7967 // (fsub x, x) -> 0.0
7969 return DAG.getConstantFP(0.0f, dl, VT);
7971 // (fsub x, (fadd x, y)) -> (fneg y)
7972 // (fsub x, (fadd y, x)) -> (fneg y)
7973 if (N1.getOpcode() == ISD::FADD) {
7974 SDValue N10 = N1->getOperand(0);
7975 SDValue N11 = N1->getOperand(1);
7977 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7978 return GetNegatedExpression(N11, DAG, LegalOperations);
7980 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7981 return GetNegatedExpression(N10, DAG, LegalOperations);
7985 // FSUB -> FMA combines:
7986 SDValue Fused = visitFSUBForFMACombine(N);
7988 AddToWorklist(Fused.getNode());
7995 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7996 SDValue N0 = N->getOperand(0);
7997 SDValue N1 = N->getOperand(1);
7998 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7999 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8000 EVT VT = N->getValueType(0);
8002 const TargetOptions &Options = DAG.getTarget().Options;
8005 if (VT.isVector()) {
8006 // This just handles C1 * C2 for vectors. Other vector folds are below.
8007 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8011 // fold (fmul c1, c2) -> c1*c2
8013 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8015 // canonicalize constant to RHS
8016 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8017 !isConstantFPBuildVectorOrConstantFP(N1))
8018 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8020 // fold (fmul A, 1.0) -> A
8021 if (N1CFP && N1CFP->isExactlyValue(1.0))
8024 if (Options.UnsafeFPMath) {
8025 // fold (fmul A, 0) -> 0
8026 if (N1CFP && N1CFP->getValueAPF().isZero())
8029 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8030 if (N0.getOpcode() == ISD::FMUL) {
8031 // Fold scalars or any vector constants (not just splats).
8032 // This fold is done in general by InstCombine, but extra fmul insts
8033 // may have been generated during lowering.
8034 SDValue N00 = N0.getOperand(0);
8035 SDValue N01 = N0.getOperand(1);
8036 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8037 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8038 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8040 // Check 1: Make sure that the first operand of the inner multiply is NOT
8041 // a constant. Otherwise, we may induce infinite looping.
8042 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8043 // Check 2: Make sure that the second operand of the inner multiply and
8044 // the second operand of the outer multiply are constants.
8045 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8046 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8047 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8048 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8053 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8054 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8055 // during an early run of DAGCombiner can prevent folding with fmuls
8056 // inserted during lowering.
8057 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8058 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8059 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8060 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8064 // fold (fmul X, 2.0) -> (fadd X, X)
8065 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8066 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8068 // fold (fmul X, -1.0) -> (fneg X)
8069 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8070 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8071 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8073 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8074 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8075 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8076 // Both can be negated for free, check to see if at least one is cheaper
8078 if (LHSNeg == 2 || RHSNeg == 2)
8079 return DAG.getNode(ISD::FMUL, DL, VT,
8080 GetNegatedExpression(N0, DAG, LegalOperations),
8081 GetNegatedExpression(N1, DAG, LegalOperations));
8088 SDValue DAGCombiner::visitFMA(SDNode *N) {
8089 SDValue N0 = N->getOperand(0);
8090 SDValue N1 = N->getOperand(1);
8091 SDValue N2 = N->getOperand(2);
8092 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8093 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8094 EVT VT = N->getValueType(0);
8096 const TargetOptions &Options = DAG.getTarget().Options;
8098 // Constant fold FMA.
8099 if (isa<ConstantFPSDNode>(N0) &&
8100 isa<ConstantFPSDNode>(N1) &&
8101 isa<ConstantFPSDNode>(N2)) {
8102 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8105 if (Options.UnsafeFPMath) {
8106 if (N0CFP && N0CFP->isZero())
8108 if (N1CFP && N1CFP->isZero())
8111 if (N0CFP && N0CFP->isExactlyValue(1.0))
8112 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8113 if (N1CFP && N1CFP->isExactlyValue(1.0))
8114 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8116 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8117 if (N0CFP && !N1CFP)
8118 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8120 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8121 if (Options.UnsafeFPMath && N1CFP &&
8122 N2.getOpcode() == ISD::FMUL &&
8123 N0 == N2.getOperand(0) &&
8124 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8125 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8126 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8130 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8131 if (Options.UnsafeFPMath &&
8132 N0.getOpcode() == ISD::FMUL && N1CFP &&
8133 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8134 return DAG.getNode(ISD::FMA, dl, VT,
8136 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8140 // (fma x, 1, y) -> (fadd x, y)
8141 // (fma x, -1, y) -> (fadd (fneg x), y)
8143 if (N1CFP->isExactlyValue(1.0))
8144 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8146 if (N1CFP->isExactlyValue(-1.0) &&
8147 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8148 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8149 AddToWorklist(RHSNeg.getNode());
8150 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8154 // (fma x, c, x) -> (fmul x, (c+1))
8155 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8156 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8157 DAG.getNode(ISD::FADD, dl, VT,
8158 N1, DAG.getConstantFP(1.0, dl, VT)));
8160 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8161 if (Options.UnsafeFPMath && N1CFP &&
8162 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8163 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8164 DAG.getNode(ISD::FADD, dl, VT,
8165 N1, DAG.getConstantFP(-1.0, dl, VT)));
8171 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8172 SDValue N0 = N->getOperand(0);
8173 SDValue N1 = N->getOperand(1);
8174 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8175 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8176 EVT VT = N->getValueType(0);
8178 const TargetOptions &Options = DAG.getTarget().Options;
8182 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8185 // fold (fdiv c1, c2) -> c1/c2
8187 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8189 if (Options.UnsafeFPMath) {
8190 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8192 // Compute the reciprocal 1.0 / c2.
8193 APFloat N1APF = N1CFP->getValueAPF();
8194 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8195 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8196 // Only do the transform if the reciprocal is a legal fp immediate that
8197 // isn't too nasty (eg NaN, denormal, ...).
8198 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8199 (!LegalOperations ||
8200 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8201 // backend)... we should handle this gracefully after Legalize.
8202 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8203 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8204 TLI.isFPImmLegal(Recip, VT)))
8205 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8206 DAG.getConstantFP(Recip, DL, VT));
8209 // If this FDIV is part of a reciprocal square root, it may be folded
8210 // into a target-specific square root estimate instruction.
8211 if (N1.getOpcode() == ISD::FSQRT) {
8212 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8213 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8215 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8216 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8217 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8218 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8219 AddToWorklist(RV.getNode());
8220 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8222 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8223 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8224 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8225 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8226 AddToWorklist(RV.getNode());
8227 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8229 } else if (N1.getOpcode() == ISD::FMUL) {
8230 // Look through an FMUL. Even though this won't remove the FDIV directly,
8231 // it's still worthwhile to get rid of the FSQRT if possible.
8234 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8235 SqrtOp = N1.getOperand(0);
8236 OtherOp = N1.getOperand(1);
8237 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8238 SqrtOp = N1.getOperand(1);
8239 OtherOp = N1.getOperand(0);
8241 if (SqrtOp.getNode()) {
8242 // We found a FSQRT, so try to make this fold:
8243 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8244 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8245 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8246 AddToWorklist(RV.getNode());
8247 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8252 // Fold into a reciprocal estimate and multiply instead of a real divide.
8253 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8254 AddToWorklist(RV.getNode());
8255 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8259 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8260 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8261 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8262 // Both can be negated for free, check to see if at least one is cheaper
8264 if (LHSNeg == 2 || RHSNeg == 2)
8265 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8266 GetNegatedExpression(N0, DAG, LegalOperations),
8267 GetNegatedExpression(N1, DAG, LegalOperations));
8271 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8273 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8274 // Notice that this is not always beneficial. One reason is different target
8275 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8276 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8277 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8278 if (Options.UnsafeFPMath) {
8279 // Skip if current node is a reciprocal.
8280 if (N0CFP && N0CFP->isExactlyValue(1.0))
8283 SmallVector<SDNode *, 4> Users;
8284 // Find all FDIV users of the same divisor.
8285 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8286 UE = N1.getNode()->use_end();
8288 SDNode *User = UI.getUse().getUser();
8289 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8290 Users.push_back(User);
8293 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8295 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8296 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8298 // Dividend / Divisor -> Dividend * Reciprocal
8299 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8300 if ((*I)->getOperand(0) != FPOne) {
8301 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8302 (*I)->getOperand(0), Reciprocal);
8303 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8313 SDValue DAGCombiner::visitFREM(SDNode *N) {
8314 SDValue N0 = N->getOperand(0);
8315 SDValue N1 = N->getOperand(1);
8316 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8317 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8318 EVT VT = N->getValueType(0);
8320 // fold (frem c1, c2) -> fmod(c1,c2)
8322 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8327 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8328 if (DAG.getTarget().Options.UnsafeFPMath &&
8329 !TLI.isFsqrtCheap()) {
8330 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8331 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8332 EVT VT = RV.getValueType();
8334 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8335 AddToWorklist(RV.getNode());
8337 // Unfortunately, RV is now NaN if the input was exactly 0.
8338 // Select out this case and force the answer to 0.
8339 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8341 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8342 N->getOperand(0), Zero, ISD::SETEQ);
8343 AddToWorklist(ZeroCmp.getNode());
8344 AddToWorklist(RV.getNode());
8346 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8347 DL, VT, ZeroCmp, Zero, RV);
8354 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8355 SDValue N0 = N->getOperand(0);
8356 SDValue N1 = N->getOperand(1);
8357 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8358 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8359 EVT VT = N->getValueType(0);
8361 if (N0CFP && N1CFP) // Constant fold
8362 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8365 const APFloat& V = N1CFP->getValueAPF();
8366 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8367 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8368 if (!V.isNegative()) {
8369 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8370 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8372 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8373 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8374 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8378 // copysign(fabs(x), y) -> copysign(x, y)
8379 // copysign(fneg(x), y) -> copysign(x, y)
8380 // copysign(copysign(x,z), y) -> copysign(x, y)
8381 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8382 N0.getOpcode() == ISD::FCOPYSIGN)
8383 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8384 N0.getOperand(0), N1);
8386 // copysign(x, abs(y)) -> abs(x)
8387 if (N1.getOpcode() == ISD::FABS)
8388 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8390 // copysign(x, copysign(y,z)) -> copysign(x, z)
8391 if (N1.getOpcode() == ISD::FCOPYSIGN)
8392 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8393 N0, N1.getOperand(1));
8395 // copysign(x, fp_extend(y)) -> copysign(x, y)
8396 // copysign(x, fp_round(y)) -> copysign(x, y)
8397 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8398 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8399 N0, N1.getOperand(0));
8404 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8405 SDValue N0 = N->getOperand(0);
8406 EVT VT = N->getValueType(0);
8407 EVT OpVT = N0.getValueType();
8409 // fold (sint_to_fp c1) -> c1fp
8410 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8411 // ...but only if the target supports immediate floating-point values
8412 (!LegalOperations ||
8413 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8414 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8416 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8417 // but UINT_TO_FP is legal on this target, try to convert.
8418 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8419 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8420 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8421 if (DAG.SignBitIsZero(N0))
8422 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8425 // The next optimizations are desirable only if SELECT_CC can be lowered.
8426 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8427 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8428 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8430 (!LegalOperations ||
8431 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8434 { N0.getOperand(0), N0.getOperand(1),
8435 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8437 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8440 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8441 // (select_cc x, y, 1.0, 0.0,, cc)
8442 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8443 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8444 (!LegalOperations ||
8445 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8448 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8449 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8450 N0.getOperand(0).getOperand(2) };
8451 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8458 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8459 SDValue N0 = N->getOperand(0);
8460 EVT VT = N->getValueType(0);
8461 EVT OpVT = N0.getValueType();
8463 // fold (uint_to_fp c1) -> c1fp
8464 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8465 // ...but only if the target supports immediate floating-point values
8466 (!LegalOperations ||
8467 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8468 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8470 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8471 // but SINT_TO_FP is legal on this target, try to convert.
8472 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8473 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8474 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8475 if (DAG.SignBitIsZero(N0))
8476 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8479 // The next optimizations are desirable only if SELECT_CC can be lowered.
8480 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8481 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8483 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8484 (!LegalOperations ||
8485 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8488 { N0.getOperand(0), N0.getOperand(1),
8489 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8491 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8498 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8499 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8500 SDValue N0 = N->getOperand(0);
8501 EVT VT = N->getValueType(0);
8503 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8506 SDValue Src = N0.getOperand(0);
8507 EVT SrcVT = Src.getValueType();
8508 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8509 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8511 // We can safely assume the conversion won't overflow the output range,
8512 // because (for example) (uint8_t)18293.f is undefined behavior.
8514 // Since we can assume the conversion won't overflow, our decision as to
8515 // whether the input will fit in the float should depend on the minimum
8516 // of the input range and output range.
8518 // This means this is also safe for a signed input and unsigned output, since
8519 // a negative input would lead to undefined behavior.
8520 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8521 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8522 unsigned ActualSize = std::min(InputSize, OutputSize);
8523 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8525 // We can only fold away the float conversion if the input range can be
8526 // represented exactly in the float range.
8527 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8528 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8529 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8531 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8533 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8534 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8537 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8542 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8543 SDValue N0 = N->getOperand(0);
8544 EVT VT = N->getValueType(0);
8546 // fold (fp_to_sint c1fp) -> c1
8547 if (isConstantFPBuildVectorOrConstantFP(N0))
8548 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8550 return FoldIntToFPToInt(N, DAG);
8553 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8554 SDValue N0 = N->getOperand(0);
8555 EVT VT = N->getValueType(0);
8557 // fold (fp_to_uint c1fp) -> c1
8558 if (isConstantFPBuildVectorOrConstantFP(N0))
8559 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8561 return FoldIntToFPToInt(N, DAG);
8564 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8565 SDValue N0 = N->getOperand(0);
8566 SDValue N1 = N->getOperand(1);
8567 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8568 EVT VT = N->getValueType(0);
8570 // fold (fp_round c1fp) -> c1fp
8572 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8574 // fold (fp_round (fp_extend x)) -> x
8575 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8576 return N0.getOperand(0);
8578 // fold (fp_round (fp_round x)) -> (fp_round x)
8579 if (N0.getOpcode() == ISD::FP_ROUND) {
8580 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8581 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8582 // If the first fp_round isn't a value preserving truncation, it might
8583 // introduce a tie in the second fp_round, that wouldn't occur in the
8584 // single-step fp_round we want to fold to.
8585 // In other words, double rounding isn't the same as rounding.
8586 // Also, this is a value preserving truncation iff both fp_round's are.
8587 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8589 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8590 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8594 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8595 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8596 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8597 N0.getOperand(0), N1);
8598 AddToWorklist(Tmp.getNode());
8599 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8600 Tmp, N0.getOperand(1));
8606 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8607 SDValue N0 = N->getOperand(0);
8608 EVT VT = N->getValueType(0);
8609 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8610 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8612 // fold (fp_round_inreg c1fp) -> c1fp
8613 if (N0CFP && isTypeLegal(EVT)) {
8615 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8616 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8622 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8623 SDValue N0 = N->getOperand(0);
8624 EVT VT = N->getValueType(0);
8626 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8627 if (N->hasOneUse() &&
8628 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8631 // fold (fp_extend c1fp) -> c1fp
8632 if (isConstantFPBuildVectorOrConstantFP(N0))
8633 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8635 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8636 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8637 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8638 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8640 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8642 if (N0.getOpcode() == ISD::FP_ROUND
8643 && N0.getNode()->getConstantOperandVal(1) == 1) {
8644 SDValue In = N0.getOperand(0);
8645 if (In.getValueType() == VT) return In;
8646 if (VT.bitsLT(In.getValueType()))
8647 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8648 In, N0.getOperand(1));
8649 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8652 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8653 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8654 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8655 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8656 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8658 LN0->getBasePtr(), N0.getValueType(),
8659 LN0->getMemOperand());
8660 CombineTo(N, ExtLoad);
8661 CombineTo(N0.getNode(),
8662 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8663 N0.getValueType(), ExtLoad,
8664 DAG.getIntPtrConstant(1, SDLoc(N0))),
8665 ExtLoad.getValue(1));
8666 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8672 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8673 SDValue N0 = N->getOperand(0);
8674 EVT VT = N->getValueType(0);
8676 // fold (fceil c1) -> fceil(c1)
8677 if (isConstantFPBuildVectorOrConstantFP(N0))
8678 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8683 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8684 SDValue N0 = N->getOperand(0);
8685 EVT VT = N->getValueType(0);
8687 // fold (ftrunc c1) -> ftrunc(c1)
8688 if (isConstantFPBuildVectorOrConstantFP(N0))
8689 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8694 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8695 SDValue N0 = N->getOperand(0);
8696 EVT VT = N->getValueType(0);
8698 // fold (ffloor c1) -> ffloor(c1)
8699 if (isConstantFPBuildVectorOrConstantFP(N0))
8700 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8705 // FIXME: FNEG and FABS have a lot in common; refactor.
8706 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8707 SDValue N0 = N->getOperand(0);
8708 EVT VT = N->getValueType(0);
8710 // Constant fold FNEG.
8711 if (isConstantFPBuildVectorOrConstantFP(N0))
8712 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8714 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8715 &DAG.getTarget().Options))
8716 return GetNegatedExpression(N0, DAG, LegalOperations);
8718 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8719 // constant pool values.
8720 if (!TLI.isFNegFree(VT) &&
8721 N0.getOpcode() == ISD::BITCAST &&
8722 N0.getNode()->hasOneUse()) {
8723 SDValue Int = N0.getOperand(0);
8724 EVT IntVT = Int.getValueType();
8725 if (IntVT.isInteger() && !IntVT.isVector()) {
8727 if (N0.getValueType().isVector()) {
8728 // For a vector, get a mask such as 0x80... per scalar element
8730 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8731 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8733 // For a scalar, just generate 0x80...
8734 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8737 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8738 DAG.getConstant(SignMask, DL0, IntVT));
8739 AddToWorklist(Int.getNode());
8740 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8744 // (fneg (fmul c, x)) -> (fmul -c, x)
8745 if (N0.getOpcode() == ISD::FMUL) {
8746 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8748 APFloat CVal = CFP1->getValueAPF();
8750 if (Level >= AfterLegalizeDAG &&
8751 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8752 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8754 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8755 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8762 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8763 SDValue N0 = N->getOperand(0);
8764 SDValue N1 = N->getOperand(1);
8765 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8766 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8768 if (N0CFP && N1CFP) {
8769 const APFloat &C0 = N0CFP->getValueAPF();
8770 const APFloat &C1 = N1CFP->getValueAPF();
8771 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8775 EVT VT = N->getValueType(0);
8776 // Canonicalize to constant on RHS.
8777 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8783 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8784 SDValue N0 = N->getOperand(0);
8785 SDValue N1 = N->getOperand(1);
8786 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8787 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8789 if (N0CFP && N1CFP) {
8790 const APFloat &C0 = N0CFP->getValueAPF();
8791 const APFloat &C1 = N1CFP->getValueAPF();
8792 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8796 EVT VT = N->getValueType(0);
8797 // Canonicalize to constant on RHS.
8798 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8804 SDValue DAGCombiner::visitFABS(SDNode *N) {
8805 SDValue N0 = N->getOperand(0);
8806 EVT VT = N->getValueType(0);
8808 // fold (fabs c1) -> fabs(c1)
8809 if (isConstantFPBuildVectorOrConstantFP(N0))
8810 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8812 // fold (fabs (fabs x)) -> (fabs x)
8813 if (N0.getOpcode() == ISD::FABS)
8814 return N->getOperand(0);
8816 // fold (fabs (fneg x)) -> (fabs x)
8817 // fold (fabs (fcopysign x, y)) -> (fabs x)
8818 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8819 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8821 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8822 // constant pool values.
8823 if (!TLI.isFAbsFree(VT) &&
8824 N0.getOpcode() == ISD::BITCAST &&
8825 N0.getNode()->hasOneUse()) {
8826 SDValue Int = N0.getOperand(0);
8827 EVT IntVT = Int.getValueType();
8828 if (IntVT.isInteger() && !IntVT.isVector()) {
8830 if (N0.getValueType().isVector()) {
8831 // For a vector, get a mask such as 0x7f... per scalar element
8833 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8834 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8836 // For a scalar, just generate 0x7f...
8837 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8840 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8841 DAG.getConstant(SignMask, DL, IntVT));
8842 AddToWorklist(Int.getNode());
8843 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8850 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8851 SDValue Chain = N->getOperand(0);
8852 SDValue N1 = N->getOperand(1);
8853 SDValue N2 = N->getOperand(2);
8855 // If N is a constant we could fold this into a fallthrough or unconditional
8856 // branch. However that doesn't happen very often in normal code, because
8857 // Instcombine/SimplifyCFG should have handled the available opportunities.
8858 // If we did this folding here, it would be necessary to update the
8859 // MachineBasicBlock CFG, which is awkward.
8861 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8863 if (N1.getOpcode() == ISD::SETCC &&
8864 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8865 N1.getOperand(0).getValueType())) {
8866 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8867 Chain, N1.getOperand(2),
8868 N1.getOperand(0), N1.getOperand(1), N2);
8871 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8872 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8873 (N1.getOperand(0).hasOneUse() &&
8874 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8875 SDNode *Trunc = nullptr;
8876 if (N1.getOpcode() == ISD::TRUNCATE) {
8877 // Look pass the truncate.
8878 Trunc = N1.getNode();
8879 N1 = N1.getOperand(0);
8882 // Match this pattern so that we can generate simpler code:
8885 // %b = and i32 %a, 2
8886 // %c = srl i32 %b, 1
8887 // brcond i32 %c ...
8892 // %b = and i32 %a, 2
8893 // %c = setcc eq %b, 0
8896 // This applies only when the AND constant value has one bit set and the
8897 // SRL constant is equal to the log2 of the AND constant. The back-end is
8898 // smart enough to convert the result into a TEST/JMP sequence.
8899 SDValue Op0 = N1.getOperand(0);
8900 SDValue Op1 = N1.getOperand(1);
8902 if (Op0.getOpcode() == ISD::AND &&
8903 Op1.getOpcode() == ISD::Constant) {
8904 SDValue AndOp1 = Op0.getOperand(1);
8906 if (AndOp1.getOpcode() == ISD::Constant) {
8907 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8909 if (AndConst.isPowerOf2() &&
8910 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8914 getSetCCResultType(Op0.getValueType()),
8915 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8918 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8919 MVT::Other, Chain, SetCC, N2);
8920 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8921 // will convert it back to (X & C1) >> C2.
8922 CombineTo(N, NewBRCond, false);
8923 // Truncate is dead.
8925 deleteAndRecombine(Trunc);
8926 // Replace the uses of SRL with SETCC
8927 WorklistRemover DeadNodes(*this);
8928 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8929 deleteAndRecombine(N1.getNode());
8930 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8936 // Restore N1 if the above transformation doesn't match.
8937 N1 = N->getOperand(1);
8940 // Transform br(xor(x, y)) -> br(x != y)
8941 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8942 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8943 SDNode *TheXor = N1.getNode();
8944 SDValue Op0 = TheXor->getOperand(0);
8945 SDValue Op1 = TheXor->getOperand(1);
8946 if (Op0.getOpcode() == Op1.getOpcode()) {
8947 // Avoid missing important xor optimizations.
8948 SDValue Tmp = visitXOR(TheXor);
8949 if (Tmp.getNode()) {
8950 if (Tmp.getNode() != TheXor) {
8951 DEBUG(dbgs() << "\nReplacing.8 ";
8953 dbgs() << "\nWith: ";
8954 Tmp.getNode()->dump(&DAG);
8956 WorklistRemover DeadNodes(*this);
8957 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8958 deleteAndRecombine(TheXor);
8959 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8960 MVT::Other, Chain, Tmp, N2);
8963 // visitXOR has changed XOR's operands or replaced the XOR completely,
8965 return SDValue(N, 0);
8969 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8971 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8972 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8973 Op0.getOpcode() == ISD::XOR) {
8974 TheXor = Op0.getNode();
8978 EVT SetCCVT = N1.getValueType();
8980 SetCCVT = getSetCCResultType(SetCCVT);
8981 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8984 Equal ? ISD::SETEQ : ISD::SETNE);
8985 // Replace the uses of XOR with SETCC
8986 WorklistRemover DeadNodes(*this);
8987 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8988 deleteAndRecombine(N1.getNode());
8989 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8990 MVT::Other, Chain, SetCC, N2);
8997 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8999 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9000 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9001 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9003 // If N is a constant we could fold this into a fallthrough or unconditional
9004 // branch. However that doesn't happen very often in normal code, because
9005 // Instcombine/SimplifyCFG should have handled the available opportunities.
9006 // If we did this folding here, it would be necessary to update the
9007 // MachineBasicBlock CFG, which is awkward.
9009 // Use SimplifySetCC to simplify SETCC's.
9010 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9011 CondLHS, CondRHS, CC->get(), SDLoc(N),
9013 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9015 // fold to a simpler setcc
9016 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9017 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9018 N->getOperand(0), Simp.getOperand(2),
9019 Simp.getOperand(0), Simp.getOperand(1),
9025 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9026 /// and that N may be folded in the load / store addressing mode.
9027 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9029 const TargetLowering &TLI) {
9031 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9032 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9034 VT = LD->getMemoryVT();
9035 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9036 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9038 VT = ST->getMemoryVT();
9042 TargetLowering::AddrMode AM;
9043 if (N->getOpcode() == ISD::ADD) {
9044 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9047 AM.BaseOffs = Offset->getSExtValue();
9051 } else if (N->getOpcode() == ISD::SUB) {
9052 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9055 AM.BaseOffs = -Offset->getSExtValue();
9062 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9065 /// Try turning a load/store into a pre-indexed load/store when the base
9066 /// pointer is an add or subtract and it has other uses besides the load/store.
9067 /// After the transformation, the new indexed load/store has effectively folded
9068 /// the add/subtract in and all of its other uses are redirected to the
9070 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9071 if (Level < AfterLegalizeDAG)
9077 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9078 if (LD->isIndexed())
9080 VT = LD->getMemoryVT();
9081 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9082 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9084 Ptr = LD->getBasePtr();
9085 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9086 if (ST->isIndexed())
9088 VT = ST->getMemoryVT();
9089 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9090 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9092 Ptr = ST->getBasePtr();
9098 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9099 // out. There is no reason to make this a preinc/predec.
9100 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9101 Ptr.getNode()->hasOneUse())
9104 // Ask the target to do addressing mode selection.
9107 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9108 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9111 // Backends without true r+i pre-indexed forms may need to pass a
9112 // constant base with a variable offset so that constant coercion
9113 // will work with the patterns in canonical form.
9114 bool Swapped = false;
9115 if (isa<ConstantSDNode>(BasePtr)) {
9116 std::swap(BasePtr, Offset);
9120 // Don't create a indexed load / store with zero offset.
9121 if (isNullConstant(Offset))
9124 // Try turning it into a pre-indexed load / store except when:
9125 // 1) The new base ptr is a frame index.
9126 // 2) If N is a store and the new base ptr is either the same as or is a
9127 // predecessor of the value being stored.
9128 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9129 // that would create a cycle.
9130 // 4) All uses are load / store ops that use it as old base ptr.
9132 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9133 // (plus the implicit offset) to a register to preinc anyway.
9134 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9139 SDValue Val = cast<StoreSDNode>(N)->getValue();
9140 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9144 // If the offset is a constant, there may be other adds of constants that
9145 // can be folded with this one. We should do this to avoid having to keep
9146 // a copy of the original base pointer.
9147 SmallVector<SDNode *, 16> OtherUses;
9148 if (isa<ConstantSDNode>(Offset))
9149 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9150 UE = BasePtr.getNode()->use_end();
9152 SDUse &Use = UI.getUse();
9153 // Skip the use that is Ptr and uses of other results from BasePtr's
9154 // node (important for nodes that return multiple results).
9155 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9158 if (Use.getUser()->isPredecessorOf(N))
9161 if (Use.getUser()->getOpcode() != ISD::ADD &&
9162 Use.getUser()->getOpcode() != ISD::SUB) {
9167 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9168 if (!isa<ConstantSDNode>(Op1)) {
9173 // FIXME: In some cases, we can be smarter about this.
9174 if (Op1.getValueType() != Offset.getValueType()) {
9179 OtherUses.push_back(Use.getUser());
9183 std::swap(BasePtr, Offset);
9185 // Now check for #3 and #4.
9186 bool RealUse = false;
9188 // Caches for hasPredecessorHelper
9189 SmallPtrSet<const SDNode *, 32> Visited;
9190 SmallVector<const SDNode *, 16> Worklist;
9192 for (SDNode *Use : Ptr.getNode()->uses()) {
9195 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9198 // If Ptr may be folded in addressing mode of other use, then it's
9199 // not profitable to do this transformation.
9200 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9209 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9210 BasePtr, Offset, AM);
9212 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9213 BasePtr, Offset, AM);
9216 DEBUG(dbgs() << "\nReplacing.4 ";
9218 dbgs() << "\nWith: ";
9219 Result.getNode()->dump(&DAG);
9221 WorklistRemover DeadNodes(*this);
9223 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9224 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9226 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9229 // Finally, since the node is now dead, remove it from the graph.
9230 deleteAndRecombine(N);
9233 std::swap(BasePtr, Offset);
9235 // Replace other uses of BasePtr that can be updated to use Ptr
9236 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9237 unsigned OffsetIdx = 1;
9238 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9240 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9241 BasePtr.getNode() && "Expected BasePtr operand");
9243 // We need to replace ptr0 in the following expression:
9244 // x0 * offset0 + y0 * ptr0 = t0
9246 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9248 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9249 // indexed load/store and the expresion that needs to be re-written.
9251 // Therefore, we have:
9252 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9254 ConstantSDNode *CN =
9255 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9257 APInt Offset0 = CN->getAPIntValue();
9258 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9260 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9261 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9262 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9263 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9265 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9267 APInt CNV = Offset0;
9268 if (X0 < 0) CNV = -CNV;
9269 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9270 else CNV = CNV - Offset1;
9272 SDLoc DL(OtherUses[i]);
9274 // We can now generate the new expression.
9275 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9276 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9278 SDValue NewUse = DAG.getNode(Opcode,
9280 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9281 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9282 deleteAndRecombine(OtherUses[i]);
9285 // Replace the uses of Ptr with uses of the updated base value.
9286 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9287 deleteAndRecombine(Ptr.getNode());
9292 /// Try to combine a load/store with a add/sub of the base pointer node into a
9293 /// post-indexed load/store. The transformation folded the add/subtract into the
9294 /// new indexed load/store effectively and all of its uses are redirected to the
9296 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9297 if (Level < AfterLegalizeDAG)
9303 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9304 if (LD->isIndexed())
9306 VT = LD->getMemoryVT();
9307 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9308 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9310 Ptr = LD->getBasePtr();
9311 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9312 if (ST->isIndexed())
9314 VT = ST->getMemoryVT();
9315 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9316 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9318 Ptr = ST->getBasePtr();
9324 if (Ptr.getNode()->hasOneUse())
9327 for (SDNode *Op : Ptr.getNode()->uses()) {
9329 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9334 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9335 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9336 // Don't create a indexed load / store with zero offset.
9337 if (isNullConstant(Offset))
9340 // Try turning it into a post-indexed load / store except when
9341 // 1) All uses are load / store ops that use it as base ptr (and
9342 // it may be folded as addressing mmode).
9343 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9344 // nor a successor of N. Otherwise, if Op is folded that would
9347 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9351 bool TryNext = false;
9352 for (SDNode *Use : BasePtr.getNode()->uses()) {
9353 if (Use == Ptr.getNode())
9356 // If all the uses are load / store addresses, then don't do the
9358 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9359 bool RealUse = false;
9360 for (SDNode *UseUse : Use->uses()) {
9361 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9376 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9377 SDValue Result = isLoad
9378 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9379 BasePtr, Offset, AM)
9380 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9381 BasePtr, Offset, AM);
9384 DEBUG(dbgs() << "\nReplacing.5 ";
9386 dbgs() << "\nWith: ";
9387 Result.getNode()->dump(&DAG);
9389 WorklistRemover DeadNodes(*this);
9391 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9392 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9394 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9397 // Finally, since the node is now dead, remove it from the graph.
9398 deleteAndRecombine(N);
9400 // Replace the uses of Use with uses of the updated base value.
9401 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9402 Result.getValue(isLoad ? 1 : 0));
9403 deleteAndRecombine(Op);
9412 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9413 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9414 ISD::MemIndexedMode AM = LD->getAddressingMode();
9415 assert(AM != ISD::UNINDEXED);
9416 SDValue BP = LD->getOperand(1);
9417 SDValue Inc = LD->getOperand(2);
9419 // Some backends use TargetConstants for load offsets, but don't expect
9420 // TargetConstants in general ADD nodes. We can convert these constants into
9421 // regular Constants (if the constant is not opaque).
9422 assert((Inc.getOpcode() != ISD::TargetConstant ||
9423 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9424 "Cannot split out indexing using opaque target constants");
9425 if (Inc.getOpcode() == ISD::TargetConstant) {
9426 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9427 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9428 ConstInc->getValueType(0));
9432 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9433 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9436 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9437 LoadSDNode *LD = cast<LoadSDNode>(N);
9438 SDValue Chain = LD->getChain();
9439 SDValue Ptr = LD->getBasePtr();
9441 // If load is not volatile and there are no uses of the loaded value (and
9442 // the updated indexed value in case of indexed loads), change uses of the
9443 // chain value into uses of the chain input (i.e. delete the dead load).
9444 if (!LD->isVolatile()) {
9445 if (N->getValueType(1) == MVT::Other) {
9447 if (!N->hasAnyUseOfValue(0)) {
9448 // It's not safe to use the two value CombineTo variant here. e.g.
9449 // v1, chain2 = load chain1, loc
9450 // v2, chain3 = load chain2, loc
9452 // Now we replace use of chain2 with chain1. This makes the second load
9453 // isomorphic to the one we are deleting, and thus makes this load live.
9454 DEBUG(dbgs() << "\nReplacing.6 ";
9456 dbgs() << "\nWith chain: ";
9457 Chain.getNode()->dump(&DAG);
9459 WorklistRemover DeadNodes(*this);
9460 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9463 deleteAndRecombine(N);
9465 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9469 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9471 // If this load has an opaque TargetConstant offset, then we cannot split
9472 // the indexing into an add/sub directly (that TargetConstant may not be
9473 // valid for a different type of node, and we cannot convert an opaque
9474 // target constant into a regular constant).
9475 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9476 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9478 if (!N->hasAnyUseOfValue(0) &&
9479 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9480 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9482 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9483 Index = SplitIndexingFromLoad(LD);
9484 // Try to fold the base pointer arithmetic into subsequent loads and
9486 AddUsersToWorklist(N);
9488 Index = DAG.getUNDEF(N->getValueType(1));
9489 DEBUG(dbgs() << "\nReplacing.7 ";
9491 dbgs() << "\nWith: ";
9492 Undef.getNode()->dump(&DAG);
9493 dbgs() << " and 2 other values\n");
9494 WorklistRemover DeadNodes(*this);
9495 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9496 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9497 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9498 deleteAndRecombine(N);
9499 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9504 // If this load is directly stored, replace the load value with the stored
9506 // TODO: Handle store large -> read small portion.
9507 // TODO: Handle TRUNCSTORE/LOADEXT
9508 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9509 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9510 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9511 if (PrevST->getBasePtr() == Ptr &&
9512 PrevST->getValue().getValueType() == N->getValueType(0))
9513 return CombineTo(N, Chain.getOperand(1), Chain);
9517 // Try to infer better alignment information than the load already has.
9518 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9519 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9520 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9522 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9523 LD->getValueType(0),
9524 Chain, Ptr, LD->getPointerInfo(),
9526 LD->isVolatile(), LD->isNonTemporal(),
9527 LD->isInvariant(), Align, LD->getAAInfo());
9528 if (NewLoad.getNode() != N)
9529 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9534 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9535 : DAG.getSubtarget().useAA();
9537 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9538 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9541 if (UseAA && LD->isUnindexed()) {
9542 // Walk up chain skipping non-aliasing memory nodes.
9543 SDValue BetterChain = FindBetterChain(N, Chain);
9545 // If there is a better chain.
9546 if (Chain != BetterChain) {
9549 // Replace the chain to void dependency.
9550 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9551 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9552 BetterChain, Ptr, LD->getMemOperand());
9554 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9555 LD->getValueType(0),
9556 BetterChain, Ptr, LD->getMemoryVT(),
9557 LD->getMemOperand());
9560 // Create token factor to keep old chain connected.
9561 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9562 MVT::Other, Chain, ReplLoad.getValue(1));
9564 // Make sure the new and old chains are cleaned up.
9565 AddToWorklist(Token.getNode());
9567 // Replace uses with load result and token factor. Don't add users
9569 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9573 // Try transforming N to an indexed load.
9574 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9575 return SDValue(N, 0);
9577 // Try to slice up N to more direct loads if the slices are mapped to
9578 // different register banks or pairing can take place.
9580 return SDValue(N, 0);
9586 /// \brief Helper structure used to slice a load in smaller loads.
9587 /// Basically a slice is obtained from the following sequence:
9588 /// Origin = load Ty1, Base
9589 /// Shift = srl Ty1 Origin, CstTy Amount
9590 /// Inst = trunc Shift to Ty2
9592 /// Then, it will be rewriten into:
9593 /// Slice = load SliceTy, Base + SliceOffset
9594 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9596 /// SliceTy is deduced from the number of bits that are actually used to
9598 struct LoadedSlice {
9599 /// \brief Helper structure used to compute the cost of a slice.
9601 /// Are we optimizing for code size.
9606 unsigned CrossRegisterBanksCopies;
9610 Cost(bool ForCodeSize = false)
9611 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9612 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9614 /// \brief Get the cost of one isolated slice.
9615 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9616 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9617 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9618 EVT TruncType = LS.Inst->getValueType(0);
9619 EVT LoadedType = LS.getLoadedType();
9620 if (TruncType != LoadedType &&
9621 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9625 /// \brief Account for slicing gain in the current cost.
9626 /// Slicing provide a few gains like removing a shift or a
9627 /// truncate. This method allows to grow the cost of the original
9628 /// load with the gain from this slice.
9629 void addSliceGain(const LoadedSlice &LS) {
9630 // Each slice saves a truncate.
9631 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9632 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9633 LS.Inst->getOperand(0).getValueType()))
9635 // If there is a shift amount, this slice gets rid of it.
9638 // If this slice can merge a cross register bank copy, account for it.
9639 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9640 ++CrossRegisterBanksCopies;
9643 Cost &operator+=(const Cost &RHS) {
9645 Truncates += RHS.Truncates;
9646 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9652 bool operator==(const Cost &RHS) const {
9653 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9654 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9655 ZExts == RHS.ZExts && Shift == RHS.Shift;
9658 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9660 bool operator<(const Cost &RHS) const {
9661 // Assume cross register banks copies are as expensive as loads.
9662 // FIXME: Do we want some more target hooks?
9663 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9664 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9665 // Unless we are optimizing for code size, consider the
9666 // expensive operation first.
9667 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9668 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9669 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9670 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9673 bool operator>(const Cost &RHS) const { return RHS < *this; }
9675 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9677 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9679 // The last instruction that represent the slice. This should be a
9680 // truncate instruction.
9682 // The original load instruction.
9684 // The right shift amount in bits from the original load.
9686 // The DAG from which Origin came from.
9687 // This is used to get some contextual information about legal types, etc.
9690 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9691 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9692 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9694 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9695 /// \return Result is \p BitWidth and has used bits set to 1 and
9696 /// not used bits set to 0.
9697 APInt getUsedBits() const {
9698 // Reproduce the trunc(lshr) sequence:
9699 // - Start from the truncated value.
9700 // - Zero extend to the desired bit width.
9702 assert(Origin && "No original load to compare against.");
9703 unsigned BitWidth = Origin->getValueSizeInBits(0);
9704 assert(Inst && "This slice is not bound to an instruction");
9705 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9706 "Extracted slice is bigger than the whole type!");
9707 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9708 UsedBits.setAllBits();
9709 UsedBits = UsedBits.zext(BitWidth);
9714 /// \brief Get the size of the slice to be loaded in bytes.
9715 unsigned getLoadedSize() const {
9716 unsigned SliceSize = getUsedBits().countPopulation();
9717 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9718 return SliceSize / 8;
9721 /// \brief Get the type that will be loaded for this slice.
9722 /// Note: This may not be the final type for the slice.
9723 EVT getLoadedType() const {
9724 assert(DAG && "Missing context");
9725 LLVMContext &Ctxt = *DAG->getContext();
9726 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9729 /// \brief Get the alignment of the load used for this slice.
9730 unsigned getAlignment() const {
9731 unsigned Alignment = Origin->getAlignment();
9732 unsigned Offset = getOffsetFromBase();
9734 Alignment = MinAlign(Alignment, Alignment + Offset);
9738 /// \brief Check if this slice can be rewritten with legal operations.
9739 bool isLegal() const {
9740 // An invalid slice is not legal.
9741 if (!Origin || !Inst || !DAG)
9744 // Offsets are for indexed load only, we do not handle that.
9745 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9748 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9750 // Check that the type is legal.
9751 EVT SliceType = getLoadedType();
9752 if (!TLI.isTypeLegal(SliceType))
9755 // Check that the load is legal for this type.
9756 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9759 // Check that the offset can be computed.
9760 // 1. Check its type.
9761 EVT PtrType = Origin->getBasePtr().getValueType();
9762 if (PtrType == MVT::Untyped || PtrType.isExtended())
9765 // 2. Check that it fits in the immediate.
9766 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9769 // 3. Check that the computation is legal.
9770 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9773 // Check that the zext is legal if it needs one.
9774 EVT TruncateType = Inst->getValueType(0);
9775 if (TruncateType != SliceType &&
9776 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9782 /// \brief Get the offset in bytes of this slice in the original chunk of
9784 /// \pre DAG != nullptr.
9785 uint64_t getOffsetFromBase() const {
9786 assert(DAG && "Missing context.");
9788 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9789 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9790 uint64_t Offset = Shift / 8;
9791 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9792 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9793 "The size of the original loaded type is not a multiple of a"
9795 // If Offset is bigger than TySizeInBytes, it means we are loading all
9796 // zeros. This should have been optimized before in the process.
9797 assert(TySizeInBytes > Offset &&
9798 "Invalid shift amount for given loaded size");
9800 Offset = TySizeInBytes - Offset - getLoadedSize();
9804 /// \brief Generate the sequence of instructions to load the slice
9805 /// represented by this object and redirect the uses of this slice to
9806 /// this new sequence of instructions.
9807 /// \pre this->Inst && this->Origin are valid Instructions and this
9808 /// object passed the legal check: LoadedSlice::isLegal returned true.
9809 /// \return The last instruction of the sequence used to load the slice.
9810 SDValue loadSlice() const {
9811 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9812 const SDValue &OldBaseAddr = Origin->getBasePtr();
9813 SDValue BaseAddr = OldBaseAddr;
9814 // Get the offset in that chunk of bytes w.r.t. the endianess.
9815 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9816 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9818 // BaseAddr = BaseAddr + Offset.
9819 EVT ArithType = BaseAddr.getValueType();
9821 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9822 DAG->getConstant(Offset, DL, ArithType));
9825 // Create the type of the loaded slice according to its size.
9826 EVT SliceType = getLoadedType();
9828 // Create the load for the slice.
9829 SDValue LastInst = DAG->getLoad(
9830 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9831 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9832 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9833 // If the final type is not the same as the loaded type, this means that
9834 // we have to pad with zero. Create a zero extend for that.
9835 EVT FinalType = Inst->getValueType(0);
9836 if (SliceType != FinalType)
9838 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9842 /// \brief Check if this slice can be merged with an expensive cross register
9843 /// bank copy. E.g.,
9845 /// f = bitcast i32 i to float
9846 bool canMergeExpensiveCrossRegisterBankCopy() const {
9847 if (!Inst || !Inst->hasOneUse())
9849 SDNode *Use = *Inst->use_begin();
9850 if (Use->getOpcode() != ISD::BITCAST)
9852 assert(DAG && "Missing context");
9853 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9854 EVT ResVT = Use->getValueType(0);
9855 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9856 const TargetRegisterClass *ArgRC =
9857 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9858 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9861 // At this point, we know that we perform a cross-register-bank copy.
9862 // Check if it is expensive.
9863 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9864 // Assume bitcasts are cheap, unless both register classes do not
9865 // explicitly share a common sub class.
9866 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9869 // Check if it will be merged with the load.
9870 // 1. Check the alignment constraint.
9871 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9872 ResVT.getTypeForEVT(*DAG->getContext()));
9874 if (RequiredAlignment > getAlignment())
9877 // 2. Check that the load is a legal operation for that type.
9878 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9881 // 3. Check that we do not have a zext in the way.
9882 if (Inst->getValueType(0) != getLoadedType())
9890 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9891 /// \p UsedBits looks like 0..0 1..1 0..0.
9892 static bool areUsedBitsDense(const APInt &UsedBits) {
9893 // If all the bits are one, this is dense!
9894 if (UsedBits.isAllOnesValue())
9897 // Get rid of the unused bits on the right.
9898 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9899 // Get rid of the unused bits on the left.
9900 if (NarrowedUsedBits.countLeadingZeros())
9901 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9902 // Check that the chunk of bits is completely used.
9903 return NarrowedUsedBits.isAllOnesValue();
9906 /// \brief Check whether or not \p First and \p Second are next to each other
9907 /// in memory. This means that there is no hole between the bits loaded
9908 /// by \p First and the bits loaded by \p Second.
9909 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9910 const LoadedSlice &Second) {
9911 assert(First.Origin == Second.Origin && First.Origin &&
9912 "Unable to match different memory origins.");
9913 APInt UsedBits = First.getUsedBits();
9914 assert((UsedBits & Second.getUsedBits()) == 0 &&
9915 "Slices are not supposed to overlap.");
9916 UsedBits |= Second.getUsedBits();
9917 return areUsedBitsDense(UsedBits);
9920 /// \brief Adjust the \p GlobalLSCost according to the target
9921 /// paring capabilities and the layout of the slices.
9922 /// \pre \p GlobalLSCost should account for at least as many loads as
9923 /// there is in the slices in \p LoadedSlices.
9924 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9925 LoadedSlice::Cost &GlobalLSCost) {
9926 unsigned NumberOfSlices = LoadedSlices.size();
9927 // If there is less than 2 elements, no pairing is possible.
9928 if (NumberOfSlices < 2)
9931 // Sort the slices so that elements that are likely to be next to each
9932 // other in memory are next to each other in the list.
9933 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9934 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9935 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9936 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9938 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9939 // First (resp. Second) is the first (resp. Second) potentially candidate
9940 // to be placed in a paired load.
9941 const LoadedSlice *First = nullptr;
9942 const LoadedSlice *Second = nullptr;
9943 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9944 // Set the beginning of the pair.
9947 Second = &LoadedSlices[CurrSlice];
9949 // If First is NULL, it means we start a new pair.
9950 // Get to the next slice.
9954 EVT LoadedType = First->getLoadedType();
9956 // If the types of the slices are different, we cannot pair them.
9957 if (LoadedType != Second->getLoadedType())
9960 // Check if the target supplies paired loads for this type.
9961 unsigned RequiredAlignment = 0;
9962 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9963 // move to the next pair, this type is hopeless.
9967 // Check if we meet the alignment requirement.
9968 if (RequiredAlignment > First->getAlignment())
9971 // Check that both loads are next to each other in memory.
9972 if (!areSlicesNextToEachOther(*First, *Second))
9975 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9976 --GlobalLSCost.Loads;
9977 // Move to the next pair.
9982 /// \brief Check the profitability of all involved LoadedSlice.
9983 /// Currently, it is considered profitable if there is exactly two
9984 /// involved slices (1) which are (2) next to each other in memory, and
9985 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9987 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9988 /// the elements themselves.
9990 /// FIXME: When the cost model will be mature enough, we can relax
9991 /// constraints (1) and (2).
9992 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9993 const APInt &UsedBits, bool ForCodeSize) {
9994 unsigned NumberOfSlices = LoadedSlices.size();
9995 if (StressLoadSlicing)
9996 return NumberOfSlices > 1;
9999 if (NumberOfSlices != 2)
10003 if (!areUsedBitsDense(UsedBits))
10007 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10008 // The original code has one big load.
10009 OrigCost.Loads = 1;
10010 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10011 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10012 // Accumulate the cost of all the slices.
10013 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10014 GlobalSlicingCost += SliceCost;
10016 // Account as cost in the original configuration the gain obtained
10017 // with the current slices.
10018 OrigCost.addSliceGain(LS);
10021 // If the target supports paired load, adjust the cost accordingly.
10022 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10023 return OrigCost > GlobalSlicingCost;
10026 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10027 /// operations, split it in the various pieces being extracted.
10029 /// This sort of thing is introduced by SROA.
10030 /// This slicing takes care not to insert overlapping loads.
10031 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10032 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10033 if (Level < AfterLegalizeDAG)
10036 LoadSDNode *LD = cast<LoadSDNode>(N);
10037 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10038 !LD->getValueType(0).isInteger())
10041 // Keep track of already used bits to detect overlapping values.
10042 // In that case, we will just abort the transformation.
10043 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10045 SmallVector<LoadedSlice, 4> LoadedSlices;
10047 // Check if this load is used as several smaller chunks of bits.
10048 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10049 // of computation for each trunc.
10050 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10051 UI != UIEnd; ++UI) {
10052 // Skip the uses of the chain.
10053 if (UI.getUse().getResNo() != 0)
10056 SDNode *User = *UI;
10057 unsigned Shift = 0;
10059 // Check if this is a trunc(lshr).
10060 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10061 isa<ConstantSDNode>(User->getOperand(1))) {
10062 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10063 User = *User->use_begin();
10066 // At this point, User is a Truncate, iff we encountered, trunc or
10068 if (User->getOpcode() != ISD::TRUNCATE)
10071 // The width of the type must be a power of 2 and greater than 8-bits.
10072 // Otherwise the load cannot be represented in LLVM IR.
10073 // Moreover, if we shifted with a non-8-bits multiple, the slice
10074 // will be across several bytes. We do not support that.
10075 unsigned Width = User->getValueSizeInBits(0);
10076 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10079 // Build the slice for this chain of computations.
10080 LoadedSlice LS(User, LD, Shift, &DAG);
10081 APInt CurrentUsedBits = LS.getUsedBits();
10083 // Check if this slice overlaps with another.
10084 if ((CurrentUsedBits & UsedBits) != 0)
10086 // Update the bits used globally.
10087 UsedBits |= CurrentUsedBits;
10089 // Check if the new slice would be legal.
10093 // Record the slice.
10094 LoadedSlices.push_back(LS);
10097 // Abort slicing if it does not seem to be profitable.
10098 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10103 // Rewrite each chain to use an independent load.
10104 // By construction, each chain can be represented by a unique load.
10106 // Prepare the argument for the new token factor for all the slices.
10107 SmallVector<SDValue, 8> ArgChains;
10108 for (SmallVectorImpl<LoadedSlice>::const_iterator
10109 LSIt = LoadedSlices.begin(),
10110 LSItEnd = LoadedSlices.end();
10111 LSIt != LSItEnd; ++LSIt) {
10112 SDValue SliceInst = LSIt->loadSlice();
10113 CombineTo(LSIt->Inst, SliceInst, true);
10114 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10115 SliceInst = SliceInst.getOperand(0);
10116 assert(SliceInst->getOpcode() == ISD::LOAD &&
10117 "It takes more than a zext to get to the loaded slice!!");
10118 ArgChains.push_back(SliceInst.getValue(1));
10121 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10123 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10127 /// Check to see if V is (and load (ptr), imm), where the load is having
10128 /// specific bytes cleared out. If so, return the byte size being masked out
10129 /// and the shift amount.
10130 static std::pair<unsigned, unsigned>
10131 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10132 std::pair<unsigned, unsigned> Result(0, 0);
10134 // Check for the structure we're looking for.
10135 if (V->getOpcode() != ISD::AND ||
10136 !isa<ConstantSDNode>(V->getOperand(1)) ||
10137 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10140 // Check the chain and pointer.
10141 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10142 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10144 // The store should be chained directly to the load or be an operand of a
10146 if (LD == Chain.getNode())
10148 else if (Chain->getOpcode() != ISD::TokenFactor)
10149 return Result; // Fail.
10152 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10153 if (Chain->getOperand(i).getNode() == LD) {
10157 if (!isOk) return Result;
10160 // This only handles simple types.
10161 if (V.getValueType() != MVT::i16 &&
10162 V.getValueType() != MVT::i32 &&
10163 V.getValueType() != MVT::i64)
10166 // Check the constant mask. Invert it so that the bits being masked out are
10167 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10168 // follow the sign bit for uniformity.
10169 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10170 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10171 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10172 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10173 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10174 if (NotMaskLZ == 64) return Result; // All zero mask.
10176 // See if we have a continuous run of bits. If so, we have 0*1+0*
10177 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10180 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10181 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10182 NotMaskLZ -= 64-V.getValueSizeInBits();
10184 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10185 switch (MaskedBytes) {
10189 default: return Result; // All one mask, or 5-byte mask.
10192 // Verify that the first bit starts at a multiple of mask so that the access
10193 // is aligned the same as the access width.
10194 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10196 Result.first = MaskedBytes;
10197 Result.second = NotMaskTZ/8;
10202 /// Check to see if IVal is something that provides a value as specified by
10203 /// MaskInfo. If so, replace the specified store with a narrower store of
10204 /// truncated IVal.
10206 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10207 SDValue IVal, StoreSDNode *St,
10209 unsigned NumBytes = MaskInfo.first;
10210 unsigned ByteShift = MaskInfo.second;
10211 SelectionDAG &DAG = DC->getDAG();
10213 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10214 // that uses this. If not, this is not a replacement.
10215 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10216 ByteShift*8, (ByteShift+NumBytes)*8);
10217 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10219 // Check that it is legal on the target to do this. It is legal if the new
10220 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10222 MVT VT = MVT::getIntegerVT(NumBytes*8);
10223 if (!DC->isTypeLegal(VT))
10226 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10227 // shifted by ByteShift and truncated down to NumBytes.
10230 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10231 DAG.getConstant(ByteShift*8, DL,
10232 DC->getShiftAmountTy(IVal.getValueType())));
10235 // Figure out the offset for the store and the alignment of the access.
10237 unsigned NewAlign = St->getAlignment();
10239 if (DAG.getTargetLoweringInfo().isLittleEndian())
10240 StOffset = ByteShift;
10242 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10244 SDValue Ptr = St->getBasePtr();
10247 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10248 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10249 NewAlign = MinAlign(NewAlign, StOffset);
10252 // Truncate down to the new size.
10253 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10256 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10257 St->getPointerInfo().getWithOffset(StOffset),
10258 false, false, NewAlign).getNode();
10262 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10263 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10264 /// narrowing the load and store if it would end up being a win for performance
10266 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10267 StoreSDNode *ST = cast<StoreSDNode>(N);
10268 if (ST->isVolatile())
10271 SDValue Chain = ST->getChain();
10272 SDValue Value = ST->getValue();
10273 SDValue Ptr = ST->getBasePtr();
10274 EVT VT = Value.getValueType();
10276 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10279 unsigned Opc = Value.getOpcode();
10281 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10282 // is a byte mask indicating a consecutive number of bytes, check to see if
10283 // Y is known to provide just those bytes. If so, we try to replace the
10284 // load + replace + store sequence with a single (narrower) store, which makes
10286 if (Opc == ISD::OR) {
10287 std::pair<unsigned, unsigned> MaskedLoad;
10288 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10289 if (MaskedLoad.first)
10290 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10291 Value.getOperand(1), ST,this))
10292 return SDValue(NewST, 0);
10294 // Or is commutative, so try swapping X and Y.
10295 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10296 if (MaskedLoad.first)
10297 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10298 Value.getOperand(0), ST,this))
10299 return SDValue(NewST, 0);
10302 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10303 Value.getOperand(1).getOpcode() != ISD::Constant)
10306 SDValue N0 = Value.getOperand(0);
10307 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10308 Chain == SDValue(N0.getNode(), 1)) {
10309 LoadSDNode *LD = cast<LoadSDNode>(N0);
10310 if (LD->getBasePtr() != Ptr ||
10311 LD->getPointerInfo().getAddrSpace() !=
10312 ST->getPointerInfo().getAddrSpace())
10315 // Find the type to narrow it the load / op / store to.
10316 SDValue N1 = Value.getOperand(1);
10317 unsigned BitWidth = N1.getValueSizeInBits();
10318 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10319 if (Opc == ISD::AND)
10320 Imm ^= APInt::getAllOnesValue(BitWidth);
10321 if (Imm == 0 || Imm.isAllOnesValue())
10323 unsigned ShAmt = Imm.countTrailingZeros();
10324 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10325 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10326 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10327 // The narrowing should be profitable, the load/store operation should be
10328 // legal (or custom) and the store size should be equal to the NewVT width.
10329 while (NewBW < BitWidth &&
10330 (NewVT.getStoreSizeInBits() != NewBW ||
10331 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10332 !TLI.isNarrowingProfitable(VT, NewVT))) {
10333 NewBW = NextPowerOf2(NewBW);
10334 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10336 if (NewBW >= BitWidth)
10339 // If the lsb changed does not start at the type bitwidth boundary,
10340 // start at the previous one.
10342 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10343 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10344 std::min(BitWidth, ShAmt + NewBW));
10345 if ((Imm & Mask) == Imm) {
10346 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10347 if (Opc == ISD::AND)
10348 NewImm ^= APInt::getAllOnesValue(NewBW);
10349 uint64_t PtrOff = ShAmt / 8;
10350 // For big endian targets, we need to adjust the offset to the pointer to
10351 // load the correct bytes.
10352 if (TLI.isBigEndian())
10353 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10355 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10356 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10357 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10360 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10361 Ptr.getValueType(), Ptr,
10362 DAG.getConstant(PtrOff, SDLoc(LD),
10363 Ptr.getValueType()));
10364 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10365 LD->getChain(), NewPtr,
10366 LD->getPointerInfo().getWithOffset(PtrOff),
10367 LD->isVolatile(), LD->isNonTemporal(),
10368 LD->isInvariant(), NewAlign,
10370 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10371 DAG.getConstant(NewImm, SDLoc(Value),
10373 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10375 ST->getPointerInfo().getWithOffset(PtrOff),
10376 false, false, NewAlign);
10378 AddToWorklist(NewPtr.getNode());
10379 AddToWorklist(NewLD.getNode());
10380 AddToWorklist(NewVal.getNode());
10381 WorklistRemover DeadNodes(*this);
10382 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10391 /// For a given floating point load / store pair, if the load value isn't used
10392 /// by any other operations, then consider transforming the pair to integer
10393 /// load / store operations if the target deems the transformation profitable.
10394 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10395 StoreSDNode *ST = cast<StoreSDNode>(N);
10396 SDValue Chain = ST->getChain();
10397 SDValue Value = ST->getValue();
10398 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10399 Value.hasOneUse() &&
10400 Chain == SDValue(Value.getNode(), 1)) {
10401 LoadSDNode *LD = cast<LoadSDNode>(Value);
10402 EVT VT = LD->getMemoryVT();
10403 if (!VT.isFloatingPoint() ||
10404 VT != ST->getMemoryVT() ||
10405 LD->isNonTemporal() ||
10406 ST->isNonTemporal() ||
10407 LD->getPointerInfo().getAddrSpace() != 0 ||
10408 ST->getPointerInfo().getAddrSpace() != 0)
10411 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10412 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10413 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10414 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10415 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10418 unsigned LDAlign = LD->getAlignment();
10419 unsigned STAlign = ST->getAlignment();
10420 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10421 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10422 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10425 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10426 LD->getChain(), LD->getBasePtr(),
10427 LD->getPointerInfo(),
10428 false, false, false, LDAlign);
10430 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10431 NewLD, ST->getBasePtr(),
10432 ST->getPointerInfo(),
10433 false, false, STAlign);
10435 AddToWorklist(NewLD.getNode());
10436 AddToWorklist(NewST.getNode());
10437 WorklistRemover DeadNodes(*this);
10438 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10447 /// Helper struct to parse and store a memory address as base + index + offset.
10448 /// We ignore sign extensions when it is safe to do so.
10449 /// The following two expressions are not equivalent. To differentiate we need
10450 /// to store whether there was a sign extension involved in the index
10452 /// (load (i64 add (i64 copyfromreg %c)
10453 /// (i64 signextend (add (i8 load %index)
10457 /// (load (i64 add (i64 copyfromreg %c)
10458 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10460 struct BaseIndexOffset {
10464 bool IsIndexSignExt;
10466 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10468 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10469 bool IsIndexSignExt) :
10470 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10472 bool equalBaseIndex(const BaseIndexOffset &Other) {
10473 return Other.Base == Base && Other.Index == Index &&
10474 Other.IsIndexSignExt == IsIndexSignExt;
10477 /// Parses tree in Ptr for base, index, offset addresses.
10478 static BaseIndexOffset match(SDValue Ptr) {
10479 bool IsIndexSignExt = false;
10481 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10482 // instruction, then it could be just the BASE or everything else we don't
10483 // know how to handle. Just use Ptr as BASE and give up.
10484 if (Ptr->getOpcode() != ISD::ADD)
10485 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10487 // We know that we have at least an ADD instruction. Try to pattern match
10488 // the simple case of BASE + OFFSET.
10489 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10490 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10491 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10495 // Inside a loop the current BASE pointer is calculated using an ADD and a
10496 // MUL instruction. In this case Ptr is the actual BASE pointer.
10497 // (i64 add (i64 %array_ptr)
10498 // (i64 mul (i64 %induction_var)
10499 // (i64 %element_size)))
10500 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10501 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10503 // Look at Base + Index + Offset cases.
10504 SDValue Base = Ptr->getOperand(0);
10505 SDValue IndexOffset = Ptr->getOperand(1);
10507 // Skip signextends.
10508 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10509 IndexOffset = IndexOffset->getOperand(0);
10510 IsIndexSignExt = true;
10513 // Either the case of Base + Index (no offset) or something else.
10514 if (IndexOffset->getOpcode() != ISD::ADD)
10515 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10517 // Now we have the case of Base + Index + offset.
10518 SDValue Index = IndexOffset->getOperand(0);
10519 SDValue Offset = IndexOffset->getOperand(1);
10521 if (!isa<ConstantSDNode>(Offset))
10522 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10524 // Ignore signextends.
10525 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10526 Index = Index->getOperand(0);
10527 IsIndexSignExt = true;
10528 } else IsIndexSignExt = false;
10530 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10531 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10536 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10537 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10538 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10539 // Make sure we have something to merge.
10543 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10544 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10545 unsigned LatestNodeUsed = 0;
10547 for (unsigned i=0; i < NumElem; ++i) {
10548 // Find a chain for the new wide-store operand. Notice that some
10549 // of the store nodes that we found may not be selected for inclusion
10550 // in the wide store. The chain we use needs to be the chain of the
10551 // latest store node which is *used* and replaced by the wide store.
10552 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10553 LatestNodeUsed = i;
10556 // The latest Node in the DAG.
10557 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10558 SDLoc DL(StoreNodes[0].MemNode);
10562 // Find a legal type for the vector store.
10563 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10564 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10565 if (IsConstantSrc) {
10566 // A vector store with a constant source implies that the constant is
10567 // zero; we only handle merging stores of constant zeros because the zero
10568 // can be materialized without a load.
10569 // It may be beneficial to loosen this restriction to allow non-zero
10571 StoredVal = DAG.getConstant(0, DL, Ty);
10573 SmallVector<SDValue, 8> Ops;
10574 for (unsigned i = 0; i < NumElem ; ++i) {
10575 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10576 SDValue Val = St->getValue();
10577 // All of the operands of a BUILD_VECTOR must have the same type.
10578 if (Val.getValueType() != MemVT)
10580 Ops.push_back(Val);
10583 // Build the extracted vector elements back into a vector.
10584 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10587 // We should always use a vector store when merging extracted vector
10588 // elements, so this path implies a store of constants.
10589 assert(IsConstantSrc && "Merged vector elements should use vector store");
10591 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10592 APInt StoreInt(StoreBW, 0);
10594 // Construct a single integer constant which is made of the smaller
10595 // constant inputs.
10596 bool IsLE = TLI.isLittleEndian();
10597 for (unsigned i = 0; i < NumElem ; ++i) {
10598 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10599 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10600 SDValue Val = St->getValue();
10601 StoreInt <<= ElementSizeBytes*8;
10602 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10603 StoreInt |= C->getAPIntValue().zext(StoreBW);
10604 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10605 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10607 llvm_unreachable("Invalid constant element type");
10611 // Create the new Load and Store operations.
10612 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10613 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10616 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10617 FirstInChain->getBasePtr(),
10618 FirstInChain->getPointerInfo(),
10620 FirstInChain->getAlignment());
10622 // Replace the last store with the new store
10623 CombineTo(LatestOp, NewStore);
10624 // Erase all other stores.
10625 for (unsigned i = 0; i < NumElem ; ++i) {
10626 if (StoreNodes[i].MemNode == LatestOp)
10628 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10629 // ReplaceAllUsesWith will replace all uses that existed when it was
10630 // called, but graph optimizations may cause new ones to appear. For
10631 // example, the case in pr14333 looks like
10633 // St's chain -> St -> another store -> X
10635 // And the only difference from St to the other store is the chain.
10636 // When we change it's chain to be St's chain they become identical,
10637 // get CSEed and the net result is that X is now a use of St.
10638 // Since we know that St is redundant, just iterate.
10639 while (!St->use_empty())
10640 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10641 deleteAndRecombine(St);
10647 static bool allowableAlignment(const SelectionDAG &DAG,
10648 const TargetLowering &TLI, EVT EVTTy,
10649 unsigned AS, unsigned Align) {
10650 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10653 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10654 unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10655 return (Align >= ABIAlignment);
10658 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10659 if (OptLevel == CodeGenOpt::None)
10662 EVT MemVT = St->getMemoryVT();
10663 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10664 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10665 Attribute::NoImplicitFloat);
10667 // This function cannot currently deal with non-byte-sized memory sizes.
10668 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10671 // Don't merge vectors into wider inputs.
10672 if (MemVT.isVector() || !MemVT.isSimple())
10675 // Perform an early exit check. Do not bother looking at stored values that
10676 // are not constants, loads, or extracted vector elements.
10677 SDValue StoredVal = St->getValue();
10678 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10679 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10680 isa<ConstantFPSDNode>(StoredVal);
10681 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10683 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10686 // Only look at ends of store sequences.
10687 SDValue Chain = SDValue(St, 0);
10688 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10691 // This holds the base pointer, index, and the offset in bytes from the base
10693 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10695 // We must have a base and an offset.
10696 if (!BasePtr.Base.getNode())
10699 // Do not handle stores to undef base pointers.
10700 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10703 // Save the LoadSDNodes that we find in the chain.
10704 // We need to make sure that these nodes do not interfere with
10705 // any of the store nodes.
10706 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10708 // Save the StoreSDNodes that we find in the chain.
10709 SmallVector<MemOpLink, 8> StoreNodes;
10711 // Walk up the chain and look for nodes with offsets from the same
10712 // base pointer. Stop when reaching an instruction with a different kind
10713 // or instruction which has a different base pointer.
10715 StoreSDNode *Index = St;
10717 // If the chain has more than one use, then we can't reorder the mem ops.
10718 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10721 // Find the base pointer and offset for this memory node.
10722 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10724 // Check that the base pointer is the same as the original one.
10725 if (!Ptr.equalBaseIndex(BasePtr))
10728 // The memory operands must not be volatile.
10729 if (Index->isVolatile() || Index->isIndexed())
10733 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10734 if (St->isTruncatingStore())
10737 // The stored memory type must be the same.
10738 if (Index->getMemoryVT() != MemVT)
10741 // We found a potential memory operand to merge.
10742 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10744 // Find the next memory operand in the chain. If the next operand in the
10745 // chain is a store then move up and continue the scan with the next
10746 // memory operand. If the next operand is a load save it and use alias
10747 // information to check if it interferes with anything.
10748 SDNode *NextInChain = Index->getChain().getNode();
10750 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10751 // We found a store node. Use it for the next iteration.
10754 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10755 if (Ldn->isVolatile()) {
10760 // Save the load node for later. Continue the scan.
10761 AliasLoadNodes.push_back(Ldn);
10762 NextInChain = Ldn->getChain().getNode();
10771 // Check if there is anything to merge.
10772 if (StoreNodes.size() < 2)
10775 // Sort the memory operands according to their distance from the base pointer.
10776 std::sort(StoreNodes.begin(), StoreNodes.end(),
10777 [](MemOpLink LHS, MemOpLink RHS) {
10778 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10779 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10780 LHS.SequenceNum > RHS.SequenceNum);
10783 // Scan the memory operations on the chain and find the first non-consecutive
10784 // store memory address.
10785 unsigned LastConsecutiveStore = 0;
10786 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10787 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10789 // Check that the addresses are consecutive starting from the second
10790 // element in the list of stores.
10792 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10793 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10797 bool Alias = false;
10798 // Check if this store interferes with any of the loads that we found.
10799 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10800 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10804 // We found a load that alias with this store. Stop the sequence.
10808 // Mark this node as useful.
10809 LastConsecutiveStore = i;
10812 // The node with the lowest store address.
10813 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10814 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10815 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10817 // Store the constants into memory as one consecutive store.
10818 if (IsConstantSrc) {
10819 unsigned LastLegalType = 0;
10820 unsigned LastLegalVectorType = 0;
10821 bool NonZero = false;
10822 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10823 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10824 SDValue StoredVal = St->getValue();
10826 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10827 NonZero |= !C->isNullValue();
10828 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10829 NonZero |= !C->getConstantFPValue()->isNullValue();
10835 // Find a legal type for the constant store.
10836 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10837 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10838 if (TLI.isTypeLegal(StoreTy) &&
10839 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10840 FirstStoreAlign)) {
10841 LastLegalType = i+1;
10842 // Or check whether a truncstore is legal.
10843 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10844 TargetLowering::TypePromoteInteger) {
10845 EVT LegalizedStoredValueTy =
10846 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10847 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10848 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10849 FirstStoreAlign)) {
10850 LastLegalType = i + 1;
10854 // Find a legal type for the vector store.
10855 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10856 if (TLI.isTypeLegal(Ty) &&
10857 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10858 LastLegalVectorType = i + 1;
10862 // We only use vectors if the constant is known to be zero and the
10863 // function is not marked with the noimplicitfloat attribute.
10864 if (NonZero || NoVectors)
10865 LastLegalVectorType = 0;
10867 // Check if we found a legal integer type to store.
10868 if (LastLegalType == 0 && LastLegalVectorType == 0)
10871 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10872 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10874 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10878 // When extracting multiple vector elements, try to store them
10879 // in one vector store rather than a sequence of scalar stores.
10880 if (IsExtractVecEltSrc) {
10881 unsigned NumElem = 0;
10882 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10883 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10884 SDValue StoredVal = St->getValue();
10885 // This restriction could be loosened.
10886 // Bail out if any stored values are not elements extracted from a vector.
10887 // It should be possible to handle mixed sources, but load sources need
10888 // more careful handling (see the block of code below that handles
10889 // consecutive loads).
10890 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10893 // Find a legal type for the vector store.
10894 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10895 if (TLI.isTypeLegal(Ty) &&
10896 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10900 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10904 // Below we handle the case of multiple consecutive stores that
10905 // come from multiple consecutive loads. We merge them into a single
10906 // wide load and a single wide store.
10908 // Look for load nodes which are used by the stored values.
10909 SmallVector<MemOpLink, 8> LoadNodes;
10911 // Find acceptable loads. Loads need to have the same chain (token factor),
10912 // must not be zext, volatile, indexed, and they must be consecutive.
10913 BaseIndexOffset LdBasePtr;
10914 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10915 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10916 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10919 // Loads must only have one use.
10920 if (!Ld->hasNUsesOfValue(1, 0))
10923 // The memory operands must not be volatile.
10924 if (Ld->isVolatile() || Ld->isIndexed())
10927 // We do not accept ext loads.
10928 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10931 // The stored memory type must be the same.
10932 if (Ld->getMemoryVT() != MemVT)
10935 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10936 // If this is not the first ptr that we check.
10937 if (LdBasePtr.Base.getNode()) {
10938 // The base ptr must be the same.
10939 if (!LdPtr.equalBaseIndex(LdBasePtr))
10942 // Check that all other base pointers are the same as this one.
10946 // We found a potential memory operand to merge.
10947 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10950 if (LoadNodes.size() < 2)
10953 // If we have load/store pair instructions and we only have two values,
10955 unsigned RequiredAlignment;
10956 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10957 St->getAlignment() >= RequiredAlignment)
10960 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10961 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
10962 unsigned FirstLoadAlign = FirstLoad->getAlignment();
10964 // Scan the memory operations on the chain and find the first non-consecutive
10965 // load memory address. These variables hold the index in the store node
10967 unsigned LastConsecutiveLoad = 0;
10968 // This variable refers to the size and not index in the array.
10969 unsigned LastLegalVectorType = 0;
10970 unsigned LastLegalIntegerType = 0;
10971 StartAddress = LoadNodes[0].OffsetFromBase;
10972 SDValue FirstChain = FirstLoad->getChain();
10973 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10974 // All loads much share the same chain.
10975 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10978 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10979 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10981 LastConsecutiveLoad = i;
10983 // Find a legal type for the vector store.
10984 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10985 if (TLI.isTypeLegal(StoreTy) &&
10986 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10987 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
10988 LastLegalVectorType = i + 1;
10991 // Find a legal type for the integer store.
10992 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10993 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10994 if (TLI.isTypeLegal(StoreTy) &&
10995 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10996 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
10997 LastLegalIntegerType = i + 1;
10998 // Or check whether a truncstore and extload is legal.
10999 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11000 TargetLowering::TypePromoteInteger) {
11001 EVT LegalizedStoredValueTy =
11002 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11003 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11004 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11005 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11006 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11007 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11008 FirstStoreAlign) &&
11009 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11011 LastLegalIntegerType = i+1;
11015 // Only use vector types if the vector type is larger than the integer type.
11016 // If they are the same, use integers.
11017 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11018 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11020 // We add +1 here because the LastXXX variables refer to location while
11021 // the NumElem refers to array/index size.
11022 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11023 NumElem = std::min(LastLegalType, NumElem);
11028 // The latest Node in the DAG.
11029 unsigned LatestNodeUsed = 0;
11030 for (unsigned i=1; i<NumElem; ++i) {
11031 // Find a chain for the new wide-store operand. Notice that some
11032 // of the store nodes that we found may not be selected for inclusion
11033 // in the wide store. The chain we use needs to be the chain of the
11034 // latest store node which is *used* and replaced by the wide store.
11035 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11036 LatestNodeUsed = i;
11039 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11041 // Find if it is better to use vectors or integers to load and store
11045 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11047 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11048 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11051 SDLoc LoadDL(LoadNodes[0].MemNode);
11052 SDLoc StoreDL(StoreNodes[0].MemNode);
11054 SDValue NewLoad = DAG.getLoad(
11055 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11056 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11058 SDValue NewStore = DAG.getStore(
11059 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11060 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11062 // Replace one of the loads with the new load.
11063 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11064 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11065 SDValue(NewLoad.getNode(), 1));
11067 // Remove the rest of the load chains.
11068 for (unsigned i = 1; i < NumElem ; ++i) {
11069 // Replace all chain users of the old load nodes with the chain of the new
11071 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11072 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11075 // Replace the last store with the new store.
11076 CombineTo(LatestOp, NewStore);
11077 // Erase all other stores.
11078 for (unsigned i = 0; i < NumElem ; ++i) {
11079 // Remove all Store nodes.
11080 if (StoreNodes[i].MemNode == LatestOp)
11082 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11083 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11084 deleteAndRecombine(St);
11090 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11091 StoreSDNode *ST = cast<StoreSDNode>(N);
11092 SDValue Chain = ST->getChain();
11093 SDValue Value = ST->getValue();
11094 SDValue Ptr = ST->getBasePtr();
11096 // If this is a store of a bit convert, store the input value if the
11097 // resultant store does not need a higher alignment than the original.
11098 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11099 ST->isUnindexed()) {
11100 unsigned OrigAlign = ST->getAlignment();
11101 EVT SVT = Value.getOperand(0).getValueType();
11102 unsigned Align = TLI.getDataLayout()->
11103 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11104 if (Align <= OrigAlign &&
11105 ((!LegalOperations && !ST->isVolatile()) ||
11106 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11107 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11108 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11109 ST->isNonTemporal(), OrigAlign,
11113 // Turn 'store undef, Ptr' -> nothing.
11114 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11117 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11118 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11119 // NOTE: If the original store is volatile, this transform must not increase
11120 // the number of stores. For example, on x86-32 an f64 can be stored in one
11121 // processor operation but an i64 (which is not legal) requires two. So the
11122 // transform should not be done in this case.
11123 if (Value.getOpcode() != ISD::TargetConstantFP) {
11125 switch (CFP->getSimpleValueType(0).SimpleTy) {
11126 default: llvm_unreachable("Unknown FP type");
11127 case MVT::f16: // We don't do this for these yet.
11133 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11134 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11136 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11137 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11139 return DAG.getStore(Chain, SDLoc(N), Tmp,
11140 Ptr, ST->getMemOperand());
11144 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11145 !ST->isVolatile()) ||
11146 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11148 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11149 getZExtValue(), SDLoc(CFP), MVT::i64);
11150 return DAG.getStore(Chain, SDLoc(N), Tmp,
11151 Ptr, ST->getMemOperand());
11154 if (!ST->isVolatile() &&
11155 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11156 // Many FP stores are not made apparent until after legalize, e.g. for
11157 // argument passing. Since this is so common, custom legalize the
11158 // 64-bit integer store into two 32-bit stores.
11159 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11160 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11161 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11162 if (TLI.isBigEndian()) std::swap(Lo, Hi);
11164 unsigned Alignment = ST->getAlignment();
11165 bool isVolatile = ST->isVolatile();
11166 bool isNonTemporal = ST->isNonTemporal();
11167 AAMDNodes AAInfo = ST->getAAInfo();
11171 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11172 Ptr, ST->getPointerInfo(),
11173 isVolatile, isNonTemporal,
11174 ST->getAlignment(), AAInfo);
11175 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11176 DAG.getConstant(4, DL, Ptr.getValueType()));
11177 Alignment = MinAlign(Alignment, 4U);
11178 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11179 Ptr, ST->getPointerInfo().getWithOffset(4),
11180 isVolatile, isNonTemporal,
11181 Alignment, AAInfo);
11182 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11191 // Try to infer better alignment information than the store already has.
11192 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11193 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11194 if (Align > ST->getAlignment()) {
11196 DAG.getTruncStore(Chain, SDLoc(N), Value,
11197 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11198 ST->isVolatile(), ST->isNonTemporal(), Align,
11200 if (NewStore.getNode() != N)
11201 return CombineTo(ST, NewStore, true);
11206 // Try transforming a pair floating point load / store ops to integer
11207 // load / store ops.
11208 SDValue NewST = TransformFPLoadStorePair(N);
11209 if (NewST.getNode())
11212 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11213 : DAG.getSubtarget().useAA();
11215 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11216 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11219 if (UseAA && ST->isUnindexed()) {
11220 // Walk up chain skipping non-aliasing memory nodes.
11221 SDValue BetterChain = FindBetterChain(N, Chain);
11223 // If there is a better chain.
11224 if (Chain != BetterChain) {
11227 // Replace the chain to avoid dependency.
11228 if (ST->isTruncatingStore()) {
11229 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11230 ST->getMemoryVT(), ST->getMemOperand());
11232 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11233 ST->getMemOperand());
11236 // Create token to keep both nodes around.
11237 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11238 MVT::Other, Chain, ReplStore);
11240 // Make sure the new and old chains are cleaned up.
11241 AddToWorklist(Token.getNode());
11243 // Don't add users to work list.
11244 return CombineTo(N, Token, false);
11248 // Try transforming N to an indexed store.
11249 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11250 return SDValue(N, 0);
11252 // FIXME: is there such a thing as a truncating indexed store?
11253 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11254 Value.getValueType().isInteger()) {
11255 // See if we can simplify the input to this truncstore with knowledge that
11256 // only the low bits are being used. For example:
11257 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11259 GetDemandedBits(Value,
11260 APInt::getLowBitsSet(
11261 Value.getValueType().getScalarType().getSizeInBits(),
11262 ST->getMemoryVT().getScalarType().getSizeInBits()));
11263 AddToWorklist(Value.getNode());
11264 if (Shorter.getNode())
11265 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11266 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11268 // Otherwise, see if we can simplify the operation with
11269 // SimplifyDemandedBits, which only works if the value has a single use.
11270 if (SimplifyDemandedBits(Value,
11271 APInt::getLowBitsSet(
11272 Value.getValueType().getScalarType().getSizeInBits(),
11273 ST->getMemoryVT().getScalarType().getSizeInBits())))
11274 return SDValue(N, 0);
11277 // If this is a load followed by a store to the same location, then the store
11279 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11280 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11281 ST->isUnindexed() && !ST->isVolatile() &&
11282 // There can't be any side effects between the load and store, such as
11283 // a call or store.
11284 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11285 // The store is dead, remove it.
11290 // If this is a store followed by a store with the same value to the same
11291 // location, then the store is dead/noop.
11292 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11293 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11294 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11295 ST1->isUnindexed() && !ST1->isVolatile()) {
11296 // The store is dead, remove it.
11301 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11302 // truncating store. We can do this even if this is already a truncstore.
11303 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11304 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11305 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11306 ST->getMemoryVT())) {
11307 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11308 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11311 // Only perform this optimization before the types are legal, because we
11312 // don't want to perform this optimization on every DAGCombine invocation.
11314 bool EverChanged = false;
11317 // There can be multiple store sequences on the same chain.
11318 // Keep trying to merge store sequences until we are unable to do so
11319 // or until we merge the last store on the chain.
11320 bool Changed = MergeConsecutiveStores(ST);
11321 EverChanged |= Changed;
11322 if (!Changed) break;
11323 } while (ST->getOpcode() != ISD::DELETED_NODE);
11326 return SDValue(N, 0);
11329 return ReduceLoadOpStoreWidth(N);
11332 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11333 SDValue InVec = N->getOperand(0);
11334 SDValue InVal = N->getOperand(1);
11335 SDValue EltNo = N->getOperand(2);
11338 // If the inserted element is an UNDEF, just use the input vector.
11339 if (InVal.getOpcode() == ISD::UNDEF)
11342 EVT VT = InVec.getValueType();
11344 // If we can't generate a legal BUILD_VECTOR, exit
11345 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11348 // Check that we know which element is being inserted
11349 if (!isa<ConstantSDNode>(EltNo))
11351 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11353 // Canonicalize insert_vector_elt dag nodes.
11355 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11356 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11358 // Do this only if the child insert_vector node has one use; also
11359 // do this only if indices are both constants and Idx1 < Idx0.
11360 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11361 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11362 unsigned OtherElt =
11363 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11364 if (Elt < OtherElt) {
11366 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11367 InVec.getOperand(0), InVal, EltNo);
11368 AddToWorklist(NewOp.getNode());
11369 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11370 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11374 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11375 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11376 // vector elements.
11377 SmallVector<SDValue, 8> Ops;
11378 // Do not combine these two vectors if the output vector will not replace
11379 // the input vector.
11380 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11381 Ops.append(InVec.getNode()->op_begin(),
11382 InVec.getNode()->op_end());
11383 } else if (InVec.getOpcode() == ISD::UNDEF) {
11384 unsigned NElts = VT.getVectorNumElements();
11385 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11390 // Insert the element
11391 if (Elt < Ops.size()) {
11392 // All the operands of BUILD_VECTOR must have the same type;
11393 // we enforce that here.
11394 EVT OpVT = Ops[0].getValueType();
11395 if (InVal.getValueType() != OpVT)
11396 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11397 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11398 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11402 // Return the new vector
11403 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11406 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11407 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11408 EVT ResultVT = EVE->getValueType(0);
11409 EVT VecEltVT = InVecVT.getVectorElementType();
11410 unsigned Align = OriginalLoad->getAlignment();
11411 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11412 VecEltVT.getTypeForEVT(*DAG.getContext()));
11414 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11419 SDValue NewPtr = OriginalLoad->getBasePtr();
11421 EVT PtrType = NewPtr.getValueType();
11422 MachinePointerInfo MPI;
11424 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11425 int Elt = ConstEltNo->getZExtValue();
11426 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11427 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11428 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11430 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11431 Offset = DAG.getNode(
11432 ISD::MUL, DL, PtrType, Offset,
11433 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11434 MPI = OriginalLoad->getPointerInfo();
11436 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11438 // The replacement we need to do here is a little tricky: we need to
11439 // replace an extractelement of a load with a load.
11440 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11441 // Note that this replacement assumes that the extractvalue is the only
11442 // use of the load; that's okay because we don't want to perform this
11443 // transformation in other cases anyway.
11446 if (ResultVT.bitsGT(VecEltVT)) {
11447 // If the result type of vextract is wider than the load, then issue an
11448 // extending load instead.
11449 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11453 Load = DAG.getExtLoad(
11454 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11455 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11456 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11457 Chain = Load.getValue(1);
11459 Load = DAG.getLoad(
11460 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11461 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11462 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11463 Chain = Load.getValue(1);
11464 if (ResultVT.bitsLT(VecEltVT))
11465 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11467 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11469 WorklistRemover DeadNodes(*this);
11470 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11471 SDValue To[] = { Load, Chain };
11472 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11473 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11474 // worklist explicitly as well.
11475 AddToWorklist(Load.getNode());
11476 AddUsersToWorklist(Load.getNode()); // Add users too
11477 // Make sure to revisit this node to clean it up; it will usually be dead.
11478 AddToWorklist(EVE);
11480 return SDValue(EVE, 0);
11483 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11484 // (vextract (scalar_to_vector val, 0) -> val
11485 SDValue InVec = N->getOperand(0);
11486 EVT VT = InVec.getValueType();
11487 EVT NVT = N->getValueType(0);
11489 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11490 // Check if the result type doesn't match the inserted element type. A
11491 // SCALAR_TO_VECTOR may truncate the inserted element and the
11492 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11493 SDValue InOp = InVec.getOperand(0);
11494 if (InOp.getValueType() != NVT) {
11495 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11496 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11501 SDValue EltNo = N->getOperand(1);
11502 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11504 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11505 // We only perform this optimization before the op legalization phase because
11506 // we may introduce new vector instructions which are not backed by TD
11507 // patterns. For example on AVX, extracting elements from a wide vector
11508 // without using extract_subvector. However, if we can find an underlying
11509 // scalar value, then we can always use that.
11510 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11512 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11513 int NumElem = VT.getVectorNumElements();
11514 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11515 // Find the new index to extract from.
11516 int OrigElt = SVOp->getMaskElt(Elt);
11518 // Extracting an undef index is undef.
11520 return DAG.getUNDEF(NVT);
11522 // Select the right vector half to extract from.
11524 if (OrigElt < NumElem) {
11525 SVInVec = InVec->getOperand(0);
11527 SVInVec = InVec->getOperand(1);
11528 OrigElt -= NumElem;
11531 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11532 SDValue InOp = SVInVec.getOperand(OrigElt);
11533 if (InOp.getValueType() != NVT) {
11534 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11535 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11541 // FIXME: We should handle recursing on other vector shuffles and
11542 // scalar_to_vector here as well.
11544 if (!LegalOperations) {
11545 EVT IndexTy = TLI.getVectorIdxTy();
11546 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11547 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11551 bool BCNumEltsChanged = false;
11552 EVT ExtVT = VT.getVectorElementType();
11555 // If the result of load has to be truncated, then it's not necessarily
11557 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11560 if (InVec.getOpcode() == ISD::BITCAST) {
11561 // Don't duplicate a load with other uses.
11562 if (!InVec.hasOneUse())
11565 EVT BCVT = InVec.getOperand(0).getValueType();
11566 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11568 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11569 BCNumEltsChanged = true;
11570 InVec = InVec.getOperand(0);
11571 ExtVT = BCVT.getVectorElementType();
11574 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11575 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11576 ISD::isNormalLoad(InVec.getNode()) &&
11577 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11578 SDValue Index = N->getOperand(1);
11579 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11580 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11584 // Perform only after legalization to ensure build_vector / vector_shuffle
11585 // optimizations have already been done.
11586 if (!LegalOperations) return SDValue();
11588 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11589 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11590 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11593 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11595 LoadSDNode *LN0 = nullptr;
11596 const ShuffleVectorSDNode *SVN = nullptr;
11597 if (ISD::isNormalLoad(InVec.getNode())) {
11598 LN0 = cast<LoadSDNode>(InVec);
11599 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11600 InVec.getOperand(0).getValueType() == ExtVT &&
11601 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11602 // Don't duplicate a load with other uses.
11603 if (!InVec.hasOneUse())
11606 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11607 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11608 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11610 // (load $addr+1*size)
11612 // Don't duplicate a load with other uses.
11613 if (!InVec.hasOneUse())
11616 // If the bit convert changed the number of elements, it is unsafe
11617 // to examine the mask.
11618 if (BCNumEltsChanged)
11621 // Select the input vector, guarding against out of range extract vector.
11622 unsigned NumElems = VT.getVectorNumElements();
11623 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11624 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11626 if (InVec.getOpcode() == ISD::BITCAST) {
11627 // Don't duplicate a load with other uses.
11628 if (!InVec.hasOneUse())
11631 InVec = InVec.getOperand(0);
11633 if (ISD::isNormalLoad(InVec.getNode())) {
11634 LN0 = cast<LoadSDNode>(InVec);
11635 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11636 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11640 // Make sure we found a non-volatile load and the extractelement is
11642 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11645 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11647 return DAG.getUNDEF(LVT);
11649 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11655 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11656 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11657 // We perform this optimization post type-legalization because
11658 // the type-legalizer often scalarizes integer-promoted vectors.
11659 // Performing this optimization before may create bit-casts which
11660 // will be type-legalized to complex code sequences.
11661 // We perform this optimization only before the operation legalizer because we
11662 // may introduce illegal operations.
11663 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11666 unsigned NumInScalars = N->getNumOperands();
11668 EVT VT = N->getValueType(0);
11670 // Check to see if this is a BUILD_VECTOR of a bunch of values
11671 // which come from any_extend or zero_extend nodes. If so, we can create
11672 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11673 // optimizations. We do not handle sign-extend because we can't fill the sign
11675 EVT SourceType = MVT::Other;
11676 bool AllAnyExt = true;
11678 for (unsigned i = 0; i != NumInScalars; ++i) {
11679 SDValue In = N->getOperand(i);
11680 // Ignore undef inputs.
11681 if (In.getOpcode() == ISD::UNDEF) continue;
11683 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11684 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11686 // Abort if the element is not an extension.
11687 if (!ZeroExt && !AnyExt) {
11688 SourceType = MVT::Other;
11692 // The input is a ZeroExt or AnyExt. Check the original type.
11693 EVT InTy = In.getOperand(0).getValueType();
11695 // Check that all of the widened source types are the same.
11696 if (SourceType == MVT::Other)
11699 else if (InTy != SourceType) {
11700 // Multiple income types. Abort.
11701 SourceType = MVT::Other;
11705 // Check if all of the extends are ANY_EXTENDs.
11706 AllAnyExt &= AnyExt;
11709 // In order to have valid types, all of the inputs must be extended from the
11710 // same source type and all of the inputs must be any or zero extend.
11711 // Scalar sizes must be a power of two.
11712 EVT OutScalarTy = VT.getScalarType();
11713 bool ValidTypes = SourceType != MVT::Other &&
11714 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11715 isPowerOf2_32(SourceType.getSizeInBits());
11717 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11718 // turn into a single shuffle instruction.
11722 bool isLE = TLI.isLittleEndian();
11723 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11724 assert(ElemRatio > 1 && "Invalid element size ratio");
11725 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11726 DAG.getConstant(0, SDLoc(N), SourceType);
11728 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11729 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11731 // Populate the new build_vector
11732 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11733 SDValue Cast = N->getOperand(i);
11734 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11735 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11736 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11738 if (Cast.getOpcode() == ISD::UNDEF)
11739 In = DAG.getUNDEF(SourceType);
11741 In = Cast->getOperand(0);
11742 unsigned Index = isLE ? (i * ElemRatio) :
11743 (i * ElemRatio + (ElemRatio - 1));
11745 assert(Index < Ops.size() && "Invalid index");
11749 // The type of the new BUILD_VECTOR node.
11750 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11751 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11752 "Invalid vector size");
11753 // Check if the new vector type is legal.
11754 if (!isTypeLegal(VecVT)) return SDValue();
11756 // Make the new BUILD_VECTOR.
11757 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11759 // The new BUILD_VECTOR node has the potential to be further optimized.
11760 AddToWorklist(BV.getNode());
11761 // Bitcast to the desired type.
11762 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11765 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11766 EVT VT = N->getValueType(0);
11768 unsigned NumInScalars = N->getNumOperands();
11771 EVT SrcVT = MVT::Other;
11772 unsigned Opcode = ISD::DELETED_NODE;
11773 unsigned NumDefs = 0;
11775 for (unsigned i = 0; i != NumInScalars; ++i) {
11776 SDValue In = N->getOperand(i);
11777 unsigned Opc = In.getOpcode();
11779 if (Opc == ISD::UNDEF)
11782 // If all scalar values are floats and converted from integers.
11783 if (Opcode == ISD::DELETED_NODE &&
11784 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11791 EVT InVT = In.getOperand(0).getValueType();
11793 // If all scalar values are typed differently, bail out. It's chosen to
11794 // simplify BUILD_VECTOR of integer types.
11795 if (SrcVT == MVT::Other)
11802 // If the vector has just one element defined, it's not worth to fold it into
11803 // a vectorized one.
11807 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11808 && "Should only handle conversion from integer to float.");
11809 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11811 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11813 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11816 // Just because the floating-point vector type is legal does not necessarily
11817 // mean that the corresponding integer vector type is.
11818 if (!isTypeLegal(NVT))
11821 SmallVector<SDValue, 8> Opnds;
11822 for (unsigned i = 0; i != NumInScalars; ++i) {
11823 SDValue In = N->getOperand(i);
11825 if (In.getOpcode() == ISD::UNDEF)
11826 Opnds.push_back(DAG.getUNDEF(SrcVT));
11828 Opnds.push_back(In.getOperand(0));
11830 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11831 AddToWorklist(BV.getNode());
11833 return DAG.getNode(Opcode, dl, VT, BV);
11836 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11837 unsigned NumInScalars = N->getNumOperands();
11839 EVT VT = N->getValueType(0);
11841 // A vector built entirely of undefs is undef.
11842 if (ISD::allOperandsUndef(N))
11843 return DAG.getUNDEF(VT);
11845 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11848 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11851 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11852 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11853 // at most two distinct vectors, turn this into a shuffle node.
11855 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11856 if (!isTypeLegal(VT))
11859 // May only combine to shuffle after legalize if shuffle is legal.
11860 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11863 SDValue VecIn1, VecIn2;
11864 bool UsesZeroVector = false;
11865 for (unsigned i = 0; i != NumInScalars; ++i) {
11866 SDValue Op = N->getOperand(i);
11867 // Ignore undef inputs.
11868 if (Op.getOpcode() == ISD::UNDEF) continue;
11870 // See if we can combine this build_vector into a blend with a zero vector.
11871 if (!VecIn2.getNode() && (isNullConstant(Op) ||
11872 (Op.getOpcode() == ISD::ConstantFP &&
11873 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11874 UsesZeroVector = true;
11878 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11879 // constant index, bail out.
11880 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11881 !isa<ConstantSDNode>(Op.getOperand(1))) {
11882 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11886 // We allow up to two distinct input vectors.
11887 SDValue ExtractedFromVec = Op.getOperand(0);
11888 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11891 if (!VecIn1.getNode()) {
11892 VecIn1 = ExtractedFromVec;
11893 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11894 VecIn2 = ExtractedFromVec;
11896 // Too many inputs.
11897 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11902 // If everything is good, we can make a shuffle operation.
11903 if (VecIn1.getNode()) {
11904 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11905 SmallVector<int, 8> Mask;
11906 for (unsigned i = 0; i != NumInScalars; ++i) {
11907 unsigned Opcode = N->getOperand(i).getOpcode();
11908 if (Opcode == ISD::UNDEF) {
11909 Mask.push_back(-1);
11913 // Operands can also be zero.
11914 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11915 assert(UsesZeroVector &&
11916 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11917 "Unexpected node found!");
11918 Mask.push_back(NumInScalars+i);
11922 // If extracting from the first vector, just use the index directly.
11923 SDValue Extract = N->getOperand(i);
11924 SDValue ExtVal = Extract.getOperand(1);
11925 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11926 if (Extract.getOperand(0) == VecIn1) {
11927 Mask.push_back(ExtIndex);
11931 // Otherwise, use InIdx + InputVecSize
11932 Mask.push_back(InNumElements + ExtIndex);
11935 // Avoid introducing illegal shuffles with zero.
11936 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11939 // We can't generate a shuffle node with mismatched input and output types.
11940 // Attempt to transform a single input vector to the correct type.
11941 if ((VT != VecIn1.getValueType())) {
11942 // If the input vector type has a different base type to the output
11943 // vector type, bail out.
11944 EVT VTElemType = VT.getVectorElementType();
11945 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11946 (VecIn2.getNode() &&
11947 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11950 // If the input vector is too small, widen it.
11951 // We only support widening of vectors which are half the size of the
11952 // output registers. For example XMM->YMM widening on X86 with AVX.
11953 EVT VecInT = VecIn1.getValueType();
11954 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11955 // If we only have one small input, widen it by adding undef values.
11956 if (!VecIn2.getNode())
11957 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11958 DAG.getUNDEF(VecIn1.getValueType()));
11959 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11960 // If we have two small inputs of the same type, try to concat them.
11961 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11962 VecIn2 = SDValue(nullptr, 0);
11965 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11966 // If the input vector is too large, try to split it.
11967 // We don't support having two input vectors that are too large.
11968 // If the zero vector was used, we can not split the vector,
11969 // since we'd need 3 inputs.
11970 if (UsesZeroVector || VecIn2.getNode())
11973 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11976 // Try to replace VecIn1 with two extract_subvectors
11977 // No need to update the masks, they should still be correct.
11978 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11979 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11980 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11981 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11986 if (UsesZeroVector)
11987 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11988 DAG.getConstantFP(0.0, dl, VT);
11990 // If VecIn2 is unused then change it to undef.
11991 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11993 // Check that we were able to transform all incoming values to the same
11995 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11996 VecIn1.getValueType() != VT)
11999 // Return the new VECTOR_SHUFFLE node.
12003 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12009 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12010 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12011 EVT OpVT = N->getOperand(0).getValueType();
12013 // If the operands are legal vectors, leave them alone.
12014 if (TLI.isTypeLegal(OpVT))
12018 EVT VT = N->getValueType(0);
12019 SmallVector<SDValue, 8> Ops;
12021 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12022 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12024 // Keep track of what we encounter.
12025 bool AnyInteger = false;
12026 bool AnyFP = false;
12027 for (const SDValue &Op : N->ops()) {
12028 if (ISD::BITCAST == Op.getOpcode() &&
12029 !Op.getOperand(0).getValueType().isVector())
12030 Ops.push_back(Op.getOperand(0));
12031 else if (ISD::UNDEF == Op.getOpcode())
12032 Ops.push_back(ScalarUndef);
12036 // Note whether we encounter an integer or floating point scalar.
12037 // If it's neither, bail out, it could be something weird like x86mmx.
12038 EVT LastOpVT = Ops.back().getValueType();
12039 if (LastOpVT.isFloatingPoint())
12041 else if (LastOpVT.isInteger())
12047 // If any of the operands is a floating point scalar bitcast to a vector,
12048 // use floating point types throughout, and bitcast everything.
12049 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12051 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12052 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12054 for (SDValue &Op : Ops) {
12055 if (Op.getValueType() == SVT)
12057 if (Op.getOpcode() == ISD::UNDEF)
12060 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12065 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12066 VT.getSizeInBits() / SVT.getSizeInBits());
12067 return DAG.getNode(ISD::BITCAST, DL, VT,
12068 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12071 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12072 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12073 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12074 // inputs come from at most two distinct vectors, turn this into a shuffle
12077 // If we only have one input vector, we don't need to do any concatenation.
12078 if (N->getNumOperands() == 1)
12079 return N->getOperand(0);
12081 // Check if all of the operands are undefs.
12082 EVT VT = N->getValueType(0);
12083 if (ISD::allOperandsUndef(N))
12084 return DAG.getUNDEF(VT);
12086 // Optimize concat_vectors where all but the first of the vectors are undef.
12087 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12088 return Op.getOpcode() == ISD::UNDEF;
12090 SDValue In = N->getOperand(0);
12091 assert(In.getValueType().isVector() && "Must concat vectors");
12093 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12094 if (In->getOpcode() == ISD::BITCAST &&
12095 !In->getOperand(0)->getValueType(0).isVector()) {
12096 SDValue Scalar = In->getOperand(0);
12098 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12099 // look through the trunc so we can still do the transform:
12100 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12101 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12102 !TLI.isTypeLegal(Scalar.getValueType()) &&
12103 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12104 Scalar = Scalar->getOperand(0);
12106 EVT SclTy = Scalar->getValueType(0);
12108 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12111 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12112 VT.getSizeInBits() / SclTy.getSizeInBits());
12113 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12116 SDLoc dl = SDLoc(N);
12117 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12118 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12122 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12123 // We have already tested above for an UNDEF only concatenation.
12124 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12125 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12126 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12127 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12129 bool AllBuildVectorsOrUndefs =
12130 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12131 if (AllBuildVectorsOrUndefs) {
12132 SmallVector<SDValue, 8> Opnds;
12133 EVT SVT = VT.getScalarType();
12136 if (!SVT.isFloatingPoint()) {
12137 // If BUILD_VECTOR are from built from integer, they may have different
12138 // operand types. Get the smallest type and truncate all operands to it.
12139 bool FoundMinVT = false;
12140 for (const SDValue &Op : N->ops())
12141 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12142 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12143 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12146 assert(FoundMinVT && "Concat vector type mismatch");
12149 for (const SDValue &Op : N->ops()) {
12150 EVT OpVT = Op.getValueType();
12151 unsigned NumElts = OpVT.getVectorNumElements();
12153 if (ISD::UNDEF == Op.getOpcode())
12154 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12156 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12157 if (SVT.isFloatingPoint()) {
12158 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12159 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12161 for (unsigned i = 0; i != NumElts; ++i)
12163 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12168 assert(VT.getVectorNumElements() == Opnds.size() &&
12169 "Concat vector type mismatch");
12170 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12173 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12174 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12177 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12178 // nodes often generate nop CONCAT_VECTOR nodes.
12179 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12180 // place the incoming vectors at the exact same location.
12181 SDValue SingleSource = SDValue();
12182 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12184 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12185 SDValue Op = N->getOperand(i);
12187 if (Op.getOpcode() == ISD::UNDEF)
12190 // Check if this is the identity extract:
12191 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12194 // Find the single incoming vector for the extract_subvector.
12195 if (SingleSource.getNode()) {
12196 if (Op.getOperand(0) != SingleSource)
12199 SingleSource = Op.getOperand(0);
12201 // Check the source type is the same as the type of the result.
12202 // If not, this concat may extend the vector, so we can not
12203 // optimize it away.
12204 if (SingleSource.getValueType() != N->getValueType(0))
12208 unsigned IdentityIndex = i * PartNumElem;
12209 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12210 // The extract index must be constant.
12214 // Check that we are reading from the identity index.
12215 if (CS->getZExtValue() != IdentityIndex)
12219 if (SingleSource.getNode())
12220 return SingleSource;
12225 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12226 EVT NVT = N->getValueType(0);
12227 SDValue V = N->getOperand(0);
12229 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12231 // (extract_subvec (concat V1, V2, ...), i)
12234 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12236 if (V->getOperand(0).getValueType() != NVT)
12238 unsigned Idx = N->getConstantOperandVal(1);
12239 unsigned NumElems = NVT.getVectorNumElements();
12240 assert((Idx % NumElems) == 0 &&
12241 "IDX in concat is not a multiple of the result vector length.");
12242 return V->getOperand(Idx / NumElems);
12246 if (V->getOpcode() == ISD::BITCAST)
12247 V = V.getOperand(0);
12249 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12251 // Handle only simple case where vector being inserted and vector
12252 // being extracted are of same type, and are half size of larger vectors.
12253 EVT BigVT = V->getOperand(0).getValueType();
12254 EVT SmallVT = V->getOperand(1).getValueType();
12255 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12258 // Only handle cases where both indexes are constants with the same type.
12259 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12260 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12262 if (InsIdx && ExtIdx &&
12263 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12264 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12266 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12268 // indices are equal or bit offsets are equal => V1
12269 // otherwise => (extract_subvec V1, ExtIdx)
12270 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12271 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12272 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12273 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12274 DAG.getNode(ISD::BITCAST, dl,
12275 N->getOperand(0).getValueType(),
12276 V->getOperand(0)), N->getOperand(1));
12283 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12284 SDValue V, SelectionDAG &DAG) {
12286 EVT VT = V.getValueType();
12288 switch (V.getOpcode()) {
12292 case ISD::CONCAT_VECTORS: {
12293 EVT OpVT = V->getOperand(0).getValueType();
12294 int OpSize = OpVT.getVectorNumElements();
12295 SmallBitVector OpUsedElements(OpSize, false);
12296 bool FoundSimplification = false;
12297 SmallVector<SDValue, 4> NewOps;
12298 NewOps.reserve(V->getNumOperands());
12299 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12300 SDValue Op = V->getOperand(i);
12301 bool OpUsed = false;
12302 for (int j = 0; j < OpSize; ++j)
12303 if (UsedElements[i * OpSize + j]) {
12304 OpUsedElements[j] = true;
12308 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12309 : DAG.getUNDEF(OpVT));
12310 FoundSimplification |= Op == NewOps.back();
12311 OpUsedElements.reset();
12313 if (FoundSimplification)
12314 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12318 case ISD::INSERT_SUBVECTOR: {
12319 SDValue BaseV = V->getOperand(0);
12320 SDValue SubV = V->getOperand(1);
12321 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12325 int SubSize = SubV.getValueType().getVectorNumElements();
12326 int Idx = IdxN->getZExtValue();
12327 bool SubVectorUsed = false;
12328 SmallBitVector SubUsedElements(SubSize, false);
12329 for (int i = 0; i < SubSize; ++i)
12330 if (UsedElements[i + Idx]) {
12331 SubVectorUsed = true;
12332 SubUsedElements[i] = true;
12333 UsedElements[i + Idx] = false;
12336 // Now recurse on both the base and sub vectors.
12337 SDValue SimplifiedSubV =
12339 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12340 : DAG.getUNDEF(SubV.getValueType());
12341 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12342 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12343 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12344 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12350 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12351 SDValue N1, SelectionDAG &DAG) {
12352 EVT VT = SVN->getValueType(0);
12353 int NumElts = VT.getVectorNumElements();
12354 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12355 for (int M : SVN->getMask())
12356 if (M >= 0 && M < NumElts)
12357 N0UsedElements[M] = true;
12358 else if (M >= NumElts)
12359 N1UsedElements[M - NumElts] = true;
12361 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12362 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12363 if (S0 == N0 && S1 == N1)
12366 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12369 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12370 // or turn a shuffle of a single concat into simpler shuffle then concat.
12371 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12372 EVT VT = N->getValueType(0);
12373 unsigned NumElts = VT.getVectorNumElements();
12375 SDValue N0 = N->getOperand(0);
12376 SDValue N1 = N->getOperand(1);
12377 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12379 SmallVector<SDValue, 4> Ops;
12380 EVT ConcatVT = N0.getOperand(0).getValueType();
12381 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12382 unsigned NumConcats = NumElts / NumElemsPerConcat;
12384 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12385 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12386 // half vector elements.
12387 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12388 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12389 SVN->getMask().end(), [](int i) { return i == -1; })) {
12390 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12391 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12392 N1 = DAG.getUNDEF(ConcatVT);
12393 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12396 // Look at every vector that's inserted. We're looking for exact
12397 // subvector-sized copies from a concatenated vector
12398 for (unsigned I = 0; I != NumConcats; ++I) {
12399 // Make sure we're dealing with a copy.
12400 unsigned Begin = I * NumElemsPerConcat;
12401 bool AllUndef = true, NoUndef = true;
12402 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12403 if (SVN->getMaskElt(J) >= 0)
12410 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12413 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12414 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12417 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12418 if (FirstElt < N0.getNumOperands())
12419 Ops.push_back(N0.getOperand(FirstElt));
12421 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12423 } else if (AllUndef) {
12424 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12425 } else { // Mixed with general masks and undefs, can't do optimization.
12430 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12433 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12434 EVT VT = N->getValueType(0);
12435 unsigned NumElts = VT.getVectorNumElements();
12437 SDValue N0 = N->getOperand(0);
12438 SDValue N1 = N->getOperand(1);
12440 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12442 // Canonicalize shuffle undef, undef -> undef
12443 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12444 return DAG.getUNDEF(VT);
12446 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12448 // Canonicalize shuffle v, v -> v, undef
12450 SmallVector<int, 8> NewMask;
12451 for (unsigned i = 0; i != NumElts; ++i) {
12452 int Idx = SVN->getMaskElt(i);
12453 if (Idx >= (int)NumElts) Idx -= NumElts;
12454 NewMask.push_back(Idx);
12456 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12460 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12461 if (N0.getOpcode() == ISD::UNDEF) {
12462 SmallVector<int, 8> NewMask;
12463 for (unsigned i = 0; i != NumElts; ++i) {
12464 int Idx = SVN->getMaskElt(i);
12466 if (Idx >= (int)NumElts)
12469 Idx = -1; // remove reference to lhs
12471 NewMask.push_back(Idx);
12473 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12477 // Remove references to rhs if it is undef
12478 if (N1.getOpcode() == ISD::UNDEF) {
12479 bool Changed = false;
12480 SmallVector<int, 8> NewMask;
12481 for (unsigned i = 0; i != NumElts; ++i) {
12482 int Idx = SVN->getMaskElt(i);
12483 if (Idx >= (int)NumElts) {
12487 NewMask.push_back(Idx);
12490 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12493 // If it is a splat, check if the argument vector is another splat or a
12495 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12496 SDNode *V = N0.getNode();
12498 // If this is a bit convert that changes the element type of the vector but
12499 // not the number of vector elements, look through it. Be careful not to
12500 // look though conversions that change things like v4f32 to v2f64.
12501 if (V->getOpcode() == ISD::BITCAST) {
12502 SDValue ConvInput = V->getOperand(0);
12503 if (ConvInput.getValueType().isVector() &&
12504 ConvInput.getValueType().getVectorNumElements() == NumElts)
12505 V = ConvInput.getNode();
12508 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12509 assert(V->getNumOperands() == NumElts &&
12510 "BUILD_VECTOR has wrong number of operands");
12512 bool AllSame = true;
12513 for (unsigned i = 0; i != NumElts; ++i) {
12514 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12515 Base = V->getOperand(i);
12519 // Splat of <u, u, u, u>, return <u, u, u, u>
12520 if (!Base.getNode())
12522 for (unsigned i = 0; i != NumElts; ++i) {
12523 if (V->getOperand(i) != Base) {
12528 // Splat of <x, x, x, x>, return <x, x, x, x>
12532 // Canonicalize any other splat as a build_vector.
12533 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12534 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12535 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12536 V->getValueType(0), Ops);
12538 // We may have jumped through bitcasts, so the type of the
12539 // BUILD_VECTOR may not match the type of the shuffle.
12540 if (V->getValueType(0) != VT)
12541 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12546 // There are various patterns used to build up a vector from smaller vectors,
12547 // subvectors, or elements. Scan chains of these and replace unused insertions
12548 // or components with undef.
12549 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12552 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12553 Level < AfterLegalizeVectorOps &&
12554 (N1.getOpcode() == ISD::UNDEF ||
12555 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12556 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12557 SDValue V = partitionShuffleOfConcats(N, DAG);
12563 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12564 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12565 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12566 SmallVector<SDValue, 8> Ops;
12567 for (int M : SVN->getMask()) {
12568 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12570 int Idx = M % NumElts;
12571 SDValue &S = (M < (int)NumElts ? N0 : N1);
12572 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12573 Op = S.getOperand(Idx);
12574 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12576 Op = S.getOperand(0);
12578 // Operand can't be combined - bail out.
12584 if (Ops.size() == VT.getVectorNumElements()) {
12585 // BUILD_VECTOR requires all inputs to be of the same type, find the
12586 // maximum type and extend them all.
12587 EVT SVT = VT.getScalarType();
12588 if (SVT.isInteger())
12589 for (SDValue &Op : Ops)
12590 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12591 if (SVT != VT.getScalarType())
12592 for (SDValue &Op : Ops)
12593 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12594 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12595 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12596 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12600 // If this shuffle only has a single input that is a bitcasted shuffle,
12601 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12602 // back to their original types.
12603 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12604 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12605 TLI.isTypeLegal(VT)) {
12607 // Peek through the bitcast only if there is one user.
12609 while (BC0.getOpcode() == ISD::BITCAST) {
12610 if (!BC0.hasOneUse())
12612 BC0 = BC0.getOperand(0);
12615 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12617 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12619 SmallVector<int, 8> NewMask;
12621 for (int s = 0; s != Scale; ++s)
12622 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12626 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12627 EVT SVT = VT.getScalarType();
12628 EVT InnerVT = BC0->getValueType(0);
12629 EVT InnerSVT = InnerVT.getScalarType();
12631 // Determine which shuffle works with the smaller scalar type.
12632 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12633 EVT ScaleSVT = ScaleVT.getScalarType();
12635 if (TLI.isTypeLegal(ScaleVT) &&
12636 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12637 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12639 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12640 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12642 // Scale the shuffle masks to the smaller scalar type.
12643 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12644 SmallVector<int, 8> InnerMask =
12645 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12646 SmallVector<int, 8> OuterMask =
12647 ScaleShuffleMask(SVN->getMask(), OuterScale);
12649 // Merge the shuffle masks.
12650 SmallVector<int, 8> NewMask;
12651 for (int M : OuterMask)
12652 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12654 // Test for shuffle mask legality over both commutations.
12655 SDValue SV0 = BC0->getOperand(0);
12656 SDValue SV1 = BC0->getOperand(1);
12657 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12659 std::swap(SV0, SV1);
12660 ShuffleVectorSDNode::commuteMask(NewMask);
12661 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12665 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12666 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12667 return DAG.getNode(
12668 ISD::BITCAST, SDLoc(N), VT,
12669 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12675 // Canonicalize shuffles according to rules:
12676 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12677 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12678 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12679 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12680 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12681 TLI.isTypeLegal(VT)) {
12682 // The incoming shuffle must be of the same type as the result of the
12683 // current shuffle.
12684 assert(N1->getOperand(0).getValueType() == VT &&
12685 "Shuffle types don't match");
12687 SDValue SV0 = N1->getOperand(0);
12688 SDValue SV1 = N1->getOperand(1);
12689 bool HasSameOp0 = N0 == SV0;
12690 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12691 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12692 // Commute the operands of this shuffle so that next rule
12694 return DAG.getCommutedVectorShuffle(*SVN);
12697 // Try to fold according to rules:
12698 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12699 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12700 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12701 // Don't try to fold shuffles with illegal type.
12702 // Only fold if this shuffle is the only user of the other shuffle.
12703 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12704 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12705 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12707 // The incoming shuffle must be of the same type as the result of the
12708 // current shuffle.
12709 assert(OtherSV->getOperand(0).getValueType() == VT &&
12710 "Shuffle types don't match");
12713 SmallVector<int, 4> Mask;
12714 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12715 // operand, and SV1 as the second operand.
12716 for (unsigned i = 0; i != NumElts; ++i) {
12717 int Idx = SVN->getMaskElt(i);
12719 // Propagate Undef.
12720 Mask.push_back(Idx);
12724 SDValue CurrentVec;
12725 if (Idx < (int)NumElts) {
12726 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12727 // shuffle mask to identify which vector is actually referenced.
12728 Idx = OtherSV->getMaskElt(Idx);
12730 // Propagate Undef.
12731 Mask.push_back(Idx);
12735 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12736 : OtherSV->getOperand(1);
12738 // This shuffle index references an element within N1.
12742 // Simple case where 'CurrentVec' is UNDEF.
12743 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12744 Mask.push_back(-1);
12748 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12749 // will be the first or second operand of the combined shuffle.
12750 Idx = Idx % NumElts;
12751 if (!SV0.getNode() || SV0 == CurrentVec) {
12752 // Ok. CurrentVec is the left hand side.
12753 // Update the mask accordingly.
12755 Mask.push_back(Idx);
12759 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12760 if (SV1.getNode() && SV1 != CurrentVec)
12763 // Ok. CurrentVec is the right hand side.
12764 // Update the mask accordingly.
12766 Mask.push_back(Idx + NumElts);
12769 // Check if all indices in Mask are Undef. In case, propagate Undef.
12770 bool isUndefMask = true;
12771 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12772 isUndefMask &= Mask[i] < 0;
12775 return DAG.getUNDEF(VT);
12777 if (!SV0.getNode())
12778 SV0 = DAG.getUNDEF(VT);
12779 if (!SV1.getNode())
12780 SV1 = DAG.getUNDEF(VT);
12782 // Avoid introducing shuffles with illegal mask.
12783 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12784 ShuffleVectorSDNode::commuteMask(Mask);
12786 if (!TLI.isShuffleMaskLegal(Mask, VT))
12789 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12790 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12791 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12792 std::swap(SV0, SV1);
12795 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12796 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12797 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12798 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12804 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12805 SDValue InVal = N->getOperand(0);
12806 EVT VT = N->getValueType(0);
12808 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12809 // with a VECTOR_SHUFFLE.
12810 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12811 SDValue InVec = InVal->getOperand(0);
12812 SDValue EltNo = InVal->getOperand(1);
12814 // FIXME: We could support implicit truncation if the shuffle can be
12815 // scaled to a smaller vector scalar type.
12816 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12817 if (C0 && VT == InVec.getValueType() &&
12818 VT.getScalarType() == InVal.getValueType()) {
12819 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12820 int Elt = C0->getZExtValue();
12823 if (TLI.isShuffleMaskLegal(NewMask, VT))
12824 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12832 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12833 SDValue N0 = N->getOperand(0);
12834 SDValue N2 = N->getOperand(2);
12836 // If the input vector is a concatenation, and the insert replaces
12837 // one of the halves, we can optimize into a single concat_vectors.
12838 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12839 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12840 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12841 EVT VT = N->getValueType(0);
12843 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12844 // (concat_vectors Z, Y)
12846 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12847 N->getOperand(1), N0.getOperand(1));
12849 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12850 // (concat_vectors X, Z)
12851 if (InsIdx == VT.getVectorNumElements()/2)
12852 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12853 N0.getOperand(0), N->getOperand(1));
12859 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12860 SDValue N0 = N->getOperand(0);
12862 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12863 if (N0->getOpcode() == ISD::FP16_TO_FP)
12864 return N0->getOperand(0);
12869 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12870 /// with the destination vector and a zero vector.
12871 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12872 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12873 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12874 EVT VT = N->getValueType(0);
12875 SDValue LHS = N->getOperand(0);
12876 SDValue RHS = N->getOperand(1);
12879 // Make sure we're not running after operation legalization where it
12880 // may have custom lowered the vector shuffles.
12881 if (LegalOperations)
12884 if (N->getOpcode() != ISD::AND)
12887 if (RHS.getOpcode() == ISD::BITCAST)
12888 RHS = RHS.getOperand(0);
12890 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12891 SmallVector<int, 8> Indices;
12892 unsigned NumElts = RHS.getNumOperands();
12894 for (unsigned i = 0; i != NumElts; ++i) {
12895 SDValue Elt = RHS.getOperand(i);
12896 if (isAllOnesConstant(Elt))
12897 Indices.push_back(i);
12898 else if (isNullConstant(Elt))
12899 Indices.push_back(NumElts+i);
12904 // Let's see if the target supports this vector_shuffle.
12905 EVT RVT = RHS.getValueType();
12906 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12909 // Return the new VECTOR_SHUFFLE node.
12910 EVT EltVT = RVT.getVectorElementType();
12911 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12912 DAG.getConstant(0, dl, EltVT));
12913 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12914 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12915 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12916 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12922 /// Visit a binary vector operation, like ADD.
12923 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12924 assert(N->getValueType(0).isVector() &&
12925 "SimplifyVBinOp only works on vectors!");
12927 SDValue LHS = N->getOperand(0);
12928 SDValue RHS = N->getOperand(1);
12930 if (SDValue Shuffle = XformToShuffleWithZero(N))
12933 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12935 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12936 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12937 // Check if both vectors are constants. If not bail out.
12938 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12939 cast<BuildVectorSDNode>(RHS)->isConstant()))
12942 SmallVector<SDValue, 8> Ops;
12943 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12944 SDValue LHSOp = LHS.getOperand(i);
12945 SDValue RHSOp = RHS.getOperand(i);
12947 // Can't fold divide by zero.
12948 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12949 N->getOpcode() == ISD::FDIV) {
12950 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
12951 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12955 EVT VT = LHSOp.getValueType();
12956 EVT RVT = RHSOp.getValueType();
12958 // Integer BUILD_VECTOR operands may have types larger than the element
12959 // size (e.g., when the element type is not legal). Prior to type
12960 // legalization, the types may not match between the two BUILD_VECTORS.
12961 // Truncate one of the operands to make them match.
12962 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12963 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12965 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12969 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12971 if (FoldOp.getOpcode() != ISD::UNDEF &&
12972 FoldOp.getOpcode() != ISD::Constant &&
12973 FoldOp.getOpcode() != ISD::ConstantFP)
12975 Ops.push_back(FoldOp);
12976 AddToWorklist(FoldOp.getNode());
12979 if (Ops.size() == LHS.getNumOperands())
12980 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12983 // Type legalization might introduce new shuffles in the DAG.
12984 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12985 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12986 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12987 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12988 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12989 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12990 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12991 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12993 if (SVN0->getMask().equals(SVN1->getMask())) {
12994 EVT VT = N->getValueType(0);
12995 SDValue UndefVector = LHS.getOperand(1);
12996 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12997 LHS.getOperand(0), RHS.getOperand(0));
12998 AddUsersToWorklist(N);
12999 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13000 &SVN0->getMask()[0]);
13007 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13008 SDValue N1, SDValue N2){
13009 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13011 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13012 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13014 // If we got a simplified select_cc node back from SimplifySelectCC, then
13015 // break it down into a new SETCC node, and a new SELECT node, and then return
13016 // the SELECT node, since we were called with a SELECT node.
13017 if (SCC.getNode()) {
13018 // Check to see if we got a select_cc back (to turn into setcc/select).
13019 // Otherwise, just return whatever node we got back, like fabs.
13020 if (SCC.getOpcode() == ISD::SELECT_CC) {
13021 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13023 SCC.getOperand(0), SCC.getOperand(1),
13024 SCC.getOperand(4));
13025 AddToWorklist(SETCC.getNode());
13026 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13027 SCC.getOperand(2), SCC.getOperand(3));
13035 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13036 /// being selected between, see if we can simplify the select. Callers of this
13037 /// should assume that TheSelect is deleted if this returns true. As such, they
13038 /// should return the appropriate thing (e.g. the node) back to the top-level of
13039 /// the DAG combiner loop to avoid it being looked at.
13040 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13043 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13044 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13045 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13046 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13047 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13048 SDValue Sqrt = RHS;
13051 const ConstantFPSDNode *NegZero = nullptr;
13053 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13054 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13055 CmpLHS = TheSelect->getOperand(0);
13056 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13058 // SELECT or VSELECT
13059 SDValue Cmp = TheSelect->getOperand(0);
13060 if (Cmp.getOpcode() == ISD::SETCC) {
13061 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13062 CmpLHS = Cmp.getOperand(0);
13063 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13066 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13067 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13068 CC == ISD::SETULT || CC == ISD::SETLT)) {
13069 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13070 CombineTo(TheSelect, Sqrt);
13075 // Cannot simplify select with vector condition
13076 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13078 // If this is a select from two identical things, try to pull the operation
13079 // through the select.
13080 if (LHS.getOpcode() != RHS.getOpcode() ||
13081 !LHS.hasOneUse() || !RHS.hasOneUse())
13084 // If this is a load and the token chain is identical, replace the select
13085 // of two loads with a load through a select of the address to load from.
13086 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13087 // constants have been dropped into the constant pool.
13088 if (LHS.getOpcode() == ISD::LOAD) {
13089 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13090 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13092 // Token chains must be identical.
13093 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13094 // Do not let this transformation reduce the number of volatile loads.
13095 LLD->isVolatile() || RLD->isVolatile() ||
13096 // FIXME: If either is a pre/post inc/dec load,
13097 // we'd need to split out the address adjustment.
13098 LLD->isIndexed() || RLD->isIndexed() ||
13099 // If this is an EXTLOAD, the VT's must match.
13100 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13101 // If this is an EXTLOAD, the kind of extension must match.
13102 (LLD->getExtensionType() != RLD->getExtensionType() &&
13103 // The only exception is if one of the extensions is anyext.
13104 LLD->getExtensionType() != ISD::EXTLOAD &&
13105 RLD->getExtensionType() != ISD::EXTLOAD) ||
13106 // FIXME: this discards src value information. This is
13107 // over-conservative. It would be beneficial to be able to remember
13108 // both potential memory locations. Since we are discarding
13109 // src value info, don't do the transformation if the memory
13110 // locations are not in the default address space.
13111 LLD->getPointerInfo().getAddrSpace() != 0 ||
13112 RLD->getPointerInfo().getAddrSpace() != 0 ||
13113 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13114 LLD->getBasePtr().getValueType()))
13117 // Check that the select condition doesn't reach either load. If so,
13118 // folding this will induce a cycle into the DAG. If not, this is safe to
13119 // xform, so create a select of the addresses.
13121 if (TheSelect->getOpcode() == ISD::SELECT) {
13122 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13123 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13124 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13126 // The loads must not depend on one another.
13127 if (LLD->isPredecessorOf(RLD) ||
13128 RLD->isPredecessorOf(LLD))
13130 Addr = DAG.getSelect(SDLoc(TheSelect),
13131 LLD->getBasePtr().getValueType(),
13132 TheSelect->getOperand(0), LLD->getBasePtr(),
13133 RLD->getBasePtr());
13134 } else { // Otherwise SELECT_CC
13135 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13136 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13138 if ((LLD->hasAnyUseOfValue(1) &&
13139 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13140 (RLD->hasAnyUseOfValue(1) &&
13141 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13144 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13145 LLD->getBasePtr().getValueType(),
13146 TheSelect->getOperand(0),
13147 TheSelect->getOperand(1),
13148 LLD->getBasePtr(), RLD->getBasePtr(),
13149 TheSelect->getOperand(4));
13153 // It is safe to replace the two loads if they have different alignments,
13154 // but the new load must be the minimum (most restrictive) alignment of the
13156 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13157 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13158 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13159 Load = DAG.getLoad(TheSelect->getValueType(0),
13161 // FIXME: Discards pointer and AA info.
13162 LLD->getChain(), Addr, MachinePointerInfo(),
13163 LLD->isVolatile(), LLD->isNonTemporal(),
13164 isInvariant, Alignment);
13166 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13167 RLD->getExtensionType() : LLD->getExtensionType(),
13169 TheSelect->getValueType(0),
13170 // FIXME: Discards pointer and AA info.
13171 LLD->getChain(), Addr, MachinePointerInfo(),
13172 LLD->getMemoryVT(), LLD->isVolatile(),
13173 LLD->isNonTemporal(), isInvariant, Alignment);
13176 // Users of the select now use the result of the load.
13177 CombineTo(TheSelect, Load);
13179 // Users of the old loads now use the new load's chain. We know the
13180 // old-load value is dead now.
13181 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13182 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13189 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13190 /// where 'cond' is the comparison specified by CC.
13191 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13192 SDValue N2, SDValue N3,
13193 ISD::CondCode CC, bool NotExtCompare) {
13194 // (x ? y : y) -> y.
13195 if (N2 == N3) return N2;
13197 EVT VT = N2.getValueType();
13198 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13199 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13201 // Determine if the condition we're dealing with is constant
13202 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13203 N0, N1, CC, DL, false);
13204 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13206 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13207 // fold select_cc true, x, y -> x
13208 // fold select_cc false, x, y -> y
13209 return !SCCC->isNullValue() ? N2 : N3;
13212 // Check to see if we can simplify the select into an fabs node
13213 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13214 // Allow either -0.0 or 0.0
13215 if (CFP->getValueAPF().isZero()) {
13216 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13217 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13218 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13219 N2 == N3.getOperand(0))
13220 return DAG.getNode(ISD::FABS, DL, VT, N0);
13222 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13223 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13224 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13225 N2.getOperand(0) == N3)
13226 return DAG.getNode(ISD::FABS, DL, VT, N3);
13230 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13231 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13232 // in it. This is a win when the constant is not otherwise available because
13233 // it replaces two constant pool loads with one. We only do this if the FP
13234 // type is known to be legal, because if it isn't, then we are before legalize
13235 // types an we want the other legalization to happen first (e.g. to avoid
13236 // messing with soft float) and if the ConstantFP is not legal, because if
13237 // it is legal, we may not need to store the FP constant in a constant pool.
13238 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13239 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13240 if (TLI.isTypeLegal(N2.getValueType()) &&
13241 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13242 TargetLowering::Legal &&
13243 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13244 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13245 // If both constants have multiple uses, then we won't need to do an
13246 // extra load, they are likely around in registers for other users.
13247 (TV->hasOneUse() || FV->hasOneUse())) {
13248 Constant *Elts[] = {
13249 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13250 const_cast<ConstantFP*>(TV->getConstantFPValue())
13252 Type *FPTy = Elts[0]->getType();
13253 const DataLayout &TD = *TLI.getDataLayout();
13255 // Create a ConstantArray of the two constants.
13256 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13257 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13258 TD.getPrefTypeAlignment(FPTy));
13259 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13261 // Get the offsets to the 0 and 1 element of the array so that we can
13262 // select between them.
13263 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13264 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13265 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13267 SDValue Cond = DAG.getSetCC(DL,
13268 getSetCCResultType(N0.getValueType()),
13270 AddToWorklist(Cond.getNode());
13271 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13273 AddToWorklist(CstOffset.getNode());
13274 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13276 AddToWorklist(CPIdx.getNode());
13277 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13278 MachinePointerInfo::getConstantPool(), false,
13279 false, false, Alignment);
13283 // Check to see if we can perform the "gzip trick", transforming
13284 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13285 if (N1C && isNullConstant(N3) && CC == ISD::SETLT &&
13286 (N1C->isNullValue() || // (a < 0) ? b : 0
13287 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
13288 EVT XType = N0.getValueType();
13289 EVT AType = N2.getValueType();
13290 if (XType.bitsGE(AType)) {
13291 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13292 // single-bit constant.
13293 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13294 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13295 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13296 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13297 getShiftAmountTy(N0.getValueType()));
13298 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13300 AddToWorklist(Shift.getNode());
13302 if (XType.bitsGT(AType)) {
13303 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13304 AddToWorklist(Shift.getNode());
13307 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13310 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13312 DAG.getConstant(XType.getSizeInBits() - 1,
13314 getShiftAmountTy(N0.getValueType())));
13315 AddToWorklist(Shift.getNode());
13317 if (XType.bitsGT(AType)) {
13318 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13319 AddToWorklist(Shift.getNode());
13322 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13326 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13327 // where y is has a single bit set.
13328 // A plaintext description would be, we can turn the SELECT_CC into an AND
13329 // when the condition can be materialized as an all-ones register. Any
13330 // single bit-test can be materialized as an all-ones register with
13331 // shift-left and shift-right-arith.
13332 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13333 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13334 SDValue AndLHS = N0->getOperand(0);
13335 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13336 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13337 // Shift the tested bit over the sign bit.
13338 APInt AndMask = ConstAndRHS->getAPIntValue();
13340 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13341 getShiftAmountTy(AndLHS.getValueType()));
13342 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13344 // Now arithmetic right shift it all the way over, so the result is either
13345 // all-ones, or zero.
13347 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13348 getShiftAmountTy(Shl.getValueType()));
13349 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13351 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13355 // fold select C, 16, 0 -> shl C, 4
13356 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13357 TLI.getBooleanContents(N0.getValueType()) ==
13358 TargetLowering::ZeroOrOneBooleanContent) {
13360 // If the caller doesn't want us to simplify this into a zext of a compare,
13362 if (NotExtCompare && N2C->getAPIntValue() == 1)
13365 // Get a SetCC of the condition
13366 // NOTE: Don't create a SETCC if it's not legal on this target.
13367 if (!LegalOperations ||
13368 TLI.isOperationLegal(ISD::SETCC,
13369 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13371 // cast from setcc result type to select result type
13373 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13375 if (N2.getValueType().bitsLT(SCC.getValueType()))
13376 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13377 N2.getValueType());
13379 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13380 N2.getValueType(), SCC);
13382 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13383 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13384 N2.getValueType(), SCC);
13387 AddToWorklist(SCC.getNode());
13388 AddToWorklist(Temp.getNode());
13390 if (N2C->getAPIntValue() == 1)
13393 // shl setcc result by log2 n2c
13394 return DAG.getNode(
13395 ISD::SHL, DL, N2.getValueType(), Temp,
13396 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13397 getShiftAmountTy(Temp.getValueType())));
13401 // Check to see if this is the equivalent of setcc
13402 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13403 // otherwise, go ahead with the folds.
13404 if (0 && isNullConstant(N3) && N2C && (N2C->getAPIntValue() == 1ULL)) {
13405 EVT XType = N0.getValueType();
13406 if (!LegalOperations ||
13407 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13408 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13409 if (Res.getValueType() != VT)
13410 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13414 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13415 if (isNullConstant(N1) && CC == ISD::SETEQ &&
13416 (!LegalOperations ||
13417 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13418 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13419 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13420 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13422 getShiftAmountTy(Ctlz.getValueType())));
13424 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13425 if (isNullConstant(N1) && CC == ISD::SETGT) {
13427 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13428 XType, DAG.getConstant(0, DL, XType), N0);
13429 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13430 return DAG.getNode(ISD::SRL, DL, XType,
13431 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13432 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13433 getShiftAmountTy(XType)));
13435 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13436 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13438 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13439 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13440 getShiftAmountTy(N0.getValueType())));
13441 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13446 // Check to see if this is an integer abs.
13447 // select_cc setg[te] X, 0, X, -X ->
13448 // select_cc setgt X, -1, X, -X ->
13449 // select_cc setl[te] X, 0, -X, X ->
13450 // select_cc setlt X, 1, -X, X ->
13451 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13453 ConstantSDNode *SubC = nullptr;
13454 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13455 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13456 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13457 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13458 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13459 (N1C->isOne() && CC == ISD::SETLT)) &&
13460 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13461 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13463 EVT XType = N0.getValueType();
13464 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13466 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13468 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13469 getShiftAmountTy(N0.getValueType())));
13470 SDValue Add = DAG.getNode(ISD::ADD, DL,
13472 AddToWorklist(Shift.getNode());
13473 AddToWorklist(Add.getNode());
13474 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13481 /// This is a stub for TargetLowering::SimplifySetCC.
13482 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13483 SDValue N1, ISD::CondCode Cond,
13484 SDLoc DL, bool foldBooleans) {
13485 TargetLowering::DAGCombinerInfo
13486 DagCombineInfo(DAG, Level, false, this);
13487 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13490 /// Given an ISD::SDIV node expressing a divide by constant, return
13491 /// a DAG expression to select that will generate the same value by multiplying
13492 /// by a magic number.
13493 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13494 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13495 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13499 // Avoid division by zero.
13500 if (C->isNullValue())
13503 std::vector<SDNode*> Built;
13505 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13507 for (SDNode *N : Built)
13512 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13513 /// DAG expression that will generate the same value by right shifting.
13514 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13515 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13519 // Avoid division by zero.
13520 if (C->isNullValue())
13523 std::vector<SDNode *> Built;
13524 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13526 for (SDNode *N : Built)
13531 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13532 /// expression that will generate the same value by multiplying by a magic
13534 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13535 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13536 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13540 // Avoid division by zero.
13541 if (C->isNullValue())
13544 std::vector<SDNode*> Built;
13546 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13548 for (SDNode *N : Built)
13553 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13554 if (Level >= AfterLegalizeDAG)
13557 // Expose the DAG combiner to the target combiner implementations.
13558 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13560 unsigned Iterations = 0;
13561 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13563 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13564 // For the reciprocal, we need to find the zero of the function:
13565 // F(X) = A X - 1 [which has a zero at X = 1/A]
13567 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13568 // does not require additional intermediate precision]
13569 EVT VT = Op.getValueType();
13571 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13573 AddToWorklist(Est.getNode());
13575 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13576 for (unsigned i = 0; i < Iterations; ++i) {
13577 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13578 AddToWorklist(NewEst.getNode());
13580 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13581 AddToWorklist(NewEst.getNode());
13583 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13584 AddToWorklist(NewEst.getNode());
13586 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13587 AddToWorklist(Est.getNode());
13596 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13597 /// For the reciprocal sqrt, we need to find the zero of the function:
13598 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13600 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13601 /// As a result, we precompute A/2 prior to the iteration loop.
13602 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13603 unsigned Iterations) {
13604 EVT VT = Arg.getValueType();
13606 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13608 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13609 // this entire sequence requires only one FP constant.
13610 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13611 AddToWorklist(HalfArg.getNode());
13613 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13614 AddToWorklist(HalfArg.getNode());
13616 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13617 for (unsigned i = 0; i < Iterations; ++i) {
13618 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13619 AddToWorklist(NewEst.getNode());
13621 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13622 AddToWorklist(NewEst.getNode());
13624 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13625 AddToWorklist(NewEst.getNode());
13627 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13628 AddToWorklist(Est.getNode());
13633 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13634 /// For the reciprocal sqrt, we need to find the zero of the function:
13635 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13637 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13638 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13639 unsigned Iterations) {
13640 EVT VT = Arg.getValueType();
13642 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13643 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13645 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13646 for (unsigned i = 0; i < Iterations; ++i) {
13647 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13648 AddToWorklist(HalfEst.getNode());
13650 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13651 AddToWorklist(Est.getNode());
13653 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13654 AddToWorklist(Est.getNode());
13656 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13657 AddToWorklist(Est.getNode());
13659 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13660 AddToWorklist(Est.getNode());
13665 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13666 if (Level >= AfterLegalizeDAG)
13669 // Expose the DAG combiner to the target combiner implementations.
13670 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13671 unsigned Iterations = 0;
13672 bool UseOneConstNR = false;
13673 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13674 AddToWorklist(Est.getNode());
13676 Est = UseOneConstNR ?
13677 BuildRsqrtNROneConst(Op, Est, Iterations) :
13678 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13686 /// Return true if base is a frame index, which is known not to alias with
13687 /// anything but itself. Provides base object and offset as results.
13688 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13689 const GlobalValue *&GV, const void *&CV) {
13690 // Assume it is a primitive operation.
13691 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13693 // If it's an adding a simple constant then integrate the offset.
13694 if (Base.getOpcode() == ISD::ADD) {
13695 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13696 Base = Base.getOperand(0);
13697 Offset += C->getZExtValue();
13701 // Return the underlying GlobalValue, and update the Offset. Return false
13702 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13703 // by multiple nodes with different offsets.
13704 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13705 GV = G->getGlobal();
13706 Offset += G->getOffset();
13710 // Return the underlying Constant value, and update the Offset. Return false
13711 // for ConstantSDNodes since the same constant pool entry may be represented
13712 // by multiple nodes with different offsets.
13713 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13714 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13715 : (const void *)C->getConstVal();
13716 Offset += C->getOffset();
13719 // If it's any of the following then it can't alias with anything but itself.
13720 return isa<FrameIndexSDNode>(Base);
13723 /// Return true if there is any possibility that the two addresses overlap.
13724 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13725 // If they are the same then they must be aliases.
13726 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13728 // If they are both volatile then they cannot be reordered.
13729 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13731 // Gather base node and offset information.
13732 SDValue Base1, Base2;
13733 int64_t Offset1, Offset2;
13734 const GlobalValue *GV1, *GV2;
13735 const void *CV1, *CV2;
13736 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13737 Base1, Offset1, GV1, CV1);
13738 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13739 Base2, Offset2, GV2, CV2);
13741 // If they have a same base address then check to see if they overlap.
13742 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13743 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13744 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13746 // It is possible for different frame indices to alias each other, mostly
13747 // when tail call optimization reuses return address slots for arguments.
13748 // To catch this case, look up the actual index of frame indices to compute
13749 // the real alias relationship.
13750 if (isFrameIndex1 && isFrameIndex2) {
13751 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13752 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13753 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13754 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13755 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13758 // Otherwise, if we know what the bases are, and they aren't identical, then
13759 // we know they cannot alias.
13760 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13763 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13764 // compared to the size and offset of the access, we may be able to prove they
13765 // do not alias. This check is conservative for now to catch cases created by
13766 // splitting vector types.
13767 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13768 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13769 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13770 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13771 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13772 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13773 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13775 // There is no overlap between these relatively aligned accesses of similar
13776 // size, return no alias.
13777 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13778 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13782 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13784 : DAG.getSubtarget().useAA();
13786 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13787 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13791 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13792 // Use alias analysis information.
13793 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13794 Op1->getSrcValueOffset());
13795 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13796 Op0->getSrcValueOffset() - MinOffset;
13797 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13798 Op1->getSrcValueOffset() - MinOffset;
13799 AliasAnalysis::AliasResult AAResult =
13800 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13802 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13803 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13805 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13806 if (AAResult == AliasAnalysis::NoAlias)
13810 // Otherwise we have to assume they alias.
13814 /// Walk up chain skipping non-aliasing memory nodes,
13815 /// looking for aliasing nodes and adding them to the Aliases vector.
13816 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13817 SmallVectorImpl<SDValue> &Aliases) {
13818 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13819 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13821 // Get alias information for node.
13822 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13825 Chains.push_back(OriginalChain);
13826 unsigned Depth = 0;
13828 // Look at each chain and determine if it is an alias. If so, add it to the
13829 // aliases list. If not, then continue up the chain looking for the next
13831 while (!Chains.empty()) {
13832 SDValue Chain = Chains.back();
13835 // For TokenFactor nodes, look at each operand and only continue up the
13836 // chain until we find two aliases. If we've seen two aliases, assume we'll
13837 // find more and revert to original chain since the xform is unlikely to be
13840 // FIXME: The depth check could be made to return the last non-aliasing
13841 // chain we found before we hit a tokenfactor rather than the original
13843 if (Depth > 6 || Aliases.size() == 2) {
13845 Aliases.push_back(OriginalChain);
13849 // Don't bother if we've been before.
13850 if (!Visited.insert(Chain.getNode()).second)
13853 switch (Chain.getOpcode()) {
13854 case ISD::EntryToken:
13855 // Entry token is ideal chain operand, but handled in FindBetterChain.
13860 // Get alias information for Chain.
13861 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13862 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13864 // If chain is alias then stop here.
13865 if (!(IsLoad && IsOpLoad) &&
13866 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13867 Aliases.push_back(Chain);
13869 // Look further up the chain.
13870 Chains.push_back(Chain.getOperand(0));
13876 case ISD::TokenFactor:
13877 // We have to check each of the operands of the token factor for "small"
13878 // token factors, so we queue them up. Adding the operands to the queue
13879 // (stack) in reverse order maintains the original order and increases the
13880 // likelihood that getNode will find a matching token factor (CSE.)
13881 if (Chain.getNumOperands() > 16) {
13882 Aliases.push_back(Chain);
13885 for (unsigned n = Chain.getNumOperands(); n;)
13886 Chains.push_back(Chain.getOperand(--n));
13891 // For all other instructions we will just have to take what we can get.
13892 Aliases.push_back(Chain);
13897 // We need to be careful here to also search for aliases through the
13898 // value operand of a store, etc. Consider the following situation:
13900 // L1 = load Token1, %52
13901 // S1 = store Token1, L1, %51
13902 // L2 = load Token1, %52+8
13903 // S2 = store Token1, L2, %51+8
13904 // Token2 = Token(S1, S2)
13905 // L3 = load Token2, %53
13906 // S3 = store Token2, L3, %52
13907 // L4 = load Token2, %53+8
13908 // S4 = store Token2, L4, %52+8
13909 // If we search for aliases of S3 (which loads address %52), and we look
13910 // only through the chain, then we'll miss the trivial dependence on L1
13911 // (which also loads from %52). We then might change all loads and
13912 // stores to use Token1 as their chain operand, which could result in
13913 // copying %53 into %52 before copying %52 into %51 (which should
13916 // The problem is, however, that searching for such data dependencies
13917 // can become expensive, and the cost is not directly related to the
13918 // chain depth. Instead, we'll rule out such configurations here by
13919 // insisting that we've visited all chain users (except for users
13920 // of the original chain, which is not necessary). When doing this,
13921 // we need to look through nodes we don't care about (otherwise, things
13922 // like register copies will interfere with trivial cases).
13924 SmallVector<const SDNode *, 16> Worklist;
13925 for (const SDNode *N : Visited)
13926 if (N != OriginalChain.getNode())
13927 Worklist.push_back(N);
13929 while (!Worklist.empty()) {
13930 const SDNode *M = Worklist.pop_back_val();
13932 // We have already visited M, and want to make sure we've visited any uses
13933 // of M that we care about. For uses that we've not visisted, and don't
13934 // care about, queue them to the worklist.
13936 for (SDNode::use_iterator UI = M->use_begin(),
13937 UIE = M->use_end(); UI != UIE; ++UI)
13938 if (UI.getUse().getValueType() == MVT::Other &&
13939 Visited.insert(*UI).second) {
13940 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13941 // We've not visited this use, and we care about it (it could have an
13942 // ordering dependency with the original node).
13944 Aliases.push_back(OriginalChain);
13948 // We've not visited this use, but we don't care about it. Mark it as
13949 // visited and enqueue it to the worklist.
13950 Worklist.push_back(*UI);
13955 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13956 /// (aliasing node.)
13957 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13958 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13960 // Accumulate all the aliases to this node.
13961 GatherAllAliases(N, OldChain, Aliases);
13963 // If no operands then chain to entry token.
13964 if (Aliases.size() == 0)
13965 return DAG.getEntryNode();
13967 // If a single operand then chain to it. We don't need to revisit it.
13968 if (Aliases.size() == 1)
13971 // Construct a custom tailored token factor.
13972 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13975 /// This is the entry point for the file.
13976 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13977 CodeGenOpt::Level OptLevel) {
13978 /// This is the main entry point to this class.
13979 DAGCombiner(*this, AA, OptLevel).Run(Level);