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 SDValue DAGCombiner::visitADD(SDNode *N) {
1589 SDValue N0 = N->getOperand(0);
1590 SDValue N1 = N->getOperand(1);
1591 EVT VT = N0.getValueType();
1594 if (VT.isVector()) {
1595 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1598 // fold (add x, 0) -> x, vector edition
1599 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1601 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1605 // fold (add x, undef) -> undef
1606 if (N0.getOpcode() == ISD::UNDEF)
1608 if (N1.getOpcode() == ISD::UNDEF)
1610 // fold (add c1, c2) -> c1+c2
1611 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1612 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1614 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1615 // canonicalize constant to RHS
1616 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1617 !isConstantIntBuildVectorOrConstantInt(N1))
1618 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1619 // fold (add x, 0) -> x
1620 if (isNullConstant(N1))
1622 // fold (add Sym, c) -> Sym+c
1623 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1624 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1625 GA->getOpcode() == ISD::GlobalAddress)
1626 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1628 (uint64_t)N1C->getSExtValue());
1629 // fold ((c1-A)+c2) -> (c1+c2)-A
1630 if (N1C && N0.getOpcode() == ISD::SUB)
1631 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1633 return DAG.getNode(ISD::SUB, DL, VT,
1634 DAG.getConstant(N1C->getAPIntValue()+
1635 N0C->getAPIntValue(), DL, VT),
1639 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1641 // fold ((0-A) + B) -> B-A
1642 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1643 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1644 // fold (A + (0-B)) -> A-B
1645 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1646 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1647 // fold (A+(B-A)) -> B
1648 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1649 return N1.getOperand(0);
1650 // fold ((B-A)+A) -> B
1651 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1652 return N0.getOperand(0);
1653 // fold (A+(B-(A+C))) to (B-C)
1654 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1655 N0 == N1.getOperand(1).getOperand(0))
1656 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1657 N1.getOperand(1).getOperand(1));
1658 // fold (A+(B-(C+A))) to (B-C)
1659 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1660 N0 == N1.getOperand(1).getOperand(1))
1661 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1662 N1.getOperand(1).getOperand(0));
1663 // fold (A+((B-A)+or-C)) to (B+or-C)
1664 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1665 N1.getOperand(0).getOpcode() == ISD::SUB &&
1666 N0 == N1.getOperand(0).getOperand(1))
1667 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1668 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1670 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1671 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1672 SDValue N00 = N0.getOperand(0);
1673 SDValue N01 = N0.getOperand(1);
1674 SDValue N10 = N1.getOperand(0);
1675 SDValue N11 = N1.getOperand(1);
1677 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1678 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1679 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1680 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1683 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1684 return SDValue(N, 0);
1686 // fold (a+b) -> (a|b) iff a and b share no bits.
1687 if (VT.isInteger() && !VT.isVector()) {
1688 APInt LHSZero, LHSOne;
1689 APInt RHSZero, RHSOne;
1690 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1692 if (LHSZero.getBoolValue()) {
1693 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1695 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1696 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1697 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1698 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1699 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1704 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1705 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1706 isNullConstant(N1.getOperand(0).getOperand(0)))
1707 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1708 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1709 N1.getOperand(0).getOperand(1),
1711 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1712 isNullConstant(N0.getOperand(0).getOperand(0)))
1713 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1714 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1715 N0.getOperand(0).getOperand(1),
1718 if (N1.getOpcode() == ISD::AND) {
1719 SDValue AndOp0 = N1.getOperand(0);
1720 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1721 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1722 unsigned DestBits = VT.getScalarType().getSizeInBits();
1724 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1725 // and similar xforms where the inner op is either ~0 or 0.
1726 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1728 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1732 // add (sext i1), X -> sub X, (zext i1)
1733 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1734 N0.getOperand(0).getValueType() == MVT::i1 &&
1735 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1737 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1738 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1741 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1742 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1743 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1744 if (TN->getVT() == MVT::i1) {
1746 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1747 DAG.getConstant(1, DL, VT));
1748 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1755 SDValue DAGCombiner::visitADDC(SDNode *N) {
1756 SDValue N0 = N->getOperand(0);
1757 SDValue N1 = N->getOperand(1);
1758 EVT VT = N0.getValueType();
1760 // If the flag result is dead, turn this into an ADD.
1761 if (!N->hasAnyUseOfValue(1))
1762 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1763 DAG.getNode(ISD::CARRY_FALSE,
1764 SDLoc(N), MVT::Glue));
1766 // canonicalize constant to RHS.
1767 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1768 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1770 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1772 // fold (addc x, 0) -> x + no carry out
1773 if (isNullConstant(N1))
1774 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1775 SDLoc(N), MVT::Glue));
1777 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1778 APInt LHSZero, LHSOne;
1779 APInt RHSZero, RHSOne;
1780 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1782 if (LHSZero.getBoolValue()) {
1783 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1785 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1786 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1787 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1788 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1789 DAG.getNode(ISD::CARRY_FALSE,
1790 SDLoc(N), MVT::Glue));
1796 SDValue DAGCombiner::visitADDE(SDNode *N) {
1797 SDValue N0 = N->getOperand(0);
1798 SDValue N1 = N->getOperand(1);
1799 SDValue CarryIn = N->getOperand(2);
1801 // canonicalize constant to RHS
1802 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1803 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1805 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1808 // fold (adde x, y, false) -> (addc x, y)
1809 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1810 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1815 // Since it may not be valid to emit a fold to zero for vector initializers
1816 // check if we can before folding.
1817 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1819 bool LegalOperations, bool LegalTypes) {
1821 return DAG.getConstant(0, DL, VT);
1822 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1823 return DAG.getConstant(0, DL, VT);
1827 SDValue DAGCombiner::visitSUB(SDNode *N) {
1828 SDValue N0 = N->getOperand(0);
1829 SDValue N1 = N->getOperand(1);
1830 EVT VT = N0.getValueType();
1833 if (VT.isVector()) {
1834 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1837 // fold (sub x, 0) -> x, vector edition
1838 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1842 // fold (sub x, x) -> 0
1843 // FIXME: Refactor this and xor and other similar operations together.
1845 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1846 // fold (sub c1, c2) -> c1-c2
1847 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1848 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1850 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1851 // fold (sub x, c) -> (add x, -c)
1854 return DAG.getNode(ISD::ADD, DL, VT, N0,
1855 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1857 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1858 if (N0C && N0C->isAllOnesValue())
1859 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1860 // fold A-(A-B) -> B
1861 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1862 return N1.getOperand(1);
1863 // fold (A+B)-A -> B
1864 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1865 return N0.getOperand(1);
1866 // fold (A+B)-B -> A
1867 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1868 return N0.getOperand(0);
1869 // fold C2-(A+C1) -> (C2-C1)-A
1870 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1871 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1872 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1874 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1876 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1879 // fold ((A+(B+or-C))-B) -> A+or-C
1880 if (N0.getOpcode() == ISD::ADD &&
1881 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1882 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1883 N0.getOperand(1).getOperand(0) == N1)
1884 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1885 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1886 // fold ((A+(C+B))-B) -> A+C
1887 if (N0.getOpcode() == ISD::ADD &&
1888 N0.getOperand(1).getOpcode() == ISD::ADD &&
1889 N0.getOperand(1).getOperand(1) == N1)
1890 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1891 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1892 // fold ((A-(B-C))-C) -> A-B
1893 if (N0.getOpcode() == ISD::SUB &&
1894 N0.getOperand(1).getOpcode() == ISD::SUB &&
1895 N0.getOperand(1).getOperand(1) == N1)
1896 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1897 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1899 // If either operand of a sub is undef, the result is undef
1900 if (N0.getOpcode() == ISD::UNDEF)
1902 if (N1.getOpcode() == ISD::UNDEF)
1905 // If the relocation model supports it, consider symbol offsets.
1906 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1907 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1908 // fold (sub Sym, c) -> Sym-c
1909 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1910 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1912 (uint64_t)N1C->getSExtValue());
1913 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1914 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1915 if (GA->getGlobal() == GB->getGlobal())
1916 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1920 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1921 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1922 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1923 if (TN->getVT() == MVT::i1) {
1925 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1926 DAG.getConstant(1, DL, VT));
1927 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1934 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1935 SDValue N0 = N->getOperand(0);
1936 SDValue N1 = N->getOperand(1);
1937 EVT VT = N0.getValueType();
1939 // If the flag result is dead, turn this into an SUB.
1940 if (!N->hasAnyUseOfValue(1))
1941 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1942 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1945 // fold (subc x, x) -> 0 + no borrow
1948 return CombineTo(N, DAG.getConstant(0, DL, VT),
1949 DAG.getNode(ISD::CARRY_FALSE, DL,
1953 // fold (subc x, 0) -> x + no borrow
1954 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1955 if (isNullConstant(N1))
1956 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1959 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1960 if (N0C && N0C->isAllOnesValue())
1961 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1962 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1968 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1969 SDValue N0 = N->getOperand(0);
1970 SDValue N1 = N->getOperand(1);
1971 SDValue CarryIn = N->getOperand(2);
1973 // fold (sube x, y, false) -> (subc x, y)
1974 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1975 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1980 SDValue DAGCombiner::visitMUL(SDNode *N) {
1981 SDValue N0 = N->getOperand(0);
1982 SDValue N1 = N->getOperand(1);
1983 EVT VT = N0.getValueType();
1985 // fold (mul x, undef) -> 0
1986 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1987 return DAG.getConstant(0, SDLoc(N), VT);
1989 bool N0IsConst = false;
1990 bool N1IsConst = false;
1991 APInt ConstValue0, ConstValue1;
1993 if (VT.isVector()) {
1994 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1997 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1998 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2000 N0IsConst = isa<ConstantSDNode>(N0);
2002 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2003 N1IsConst = isa<ConstantSDNode>(N1);
2005 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2008 // fold (mul c1, c2) -> c1*c2
2009 if (N0IsConst && N1IsConst)
2010 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2011 N0.getNode(), N1.getNode());
2013 // canonicalize constant to RHS (vector doesn't have to splat)
2014 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2015 !isConstantIntBuildVectorOrConstantInt(N1))
2016 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2017 // fold (mul x, 0) -> 0
2018 if (N1IsConst && ConstValue1 == 0)
2020 // We require a splat of the entire scalar bit width for non-contiguous
2023 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2024 // fold (mul x, 1) -> x
2025 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2027 // fold (mul x, -1) -> 0-x
2028 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2030 return DAG.getNode(ISD::SUB, DL, VT,
2031 DAG.getConstant(0, DL, VT), N0);
2033 // fold (mul x, (1 << c)) -> x << c
2034 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2036 return DAG.getNode(ISD::SHL, DL, VT, N0,
2037 DAG.getConstant(ConstValue1.logBase2(), DL,
2038 getShiftAmountTy(N0.getValueType())));
2040 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2041 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2042 unsigned Log2Val = (-ConstValue1).logBase2();
2044 // FIXME: If the input is something that is easily negated (e.g. a
2045 // single-use add), we should put the negate there.
2046 return DAG.getNode(ISD::SUB, DL, VT,
2047 DAG.getConstant(0, DL, VT),
2048 DAG.getNode(ISD::SHL, DL, VT, N0,
2049 DAG.getConstant(Log2Val, DL,
2050 getShiftAmountTy(N0.getValueType()))));
2054 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2055 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2056 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2057 isa<ConstantSDNode>(N0.getOperand(1)))) {
2058 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2059 N1, N0.getOperand(1));
2060 AddToWorklist(C3.getNode());
2061 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2062 N0.getOperand(0), C3);
2065 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2068 SDValue Sh(nullptr,0), Y(nullptr,0);
2069 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2070 if (N0.getOpcode() == ISD::SHL &&
2071 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2072 isa<ConstantSDNode>(N0.getOperand(1))) &&
2073 N0.getNode()->hasOneUse()) {
2075 } else if (N1.getOpcode() == ISD::SHL &&
2076 isa<ConstantSDNode>(N1.getOperand(1)) &&
2077 N1.getNode()->hasOneUse()) {
2082 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2083 Sh.getOperand(0), Y);
2084 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2085 Mul, Sh.getOperand(1));
2089 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2090 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2091 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2092 isa<ConstantSDNode>(N0.getOperand(1))))
2093 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2094 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2095 N0.getOperand(0), N1),
2096 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2097 N0.getOperand(1), N1));
2100 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2106 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2107 SDValue N0 = N->getOperand(0);
2108 SDValue N1 = N->getOperand(1);
2109 EVT VT = N->getValueType(0);
2113 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2116 // fold (sdiv c1, c2) -> c1/c2
2117 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2118 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2119 if (N0C && N1C && !N1C->isNullValue())
2120 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2121 // fold (sdiv X, 1) -> X
2122 if (N1C && N1C->getAPIntValue() == 1LL)
2124 // fold (sdiv X, -1) -> 0-X
2125 if (N1C && N1C->isAllOnesValue()) {
2127 return DAG.getNode(ISD::SUB, DL, VT,
2128 DAG.getConstant(0, DL, VT), N0);
2130 // If we know the sign bits of both operands are zero, strength reduce to a
2131 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2132 if (!VT.isVector()) {
2133 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2134 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2138 // fold (sdiv X, pow2) -> simple ops after legalize
2139 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2140 (-N1C->getAPIntValue()).isPowerOf2())) {
2141 // If dividing by powers of two is cheap, then don't perform the following
2143 if (TLI.isPow2SDivCheap())
2146 // Target-specific implementation of sdiv x, pow2.
2147 SDValue Res = BuildSDIVPow2(N);
2151 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2154 // Splat the sign bit into the register
2156 DAG.getNode(ISD::SRA, DL, VT, N0,
2157 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2158 getShiftAmountTy(N0.getValueType())));
2159 AddToWorklist(SGN.getNode());
2161 // Add (N0 < 0) ? abs2 - 1 : 0;
2163 DAG.getNode(ISD::SRL, DL, VT, SGN,
2164 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2165 getShiftAmountTy(SGN.getValueType())));
2166 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2167 AddToWorklist(SRL.getNode());
2168 AddToWorklist(ADD.getNode()); // Divide by pow2
2169 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2170 DAG.getConstant(lg2, DL,
2171 getShiftAmountTy(ADD.getValueType())));
2173 // If we're dividing by a positive value, we're done. Otherwise, we must
2174 // negate the result.
2175 if (N1C->getAPIntValue().isNonNegative())
2178 AddToWorklist(SRA.getNode());
2179 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2182 // If integer divide is expensive and we satisfy the requirements, emit an
2183 // alternate sequence.
2184 if (N1C && !TLI.isIntDivCheap()) {
2185 SDValue Op = BuildSDIV(N);
2186 if (Op.getNode()) return Op;
2190 if (N0.getOpcode() == ISD::UNDEF)
2191 return DAG.getConstant(0, SDLoc(N), VT);
2192 // X / undef -> undef
2193 if (N1.getOpcode() == ISD::UNDEF)
2199 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2200 SDValue N0 = N->getOperand(0);
2201 SDValue N1 = N->getOperand(1);
2202 EVT VT = N->getValueType(0);
2206 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2209 // fold (udiv c1, c2) -> c1/c2
2210 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2211 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2212 if (N0C && N1C && !N1C->isNullValue())
2213 return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2214 // fold (udiv x, (1 << c)) -> x >>u c
2215 if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2217 return DAG.getNode(ISD::SRL, DL, VT, N0,
2218 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2219 getShiftAmountTy(N0.getValueType())));
2221 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2222 if (N1.getOpcode() == ISD::SHL) {
2223 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2224 if (SHC->getAPIntValue().isPowerOf2()) {
2225 EVT ADDVT = N1.getOperand(1).getValueType();
2227 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2229 DAG.getConstant(SHC->getAPIntValue()
2232 AddToWorklist(Add.getNode());
2233 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2237 // fold (udiv x, c) -> alternate
2238 if (N1C && !TLI.isIntDivCheap()) {
2239 SDValue Op = BuildUDIV(N);
2240 if (Op.getNode()) return Op;
2244 if (N0.getOpcode() == ISD::UNDEF)
2245 return DAG.getConstant(0, SDLoc(N), VT);
2246 // X / undef -> undef
2247 if (N1.getOpcode() == ISD::UNDEF)
2253 SDValue DAGCombiner::visitSREM(SDNode *N) {
2254 SDValue N0 = N->getOperand(0);
2255 SDValue N1 = N->getOperand(1);
2256 EVT VT = N->getValueType(0);
2258 // fold (srem c1, c2) -> c1%c2
2259 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2260 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2261 if (N0C && N1C && !N1C->isNullValue())
2262 return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2263 // If we know the sign bits of both operands are zero, strength reduce to a
2264 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2265 if (!VT.isVector()) {
2266 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2267 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2270 // If X/C can be simplified by the division-by-constant logic, lower
2271 // X%C to the equivalent of X-X/C*C.
2272 if (N1C && !N1C->isNullValue()) {
2273 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2274 AddToWorklist(Div.getNode());
2275 SDValue OptimizedDiv = combine(Div.getNode());
2276 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2277 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2279 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2280 AddToWorklist(Mul.getNode());
2286 if (N0.getOpcode() == ISD::UNDEF)
2287 return DAG.getConstant(0, SDLoc(N), VT);
2288 // X % undef -> undef
2289 if (N1.getOpcode() == ISD::UNDEF)
2295 SDValue DAGCombiner::visitUREM(SDNode *N) {
2296 SDValue N0 = N->getOperand(0);
2297 SDValue N1 = N->getOperand(1);
2298 EVT VT = N->getValueType(0);
2300 // fold (urem c1, c2) -> c1%c2
2301 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2302 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2303 if (N0C && N1C && !N1C->isNullValue())
2304 return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2305 // fold (urem x, pow2) -> (and x, pow2-1)
2306 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2308 return DAG.getNode(ISD::AND, DL, VT, N0,
2309 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2311 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2312 if (N1.getOpcode() == ISD::SHL) {
2313 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2314 if (SHC->getAPIntValue().isPowerOf2()) {
2317 DAG.getNode(ISD::ADD, DL, VT, N1,
2318 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2320 AddToWorklist(Add.getNode());
2321 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2326 // If X/C can be simplified by the division-by-constant logic, lower
2327 // X%C to the equivalent of X-X/C*C.
2328 if (N1C && !N1C->isNullValue()) {
2329 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2330 AddToWorklist(Div.getNode());
2331 SDValue OptimizedDiv = combine(Div.getNode());
2332 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2333 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2335 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2336 AddToWorklist(Mul.getNode());
2342 if (N0.getOpcode() == ISD::UNDEF)
2343 return DAG.getConstant(0, SDLoc(N), VT);
2344 // X % undef -> undef
2345 if (N1.getOpcode() == ISD::UNDEF)
2351 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2352 SDValue N0 = N->getOperand(0);
2353 SDValue N1 = N->getOperand(1);
2354 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2355 EVT VT = N->getValueType(0);
2358 // fold (mulhs x, 0) -> 0
2359 if (isNullConstant(N1))
2361 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2362 if (N1C && N1C->getAPIntValue() == 1) {
2364 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2365 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2367 getShiftAmountTy(N0.getValueType())));
2369 // fold (mulhs x, undef) -> 0
2370 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2371 return DAG.getConstant(0, SDLoc(N), VT);
2373 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2375 if (VT.isSimple() && !VT.isVector()) {
2376 MVT Simple = VT.getSimpleVT();
2377 unsigned SimpleSize = Simple.getSizeInBits();
2378 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2379 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2380 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2381 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2382 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2383 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2384 DAG.getConstant(SimpleSize, DL,
2385 getShiftAmountTy(N1.getValueType())));
2386 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2393 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2394 SDValue N0 = N->getOperand(0);
2395 SDValue N1 = N->getOperand(1);
2396 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2397 EVT VT = N->getValueType(0);
2400 // fold (mulhu x, 0) -> 0
2401 if (isNullConstant(N1))
2403 // fold (mulhu x, 1) -> 0
2404 if (N1C && N1C->getAPIntValue() == 1)
2405 return DAG.getConstant(0, DL, N0.getValueType());
2406 // fold (mulhu x, undef) -> 0
2407 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2408 return DAG.getConstant(0, DL, VT);
2410 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2412 if (VT.isSimple() && !VT.isVector()) {
2413 MVT Simple = VT.getSimpleVT();
2414 unsigned SimpleSize = Simple.getSizeInBits();
2415 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2416 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2417 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2418 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2419 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2420 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2421 DAG.getConstant(SimpleSize, DL,
2422 getShiftAmountTy(N1.getValueType())));
2423 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2430 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2431 /// give the opcodes for the two computations that are being performed. Return
2432 /// true if a simplification was made.
2433 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2435 // If the high half is not needed, just compute the low half.
2436 bool HiExists = N->hasAnyUseOfValue(1);
2438 (!LegalOperations ||
2439 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2440 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2441 return CombineTo(N, Res, Res);
2444 // If the low half is not needed, just compute the high half.
2445 bool LoExists = N->hasAnyUseOfValue(0);
2447 (!LegalOperations ||
2448 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2449 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2450 return CombineTo(N, Res, Res);
2453 // If both halves are used, return as it is.
2454 if (LoExists && HiExists)
2457 // If the two computed results can be simplified separately, separate them.
2459 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2460 AddToWorklist(Lo.getNode());
2461 SDValue LoOpt = combine(Lo.getNode());
2462 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2463 (!LegalOperations ||
2464 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2465 return CombineTo(N, LoOpt, LoOpt);
2469 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2470 AddToWorklist(Hi.getNode());
2471 SDValue HiOpt = combine(Hi.getNode());
2472 if (HiOpt.getNode() && HiOpt != Hi &&
2473 (!LegalOperations ||
2474 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2475 return CombineTo(N, HiOpt, HiOpt);
2481 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2482 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2483 if (Res.getNode()) return Res;
2485 EVT VT = N->getValueType(0);
2488 // If the type is twice as wide is legal, transform the mulhu to a wider
2489 // multiply plus a shift.
2490 if (VT.isSimple() && !VT.isVector()) {
2491 MVT Simple = VT.getSimpleVT();
2492 unsigned SimpleSize = Simple.getSizeInBits();
2493 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2494 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2495 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2496 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2497 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2498 // Compute the high part as N1.
2499 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2500 DAG.getConstant(SimpleSize, DL,
2501 getShiftAmountTy(Lo.getValueType())));
2502 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2503 // Compute the low part as N0.
2504 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2505 return CombineTo(N, Lo, Hi);
2512 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2513 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2514 if (Res.getNode()) return Res;
2516 EVT VT = N->getValueType(0);
2519 // If the type is twice as wide is legal, transform the mulhu to a wider
2520 // multiply plus a shift.
2521 if (VT.isSimple() && !VT.isVector()) {
2522 MVT Simple = VT.getSimpleVT();
2523 unsigned SimpleSize = Simple.getSizeInBits();
2524 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2525 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2526 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2527 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2528 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2529 // Compute the high part as N1.
2530 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2531 DAG.getConstant(SimpleSize, DL,
2532 getShiftAmountTy(Lo.getValueType())));
2533 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2534 // Compute the low part as N0.
2535 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2536 return CombineTo(N, Lo, Hi);
2543 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2544 // (smulo x, 2) -> (saddo x, x)
2545 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2546 if (C2->getAPIntValue() == 2)
2547 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2548 N->getOperand(0), N->getOperand(0));
2553 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2554 // (umulo x, 2) -> (uaddo x, x)
2555 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2556 if (C2->getAPIntValue() == 2)
2557 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2558 N->getOperand(0), N->getOperand(0));
2563 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2564 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2565 if (Res.getNode()) return Res;
2570 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2571 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2572 if (Res.getNode()) return Res;
2577 /// If this is a binary operator with two operands of the same opcode, try to
2579 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2580 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2581 EVT VT = N0.getValueType();
2582 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2584 // Bail early if none of these transforms apply.
2585 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2587 // For each of OP in AND/OR/XOR:
2588 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2589 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2590 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2591 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2592 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2594 // do not sink logical op inside of a vector extend, since it may combine
2596 EVT Op0VT = N0.getOperand(0).getValueType();
2597 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2598 N0.getOpcode() == ISD::SIGN_EXTEND ||
2599 N0.getOpcode() == ISD::BSWAP ||
2600 // Avoid infinite looping with PromoteIntBinOp.
2601 (N0.getOpcode() == ISD::ANY_EXTEND &&
2602 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2603 (N0.getOpcode() == ISD::TRUNCATE &&
2604 (!TLI.isZExtFree(VT, Op0VT) ||
2605 !TLI.isTruncateFree(Op0VT, VT)) &&
2606 TLI.isTypeLegal(Op0VT))) &&
2608 Op0VT == N1.getOperand(0).getValueType() &&
2609 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2610 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2611 N0.getOperand(0).getValueType(),
2612 N0.getOperand(0), N1.getOperand(0));
2613 AddToWorklist(ORNode.getNode());
2614 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2617 // For each of OP in SHL/SRL/SRA/AND...
2618 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2619 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2620 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2621 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2622 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2623 N0.getOperand(1) == N1.getOperand(1)) {
2624 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2625 N0.getOperand(0).getValueType(),
2626 N0.getOperand(0), N1.getOperand(0));
2627 AddToWorklist(ORNode.getNode());
2628 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2629 ORNode, N0.getOperand(1));
2632 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2633 // Only perform this optimization after type legalization and before
2634 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2635 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2636 // we don't want to undo this promotion.
2637 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2639 if ((N0.getOpcode() == ISD::BITCAST ||
2640 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2641 Level == AfterLegalizeTypes) {
2642 SDValue In0 = N0.getOperand(0);
2643 SDValue In1 = N1.getOperand(0);
2644 EVT In0Ty = In0.getValueType();
2645 EVT In1Ty = In1.getValueType();
2647 // If both incoming values are integers, and the original types are the
2649 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2650 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2651 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2652 AddToWorklist(Op.getNode());
2657 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2658 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2659 // If both shuffles use the same mask, and both shuffle within a single
2660 // vector, then it is worthwhile to move the swizzle after the operation.
2661 // The type-legalizer generates this pattern when loading illegal
2662 // vector types from memory. In many cases this allows additional shuffle
2664 // There are other cases where moving the shuffle after the xor/and/or
2665 // is profitable even if shuffles don't perform a swizzle.
2666 // If both shuffles use the same mask, and both shuffles have the same first
2667 // or second operand, then it might still be profitable to move the shuffle
2668 // after the xor/and/or operation.
2669 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2670 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2671 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2673 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2674 "Inputs to shuffles are not the same type");
2676 // Check that both shuffles use the same mask. The masks are known to be of
2677 // the same length because the result vector type is the same.
2678 // Check also that shuffles have only one use to avoid introducing extra
2680 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2681 SVN0->getMask().equals(SVN1->getMask())) {
2682 SDValue ShOp = N0->getOperand(1);
2684 // Don't try to fold this node if it requires introducing a
2685 // build vector of all zeros that might be illegal at this stage.
2686 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2688 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2693 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2694 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2695 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2696 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2697 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2698 N0->getOperand(0), N1->getOperand(0));
2699 AddToWorklist(NewNode.getNode());
2700 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2701 &SVN0->getMask()[0]);
2704 // Don't try to fold this node if it requires introducing a
2705 // build vector of all zeros that might be illegal at this stage.
2706 ShOp = N0->getOperand(0);
2707 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2709 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2714 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2715 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2716 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2717 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2718 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2719 N0->getOperand(1), N1->getOperand(1));
2720 AddToWorklist(NewNode.getNode());
2721 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2722 &SVN0->getMask()[0]);
2730 /// This contains all DAGCombine rules which reduce two values combined by
2731 /// an And operation to a single value. This makes them reusable in the context
2732 /// of visitSELECT(). Rules involving constants are not included as
2733 /// visitSELECT() already handles those cases.
2734 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2735 SDNode *LocReference) {
2736 EVT VT = N1.getValueType();
2738 // fold (and x, undef) -> 0
2739 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2740 return DAG.getConstant(0, SDLoc(LocReference), VT);
2741 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2742 SDValue LL, LR, RL, RR, CC0, CC1;
2743 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2744 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2745 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2747 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2748 LL.getValueType().isInteger()) {
2749 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2750 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2751 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2752 LR.getValueType(), LL, RL);
2753 AddToWorklist(ORNode.getNode());
2754 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2756 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2757 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2758 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2759 LR.getValueType(), LL, RL);
2760 AddToWorklist(ANDNode.getNode());
2761 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2763 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2764 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2765 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2766 LR.getValueType(), LL, RL);
2767 AddToWorklist(ORNode.getNode());
2768 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2771 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2772 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2773 Op0 == Op1 && LL.getValueType().isInteger() &&
2774 Op0 == ISD::SETNE && ((isNullConstant(LR) &&
2775 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2776 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2777 isNullConstant(RR)))) {
2779 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2780 LL, DAG.getConstant(1, DL,
2781 LL.getValueType()));
2782 AddToWorklist(ADDNode.getNode());
2783 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2784 DAG.getConstant(2, DL, LL.getValueType()),
2787 // canonicalize equivalent to ll == rl
2788 if (LL == RR && LR == RL) {
2789 Op1 = ISD::getSetCCSwappedOperands(Op1);
2792 if (LL == RL && LR == RR) {
2793 bool isInteger = LL.getValueType().isInteger();
2794 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2795 if (Result != ISD::SETCC_INVALID &&
2796 (!LegalOperations ||
2797 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2798 TLI.isOperationLegal(ISD::SETCC,
2799 getSetCCResultType(N0.getSimpleValueType())))))
2800 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2805 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2806 VT.getSizeInBits() <= 64) {
2807 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2808 APInt ADDC = ADDI->getAPIntValue();
2809 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2810 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2811 // immediate for an add, but it is legal if its top c2 bits are set,
2812 // transform the ADD so the immediate doesn't need to be materialized
2814 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2815 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2816 SRLI->getZExtValue());
2817 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2819 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2822 DAG.getNode(ISD::ADD, DL, VT,
2823 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2824 CombineTo(N0.getNode(), NewAdd);
2825 // Return N so it doesn't get rechecked!
2826 return SDValue(LocReference, 0);
2837 SDValue DAGCombiner::visitAND(SDNode *N) {
2838 SDValue N0 = N->getOperand(0);
2839 SDValue N1 = N->getOperand(1);
2840 EVT VT = N1.getValueType();
2843 if (VT.isVector()) {
2844 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2847 // fold (and x, 0) -> 0, vector edition
2848 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2849 // do not return N0, because undef node may exist in N0
2850 return DAG.getConstant(
2851 APInt::getNullValue(
2852 N0.getValueType().getScalarType().getSizeInBits()),
2853 SDLoc(N), N0.getValueType());
2854 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2855 // do not return N1, because undef node may exist in N1
2856 return DAG.getConstant(
2857 APInt::getNullValue(
2858 N1.getValueType().getScalarType().getSizeInBits()),
2859 SDLoc(N), N1.getValueType());
2861 // fold (and x, -1) -> x, vector edition
2862 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2864 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2868 // fold (and c1, c2) -> c1&c2
2869 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2870 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2872 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2873 // canonicalize constant to RHS
2874 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2875 !isConstantIntBuildVectorOrConstantInt(N1))
2876 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2877 // fold (and x, -1) -> x
2878 if (N1C && N1C->isAllOnesValue())
2880 // if (and x, c) is known to be zero, return 0
2881 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2882 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2883 APInt::getAllOnesValue(BitWidth)))
2884 return DAG.getConstant(0, SDLoc(N), VT);
2886 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2888 // fold (and (or x, C), D) -> D if (C & D) == D
2889 if (N1C && N0.getOpcode() == ISD::OR)
2890 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2891 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2893 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2894 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2895 SDValue N0Op0 = N0.getOperand(0);
2896 APInt Mask = ~N1C->getAPIntValue();
2897 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2898 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2899 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2900 N0.getValueType(), N0Op0);
2902 // Replace uses of the AND with uses of the Zero extend node.
2905 // We actually want to replace all uses of the any_extend with the
2906 // zero_extend, to avoid duplicating things. This will later cause this
2907 // AND to be folded.
2908 CombineTo(N0.getNode(), Zext);
2909 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2912 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2913 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2914 // already be zero by virtue of the width of the base type of the load.
2916 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2918 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2919 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2920 N0.getOpcode() == ISD::LOAD) {
2921 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2922 N0 : N0.getOperand(0) );
2924 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2925 // This can be a pure constant or a vector splat, in which case we treat the
2926 // vector as a scalar and use the splat value.
2927 APInt Constant = APInt::getNullValue(1);
2928 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2929 Constant = C->getAPIntValue();
2930 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2931 APInt SplatValue, SplatUndef;
2932 unsigned SplatBitSize;
2934 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2935 SplatBitSize, HasAnyUndefs);
2937 // Undef bits can contribute to a possible optimisation if set, so
2939 SplatValue |= SplatUndef;
2941 // The splat value may be something like "0x00FFFFFF", which means 0 for
2942 // the first vector value and FF for the rest, repeating. We need a mask
2943 // that will apply equally to all members of the vector, so AND all the
2944 // lanes of the constant together.
2945 EVT VT = Vector->getValueType(0);
2946 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2948 // If the splat value has been compressed to a bitlength lower
2949 // than the size of the vector lane, we need to re-expand it to
2951 if (BitWidth > SplatBitSize)
2952 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2953 SplatBitSize < BitWidth;
2954 SplatBitSize = SplatBitSize * 2)
2955 SplatValue |= SplatValue.shl(SplatBitSize);
2957 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2958 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2959 if (SplatBitSize % BitWidth == 0) {
2960 Constant = APInt::getAllOnesValue(BitWidth);
2961 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2962 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2967 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2968 // actually legal and isn't going to get expanded, else this is a false
2970 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2971 Load->getValueType(0),
2972 Load->getMemoryVT());
2974 // Resize the constant to the same size as the original memory access before
2975 // extension. If it is still the AllOnesValue then this AND is completely
2978 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2981 switch (Load->getExtensionType()) {
2982 default: B = false; break;
2983 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2985 case ISD::NON_EXTLOAD: B = true; break;
2988 if (B && Constant.isAllOnesValue()) {
2989 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2990 // preserve semantics once we get rid of the AND.
2991 SDValue NewLoad(Load, 0);
2992 if (Load->getExtensionType() == ISD::EXTLOAD) {
2993 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2994 Load->getValueType(0), SDLoc(Load),
2995 Load->getChain(), Load->getBasePtr(),
2996 Load->getOffset(), Load->getMemoryVT(),
2997 Load->getMemOperand());
2998 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2999 if (Load->getNumValues() == 3) {
3000 // PRE/POST_INC loads have 3 values.
3001 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3002 NewLoad.getValue(2) };
3003 CombineTo(Load, To, 3, true);
3005 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3009 // Fold the AND away, taking care not to fold to the old load node if we
3011 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3013 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3017 // fold (and (load x), 255) -> (zextload x, i8)
3018 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3019 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3020 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3021 (N0.getOpcode() == ISD::ANY_EXTEND &&
3022 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3023 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3024 LoadSDNode *LN0 = HasAnyExt
3025 ? cast<LoadSDNode>(N0.getOperand(0))
3026 : cast<LoadSDNode>(N0);
3027 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3028 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3029 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3030 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3031 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3032 EVT LoadedVT = LN0->getMemoryVT();
3033 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3035 if (ExtVT == LoadedVT &&
3036 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3040 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3041 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3042 LN0->getMemOperand());
3044 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3045 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3048 // Do not change the width of a volatile load.
3049 // Do not generate loads of non-round integer types since these can
3050 // be expensive (and would be wrong if the type is not byte sized).
3051 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3052 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3054 EVT PtrType = LN0->getOperand(1).getValueType();
3056 unsigned Alignment = LN0->getAlignment();
3057 SDValue NewPtr = LN0->getBasePtr();
3059 // For big endian targets, we need to add an offset to the pointer
3060 // to load the correct bytes. For little endian systems, we merely
3061 // need to read fewer bytes from the same pointer.
3062 if (TLI.isBigEndian()) {
3063 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3064 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3065 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3067 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3068 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3069 Alignment = MinAlign(Alignment, PtrOff);
3072 AddToWorklist(NewPtr.getNode());
3075 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3076 LN0->getChain(), NewPtr,
3077 LN0->getPointerInfo(),
3078 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3079 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3081 CombineTo(LN0, Load, Load.getValue(1));
3082 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3088 if (SDValue Combined = visitANDLike(N0, N1, N))
3091 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3092 if (N0.getOpcode() == N1.getOpcode()) {
3093 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3094 if (Tmp.getNode()) return Tmp;
3097 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3098 // fold (and (sra)) -> (and (srl)) when possible.
3099 if (!VT.isVector() &&
3100 SimplifyDemandedBits(SDValue(N, 0)))
3101 return SDValue(N, 0);
3103 // fold (zext_inreg (extload x)) -> (zextload x)
3104 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3105 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3106 EVT MemVT = LN0->getMemoryVT();
3107 // If we zero all the possible extended bits, then we can turn this into
3108 // a zextload if we are running before legalize or the operation is legal.
3109 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3110 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3111 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3112 ((!LegalOperations && !LN0->isVolatile()) ||
3113 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3114 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3115 LN0->getChain(), LN0->getBasePtr(),
3116 MemVT, LN0->getMemOperand());
3118 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3119 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3122 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3123 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3125 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3126 EVT MemVT = LN0->getMemoryVT();
3127 // If we zero all the possible extended bits, then we can turn this into
3128 // a zextload if we are running before legalize or the operation is legal.
3129 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3130 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3131 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3132 ((!LegalOperations && !LN0->isVolatile()) ||
3133 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3134 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3135 LN0->getChain(), LN0->getBasePtr(),
3136 MemVT, LN0->getMemOperand());
3138 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3139 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3142 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3143 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3144 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3145 N0.getOperand(1), false);
3146 if (BSwap.getNode())
3153 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3154 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3155 bool DemandHighBits) {
3156 if (!LegalOperations)
3159 EVT VT = N->getValueType(0);
3160 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3162 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3165 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3166 bool LookPassAnd0 = false;
3167 bool LookPassAnd1 = false;
3168 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3170 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3172 if (N0.getOpcode() == ISD::AND) {
3173 if (!N0.getNode()->hasOneUse())
3175 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3176 if (!N01C || N01C->getZExtValue() != 0xFF00)
3178 N0 = N0.getOperand(0);
3179 LookPassAnd0 = true;
3182 if (N1.getOpcode() == ISD::AND) {
3183 if (!N1.getNode()->hasOneUse())
3185 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3186 if (!N11C || N11C->getZExtValue() != 0xFF)
3188 N1 = N1.getOperand(0);
3189 LookPassAnd1 = true;
3192 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3194 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3196 if (!N0.getNode()->hasOneUse() ||
3197 !N1.getNode()->hasOneUse())
3200 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3201 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3204 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3207 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3208 SDValue N00 = N0->getOperand(0);
3209 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3210 if (!N00.getNode()->hasOneUse())
3212 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3213 if (!N001C || N001C->getZExtValue() != 0xFF)
3215 N00 = N00.getOperand(0);
3216 LookPassAnd0 = true;
3219 SDValue N10 = N1->getOperand(0);
3220 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3221 if (!N10.getNode()->hasOneUse())
3223 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3224 if (!N101C || N101C->getZExtValue() != 0xFF00)
3226 N10 = N10.getOperand(0);
3227 LookPassAnd1 = true;
3233 // Make sure everything beyond the low halfword gets set to zero since the SRL
3234 // 16 will clear the top bits.
3235 unsigned OpSizeInBits = VT.getSizeInBits();
3236 if (DemandHighBits && OpSizeInBits > 16) {
3237 // If the left-shift isn't masked out then the only way this is a bswap is
3238 // if all bits beyond the low 8 are 0. In that case the entire pattern
3239 // reduces to a left shift anyway: leave it for other parts of the combiner.
3243 // However, if the right shift isn't masked out then it might be because
3244 // it's not needed. See if we can spot that too.
3245 if (!LookPassAnd1 &&
3246 !DAG.MaskedValueIsZero(
3247 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3251 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3252 if (OpSizeInBits > 16) {
3254 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3255 DAG.getConstant(OpSizeInBits - 16, DL,
3256 getShiftAmountTy(VT)));
3261 /// Return true if the specified node is an element that makes up a 32-bit
3262 /// packed halfword byteswap.
3263 /// ((x & 0x000000ff) << 8) |
3264 /// ((x & 0x0000ff00) >> 8) |
3265 /// ((x & 0x00ff0000) << 8) |
3266 /// ((x & 0xff000000) >> 8)
3267 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3268 if (!N.getNode()->hasOneUse())
3271 unsigned Opc = N.getOpcode();
3272 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3275 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3280 switch (N1C->getZExtValue()) {
3283 case 0xFF: Num = 0; break;
3284 case 0xFF00: Num = 1; break;
3285 case 0xFF0000: Num = 2; break;
3286 case 0xFF000000: Num = 3; break;
3289 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3290 SDValue N0 = N.getOperand(0);
3291 if (Opc == ISD::AND) {
3292 if (Num == 0 || Num == 2) {
3294 // (x >> 8) & 0xff0000
3295 if (N0.getOpcode() != ISD::SRL)
3297 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3298 if (!C || C->getZExtValue() != 8)
3301 // (x << 8) & 0xff00
3302 // (x << 8) & 0xff000000
3303 if (N0.getOpcode() != ISD::SHL)
3305 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3306 if (!C || C->getZExtValue() != 8)
3309 } else if (Opc == ISD::SHL) {
3311 // (x & 0xff0000) << 8
3312 if (Num != 0 && Num != 2)
3314 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3315 if (!C || C->getZExtValue() != 8)
3317 } else { // Opc == ISD::SRL
3318 // (x & 0xff00) >> 8
3319 // (x & 0xff000000) >> 8
3320 if (Num != 1 && Num != 3)
3322 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3323 if (!C || C->getZExtValue() != 8)
3330 Parts[Num] = N0.getOperand(0).getNode();
3334 /// Match a 32-bit packed halfword bswap. That is
3335 /// ((x & 0x000000ff) << 8) |
3336 /// ((x & 0x0000ff00) >> 8) |
3337 /// ((x & 0x00ff0000) << 8) |
3338 /// ((x & 0xff000000) >> 8)
3339 /// => (rotl (bswap x), 16)
3340 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3341 if (!LegalOperations)
3344 EVT VT = N->getValueType(0);
3347 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3351 // (or (or (and), (and)), (or (and), (and)))
3352 // (or (or (or (and), (and)), (and)), (and))
3353 if (N0.getOpcode() != ISD::OR)
3355 SDValue N00 = N0.getOperand(0);
3356 SDValue N01 = N0.getOperand(1);
3357 SDNode *Parts[4] = {};
3359 if (N1.getOpcode() == ISD::OR &&
3360 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3361 // (or (or (and), (and)), (or (and), (and)))
3362 SDValue N000 = N00.getOperand(0);
3363 if (!isBSwapHWordElement(N000, Parts))
3366 SDValue N001 = N00.getOperand(1);
3367 if (!isBSwapHWordElement(N001, Parts))
3369 SDValue N010 = N01.getOperand(0);
3370 if (!isBSwapHWordElement(N010, Parts))
3372 SDValue N011 = N01.getOperand(1);
3373 if (!isBSwapHWordElement(N011, Parts))
3376 // (or (or (or (and), (and)), (and)), (and))
3377 if (!isBSwapHWordElement(N1, Parts))
3379 if (!isBSwapHWordElement(N01, Parts))
3381 if (N00.getOpcode() != ISD::OR)
3383 SDValue N000 = N00.getOperand(0);
3384 if (!isBSwapHWordElement(N000, Parts))
3386 SDValue N001 = N00.getOperand(1);
3387 if (!isBSwapHWordElement(N001, Parts))
3391 // Make sure the parts are all coming from the same node.
3392 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3396 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3397 SDValue(Parts[0], 0));
3399 // Result of the bswap should be rotated by 16. If it's not legal, then
3400 // do (x << 16) | (x >> 16).
3401 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3402 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3403 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3404 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3405 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3406 return DAG.getNode(ISD::OR, DL, VT,
3407 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3408 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3411 /// This contains all DAGCombine rules which reduce two values combined by
3412 /// an Or operation to a single value \see visitANDLike().
3413 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3414 EVT VT = N1.getValueType();
3415 // fold (or x, undef) -> -1
3416 if (!LegalOperations &&
3417 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3418 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3419 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3420 SDLoc(LocReference), VT);
3422 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3423 SDValue LL, LR, RL, RR, CC0, CC1;
3424 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3425 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3426 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3428 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3429 LL.getValueType().isInteger()) {
3430 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3431 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3432 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3433 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3434 LR.getValueType(), LL, RL);
3435 AddToWorklist(ORNode.getNode());
3436 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3438 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3439 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3440 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3441 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3442 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3443 LR.getValueType(), LL, RL);
3444 AddToWorklist(ANDNode.getNode());
3445 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3448 // canonicalize equivalent to ll == rl
3449 if (LL == RR && LR == RL) {
3450 Op1 = ISD::getSetCCSwappedOperands(Op1);
3453 if (LL == RL && LR == RR) {
3454 bool isInteger = LL.getValueType().isInteger();
3455 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3456 if (Result != ISD::SETCC_INVALID &&
3457 (!LegalOperations ||
3458 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3459 TLI.isOperationLegal(ISD::SETCC,
3460 getSetCCResultType(N0.getValueType())))))
3461 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3466 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3467 if (N0.getOpcode() == ISD::AND &&
3468 N1.getOpcode() == ISD::AND &&
3469 N0.getOperand(1).getOpcode() == ISD::Constant &&
3470 N1.getOperand(1).getOpcode() == ISD::Constant &&
3471 // Don't increase # computations.
3472 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3473 // We can only do this xform if we know that bits from X that are set in C2
3474 // but not in C1 are already zero. Likewise for Y.
3475 const APInt &LHSMask =
3476 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3477 const APInt &RHSMask =
3478 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3480 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3481 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3482 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3483 N0.getOperand(0), N1.getOperand(0));
3484 SDLoc DL(LocReference);
3485 return DAG.getNode(ISD::AND, DL, VT, X,
3486 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3490 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3491 if (N0.getOpcode() == ISD::AND &&
3492 N1.getOpcode() == ISD::AND &&
3493 N0.getOperand(0) == N1.getOperand(0) &&
3494 // Don't increase # computations.
3495 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3496 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3497 N0.getOperand(1), N1.getOperand(1));
3498 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3504 SDValue DAGCombiner::visitOR(SDNode *N) {
3505 SDValue N0 = N->getOperand(0);
3506 SDValue N1 = N->getOperand(1);
3507 EVT VT = N1.getValueType();
3510 if (VT.isVector()) {
3511 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3514 // fold (or x, 0) -> x, vector edition
3515 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3517 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3520 // fold (or x, -1) -> -1, vector edition
3521 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3522 // do not return N0, because undef node may exist in N0
3523 return DAG.getConstant(
3524 APInt::getAllOnesValue(
3525 N0.getValueType().getScalarType().getSizeInBits()),
3526 SDLoc(N), N0.getValueType());
3527 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3528 // do not return N1, because undef node may exist in N1
3529 return DAG.getConstant(
3530 APInt::getAllOnesValue(
3531 N1.getValueType().getScalarType().getSizeInBits()),
3532 SDLoc(N), N1.getValueType());
3534 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3535 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3536 // Do this only if the resulting shuffle is legal.
3537 if (isa<ShuffleVectorSDNode>(N0) &&
3538 isa<ShuffleVectorSDNode>(N1) &&
3539 // Avoid folding a node with illegal type.
3540 TLI.isTypeLegal(VT) &&
3541 N0->getOperand(1) == N1->getOperand(1) &&
3542 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3543 bool CanFold = true;
3544 unsigned NumElts = VT.getVectorNumElements();
3545 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3546 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3547 // We construct two shuffle masks:
3548 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3549 // and N1 as the second operand.
3550 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3551 // and N0 as the second operand.
3552 // We do this because OR is commutable and therefore there might be
3553 // two ways to fold this node into a shuffle.
3554 SmallVector<int,4> Mask1;
3555 SmallVector<int,4> Mask2;
3557 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3558 int M0 = SV0->getMaskElt(i);
3559 int M1 = SV1->getMaskElt(i);
3561 // Both shuffle indexes are undef. Propagate Undef.
3562 if (M0 < 0 && M1 < 0) {
3563 Mask1.push_back(M0);
3564 Mask2.push_back(M0);
3568 if (M0 < 0 || M1 < 0 ||
3569 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3570 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3575 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3576 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3580 // Fold this sequence only if the resulting shuffle is 'legal'.
3581 if (TLI.isShuffleMaskLegal(Mask1, VT))
3582 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3583 N1->getOperand(0), &Mask1[0]);
3584 if (TLI.isShuffleMaskLegal(Mask2, VT))
3585 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3586 N0->getOperand(0), &Mask2[0]);
3591 // fold (or c1, c2) -> c1|c2
3592 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3593 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3595 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3596 // canonicalize constant to RHS
3597 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3598 !isConstantIntBuildVectorOrConstantInt(N1))
3599 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3600 // fold (or x, 0) -> x
3601 if (isNullConstant(N1))
3603 // fold (or x, -1) -> -1
3604 if (N1C && N1C->isAllOnesValue())
3606 // fold (or x, c) -> c iff (x & ~c) == 0
3607 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3610 if (SDValue Combined = visitORLike(N0, N1, N))
3613 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3614 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3615 if (BSwap.getNode())
3617 BSwap = MatchBSwapHWordLow(N, N0, N1);
3618 if (BSwap.getNode())
3622 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3624 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3625 // iff (c1 & c2) == 0.
3626 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3627 isa<ConstantSDNode>(N0.getOperand(1))) {
3628 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3629 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3630 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3633 ISD::AND, SDLoc(N), VT,
3634 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3638 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3639 if (N0.getOpcode() == N1.getOpcode()) {
3640 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3641 if (Tmp.getNode()) return Tmp;
3644 // See if this is some rotate idiom.
3645 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3646 return SDValue(Rot, 0);
3648 // Simplify the operands using demanded-bits information.
3649 if (!VT.isVector() &&
3650 SimplifyDemandedBits(SDValue(N, 0)))
3651 return SDValue(N, 0);
3656 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3657 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3658 if (Op.getOpcode() == ISD::AND) {
3659 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3660 Mask = Op.getOperand(1);
3661 Op = Op.getOperand(0);
3667 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3675 // Return true if we can prove that, whenever Neg and Pos are both in the
3676 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3677 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3679 // (or (shift1 X, Neg), (shift2 X, Pos))
3681 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3682 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3683 // to consider shift amounts with defined behavior.
3684 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3685 // If OpSize is a power of 2 then:
3687 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3688 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3690 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3691 // for the stronger condition:
3693 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3695 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3696 // we can just replace Neg with Neg' for the rest of the function.
3698 // In other cases we check for the even stronger condition:
3700 // Neg == OpSize - Pos [B]
3702 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3703 // behavior if Pos == 0 (and consequently Neg == OpSize).
3705 // We could actually use [A] whenever OpSize is a power of 2, but the
3706 // only extra cases that it would match are those uninteresting ones
3707 // where Neg and Pos are never in range at the same time. E.g. for
3708 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3709 // as well as (sub 32, Pos), but:
3711 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3713 // always invokes undefined behavior for 32-bit X.
3715 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3716 unsigned MaskLoBits = 0;
3717 if (Neg.getOpcode() == ISD::AND &&
3718 isPowerOf2_64(OpSize) &&
3719 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3720 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3721 Neg = Neg.getOperand(0);
3722 MaskLoBits = Log2_64(OpSize);
3725 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3726 if (Neg.getOpcode() != ISD::SUB)
3728 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3731 SDValue NegOp1 = Neg.getOperand(1);
3733 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3734 // Pos'. The truncation is redundant for the purpose of the equality.
3736 Pos.getOpcode() == ISD::AND &&
3737 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3738 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3739 Pos = Pos.getOperand(0);
3741 // The condition we need is now:
3743 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3745 // If NegOp1 == Pos then we need:
3747 // OpSize & Mask == NegC & Mask
3749 // (because "x & Mask" is a truncation and distributes through subtraction).
3752 Width = NegC->getAPIntValue();
3753 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3754 // Then the condition we want to prove becomes:
3756 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3758 // which, again because "x & Mask" is a truncation, becomes:
3760 // NegC & Mask == (OpSize - PosC) & Mask
3761 // OpSize & Mask == (NegC + PosC) & Mask
3762 else if (Pos.getOpcode() == ISD::ADD &&
3763 Pos.getOperand(0) == NegOp1 &&
3764 Pos.getOperand(1).getOpcode() == ISD::Constant)
3765 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3766 NegC->getAPIntValue());
3770 // Now we just need to check that OpSize & Mask == Width & Mask.
3772 // Opsize & Mask is 0 since Mask is Opsize - 1.
3773 return Width.getLoBits(MaskLoBits) == 0;
3774 return Width == OpSize;
3777 // A subroutine of MatchRotate used once we have found an OR of two opposite
3778 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3779 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3780 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3781 // Neg with outer conversions stripped away.
3782 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3783 SDValue Neg, SDValue InnerPos,
3784 SDValue InnerNeg, unsigned PosOpcode,
3785 unsigned NegOpcode, SDLoc DL) {
3786 // fold (or (shl x, (*ext y)),
3787 // (srl x, (*ext (sub 32, y)))) ->
3788 // (rotl x, y) or (rotr x, (sub 32, y))
3790 // fold (or (shl x, (*ext (sub 32, y))),
3791 // (srl x, (*ext y))) ->
3792 // (rotr x, y) or (rotl x, (sub 32, y))
3793 EVT VT = Shifted.getValueType();
3794 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3795 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3796 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3797 HasPos ? Pos : Neg).getNode();
3803 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3804 // idioms for rotate, and if the target supports rotation instructions, generate
3806 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3807 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3808 EVT VT = LHS.getValueType();
3809 if (!TLI.isTypeLegal(VT)) return nullptr;
3811 // The target must have at least one rotate flavor.
3812 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3813 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3814 if (!HasROTL && !HasROTR) return nullptr;
3816 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3817 SDValue LHSShift; // The shift.
3818 SDValue LHSMask; // AND value if any.
3819 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3820 return nullptr; // Not part of a rotate.
3822 SDValue RHSShift; // The shift.
3823 SDValue RHSMask; // AND value if any.
3824 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3825 return nullptr; // Not part of a rotate.
3827 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3828 return nullptr; // Not shifting the same value.
3830 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3831 return nullptr; // Shifts must disagree.
3833 // Canonicalize shl to left side in a shl/srl pair.
3834 if (RHSShift.getOpcode() == ISD::SHL) {
3835 std::swap(LHS, RHS);
3836 std::swap(LHSShift, RHSShift);
3837 std::swap(LHSMask , RHSMask );
3840 unsigned OpSizeInBits = VT.getSizeInBits();
3841 SDValue LHSShiftArg = LHSShift.getOperand(0);
3842 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3843 SDValue RHSShiftArg = RHSShift.getOperand(0);
3844 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3846 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3847 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3848 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3849 RHSShiftAmt.getOpcode() == ISD::Constant) {
3850 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3851 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3852 if ((LShVal + RShVal) != OpSizeInBits)
3855 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3856 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3858 // If there is an AND of either shifted operand, apply it to the result.
3859 if (LHSMask.getNode() || RHSMask.getNode()) {
3860 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3862 if (LHSMask.getNode()) {
3863 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3864 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3866 if (RHSMask.getNode()) {
3867 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3868 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3871 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3874 return Rot.getNode();
3877 // If there is a mask here, and we have a variable shift, we can't be sure
3878 // that we're masking out the right stuff.
3879 if (LHSMask.getNode() || RHSMask.getNode())
3882 // If the shift amount is sign/zext/any-extended just peel it off.
3883 SDValue LExtOp0 = LHSShiftAmt;
3884 SDValue RExtOp0 = RHSShiftAmt;
3885 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3886 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3887 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3888 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3889 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3890 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3891 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3892 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3893 LExtOp0 = LHSShiftAmt.getOperand(0);
3894 RExtOp0 = RHSShiftAmt.getOperand(0);
3897 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3898 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3902 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3903 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3910 SDValue DAGCombiner::visitXOR(SDNode *N) {
3911 SDValue N0 = N->getOperand(0);
3912 SDValue N1 = N->getOperand(1);
3913 EVT VT = N0.getValueType();
3916 if (VT.isVector()) {
3917 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3920 // fold (xor x, 0) -> x, vector edition
3921 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3923 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3927 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3928 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3929 return DAG.getConstant(0, SDLoc(N), VT);
3930 // fold (xor x, undef) -> undef
3931 if (N0.getOpcode() == ISD::UNDEF)
3933 if (N1.getOpcode() == ISD::UNDEF)
3935 // fold (xor c1, c2) -> c1^c2
3936 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3937 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3939 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3940 // canonicalize constant to RHS
3941 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3942 !isConstantIntBuildVectorOrConstantInt(N1))
3943 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3944 // fold (xor x, 0) -> x
3945 if (isNullConstant(N1))
3948 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3951 // fold !(x cc y) -> (x !cc y)
3952 SDValue LHS, RHS, CC;
3953 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3954 bool isInt = LHS.getValueType().isInteger();
3955 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3958 if (!LegalOperations ||
3959 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3960 switch (N0.getOpcode()) {
3962 llvm_unreachable("Unhandled SetCC Equivalent!");
3964 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3965 case ISD::SELECT_CC:
3966 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3967 N0.getOperand(3), NotCC);
3972 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3973 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3974 N0.getNode()->hasOneUse() &&
3975 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3976 SDValue V = N0.getOperand(0);
3978 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3979 DAG.getConstant(1, DL, V.getValueType()));
3980 AddToWorklist(V.getNode());
3981 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3984 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3985 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3986 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3987 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3988 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3989 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3990 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3991 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3992 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3993 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3996 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3997 if (N1C && N1C->isAllOnesValue() &&
3998 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3999 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4000 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4001 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4002 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4003 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4004 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4005 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4008 // fold (xor (and x, y), y) -> (and (not x), y)
4009 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4010 N0->getOperand(1) == N1) {
4011 SDValue X = N0->getOperand(0);
4012 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4013 AddToWorklist(NotX.getNode());
4014 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4016 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4017 if (N1C && N0.getOpcode() == ISD::XOR) {
4018 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4019 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4022 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4023 DAG.getConstant(N1C->getAPIntValue() ^
4024 N00C->getAPIntValue(), DL, VT));
4028 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4029 DAG.getConstant(N1C->getAPIntValue() ^
4030 N01C->getAPIntValue(), DL, VT));
4033 // fold (xor x, x) -> 0
4035 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4037 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4038 // Here is a concrete example of this equivalence:
4040 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4041 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4045 // i16 ~1 == 0b1111111111111110
4046 // i16 rol(~1, 14) == 0b1011111111111111
4048 // Some additional tips to help conceptualize this transform:
4049 // - Try to see the operation as placing a single zero in a value of all ones.
4050 // - There exists no value for x which would allow the result to contain zero.
4051 // - Values of x larger than the bitwidth are undefined and do not require a
4052 // consistent result.
4053 // - Pushing the zero left requires shifting one bits in from the right.
4054 // A rotate left of ~1 is a nice way of achieving the desired result.
4055 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4056 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4057 if (N0.getOpcode() == ISD::SHL)
4058 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4059 if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4061 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4065 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4066 if (N0.getOpcode() == N1.getOpcode()) {
4067 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4068 if (Tmp.getNode()) return Tmp;
4071 // Simplify the expression using non-local knowledge.
4072 if (!VT.isVector() &&
4073 SimplifyDemandedBits(SDValue(N, 0)))
4074 return SDValue(N, 0);
4079 /// Handle transforms common to the three shifts, when the shift amount is a
4081 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4082 // We can't and shouldn't fold opaque constants.
4083 if (Amt->isOpaque())
4086 SDNode *LHS = N->getOperand(0).getNode();
4087 if (!LHS->hasOneUse()) return SDValue();
4089 // We want to pull some binops through shifts, so that we have (and (shift))
4090 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4091 // thing happens with address calculations, so it's important to canonicalize
4093 bool HighBitSet = false; // Can we transform this if the high bit is set?
4095 switch (LHS->getOpcode()) {
4096 default: return SDValue();
4099 HighBitSet = false; // We can only transform sra if the high bit is clear.
4102 HighBitSet = true; // We can only transform sra if the high bit is set.
4105 if (N->getOpcode() != ISD::SHL)
4106 return SDValue(); // only shl(add) not sr[al](add).
4107 HighBitSet = false; // We can only transform sra if the high bit is clear.
4111 // We require the RHS of the binop to be a constant and not opaque as well.
4112 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4113 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4115 // FIXME: disable this unless the input to the binop is a shift by a constant.
4116 // If it is not a shift, it pessimizes some common cases like:
4118 // void foo(int *X, int i) { X[i & 1235] = 1; }
4119 // int bar(int *X, int i) { return X[i & 255]; }
4120 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4121 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4122 BinOpLHSVal->getOpcode() != ISD::SRA &&
4123 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4124 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4127 EVT VT = N->getValueType(0);
4129 // If this is a signed shift right, and the high bit is modified by the
4130 // logical operation, do not perform the transformation. The highBitSet
4131 // boolean indicates the value of the high bit of the constant which would
4132 // cause it to be modified for this operation.
4133 if (N->getOpcode() == ISD::SRA) {
4134 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4135 if (BinOpRHSSignSet != HighBitSet)
4139 if (!TLI.isDesirableToCommuteWithShift(LHS))
4142 // Fold the constants, shifting the binop RHS by the shift amount.
4143 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4145 LHS->getOperand(1), N->getOperand(1));
4146 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4148 // Create the new shift.
4149 SDValue NewShift = DAG.getNode(N->getOpcode(),
4150 SDLoc(LHS->getOperand(0)),
4151 VT, LHS->getOperand(0), N->getOperand(1));
4153 // Create the new binop.
4154 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4157 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4158 assert(N->getOpcode() == ISD::TRUNCATE);
4159 assert(N->getOperand(0).getOpcode() == ISD::AND);
4161 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4162 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4163 SDValue N01 = N->getOperand(0).getOperand(1);
4165 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4166 EVT TruncVT = N->getValueType(0);
4167 SDValue N00 = N->getOperand(0).getOperand(0);
4168 APInt TruncC = N01C->getAPIntValue();
4169 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4172 return DAG.getNode(ISD::AND, DL, TruncVT,
4173 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4174 DAG.getConstant(TruncC, DL, TruncVT));
4181 SDValue DAGCombiner::visitRotate(SDNode *N) {
4182 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4183 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4184 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4185 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4186 if (NewOp1.getNode())
4187 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4188 N->getOperand(0), NewOp1);
4193 SDValue DAGCombiner::visitSHL(SDNode *N) {
4194 SDValue N0 = N->getOperand(0);
4195 SDValue N1 = N->getOperand(1);
4196 EVT VT = N0.getValueType();
4197 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4200 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4201 if (VT.isVector()) {
4202 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4205 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4206 // If setcc produces all-one true value then:
4207 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4208 if (N1CV && N1CV->isConstant()) {
4209 if (N0.getOpcode() == ISD::AND) {
4210 SDValue N00 = N0->getOperand(0);
4211 SDValue N01 = N0->getOperand(1);
4212 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4214 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4215 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4216 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4217 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4219 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4222 N1C = isConstOrConstSplat(N1);
4227 // fold (shl c1, c2) -> c1<<c2
4228 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4230 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4231 // fold (shl 0, x) -> 0
4232 if (isNullConstant(N0))
4234 // fold (shl x, c >= size(x)) -> undef
4235 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4236 return DAG.getUNDEF(VT);
4237 // fold (shl x, 0) -> x
4238 if (N1C && N1C->isNullValue())
4240 // fold (shl undef, x) -> 0
4241 if (N0.getOpcode() == ISD::UNDEF)
4242 return DAG.getConstant(0, SDLoc(N), VT);
4243 // if (shl x, c) is known to be zero, return 0
4244 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4245 APInt::getAllOnesValue(OpSizeInBits)))
4246 return DAG.getConstant(0, SDLoc(N), VT);
4247 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4248 if (N1.getOpcode() == ISD::TRUNCATE &&
4249 N1.getOperand(0).getOpcode() == ISD::AND) {
4250 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4251 if (NewOp1.getNode())
4252 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4255 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4256 return SDValue(N, 0);
4258 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4259 if (N1C && N0.getOpcode() == ISD::SHL) {
4260 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4261 uint64_t c1 = N0C1->getZExtValue();
4262 uint64_t c2 = N1C->getZExtValue();
4264 if (c1 + c2 >= OpSizeInBits)
4265 return DAG.getConstant(0, DL, VT);
4266 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4267 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4271 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4272 // For this to be valid, the second form must not preserve any of the bits
4273 // that are shifted out by the inner shift in the first form. This means
4274 // the outer shift size must be >= the number of bits added by the ext.
4275 // As a corollary, we don't care what kind of ext it is.
4276 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4277 N0.getOpcode() == ISD::ANY_EXTEND ||
4278 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4279 N0.getOperand(0).getOpcode() == ISD::SHL) {
4280 SDValue N0Op0 = N0.getOperand(0);
4281 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4282 uint64_t c1 = N0Op0C1->getZExtValue();
4283 uint64_t c2 = N1C->getZExtValue();
4284 EVT InnerShiftVT = N0Op0.getValueType();
4285 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4286 if (c2 >= OpSizeInBits - InnerShiftSize) {
4288 if (c1 + c2 >= OpSizeInBits)
4289 return DAG.getConstant(0, DL, VT);
4290 return DAG.getNode(ISD::SHL, DL, VT,
4291 DAG.getNode(N0.getOpcode(), DL, VT,
4292 N0Op0->getOperand(0)),
4293 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4298 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4299 // Only fold this if the inner zext has no other uses to avoid increasing
4300 // the total number of instructions.
4301 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4302 N0.getOperand(0).getOpcode() == ISD::SRL) {
4303 SDValue N0Op0 = N0.getOperand(0);
4304 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4305 uint64_t c1 = N0Op0C1->getZExtValue();
4306 if (c1 < VT.getScalarSizeInBits()) {
4307 uint64_t c2 = N1C->getZExtValue();
4309 SDValue NewOp0 = N0.getOperand(0);
4310 EVT CountVT = NewOp0.getOperand(1).getValueType();
4312 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4314 DAG.getConstant(c2, DL, CountVT));
4315 AddToWorklist(NewSHL.getNode());
4316 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4322 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4323 // (and (srl x, (sub c1, c2), MASK)
4324 // Only fold this if the inner shift has no other uses -- if it does, folding
4325 // this will increase the total number of instructions.
4326 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4327 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4328 uint64_t c1 = N0C1->getZExtValue();
4329 if (c1 < OpSizeInBits) {
4330 uint64_t c2 = N1C->getZExtValue();
4331 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4334 Mask = Mask.shl(c2 - c1);
4336 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4337 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4339 Mask = Mask.lshr(c1 - c2);
4341 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4342 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4345 return DAG.getNode(ISD::AND, DL, VT, Shift,
4346 DAG.getConstant(Mask, DL, VT));
4350 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4351 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4352 unsigned BitSize = VT.getScalarSizeInBits();
4354 SDValue HiBitsMask =
4355 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4356 BitSize - N1C->getZExtValue()),
4358 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4362 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4363 // Variant of version done on multiply, except mul by a power of 2 is turned
4366 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4367 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4368 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4369 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4370 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4371 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4375 SDValue NewSHL = visitShiftByConstant(N, N1C);
4376 if (NewSHL.getNode())
4383 SDValue DAGCombiner::visitSRA(SDNode *N) {
4384 SDValue N0 = N->getOperand(0);
4385 SDValue N1 = N->getOperand(1);
4386 EVT VT = N0.getValueType();
4387 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4390 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4391 if (VT.isVector()) {
4392 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4395 N1C = isConstOrConstSplat(N1);
4398 // fold (sra c1, c2) -> (sra c1, c2)
4399 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4401 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4402 // fold (sra 0, x) -> 0
4403 if (isNullConstant(N0))
4405 // fold (sra -1, x) -> -1
4406 if (N0C && N0C->isAllOnesValue())
4408 // fold (sra x, (setge c, size(x))) -> undef
4409 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4410 return DAG.getUNDEF(VT);
4411 // fold (sra x, 0) -> x
4412 if (N1C && N1C->isNullValue())
4414 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4416 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4417 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4418 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4420 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4421 ExtVT, VT.getVectorNumElements());
4422 if ((!LegalOperations ||
4423 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4424 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4425 N0.getOperand(0), DAG.getValueType(ExtVT));
4428 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4429 if (N1C && N0.getOpcode() == ISD::SRA) {
4430 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4431 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4432 if (Sum >= OpSizeInBits)
4433 Sum = OpSizeInBits - 1;
4435 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4436 DAG.getConstant(Sum, DL, N1.getValueType()));
4440 // fold (sra (shl X, m), (sub result_size, n))
4441 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4442 // result_size - n != m.
4443 // If truncate is free for the target sext(shl) is likely to result in better
4445 if (N0.getOpcode() == ISD::SHL && N1C) {
4446 // Get the two constanst of the shifts, CN0 = m, CN = n.
4447 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4449 LLVMContext &Ctx = *DAG.getContext();
4450 // Determine what the truncate's result bitsize and type would be.
4451 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4454 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4456 // Determine the residual right-shift amount.
4457 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4459 // If the shift is not a no-op (in which case this should be just a sign
4460 // extend already), the truncated to type is legal, sign_extend is legal
4461 // on that type, and the truncate to that type is both legal and free,
4462 // perform the transform.
4463 if ((ShiftAmt > 0) &&
4464 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4465 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4466 TLI.isTruncateFree(VT, TruncVT)) {
4469 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4470 getShiftAmountTy(N0.getOperand(0).getValueType()));
4471 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4472 N0.getOperand(0), Amt);
4473 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4475 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4476 N->getValueType(0), Trunc);
4481 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4482 if (N1.getOpcode() == ISD::TRUNCATE &&
4483 N1.getOperand(0).getOpcode() == ISD::AND) {
4484 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4485 if (NewOp1.getNode())
4486 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4489 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4490 // if c1 is equal to the number of bits the trunc removes
4491 if (N0.getOpcode() == ISD::TRUNCATE &&
4492 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4493 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4494 N0.getOperand(0).hasOneUse() &&
4495 N0.getOperand(0).getOperand(1).hasOneUse() &&
4497 SDValue N0Op0 = N0.getOperand(0);
4498 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4499 unsigned LargeShiftVal = LargeShift->getZExtValue();
4500 EVT LargeVT = N0Op0.getValueType();
4502 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4505 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4506 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4507 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4508 N0Op0.getOperand(0), Amt);
4509 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4514 // Simplify, based on bits shifted out of the LHS.
4515 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4516 return SDValue(N, 0);
4519 // If the sign bit is known to be zero, switch this to a SRL.
4520 if (DAG.SignBitIsZero(N0))
4521 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4524 SDValue NewSRA = visitShiftByConstant(N, N1C);
4525 if (NewSRA.getNode())
4532 SDValue DAGCombiner::visitSRL(SDNode *N) {
4533 SDValue N0 = N->getOperand(0);
4534 SDValue N1 = N->getOperand(1);
4535 EVT VT = N0.getValueType();
4536 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4539 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4540 if (VT.isVector()) {
4541 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4544 N1C = isConstOrConstSplat(N1);
4547 // fold (srl c1, c2) -> c1 >>u c2
4548 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4550 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4551 // fold (srl 0, x) -> 0
4552 if (isNullConstant(N0))
4554 // fold (srl x, c >= size(x)) -> undef
4555 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4556 return DAG.getUNDEF(VT);
4557 // fold (srl x, 0) -> x
4558 if (N1C && N1C->isNullValue())
4560 // if (srl x, c) is known to be zero, return 0
4561 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4562 APInt::getAllOnesValue(OpSizeInBits)))
4563 return DAG.getConstant(0, SDLoc(N), VT);
4565 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4566 if (N1C && N0.getOpcode() == ISD::SRL) {
4567 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4568 uint64_t c1 = N01C->getZExtValue();
4569 uint64_t c2 = N1C->getZExtValue();
4571 if (c1 + c2 >= OpSizeInBits)
4572 return DAG.getConstant(0, DL, VT);
4573 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4574 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4578 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4579 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4580 N0.getOperand(0).getOpcode() == ISD::SRL &&
4581 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4583 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4584 uint64_t c2 = N1C->getZExtValue();
4585 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4586 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4587 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4588 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4589 if (c1 + OpSizeInBits == InnerShiftSize) {
4591 if (c1 + c2 >= InnerShiftSize)
4592 return DAG.getConstant(0, DL, VT);
4593 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4594 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4595 N0.getOperand(0)->getOperand(0),
4596 DAG.getConstant(c1 + c2, DL,
4601 // fold (srl (shl x, c), c) -> (and x, cst2)
4602 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4603 unsigned BitSize = N0.getScalarValueSizeInBits();
4604 if (BitSize <= 64) {
4605 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4607 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4608 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4612 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4613 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4614 // Shifting in all undef bits?
4615 EVT SmallVT = N0.getOperand(0).getValueType();
4616 unsigned BitSize = SmallVT.getScalarSizeInBits();
4617 if (N1C->getZExtValue() >= BitSize)
4618 return DAG.getUNDEF(VT);
4620 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4621 uint64_t ShiftAmt = N1C->getZExtValue();
4623 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4625 DAG.getConstant(ShiftAmt, DL0,
4626 getShiftAmountTy(SmallVT)));
4627 AddToWorklist(SmallShift.getNode());
4628 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4630 return DAG.getNode(ISD::AND, DL, VT,
4631 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4632 DAG.getConstant(Mask, DL, VT));
4636 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4637 // bit, which is unmodified by sra.
4638 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4639 if (N0.getOpcode() == ISD::SRA)
4640 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4643 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4644 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4645 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4646 APInt KnownZero, KnownOne;
4647 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4649 // If any of the input bits are KnownOne, then the input couldn't be all
4650 // zeros, thus the result of the srl will always be zero.
4651 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4653 // If all of the bits input the to ctlz node are known to be zero, then
4654 // the result of the ctlz is "32" and the result of the shift is one.
4655 APInt UnknownBits = ~KnownZero;
4656 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4658 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4659 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4660 // Okay, we know that only that the single bit specified by UnknownBits
4661 // could be set on input to the CTLZ node. If this bit is set, the SRL
4662 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4663 // to an SRL/XOR pair, which is likely to simplify more.
4664 unsigned ShAmt = UnknownBits.countTrailingZeros();
4665 SDValue Op = N0.getOperand(0);
4669 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4670 DAG.getConstant(ShAmt, DL,
4671 getShiftAmountTy(Op.getValueType())));
4672 AddToWorklist(Op.getNode());
4676 return DAG.getNode(ISD::XOR, DL, VT,
4677 Op, DAG.getConstant(1, DL, VT));
4681 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4682 if (N1.getOpcode() == ISD::TRUNCATE &&
4683 N1.getOperand(0).getOpcode() == ISD::AND) {
4684 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4685 if (NewOp1.getNode())
4686 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4689 // fold operands of srl based on knowledge that the low bits are not
4691 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4692 return SDValue(N, 0);
4695 SDValue NewSRL = visitShiftByConstant(N, N1C);
4696 if (NewSRL.getNode())
4700 // Attempt to convert a srl of a load into a narrower zero-extending load.
4701 SDValue NarrowLoad = ReduceLoadWidth(N);
4702 if (NarrowLoad.getNode())
4705 // Here is a common situation. We want to optimize:
4708 // %b = and i32 %a, 2
4709 // %c = srl i32 %b, 1
4710 // brcond i32 %c ...
4716 // %c = setcc eq %b, 0
4719 // However when after the source operand of SRL is optimized into AND, the SRL
4720 // itself may not be optimized further. Look for it and add the BRCOND into
4722 if (N->hasOneUse()) {
4723 SDNode *Use = *N->use_begin();
4724 if (Use->getOpcode() == ISD::BRCOND)
4726 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4727 // Also look pass the truncate.
4728 Use = *Use->use_begin();
4729 if (Use->getOpcode() == ISD::BRCOND)
4737 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4738 SDValue N0 = N->getOperand(0);
4739 EVT VT = N->getValueType(0);
4741 // fold (ctlz c1) -> c2
4742 if (isa<ConstantSDNode>(N0))
4743 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4747 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4748 SDValue N0 = N->getOperand(0);
4749 EVT VT = N->getValueType(0);
4751 // fold (ctlz_zero_undef c1) -> c2
4752 if (isa<ConstantSDNode>(N0))
4753 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4757 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4758 SDValue N0 = N->getOperand(0);
4759 EVT VT = N->getValueType(0);
4761 // fold (cttz c1) -> c2
4762 if (isa<ConstantSDNode>(N0))
4763 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4767 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4768 SDValue N0 = N->getOperand(0);
4769 EVT VT = N->getValueType(0);
4771 // fold (cttz_zero_undef c1) -> c2
4772 if (isa<ConstantSDNode>(N0))
4773 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4777 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4778 SDValue N0 = N->getOperand(0);
4779 EVT VT = N->getValueType(0);
4781 // fold (ctpop c1) -> c2
4782 if (isa<ConstantSDNode>(N0))
4783 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4788 /// \brief Generate Min/Max node
4789 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4790 SDValue True, SDValue False,
4791 ISD::CondCode CC, const TargetLowering &TLI,
4792 SelectionDAG &DAG) {
4793 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4803 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4804 if (TLI.isOperationLegal(Opcode, VT))
4805 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4814 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4815 if (TLI.isOperationLegal(Opcode, VT))
4816 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4824 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4825 SDValue N0 = N->getOperand(0);
4826 SDValue N1 = N->getOperand(1);
4827 SDValue N2 = N->getOperand(2);
4828 EVT VT = N->getValueType(0);
4829 EVT VT0 = N0.getValueType();
4831 // fold (select C, X, X) -> X
4834 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4835 // fold (select true, X, Y) -> X
4836 // fold (select false, X, Y) -> Y
4837 return !N0C->isNullValue() ? N1 : N2;
4839 // fold (select C, 1, X) -> (or C, X)
4840 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4841 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4842 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4843 // fold (select C, 0, 1) -> (xor C, 1)
4844 // We can't do this reliably if integer based booleans have different contents
4845 // to floating point based booleans. This is because we can't tell whether we
4846 // have an integer-based boolean or a floating-point-based boolean unless we
4847 // can find the SETCC that produced it and inspect its operands. This is
4848 // fairly easy if C is the SETCC node, but it can potentially be
4849 // undiscoverable (or not reasonably discoverable). For example, it could be
4850 // in another basic block or it could require searching a complicated
4852 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4853 if (VT.isInteger() &&
4854 (VT0 == MVT::i1 || (VT0.isInteger() &&
4855 TLI.getBooleanContents(false, false) ==
4856 TLI.getBooleanContents(false, true) &&
4857 TLI.getBooleanContents(false, false) ==
4858 TargetLowering::ZeroOrOneBooleanContent)) &&
4859 isNullConstant(N1) && N2C && N2C->isOne()) {
4863 return DAG.getNode(ISD::XOR, DL, VT0,
4864 N0, DAG.getConstant(1, DL, VT0));
4867 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4868 N0, DAG.getConstant(1, DL0, VT0));
4869 AddToWorklist(XORNode.getNode());
4871 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4872 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4874 // fold (select C, 0, X) -> (and (not C), X)
4875 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4876 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4877 AddToWorklist(NOTNode.getNode());
4878 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4880 // fold (select C, X, 1) -> (or (not C), X)
4881 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4882 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4883 AddToWorklist(NOTNode.getNode());
4884 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4886 // fold (select C, X, 0) -> (and C, X)
4887 if (VT == MVT::i1 && isNullConstant(N2))
4888 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4889 // fold (select X, X, Y) -> (or X, Y)
4890 // fold (select X, 1, Y) -> (or X, Y)
4891 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4892 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4893 // fold (select X, Y, X) -> (and X, Y)
4894 // fold (select X, Y, 0) -> (and X, Y)
4895 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4896 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4898 // If we can fold this based on the true/false value, do so.
4899 if (SimplifySelectOps(N, N1, N2))
4900 return SDValue(N, 0); // Don't revisit N.
4902 // fold selects based on a setcc into other things, such as min/max/abs
4903 if (N0.getOpcode() == ISD::SETCC) {
4904 // select x, y (fcmp lt x, y) -> fminnum x, y
4905 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4907 // This is OK if we don't care about what happens if either operand is a
4911 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4912 // no signed zeros as well as no nans.
4913 const TargetOptions &Options = DAG.getTarget().Options;
4914 if (Options.UnsafeFPMath &&
4915 VT.isFloatingPoint() && N0.hasOneUse() &&
4916 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4917 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4920 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4921 N1, N2, CC, TLI, DAG);
4926 if ((!LegalOperations &&
4927 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4928 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4929 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4930 N0.getOperand(0), N0.getOperand(1),
4931 N1, N2, N0.getOperand(2));
4932 return SimplifySelect(SDLoc(N), N0, N1, N2);
4935 if (VT0 == MVT::i1) {
4936 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4937 // select (and Cond0, Cond1), X, Y
4938 // -> select Cond0, (select Cond1, X, Y), Y
4939 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4940 SDValue Cond0 = N0->getOperand(0);
4941 SDValue Cond1 = N0->getOperand(1);
4942 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4943 N1.getValueType(), Cond1, N1, N2);
4944 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4947 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4948 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4949 SDValue Cond0 = N0->getOperand(0);
4950 SDValue Cond1 = N0->getOperand(1);
4951 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4952 N1.getValueType(), Cond1, N1, N2);
4953 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4958 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4959 if (N1->getOpcode() == ISD::SELECT) {
4960 SDValue N1_0 = N1->getOperand(0);
4961 SDValue N1_1 = N1->getOperand(1);
4962 SDValue N1_2 = N1->getOperand(2);
4963 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4964 // Create the actual and node if we can generate good code for it.
4965 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4966 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4968 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4971 // Otherwise see if we can optimize the "and" to a better pattern.
4972 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4973 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4977 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4978 if (N2->getOpcode() == ISD::SELECT) {
4979 SDValue N2_0 = N2->getOperand(0);
4980 SDValue N2_1 = N2->getOperand(1);
4981 SDValue N2_2 = N2->getOperand(2);
4982 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4983 // Create the actual or node if we can generate good code for it.
4984 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4985 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4987 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4990 // Otherwise see if we can optimize to a better pattern.
4991 if (SDValue Combined = visitORLike(N0, N2_0, N))
4992 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5002 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5005 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5007 // Split the inputs.
5008 SDValue Lo, Hi, LL, LH, RL, RH;
5009 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5010 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5012 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5013 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5015 return std::make_pair(Lo, Hi);
5018 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5019 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5020 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5022 SDValue Cond = N->getOperand(0);
5023 SDValue LHS = N->getOperand(1);
5024 SDValue RHS = N->getOperand(2);
5025 EVT VT = N->getValueType(0);
5026 int NumElems = VT.getVectorNumElements();
5027 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5028 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5029 Cond.getOpcode() == ISD::BUILD_VECTOR);
5031 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5032 // binary ones here.
5033 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5036 // We're sure we have an even number of elements due to the
5037 // concat_vectors we have as arguments to vselect.
5038 // Skip BV elements until we find one that's not an UNDEF
5039 // After we find an UNDEF element, keep looping until we get to half the
5040 // length of the BV and see if all the non-undef nodes are the same.
5041 ConstantSDNode *BottomHalf = nullptr;
5042 for (int i = 0; i < NumElems / 2; ++i) {
5043 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5046 if (BottomHalf == nullptr)
5047 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5048 else if (Cond->getOperand(i).getNode() != BottomHalf)
5052 // Do the same for the second half of the BuildVector
5053 ConstantSDNode *TopHalf = nullptr;
5054 for (int i = NumElems / 2; i < NumElems; ++i) {
5055 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5058 if (TopHalf == nullptr)
5059 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5060 else if (Cond->getOperand(i).getNode() != TopHalf)
5064 assert(TopHalf && BottomHalf &&
5065 "One half of the selector was all UNDEFs and the other was all the "
5066 "same value. This should have been addressed before this function.");
5068 ISD::CONCAT_VECTORS, dl, VT,
5069 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5070 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5073 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5075 if (Level >= AfterLegalizeTypes)
5078 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5079 SDValue Mask = MSC->getMask();
5080 SDValue Data = MSC->getValue();
5083 // If the MSCATTER data type requires splitting and the mask is provided by a
5084 // SETCC, then split both nodes and its operands before legalization. This
5085 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5086 // and enables future optimizations (e.g. min/max pattern matching on X86).
5087 if (Mask.getOpcode() != ISD::SETCC)
5090 // Check if any splitting is required.
5091 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5092 TargetLowering::TypeSplitVector)
5094 SDValue MaskLo, MaskHi, Lo, Hi;
5095 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5098 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5100 SDValue Chain = MSC->getChain();
5102 EVT MemoryVT = MSC->getMemoryVT();
5103 unsigned Alignment = MSC->getOriginalAlignment();
5105 EVT LoMemVT, HiMemVT;
5106 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5108 SDValue DataLo, DataHi;
5109 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5111 SDValue BasePtr = MSC->getBasePtr();
5112 SDValue IndexLo, IndexHi;
5113 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5115 MachineMemOperand *MMO = DAG.getMachineFunction().
5116 getMachineMemOperand(MSC->getPointerInfo(),
5117 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5118 Alignment, MSC->getAAInfo(), MSC->getRanges());
5120 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5121 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5124 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5125 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5128 AddToWorklist(Lo.getNode());
5129 AddToWorklist(Hi.getNode());
5131 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5134 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5136 if (Level >= AfterLegalizeTypes)
5139 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5140 SDValue Mask = MST->getMask();
5141 SDValue Data = MST->getValue();
5144 // If the MSTORE data type requires splitting and the mask is provided by a
5145 // SETCC, then split both nodes and its operands before legalization. This
5146 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5147 // and enables future optimizations (e.g. min/max pattern matching on X86).
5148 if (Mask.getOpcode() == ISD::SETCC) {
5150 // Check if any splitting is required.
5151 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5152 TargetLowering::TypeSplitVector)
5155 SDValue MaskLo, MaskHi, Lo, Hi;
5156 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5159 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5161 SDValue Chain = MST->getChain();
5162 SDValue Ptr = MST->getBasePtr();
5164 EVT MemoryVT = MST->getMemoryVT();
5165 unsigned Alignment = MST->getOriginalAlignment();
5167 // if Alignment is equal to the vector size,
5168 // take the half of it for the second part
5169 unsigned SecondHalfAlignment =
5170 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5171 Alignment/2 : Alignment;
5173 EVT LoMemVT, HiMemVT;
5174 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5176 SDValue DataLo, DataHi;
5177 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5179 MachineMemOperand *MMO = DAG.getMachineFunction().
5180 getMachineMemOperand(MST->getPointerInfo(),
5181 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5182 Alignment, MST->getAAInfo(), MST->getRanges());
5184 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5185 MST->isTruncatingStore());
5187 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5188 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5189 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5191 MMO = DAG.getMachineFunction().
5192 getMachineMemOperand(MST->getPointerInfo(),
5193 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5194 SecondHalfAlignment, MST->getAAInfo(),
5197 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5198 MST->isTruncatingStore());
5200 AddToWorklist(Lo.getNode());
5201 AddToWorklist(Hi.getNode());
5203 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5208 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5210 if (Level >= AfterLegalizeTypes)
5213 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5214 SDValue Mask = MGT->getMask();
5217 // If the MGATHER result requires splitting and the mask is provided by a
5218 // SETCC, then split both nodes and its operands before legalization. This
5219 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5220 // and enables future optimizations (e.g. min/max pattern matching on X86).
5222 if (Mask.getOpcode() != ISD::SETCC)
5225 EVT VT = N->getValueType(0);
5227 // Check if any splitting is required.
5228 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5229 TargetLowering::TypeSplitVector)
5232 SDValue MaskLo, MaskHi, Lo, Hi;
5233 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5235 SDValue Src0 = MGT->getValue();
5236 SDValue Src0Lo, Src0Hi;
5237 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5240 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5242 SDValue Chain = MGT->getChain();
5243 EVT MemoryVT = MGT->getMemoryVT();
5244 unsigned Alignment = MGT->getOriginalAlignment();
5246 EVT LoMemVT, HiMemVT;
5247 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5249 SDValue BasePtr = MGT->getBasePtr();
5250 SDValue Index = MGT->getIndex();
5251 SDValue IndexLo, IndexHi;
5252 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5254 MachineMemOperand *MMO = DAG.getMachineFunction().
5255 getMachineMemOperand(MGT->getPointerInfo(),
5256 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5257 Alignment, MGT->getAAInfo(), MGT->getRanges());
5259 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5260 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5263 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5264 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5267 AddToWorklist(Lo.getNode());
5268 AddToWorklist(Hi.getNode());
5270 // Build a factor node to remember that this load is independent of the
5272 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5275 // Legalized the chain result - switch anything that used the old chain to
5277 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5279 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5281 SDValue RetOps[] = { GatherRes, Chain };
5282 return DAG.getMergeValues(RetOps, DL);
5285 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5287 if (Level >= AfterLegalizeTypes)
5290 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5291 SDValue Mask = MLD->getMask();
5294 // If the MLOAD result requires splitting and the mask is provided by a
5295 // SETCC, then split both nodes and its operands before legalization. This
5296 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5297 // and enables future optimizations (e.g. min/max pattern matching on X86).
5299 if (Mask.getOpcode() == ISD::SETCC) {
5300 EVT VT = N->getValueType(0);
5302 // Check if any splitting is required.
5303 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5304 TargetLowering::TypeSplitVector)
5307 SDValue MaskLo, MaskHi, Lo, Hi;
5308 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5310 SDValue Src0 = MLD->getSrc0();
5311 SDValue Src0Lo, Src0Hi;
5312 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5315 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5317 SDValue Chain = MLD->getChain();
5318 SDValue Ptr = MLD->getBasePtr();
5319 EVT MemoryVT = MLD->getMemoryVT();
5320 unsigned Alignment = MLD->getOriginalAlignment();
5322 // if Alignment is equal to the vector size,
5323 // take the half of it for the second part
5324 unsigned SecondHalfAlignment =
5325 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5326 Alignment/2 : Alignment;
5328 EVT LoMemVT, HiMemVT;
5329 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5331 MachineMemOperand *MMO = DAG.getMachineFunction().
5332 getMachineMemOperand(MLD->getPointerInfo(),
5333 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5334 Alignment, MLD->getAAInfo(), MLD->getRanges());
5336 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5339 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5340 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5341 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5343 MMO = DAG.getMachineFunction().
5344 getMachineMemOperand(MLD->getPointerInfo(),
5345 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5346 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5348 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5351 AddToWorklist(Lo.getNode());
5352 AddToWorklist(Hi.getNode());
5354 // Build a factor node to remember that this load is independent of the
5356 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5359 // Legalized the chain result - switch anything that used the old chain to
5361 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5363 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5365 SDValue RetOps[] = { LoadRes, Chain };
5366 return DAG.getMergeValues(RetOps, DL);
5371 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5372 SDValue N0 = N->getOperand(0);
5373 SDValue N1 = N->getOperand(1);
5374 SDValue N2 = N->getOperand(2);
5377 // Canonicalize integer abs.
5378 // vselect (setg[te] X, 0), X, -X ->
5379 // vselect (setgt X, -1), X, -X ->
5380 // vselect (setl[te] X, 0), -X, X ->
5381 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5382 if (N0.getOpcode() == ISD::SETCC) {
5383 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5384 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5386 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5388 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5389 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5390 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5391 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5392 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5393 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5394 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5397 EVT VT = LHS.getValueType();
5398 SDValue Shift = DAG.getNode(
5399 ISD::SRA, DL, VT, LHS,
5400 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5401 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5402 AddToWorklist(Shift.getNode());
5403 AddToWorklist(Add.getNode());
5404 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5408 if (SimplifySelectOps(N, N1, N2))
5409 return SDValue(N, 0); // Don't revisit N.
5411 // If the VSELECT result requires splitting and the mask is provided by a
5412 // SETCC, then split both nodes and its operands before legalization. This
5413 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5414 // and enables future optimizations (e.g. min/max pattern matching on X86).
5415 if (N0.getOpcode() == ISD::SETCC) {
5416 EVT VT = N->getValueType(0);
5418 // Check if any splitting is required.
5419 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5420 TargetLowering::TypeSplitVector)
5423 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5424 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5425 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5426 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5428 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5429 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5431 // Add the new VSELECT nodes to the work list in case they need to be split
5433 AddToWorklist(Lo.getNode());
5434 AddToWorklist(Hi.getNode());
5436 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5439 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5440 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5442 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5443 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5446 // The ConvertSelectToConcatVector function is assuming both the above
5447 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5449 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5450 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5451 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5452 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5460 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5461 SDValue N0 = N->getOperand(0);
5462 SDValue N1 = N->getOperand(1);
5463 SDValue N2 = N->getOperand(2);
5464 SDValue N3 = N->getOperand(3);
5465 SDValue N4 = N->getOperand(4);
5466 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5468 // fold select_cc lhs, rhs, x, x, cc -> x
5472 // Determine if the condition we're dealing with is constant
5473 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5474 N0, N1, CC, SDLoc(N), false);
5475 if (SCC.getNode()) {
5476 AddToWorklist(SCC.getNode());
5478 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5479 if (!SCCC->isNullValue())
5480 return N2; // cond always true -> true val
5482 return N3; // cond always false -> false val
5483 } else if (SCC->getOpcode() == ISD::UNDEF) {
5484 // When the condition is UNDEF, just return the first operand. This is
5485 // coherent the DAG creation, no setcc node is created in this case
5487 } else if (SCC.getOpcode() == ISD::SETCC) {
5488 // Fold to a simpler select_cc
5489 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5490 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5495 // If we can fold this based on the true/false value, do so.
5496 if (SimplifySelectOps(N, N2, N3))
5497 return SDValue(N, 0); // Don't revisit N.
5499 // fold select_cc into other things, such as min/max/abs
5500 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5503 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5504 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5505 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5509 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5510 // dag node into a ConstantSDNode or a build_vector of constants.
5511 // This function is called by the DAGCombiner when visiting sext/zext/aext
5512 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5513 // Vector extends are not folded if operations are legal; this is to
5514 // avoid introducing illegal build_vector dag nodes.
5515 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5516 SelectionDAG &DAG, bool LegalTypes,
5517 bool LegalOperations) {
5518 unsigned Opcode = N->getOpcode();
5519 SDValue N0 = N->getOperand(0);
5520 EVT VT = N->getValueType(0);
5522 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5523 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5525 // fold (sext c1) -> c1
5526 // fold (zext c1) -> c1
5527 // fold (aext c1) -> c1
5528 if (isa<ConstantSDNode>(N0))
5529 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5531 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5532 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5533 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5534 EVT SVT = VT.getScalarType();
5535 if (!(VT.isVector() &&
5536 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5537 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5540 // We can fold this node into a build_vector.
5541 unsigned VTBits = SVT.getSizeInBits();
5542 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5543 unsigned ShAmt = VTBits - EVTBits;
5544 SmallVector<SDValue, 8> Elts;
5545 unsigned NumElts = N0->getNumOperands();
5548 for (unsigned i=0; i != NumElts; ++i) {
5549 SDValue Op = N0->getOperand(i);
5550 if (Op->getOpcode() == ISD::UNDEF) {
5551 Elts.push_back(DAG.getUNDEF(SVT));
5556 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5557 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5558 if (Opcode == ISD::SIGN_EXTEND)
5559 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5562 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5566 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5569 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5570 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5571 // transformation. Returns true if extension are possible and the above
5572 // mentioned transformation is profitable.
5573 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5575 SmallVectorImpl<SDNode *> &ExtendNodes,
5576 const TargetLowering &TLI) {
5577 bool HasCopyToRegUses = false;
5578 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5579 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5580 UE = N0.getNode()->use_end();
5585 if (UI.getUse().getResNo() != N0.getResNo())
5587 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5588 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5589 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5590 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5591 // Sign bits will be lost after a zext.
5594 for (unsigned i = 0; i != 2; ++i) {
5595 SDValue UseOp = User->getOperand(i);
5598 if (!isa<ConstantSDNode>(UseOp))
5603 ExtendNodes.push_back(User);
5606 // If truncates aren't free and there are users we can't
5607 // extend, it isn't worthwhile.
5610 // Remember if this value is live-out.
5611 if (User->getOpcode() == ISD::CopyToReg)
5612 HasCopyToRegUses = true;
5615 if (HasCopyToRegUses) {
5616 bool BothLiveOut = false;
5617 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5619 SDUse &Use = UI.getUse();
5620 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5626 // Both unextended and extended values are live out. There had better be
5627 // a good reason for the transformation.
5628 return ExtendNodes.size();
5633 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5634 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5635 ISD::NodeType ExtType) {
5636 // Extend SetCC uses if necessary.
5637 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5638 SDNode *SetCC = SetCCs[i];
5639 SmallVector<SDValue, 4> Ops;
5641 for (unsigned j = 0; j != 2; ++j) {
5642 SDValue SOp = SetCC->getOperand(j);
5644 Ops.push_back(ExtLoad);
5646 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5649 Ops.push_back(SetCC->getOperand(2));
5650 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5654 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5655 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5656 SDValue N0 = N->getOperand(0);
5657 EVT DstVT = N->getValueType(0);
5658 EVT SrcVT = N0.getValueType();
5660 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5661 N->getOpcode() == ISD::ZERO_EXTEND) &&
5662 "Unexpected node type (not an extend)!");
5664 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5665 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5666 // (v8i32 (sext (v8i16 (load x))))
5668 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5669 // (v4i32 (sextload (x + 16)))))
5670 // Where uses of the original load, i.e.:
5672 // are replaced with:
5674 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5675 // (v4i32 (sextload (x + 16)))))))
5677 // This combine is only applicable to illegal, but splittable, vectors.
5678 // All legal types, and illegal non-vector types, are handled elsewhere.
5679 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5681 if (N0->getOpcode() != ISD::LOAD)
5684 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5686 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5687 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5688 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5691 SmallVector<SDNode *, 4> SetCCs;
5692 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5695 ISD::LoadExtType ExtType =
5696 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5698 // Try to split the vector types to get down to legal types.
5699 EVT SplitSrcVT = SrcVT;
5700 EVT SplitDstVT = DstVT;
5701 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5702 SplitSrcVT.getVectorNumElements() > 1) {
5703 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5704 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5707 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5711 const unsigned NumSplits =
5712 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5713 const unsigned Stride = SplitSrcVT.getStoreSize();
5714 SmallVector<SDValue, 4> Loads;
5715 SmallVector<SDValue, 4> Chains;
5717 SDValue BasePtr = LN0->getBasePtr();
5718 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5719 const unsigned Offset = Idx * Stride;
5720 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5722 SDValue SplitLoad = DAG.getExtLoad(
5723 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5724 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5725 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5726 Align, LN0->getAAInfo());
5728 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5729 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5731 Loads.push_back(SplitLoad.getValue(0));
5732 Chains.push_back(SplitLoad.getValue(1));
5735 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5736 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5738 CombineTo(N, NewValue);
5740 // Replace uses of the original load (before extension)
5741 // with a truncate of the concatenated sextloaded vectors.
5743 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5744 CombineTo(N0.getNode(), Trunc, NewChain);
5745 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5746 (ISD::NodeType)N->getOpcode());
5747 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5750 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5751 SDValue N0 = N->getOperand(0);
5752 EVT VT = N->getValueType(0);
5754 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5756 return SDValue(Res, 0);
5758 // fold (sext (sext x)) -> (sext x)
5759 // fold (sext (aext x)) -> (sext x)
5760 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5761 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5764 if (N0.getOpcode() == ISD::TRUNCATE) {
5765 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5766 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5767 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5768 if (NarrowLoad.getNode()) {
5769 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5770 if (NarrowLoad.getNode() != N0.getNode()) {
5771 CombineTo(N0.getNode(), NarrowLoad);
5772 // CombineTo deleted the truncate, if needed, but not what's under it.
5775 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5778 // See if the value being truncated is already sign extended. If so, just
5779 // eliminate the trunc/sext pair.
5780 SDValue Op = N0.getOperand(0);
5781 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5782 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5783 unsigned DestBits = VT.getScalarType().getSizeInBits();
5784 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5786 if (OpBits == DestBits) {
5787 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5788 // bits, it is already ready.
5789 if (NumSignBits > DestBits-MidBits)
5791 } else if (OpBits < DestBits) {
5792 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5793 // bits, just sext from i32.
5794 if (NumSignBits > OpBits-MidBits)
5795 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5797 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5798 // bits, just truncate to i32.
5799 if (NumSignBits > OpBits-MidBits)
5800 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5803 // fold (sext (truncate x)) -> (sextinreg x).
5804 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5805 N0.getValueType())) {
5806 if (OpBits < DestBits)
5807 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5808 else if (OpBits > DestBits)
5809 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5810 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5811 DAG.getValueType(N0.getValueType()));
5815 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5816 // Only generate vector extloads when 1) they're legal, and 2) they are
5817 // deemed desirable by the target.
5818 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5819 ((!LegalOperations && !VT.isVector() &&
5820 !cast<LoadSDNode>(N0)->isVolatile()) ||
5821 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5822 bool DoXform = true;
5823 SmallVector<SDNode*, 4> SetCCs;
5824 if (!N0.hasOneUse())
5825 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5827 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5829 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5830 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5832 LN0->getBasePtr(), N0.getValueType(),
5833 LN0->getMemOperand());
5834 CombineTo(N, ExtLoad);
5835 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5836 N0.getValueType(), ExtLoad);
5837 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5838 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5840 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5844 // fold (sext (load x)) to multiple smaller sextloads.
5845 // Only on illegal but splittable vectors.
5846 if (SDValue ExtLoad = CombineExtLoad(N))
5849 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5850 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5851 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5852 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5853 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5854 EVT MemVT = LN0->getMemoryVT();
5855 if ((!LegalOperations && !LN0->isVolatile()) ||
5856 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5857 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5859 LN0->getBasePtr(), MemVT,
5860 LN0->getMemOperand());
5861 CombineTo(N, ExtLoad);
5862 CombineTo(N0.getNode(),
5863 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5864 N0.getValueType(), ExtLoad),
5865 ExtLoad.getValue(1));
5866 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5870 // fold (sext (and/or/xor (load x), cst)) ->
5871 // (and/or/xor (sextload x), (sext cst))
5872 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5873 N0.getOpcode() == ISD::XOR) &&
5874 isa<LoadSDNode>(N0.getOperand(0)) &&
5875 N0.getOperand(1).getOpcode() == ISD::Constant &&
5876 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5877 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5878 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5879 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5880 bool DoXform = true;
5881 SmallVector<SDNode*, 4> SetCCs;
5882 if (!N0.hasOneUse())
5883 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5886 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5887 LN0->getChain(), LN0->getBasePtr(),
5889 LN0->getMemOperand());
5890 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5891 Mask = Mask.sext(VT.getSizeInBits());
5893 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5894 ExtLoad, DAG.getConstant(Mask, DL, VT));
5895 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5896 SDLoc(N0.getOperand(0)),
5897 N0.getOperand(0).getValueType(), ExtLoad);
5899 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5900 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5902 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5907 if (N0.getOpcode() == ISD::SETCC) {
5908 EVT N0VT = N0.getOperand(0).getValueType();
5909 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5910 // Only do this before legalize for now.
5911 if (VT.isVector() && !LegalOperations &&
5912 TLI.getBooleanContents(N0VT) ==
5913 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5914 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5915 // of the same size as the compared operands. Only optimize sext(setcc())
5916 // if this is the case.
5917 EVT SVT = getSetCCResultType(N0VT);
5919 // We know that the # elements of the results is the same as the
5920 // # elements of the compare (and the # elements of the compare result
5921 // for that matter). Check to see that they are the same size. If so,
5922 // we know that the element size of the sext'd result matches the
5923 // element size of the compare operands.
5924 if (VT.getSizeInBits() == SVT.getSizeInBits())
5925 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5927 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5929 // If the desired elements are smaller or larger than the source
5930 // elements we can use a matching integer vector type and then
5931 // truncate/sign extend
5932 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5933 if (SVT == MatchingVectorType) {
5934 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5935 N0.getOperand(0), N0.getOperand(1),
5936 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5937 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5941 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5942 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5945 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5947 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5948 NegOne, DAG.getConstant(0, DL, VT),
5949 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5950 if (SCC.getNode()) return SCC;
5952 if (!VT.isVector()) {
5953 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5954 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5956 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5957 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5958 N0.getOperand(0), N0.getOperand(1), CC);
5959 return DAG.getSelect(DL, VT, SetCC,
5960 NegOne, DAG.getConstant(0, DL, VT));
5965 // fold (sext x) -> (zext x) if the sign bit is known zero.
5966 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5967 DAG.SignBitIsZero(N0))
5968 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5973 // isTruncateOf - If N is a truncate of some other value, return true, record
5974 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5975 // This function computes KnownZero to avoid a duplicated call to
5976 // computeKnownBits in the caller.
5977 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5980 if (N->getOpcode() == ISD::TRUNCATE) {
5981 Op = N->getOperand(0);
5982 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5986 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5987 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5990 SDValue Op0 = N->getOperand(0);
5991 SDValue Op1 = N->getOperand(1);
5992 assert(Op0.getValueType() == Op1.getValueType());
5994 if (isNullConstant(Op0))
5996 else if (isNullConstant(Op1))
6001 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6003 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6009 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6010 SDValue N0 = N->getOperand(0);
6011 EVT VT = N->getValueType(0);
6013 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6015 return SDValue(Res, 0);
6017 // fold (zext (zext x)) -> (zext x)
6018 // fold (zext (aext x)) -> (zext x)
6019 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6020 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6023 // fold (zext (truncate x)) -> (zext x) or
6024 // (zext (truncate x)) -> (truncate x)
6025 // This is valid when the truncated bits of x are already zero.
6026 // FIXME: We should extend this to work for vectors too.
6029 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6030 APInt TruncatedBits =
6031 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6032 APInt(Op.getValueSizeInBits(), 0) :
6033 APInt::getBitsSet(Op.getValueSizeInBits(),
6034 N0.getValueSizeInBits(),
6035 std::min(Op.getValueSizeInBits(),
6036 VT.getSizeInBits()));
6037 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6038 if (VT.bitsGT(Op.getValueType()))
6039 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6040 if (VT.bitsLT(Op.getValueType()))
6041 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6047 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6048 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6049 if (N0.getOpcode() == ISD::TRUNCATE) {
6050 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6051 if (NarrowLoad.getNode()) {
6052 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6053 if (NarrowLoad.getNode() != N0.getNode()) {
6054 CombineTo(N0.getNode(), NarrowLoad);
6055 // CombineTo deleted the truncate, if needed, but not what's under it.
6058 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6062 // fold (zext (truncate x)) -> (and x, mask)
6063 if (N0.getOpcode() == ISD::TRUNCATE &&
6064 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6066 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6067 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6068 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6069 if (NarrowLoad.getNode()) {
6070 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6071 if (NarrowLoad.getNode() != N0.getNode()) {
6072 CombineTo(N0.getNode(), NarrowLoad);
6073 // CombineTo deleted the truncate, if needed, but not what's under it.
6076 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6079 SDValue Op = N0.getOperand(0);
6080 if (Op.getValueType().bitsLT(VT)) {
6081 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6082 AddToWorklist(Op.getNode());
6083 } else if (Op.getValueType().bitsGT(VT)) {
6084 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6085 AddToWorklist(Op.getNode());
6087 return DAG.getZeroExtendInReg(Op, SDLoc(N),
6088 N0.getValueType().getScalarType());
6091 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6092 // if either of the casts is not free.
6093 if (N0.getOpcode() == ISD::AND &&
6094 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6095 N0.getOperand(1).getOpcode() == ISD::Constant &&
6096 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6097 N0.getValueType()) ||
6098 !TLI.isZExtFree(N0.getValueType(), VT))) {
6099 SDValue X = N0.getOperand(0).getOperand(0);
6100 if (X.getValueType().bitsLT(VT)) {
6101 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6102 } else if (X.getValueType().bitsGT(VT)) {
6103 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6105 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6106 Mask = Mask.zext(VT.getSizeInBits());
6108 return DAG.getNode(ISD::AND, DL, VT,
6109 X, DAG.getConstant(Mask, DL, VT));
6112 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6113 // Only generate vector extloads when 1) they're legal, and 2) they are
6114 // deemed desirable by the target.
6115 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6116 ((!LegalOperations && !VT.isVector() &&
6117 !cast<LoadSDNode>(N0)->isVolatile()) ||
6118 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6119 bool DoXform = true;
6120 SmallVector<SDNode*, 4> SetCCs;
6121 if (!N0.hasOneUse())
6122 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6124 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6126 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6127 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6129 LN0->getBasePtr(), N0.getValueType(),
6130 LN0->getMemOperand());
6131 CombineTo(N, ExtLoad);
6132 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6133 N0.getValueType(), ExtLoad);
6134 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6136 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6138 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6142 // fold (zext (load x)) to multiple smaller zextloads.
6143 // Only on illegal but splittable vectors.
6144 if (SDValue ExtLoad = CombineExtLoad(N))
6147 // fold (zext (and/or/xor (load x), cst)) ->
6148 // (and/or/xor (zextload x), (zext cst))
6149 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6150 N0.getOpcode() == ISD::XOR) &&
6151 isa<LoadSDNode>(N0.getOperand(0)) &&
6152 N0.getOperand(1).getOpcode() == ISD::Constant &&
6153 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6154 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6155 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6156 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6157 bool DoXform = true;
6158 SmallVector<SDNode*, 4> SetCCs;
6159 if (!N0.hasOneUse())
6160 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6163 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6164 LN0->getChain(), LN0->getBasePtr(),
6166 LN0->getMemOperand());
6167 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6168 Mask = Mask.zext(VT.getSizeInBits());
6170 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6171 ExtLoad, DAG.getConstant(Mask, DL, VT));
6172 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6173 SDLoc(N0.getOperand(0)),
6174 N0.getOperand(0).getValueType(), ExtLoad);
6176 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6177 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6179 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6184 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6185 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6186 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6187 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6188 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6189 EVT MemVT = LN0->getMemoryVT();
6190 if ((!LegalOperations && !LN0->isVolatile()) ||
6191 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6192 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6194 LN0->getBasePtr(), MemVT,
6195 LN0->getMemOperand());
6196 CombineTo(N, ExtLoad);
6197 CombineTo(N0.getNode(),
6198 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6200 ExtLoad.getValue(1));
6201 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6205 if (N0.getOpcode() == ISD::SETCC) {
6206 if (!LegalOperations && VT.isVector() &&
6207 N0.getValueType().getVectorElementType() == MVT::i1) {
6208 EVT N0VT = N0.getOperand(0).getValueType();
6209 if (getSetCCResultType(N0VT) == N0.getValueType())
6212 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6213 // Only do this before legalize for now.
6214 EVT EltVT = VT.getVectorElementType();
6216 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6217 DAG.getConstant(1, DL, EltVT));
6218 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6219 // We know that the # elements of the results is the same as the
6220 // # elements of the compare (and the # elements of the compare result
6221 // for that matter). Check to see that they are the same size. If so,
6222 // we know that the element size of the sext'd result matches the
6223 // element size of the compare operands.
6224 return DAG.getNode(ISD::AND, DL, VT,
6225 DAG.getSetCC(DL, VT, N0.getOperand(0),
6227 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6228 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6231 // If the desired elements are smaller or larger than the source
6232 // elements we can use a matching integer vector type and then
6233 // truncate/sign extend
6234 EVT MatchingElementType =
6235 EVT::getIntegerVT(*DAG.getContext(),
6236 N0VT.getScalarType().getSizeInBits());
6237 EVT MatchingVectorType =
6238 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6239 N0VT.getVectorNumElements());
6241 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6243 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6244 return DAG.getNode(ISD::AND, DL, VT,
6245 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6246 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6249 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6252 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6253 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6254 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6255 if (SCC.getNode()) return SCC;
6258 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6259 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6260 isa<ConstantSDNode>(N0.getOperand(1)) &&
6261 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6263 SDValue ShAmt = N0.getOperand(1);
6264 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6265 if (N0.getOpcode() == ISD::SHL) {
6266 SDValue InnerZExt = N0.getOperand(0);
6267 // If the original shl may be shifting out bits, do not perform this
6269 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6270 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6271 if (ShAmtVal > KnownZeroBits)
6277 // Ensure that the shift amount is wide enough for the shifted value.
6278 if (VT.getSizeInBits() >= 256)
6279 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6281 return DAG.getNode(N0.getOpcode(), DL, VT,
6282 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6289 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6290 SDValue N0 = N->getOperand(0);
6291 EVT VT = N->getValueType(0);
6293 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6295 return SDValue(Res, 0);
6297 // fold (aext (aext x)) -> (aext x)
6298 // fold (aext (zext x)) -> (zext x)
6299 // fold (aext (sext x)) -> (sext x)
6300 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6301 N0.getOpcode() == ISD::ZERO_EXTEND ||
6302 N0.getOpcode() == ISD::SIGN_EXTEND)
6303 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6305 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6306 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6307 if (N0.getOpcode() == ISD::TRUNCATE) {
6308 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6309 if (NarrowLoad.getNode()) {
6310 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6311 if (NarrowLoad.getNode() != N0.getNode()) {
6312 CombineTo(N0.getNode(), NarrowLoad);
6313 // CombineTo deleted the truncate, if needed, but not what's under it.
6316 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6320 // fold (aext (truncate x))
6321 if (N0.getOpcode() == ISD::TRUNCATE) {
6322 SDValue TruncOp = N0.getOperand(0);
6323 if (TruncOp.getValueType() == VT)
6324 return TruncOp; // x iff x size == zext size.
6325 if (TruncOp.getValueType().bitsGT(VT))
6326 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6327 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6330 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6331 // if the trunc is not free.
6332 if (N0.getOpcode() == ISD::AND &&
6333 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6334 N0.getOperand(1).getOpcode() == ISD::Constant &&
6335 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6336 N0.getValueType())) {
6337 SDValue X = N0.getOperand(0).getOperand(0);
6338 if (X.getValueType().bitsLT(VT)) {
6339 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6340 } else if (X.getValueType().bitsGT(VT)) {
6341 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6343 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6344 Mask = Mask.zext(VT.getSizeInBits());
6346 return DAG.getNode(ISD::AND, DL, VT,
6347 X, DAG.getConstant(Mask, DL, VT));
6350 // fold (aext (load x)) -> (aext (truncate (extload x)))
6351 // None of the supported targets knows how to perform load and any_ext
6352 // on vectors in one instruction. We only perform this transformation on
6354 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6355 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6356 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6357 bool DoXform = true;
6358 SmallVector<SDNode*, 4> SetCCs;
6359 if (!N0.hasOneUse())
6360 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6362 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6363 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6365 LN0->getBasePtr(), N0.getValueType(),
6366 LN0->getMemOperand());
6367 CombineTo(N, ExtLoad);
6368 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6369 N0.getValueType(), ExtLoad);
6370 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6371 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6373 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6377 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6378 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6379 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6380 if (N0.getOpcode() == ISD::LOAD &&
6381 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6383 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6384 ISD::LoadExtType ExtType = LN0->getExtensionType();
6385 EVT MemVT = LN0->getMemoryVT();
6386 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6387 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6388 VT, LN0->getChain(), LN0->getBasePtr(),
6389 MemVT, LN0->getMemOperand());
6390 CombineTo(N, ExtLoad);
6391 CombineTo(N0.getNode(),
6392 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6393 N0.getValueType(), ExtLoad),
6394 ExtLoad.getValue(1));
6395 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6399 if (N0.getOpcode() == ISD::SETCC) {
6401 // aext(setcc) -> vsetcc
6402 // aext(setcc) -> truncate(vsetcc)
6403 // aext(setcc) -> aext(vsetcc)
6404 // Only do this before legalize for now.
6405 if (VT.isVector() && !LegalOperations) {
6406 EVT N0VT = N0.getOperand(0).getValueType();
6407 // We know that the # elements of the results is the same as the
6408 // # elements of the compare (and the # elements of the compare result
6409 // for that matter). Check to see that they are the same size. If so,
6410 // we know that the element size of the sext'd result matches the
6411 // element size of the compare operands.
6412 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6413 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6415 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6416 // If the desired elements are smaller or larger than the source
6417 // elements we can use a matching integer vector type and then
6418 // truncate/any extend
6420 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6422 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6424 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6425 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6429 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6432 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6433 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6434 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6442 /// See if the specified operand can be simplified with the knowledge that only
6443 /// the bits specified by Mask are used. If so, return the simpler operand,
6444 /// otherwise return a null SDValue.
6445 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6446 switch (V.getOpcode()) {
6448 case ISD::Constant: {
6449 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6450 assert(CV && "Const value should be ConstSDNode.");
6451 const APInt &CVal = CV->getAPIntValue();
6452 APInt NewVal = CVal & Mask;
6454 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6459 // If the LHS or RHS don't contribute bits to the or, drop them.
6460 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6461 return V.getOperand(1);
6462 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6463 return V.getOperand(0);
6466 // Only look at single-use SRLs.
6467 if (!V.getNode()->hasOneUse())
6469 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6470 // See if we can recursively simplify the LHS.
6471 unsigned Amt = RHSC->getZExtValue();
6473 // Watch out for shift count overflow though.
6474 if (Amt >= Mask.getBitWidth()) break;
6475 APInt NewMask = Mask << Amt;
6476 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6477 if (SimplifyLHS.getNode())
6478 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6479 SimplifyLHS, V.getOperand(1));
6485 /// If the result of a wider load is shifted to right of N bits and then
6486 /// truncated to a narrower type and where N is a multiple of number of bits of
6487 /// the narrower type, transform it to a narrower load from address + N / num of
6488 /// bits of new type. If the result is to be extended, also fold the extension
6489 /// to form a extending load.
6490 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6491 unsigned Opc = N->getOpcode();
6493 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6494 SDValue N0 = N->getOperand(0);
6495 EVT VT = N->getValueType(0);
6498 // This transformation isn't valid for vector loads.
6502 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6504 if (Opc == ISD::SIGN_EXTEND_INREG) {
6505 ExtType = ISD::SEXTLOAD;
6506 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6507 } else if (Opc == ISD::SRL) {
6508 // Another special-case: SRL is basically zero-extending a narrower value.
6509 ExtType = ISD::ZEXTLOAD;
6511 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6512 if (!N01) return SDValue();
6513 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6514 VT.getSizeInBits() - N01->getZExtValue());
6516 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6519 unsigned EVTBits = ExtVT.getSizeInBits();
6521 // Do not generate loads of non-round integer types since these can
6522 // be expensive (and would be wrong if the type is not byte sized).
6523 if (!ExtVT.isRound())
6527 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6528 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6529 ShAmt = N01->getZExtValue();
6530 // Is the shift amount a multiple of size of VT?
6531 if ((ShAmt & (EVTBits-1)) == 0) {
6532 N0 = N0.getOperand(0);
6533 // Is the load width a multiple of size of VT?
6534 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6538 // At this point, we must have a load or else we can't do the transform.
6539 if (!isa<LoadSDNode>(N0)) return SDValue();
6541 // Because a SRL must be assumed to *need* to zero-extend the high bits
6542 // (as opposed to anyext the high bits), we can't combine the zextload
6543 // lowering of SRL and an sextload.
6544 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6547 // If the shift amount is larger than the input type then we're not
6548 // accessing any of the loaded bytes. If the load was a zextload/extload
6549 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6550 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6555 // If the load is shifted left (and the result isn't shifted back right),
6556 // we can fold the truncate through the shift.
6557 unsigned ShLeftAmt = 0;
6558 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6559 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6560 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6561 ShLeftAmt = N01->getZExtValue();
6562 N0 = N0.getOperand(0);
6566 // If we haven't found a load, we can't narrow it. Don't transform one with
6567 // multiple uses, this would require adding a new load.
6568 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6571 // Don't change the width of a volatile load.
6572 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6573 if (LN0->isVolatile())
6576 // Verify that we are actually reducing a load width here.
6577 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6580 // For the transform to be legal, the load must produce only two values
6581 // (the value loaded and the chain). Don't transform a pre-increment
6582 // load, for example, which produces an extra value. Otherwise the
6583 // transformation is not equivalent, and the downstream logic to replace
6584 // uses gets things wrong.
6585 if (LN0->getNumValues() > 2)
6588 // If the load that we're shrinking is an extload and we're not just
6589 // discarding the extension we can't simply shrink the load. Bail.
6590 // TODO: It would be possible to merge the extensions in some cases.
6591 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6592 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6595 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6598 EVT PtrType = N0.getOperand(1).getValueType();
6600 if (PtrType == MVT::Untyped || PtrType.isExtended())
6601 // It's not possible to generate a constant of extended or untyped type.
6604 // For big endian targets, we need to adjust the offset to the pointer to
6605 // load the correct bytes.
6606 if (TLI.isBigEndian()) {
6607 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6608 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6609 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6612 uint64_t PtrOff = ShAmt / 8;
6613 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6615 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6616 PtrType, LN0->getBasePtr(),
6617 DAG.getConstant(PtrOff, DL, PtrType));
6618 AddToWorklist(NewPtr.getNode());
6621 if (ExtType == ISD::NON_EXTLOAD)
6622 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6623 LN0->getPointerInfo().getWithOffset(PtrOff),
6624 LN0->isVolatile(), LN0->isNonTemporal(),
6625 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6627 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6628 LN0->getPointerInfo().getWithOffset(PtrOff),
6629 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6630 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6632 // Replace the old load's chain with the new load's chain.
6633 WorklistRemover DeadNodes(*this);
6634 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6636 // Shift the result left, if we've swallowed a left shift.
6637 SDValue Result = Load;
6638 if (ShLeftAmt != 0) {
6639 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6640 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6642 // If the shift amount is as large as the result size (but, presumably,
6643 // no larger than the source) then the useful bits of the result are
6644 // zero; we can't simply return the shortened shift, because the result
6645 // of that operation is undefined.
6647 if (ShLeftAmt >= VT.getSizeInBits())
6648 Result = DAG.getConstant(0, DL, VT);
6650 Result = DAG.getNode(ISD::SHL, DL, VT,
6651 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6654 // Return the new loaded value.
6658 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6659 SDValue N0 = N->getOperand(0);
6660 SDValue N1 = N->getOperand(1);
6661 EVT VT = N->getValueType(0);
6662 EVT EVT = cast<VTSDNode>(N1)->getVT();
6663 unsigned VTBits = VT.getScalarType().getSizeInBits();
6664 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6666 // fold (sext_in_reg c1) -> c1
6667 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6668 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6670 // If the input is already sign extended, just drop the extension.
6671 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6674 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6675 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6676 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6677 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6678 N0.getOperand(0), N1);
6680 // fold (sext_in_reg (sext x)) -> (sext x)
6681 // fold (sext_in_reg (aext x)) -> (sext x)
6682 // if x is small enough.
6683 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6684 SDValue N00 = N0.getOperand(0);
6685 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6686 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6687 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6690 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6691 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6692 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6694 // fold operands of sext_in_reg based on knowledge that the top bits are not
6696 if (SimplifyDemandedBits(SDValue(N, 0)))
6697 return SDValue(N, 0);
6699 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6700 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6701 SDValue NarrowLoad = ReduceLoadWidth(N);
6702 if (NarrowLoad.getNode())
6705 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6706 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6707 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6708 if (N0.getOpcode() == ISD::SRL) {
6709 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6710 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6711 // We can turn this into an SRA iff the input to the SRL is already sign
6713 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6714 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6715 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6716 N0.getOperand(0), N0.getOperand(1));
6720 // fold (sext_inreg (extload x)) -> (sextload x)
6721 if (ISD::isEXTLoad(N0.getNode()) &&
6722 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6723 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6724 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6725 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6726 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6727 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6729 LN0->getBasePtr(), EVT,
6730 LN0->getMemOperand());
6731 CombineTo(N, ExtLoad);
6732 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6733 AddToWorklist(ExtLoad.getNode());
6734 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6736 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6737 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6739 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6740 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6741 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6742 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6743 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6745 LN0->getBasePtr(), EVT,
6746 LN0->getMemOperand());
6747 CombineTo(N, ExtLoad);
6748 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6749 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6752 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6753 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6754 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6755 N0.getOperand(1), false);
6756 if (BSwap.getNode())
6757 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6761 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6762 // into a build_vector.
6763 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6764 SmallVector<SDValue, 8> Elts;
6765 unsigned NumElts = N0->getNumOperands();
6766 unsigned ShAmt = VTBits - EVTBits;
6768 for (unsigned i = 0; i != NumElts; ++i) {
6769 SDValue Op = N0->getOperand(i);
6770 if (Op->getOpcode() == ISD::UNDEF) {
6775 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6776 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6777 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6778 SDLoc(Op), Op.getValueType()));
6781 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6787 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6788 SDValue N0 = N->getOperand(0);
6789 EVT VT = N->getValueType(0);
6790 bool isLE = TLI.isLittleEndian();
6793 if (N0.getValueType() == N->getValueType(0))
6795 // fold (truncate c1) -> c1
6796 if (isConstantIntBuildVectorOrConstantInt(N0))
6797 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6798 // fold (truncate (truncate x)) -> (truncate x)
6799 if (N0.getOpcode() == ISD::TRUNCATE)
6800 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6801 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6802 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6803 N0.getOpcode() == ISD::SIGN_EXTEND ||
6804 N0.getOpcode() == ISD::ANY_EXTEND) {
6805 if (N0.getOperand(0).getValueType().bitsLT(VT))
6806 // if the source is smaller than the dest, we still need an extend
6807 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6809 if (N0.getOperand(0).getValueType().bitsGT(VT))
6810 // if the source is larger than the dest, than we just need the truncate
6811 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6812 // if the source and dest are the same type, we can drop both the extend
6813 // and the truncate.
6814 return N0.getOperand(0);
6817 // Fold extract-and-trunc into a narrow extract. For example:
6818 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6819 // i32 y = TRUNCATE(i64 x)
6821 // v16i8 b = BITCAST (v2i64 val)
6822 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6824 // Note: We only run this optimization after type legalization (which often
6825 // creates this pattern) and before operation legalization after which
6826 // we need to be more careful about the vector instructions that we generate.
6827 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6828 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6830 EVT VecTy = N0.getOperand(0).getValueType();
6831 EVT ExTy = N0.getValueType();
6832 EVT TrTy = N->getValueType(0);
6834 unsigned NumElem = VecTy.getVectorNumElements();
6835 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6837 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6838 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6840 SDValue EltNo = N0->getOperand(1);
6841 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6842 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6843 EVT IndexTy = TLI.getVectorIdxTy();
6844 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6846 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6847 NVT, N0.getOperand(0));
6850 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6852 DAG.getConstant(Index, DL, IndexTy));
6856 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6857 if (N0.getOpcode() == ISD::SELECT) {
6858 EVT SrcVT = N0.getValueType();
6859 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6860 TLI.isTruncateFree(SrcVT, VT)) {
6862 SDValue Cond = N0.getOperand(0);
6863 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6864 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6865 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6869 // Fold a series of buildvector, bitcast, and truncate if possible.
6871 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6872 // (2xi32 (buildvector x, y)).
6873 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6874 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6875 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6876 N0.getOperand(0).hasOneUse()) {
6878 SDValue BuildVect = N0.getOperand(0);
6879 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6880 EVT TruncVecEltTy = VT.getVectorElementType();
6882 // Check that the element types match.
6883 if (BuildVectEltTy == TruncVecEltTy) {
6884 // Now we only need to compute the offset of the truncated elements.
6885 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6886 unsigned TruncVecNumElts = VT.getVectorNumElements();
6887 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6889 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6890 "Invalid number of elements");
6892 SmallVector<SDValue, 8> Opnds;
6893 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6894 Opnds.push_back(BuildVect.getOperand(i));
6896 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6900 // See if we can simplify the input to this truncate through knowledge that
6901 // only the low bits are being used.
6902 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6903 // Currently we only perform this optimization on scalars because vectors
6904 // may have different active low bits.
6905 if (!VT.isVector()) {
6907 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6908 VT.getSizeInBits()));
6909 if (Shorter.getNode())
6910 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6912 // fold (truncate (load x)) -> (smaller load x)
6913 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6914 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6915 SDValue Reduced = ReduceLoadWidth(N);
6916 if (Reduced.getNode())
6918 // Handle the case where the load remains an extending load even
6919 // after truncation.
6920 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6921 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6922 if (!LN0->isVolatile() &&
6923 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6924 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6925 VT, LN0->getChain(), LN0->getBasePtr(),
6927 LN0->getMemOperand());
6928 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6933 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6934 // where ... are all 'undef'.
6935 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6936 SmallVector<EVT, 8> VTs;
6939 unsigned NumDefs = 0;
6941 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6942 SDValue X = N0.getOperand(i);
6943 if (X.getOpcode() != ISD::UNDEF) {
6948 // Stop if more than one members are non-undef.
6951 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6952 VT.getVectorElementType(),
6953 X.getValueType().getVectorNumElements()));
6957 return DAG.getUNDEF(VT);
6960 assert(V.getNode() && "The single defined operand is empty!");
6961 SmallVector<SDValue, 8> Opnds;
6962 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6964 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6967 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6968 AddToWorklist(NV.getNode());
6969 Opnds.push_back(NV);
6971 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6975 // Simplify the operands using demanded-bits information.
6976 if (!VT.isVector() &&
6977 SimplifyDemandedBits(SDValue(N, 0)))
6978 return SDValue(N, 0);
6983 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6984 SDValue Elt = N->getOperand(i);
6985 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6986 return Elt.getNode();
6987 return Elt.getOperand(Elt.getResNo()).getNode();
6990 /// build_pair (load, load) -> load
6991 /// if load locations are consecutive.
6992 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6993 assert(N->getOpcode() == ISD::BUILD_PAIR);
6995 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6996 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6997 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6998 LD1->getAddressSpace() != LD2->getAddressSpace())
7000 EVT LD1VT = LD1->getValueType(0);
7002 if (ISD::isNON_EXTLoad(LD2) &&
7004 // If both are volatile this would reduce the number of volatile loads.
7005 // If one is volatile it might be ok, but play conservative and bail out.
7006 !LD1->isVolatile() &&
7007 !LD2->isVolatile() &&
7008 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7009 unsigned Align = LD1->getAlignment();
7010 unsigned NewAlign = TLI.getDataLayout()->
7011 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7013 if (NewAlign <= Align &&
7014 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7015 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7016 LD1->getBasePtr(), LD1->getPointerInfo(),
7017 false, false, false, Align);
7023 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7024 SDValue N0 = N->getOperand(0);
7025 EVT VT = N->getValueType(0);
7027 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7028 // Only do this before legalize, since afterward the target may be depending
7029 // on the bitconvert.
7030 // First check to see if this is all constant.
7032 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7034 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7036 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7037 assert(!DestEltVT.isVector() &&
7038 "Element type of vector ValueType must not be vector!");
7040 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7043 // If the input is a constant, let getNode fold it.
7044 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7045 // If we can't allow illegal operations, we need to check that this is just
7046 // a fp -> int or int -> conversion and that the resulting operation will
7048 if (!LegalOperations ||
7049 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7050 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7051 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7052 TLI.isOperationLegal(ISD::Constant, VT)))
7053 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7056 // (conv (conv x, t1), t2) -> (conv x, t2)
7057 if (N0.getOpcode() == ISD::BITCAST)
7058 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7061 // fold (conv (load x)) -> (load (conv*)x)
7062 // If the resultant load doesn't need a higher alignment than the original!
7063 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7064 // Do not change the width of a volatile load.
7065 !cast<LoadSDNode>(N0)->isVolatile() &&
7066 // Do not remove the cast if the types differ in endian layout.
7067 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7068 TLI.hasBigEndianPartOrdering(VT) &&
7069 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7070 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7071 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7072 unsigned Align = TLI.getDataLayout()->
7073 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7074 unsigned OrigAlign = LN0->getAlignment();
7076 if (Align <= OrigAlign) {
7077 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7078 LN0->getBasePtr(), LN0->getPointerInfo(),
7079 LN0->isVolatile(), LN0->isNonTemporal(),
7080 LN0->isInvariant(), OrigAlign,
7082 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7087 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7088 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7089 // This often reduces constant pool loads.
7090 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7091 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7092 N0.getNode()->hasOneUse() && VT.isInteger() &&
7093 !VT.isVector() && !N0.getValueType().isVector()) {
7094 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7096 AddToWorklist(NewConv.getNode());
7099 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7100 if (N0.getOpcode() == ISD::FNEG)
7101 return DAG.getNode(ISD::XOR, DL, VT,
7102 NewConv, DAG.getConstant(SignBit, DL, VT));
7103 assert(N0.getOpcode() == ISD::FABS);
7104 return DAG.getNode(ISD::AND, DL, VT,
7105 NewConv, DAG.getConstant(~SignBit, DL, VT));
7108 // fold (bitconvert (fcopysign cst, x)) ->
7109 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7110 // Note that we don't handle (copysign x, cst) because this can always be
7111 // folded to an fneg or fabs.
7112 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7113 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7114 VT.isInteger() && !VT.isVector()) {
7115 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7116 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7117 if (isTypeLegal(IntXVT)) {
7118 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7119 IntXVT, N0.getOperand(1));
7120 AddToWorklist(X.getNode());
7122 // If X has a different width than the result/lhs, sext it or truncate it.
7123 unsigned VTWidth = VT.getSizeInBits();
7124 if (OrigXWidth < VTWidth) {
7125 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7126 AddToWorklist(X.getNode());
7127 } else if (OrigXWidth > VTWidth) {
7128 // To get the sign bit in the right place, we have to shift it right
7129 // before truncating.
7131 X = DAG.getNode(ISD::SRL, DL,
7132 X.getValueType(), X,
7133 DAG.getConstant(OrigXWidth-VTWidth, DL,
7135 AddToWorklist(X.getNode());
7136 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7137 AddToWorklist(X.getNode());
7140 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7141 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7142 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7143 AddToWorklist(X.getNode());
7145 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7146 VT, N0.getOperand(0));
7147 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7148 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7149 AddToWorklist(Cst.getNode());
7151 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7155 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7156 if (N0.getOpcode() == ISD::BUILD_PAIR) {
7157 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7158 if (CombineLD.getNode())
7162 // Remove double bitcasts from shuffles - this is often a legacy of
7163 // XformToShuffleWithZero being used to combine bitmaskings (of
7164 // float vectors bitcast to integer vectors) into shuffles.
7165 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7166 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7167 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7168 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7169 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7170 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7172 // If operands are a bitcast, peek through if it casts the original VT.
7173 // If operands are a UNDEF or constant, just bitcast back to original VT.
7174 auto PeekThroughBitcast = [&](SDValue Op) {
7175 if (Op.getOpcode() == ISD::BITCAST &&
7176 Op.getOperand(0)->getValueType(0) == VT)
7177 return SDValue(Op.getOperand(0));
7178 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7179 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7180 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7184 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7185 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7190 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7191 SmallVector<int, 8> NewMask;
7192 for (int M : SVN->getMask())
7193 for (int i = 0; i != MaskScale; ++i)
7194 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7196 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7198 std::swap(SV0, SV1);
7199 ShuffleVectorSDNode::commuteMask(NewMask);
7200 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7204 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7210 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7211 EVT VT = N->getValueType(0);
7212 return CombineConsecutiveLoads(N, VT);
7215 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7216 /// operands. DstEltVT indicates the destination element value type.
7217 SDValue DAGCombiner::
7218 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7219 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7221 // If this is already the right type, we're done.
7222 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7224 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7225 unsigned DstBitSize = DstEltVT.getSizeInBits();
7227 // If this is a conversion of N elements of one type to N elements of another
7228 // type, convert each element. This handles FP<->INT cases.
7229 if (SrcBitSize == DstBitSize) {
7230 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7231 BV->getValueType(0).getVectorNumElements());
7233 // Due to the FP element handling below calling this routine recursively,
7234 // we can end up with a scalar-to-vector node here.
7235 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7236 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7237 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7238 DstEltVT, BV->getOperand(0)));
7240 SmallVector<SDValue, 8> Ops;
7241 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7242 SDValue Op = BV->getOperand(i);
7243 // If the vector element type is not legal, the BUILD_VECTOR operands
7244 // are promoted and implicitly truncated. Make that explicit here.
7245 if (Op.getValueType() != SrcEltVT)
7246 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7247 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7249 AddToWorklist(Ops.back().getNode());
7251 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7254 // Otherwise, we're growing or shrinking the elements. To avoid having to
7255 // handle annoying details of growing/shrinking FP values, we convert them to
7257 if (SrcEltVT.isFloatingPoint()) {
7258 // Convert the input float vector to a int vector where the elements are the
7260 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7261 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7265 // Now we know the input is an integer vector. If the output is a FP type,
7266 // convert to integer first, then to FP of the right size.
7267 if (DstEltVT.isFloatingPoint()) {
7268 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7269 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7271 // Next, convert to FP elements of the same size.
7272 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7277 // Okay, we know the src/dst types are both integers of differing types.
7278 // Handling growing first.
7279 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7280 if (SrcBitSize < DstBitSize) {
7281 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7283 SmallVector<SDValue, 8> Ops;
7284 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7285 i += NumInputsPerOutput) {
7286 bool isLE = TLI.isLittleEndian();
7287 APInt NewBits = APInt(DstBitSize, 0);
7288 bool EltIsUndef = true;
7289 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7290 // Shift the previously computed bits over.
7291 NewBits <<= SrcBitSize;
7292 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7293 if (Op.getOpcode() == ISD::UNDEF) continue;
7296 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7297 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7301 Ops.push_back(DAG.getUNDEF(DstEltVT));
7303 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7306 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7307 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7310 // Finally, this must be the case where we are shrinking elements: each input
7311 // turns into multiple outputs.
7312 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7313 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7314 NumOutputsPerInput*BV->getNumOperands());
7315 SmallVector<SDValue, 8> Ops;
7317 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7318 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7319 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7323 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7324 getAPIntValue().zextOrTrunc(SrcBitSize);
7326 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7327 APInt ThisVal = OpVal.trunc(DstBitSize);
7328 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7329 OpVal = OpVal.lshr(DstBitSize);
7332 // For big endian targets, swap the order of the pieces of each element.
7333 if (TLI.isBigEndian())
7334 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7337 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7340 /// Try to perform FMA combining on a given FADD node.
7341 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7342 SDValue N0 = N->getOperand(0);
7343 SDValue N1 = N->getOperand(1);
7344 EVT VT = N->getValueType(0);
7347 const TargetOptions &Options = DAG.getTarget().Options;
7348 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7349 Options.UnsafeFPMath);
7351 // Floating-point multiply-add with intermediate rounding.
7352 bool HasFMAD = (LegalOperations &&
7353 TLI.isOperationLegal(ISD::FMAD, VT));
7355 // Floating-point multiply-add without intermediate rounding.
7356 bool HasFMA = ((!LegalOperations ||
7357 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7358 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7361 // No valid opcode, do not combine.
7362 if (!HasFMAD && !HasFMA)
7365 // Always prefer FMAD to FMA for precision.
7366 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7367 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7368 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7370 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7371 if (N0.getOpcode() == ISD::FMUL &&
7372 (Aggressive || N0->hasOneUse())) {
7373 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7374 N0.getOperand(0), N0.getOperand(1), N1);
7377 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7378 // Note: Commutes FADD operands.
7379 if (N1.getOpcode() == ISD::FMUL &&
7380 (Aggressive || N1->hasOneUse())) {
7381 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7382 N1.getOperand(0), N1.getOperand(1), N0);
7385 // Look through FP_EXTEND nodes to do more combining.
7386 if (UnsafeFPMath && LookThroughFPExt) {
7387 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7388 if (N0.getOpcode() == ISD::FP_EXTEND) {
7389 SDValue N00 = N0.getOperand(0);
7390 if (N00.getOpcode() == ISD::FMUL)
7391 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7392 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7394 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7395 N00.getOperand(1)), N1);
7398 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7399 // Note: Commutes FADD operands.
7400 if (N1.getOpcode() == ISD::FP_EXTEND) {
7401 SDValue N10 = N1.getOperand(0);
7402 if (N10.getOpcode() == ISD::FMUL)
7403 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7404 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7406 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7407 N10.getOperand(1)), N0);
7411 // More folding opportunities when target permits.
7412 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7413 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7414 if (N0.getOpcode() == PreferredFusedOpcode &&
7415 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7416 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7417 N0.getOperand(0), N0.getOperand(1),
7418 DAG.getNode(PreferredFusedOpcode, SL, VT,
7419 N0.getOperand(2).getOperand(0),
7420 N0.getOperand(2).getOperand(1),
7424 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7425 if (N1->getOpcode() == PreferredFusedOpcode &&
7426 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7427 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7428 N1.getOperand(0), N1.getOperand(1),
7429 DAG.getNode(PreferredFusedOpcode, SL, VT,
7430 N1.getOperand(2).getOperand(0),
7431 N1.getOperand(2).getOperand(1),
7435 if (UnsafeFPMath && LookThroughFPExt) {
7436 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7437 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7438 auto FoldFAddFMAFPExtFMul = [&] (
7439 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7440 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7441 DAG.getNode(PreferredFusedOpcode, SL, VT,
7442 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7443 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7446 if (N0.getOpcode() == PreferredFusedOpcode) {
7447 SDValue N02 = N0.getOperand(2);
7448 if (N02.getOpcode() == ISD::FP_EXTEND) {
7449 SDValue N020 = N02.getOperand(0);
7450 if (N020.getOpcode() == ISD::FMUL)
7451 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7452 N020.getOperand(0), N020.getOperand(1),
7457 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7458 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7459 // FIXME: This turns two single-precision and one double-precision
7460 // operation into two double-precision operations, which might not be
7461 // interesting for all targets, especially GPUs.
7462 auto FoldFAddFPExtFMAFMul = [&] (
7463 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7464 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7465 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7466 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7467 DAG.getNode(PreferredFusedOpcode, SL, VT,
7468 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7469 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7472 if (N0.getOpcode() == ISD::FP_EXTEND) {
7473 SDValue N00 = N0.getOperand(0);
7474 if (N00.getOpcode() == PreferredFusedOpcode) {
7475 SDValue N002 = N00.getOperand(2);
7476 if (N002.getOpcode() == ISD::FMUL)
7477 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7478 N002.getOperand(0), N002.getOperand(1),
7483 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7484 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7485 if (N1.getOpcode() == PreferredFusedOpcode) {
7486 SDValue N12 = N1.getOperand(2);
7487 if (N12.getOpcode() == ISD::FP_EXTEND) {
7488 SDValue N120 = N12.getOperand(0);
7489 if (N120.getOpcode() == ISD::FMUL)
7490 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7491 N120.getOperand(0), N120.getOperand(1),
7496 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7497 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7498 // FIXME: This turns two single-precision and one double-precision
7499 // operation into two double-precision operations, which might not be
7500 // interesting for all targets, especially GPUs.
7501 if (N1.getOpcode() == ISD::FP_EXTEND) {
7502 SDValue N10 = N1.getOperand(0);
7503 if (N10.getOpcode() == PreferredFusedOpcode) {
7504 SDValue N102 = N10.getOperand(2);
7505 if (N102.getOpcode() == ISD::FMUL)
7506 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7507 N102.getOperand(0), N102.getOperand(1),
7517 /// Try to perform FMA combining on a given FSUB node.
7518 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7519 SDValue N0 = N->getOperand(0);
7520 SDValue N1 = N->getOperand(1);
7521 EVT VT = N->getValueType(0);
7524 const TargetOptions &Options = DAG.getTarget().Options;
7525 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7526 Options.UnsafeFPMath);
7528 // Floating-point multiply-add with intermediate rounding.
7529 bool HasFMAD = (LegalOperations &&
7530 TLI.isOperationLegal(ISD::FMAD, VT));
7532 // Floating-point multiply-add without intermediate rounding.
7533 bool HasFMA = ((!LegalOperations ||
7534 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7535 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7538 // No valid opcode, do not combine.
7539 if (!HasFMAD && !HasFMA)
7542 // Always prefer FMAD to FMA for precision.
7543 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7544 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7545 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7547 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7548 if (N0.getOpcode() == ISD::FMUL &&
7549 (Aggressive || N0->hasOneUse())) {
7550 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7551 N0.getOperand(0), N0.getOperand(1),
7552 DAG.getNode(ISD::FNEG, SL, VT, N1));
7555 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7556 // Note: Commutes FSUB operands.
7557 if (N1.getOpcode() == ISD::FMUL &&
7558 (Aggressive || N1->hasOneUse()))
7559 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7560 DAG.getNode(ISD::FNEG, SL, VT,
7562 N1.getOperand(1), N0);
7564 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7565 if (N0.getOpcode() == ISD::FNEG &&
7566 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7567 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7568 SDValue N00 = N0.getOperand(0).getOperand(0);
7569 SDValue N01 = N0.getOperand(0).getOperand(1);
7570 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7571 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7572 DAG.getNode(ISD::FNEG, SL, VT, N1));
7575 // Look through FP_EXTEND nodes to do more combining.
7576 if (UnsafeFPMath && LookThroughFPExt) {
7577 // fold (fsub (fpext (fmul x, y)), z)
7578 // -> (fma (fpext x), (fpext y), (fneg z))
7579 if (N0.getOpcode() == ISD::FP_EXTEND) {
7580 SDValue N00 = N0.getOperand(0);
7581 if (N00.getOpcode() == ISD::FMUL)
7582 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7583 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7585 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7587 DAG.getNode(ISD::FNEG, SL, VT, N1));
7590 // fold (fsub x, (fpext (fmul y, z)))
7591 // -> (fma (fneg (fpext y)), (fpext z), x)
7592 // Note: Commutes FSUB operands.
7593 if (N1.getOpcode() == ISD::FP_EXTEND) {
7594 SDValue N10 = N1.getOperand(0);
7595 if (N10.getOpcode() == ISD::FMUL)
7596 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7597 DAG.getNode(ISD::FNEG, SL, VT,
7598 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7599 N10.getOperand(0))),
7600 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7605 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7606 // -> (fneg (fma (fpext x), (fpext y), z))
7607 // Note: This could be removed with appropriate canonicalization of the
7608 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7609 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7610 // from implementing the canonicalization in visitFSUB.
7611 if (N0.getOpcode() == ISD::FP_EXTEND) {
7612 SDValue N00 = N0.getOperand(0);
7613 if (N00.getOpcode() == ISD::FNEG) {
7614 SDValue N000 = N00.getOperand(0);
7615 if (N000.getOpcode() == ISD::FMUL) {
7616 return DAG.getNode(ISD::FNEG, SL, VT,
7617 DAG.getNode(PreferredFusedOpcode, SL, VT,
7618 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7619 N000.getOperand(0)),
7620 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7621 N000.getOperand(1)),
7627 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7628 // -> (fneg (fma (fpext x)), (fpext y), z)
7629 // Note: This could be removed with appropriate canonicalization of the
7630 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7631 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7632 // from implementing the canonicalization in visitFSUB.
7633 if (N0.getOpcode() == ISD::FNEG) {
7634 SDValue N00 = N0.getOperand(0);
7635 if (N00.getOpcode() == ISD::FP_EXTEND) {
7636 SDValue N000 = N00.getOperand(0);
7637 if (N000.getOpcode() == ISD::FMUL) {
7638 return DAG.getNode(ISD::FNEG, SL, VT,
7639 DAG.getNode(PreferredFusedOpcode, SL, VT,
7640 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7641 N000.getOperand(0)),
7642 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7643 N000.getOperand(1)),
7651 // More folding opportunities when target permits.
7652 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7653 // fold (fsub (fma x, y, (fmul u, v)), z)
7654 // -> (fma x, y (fma u, v, (fneg z)))
7655 if (N0.getOpcode() == PreferredFusedOpcode &&
7656 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7657 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7658 N0.getOperand(0), N0.getOperand(1),
7659 DAG.getNode(PreferredFusedOpcode, SL, VT,
7660 N0.getOperand(2).getOperand(0),
7661 N0.getOperand(2).getOperand(1),
7662 DAG.getNode(ISD::FNEG, SL, VT,
7666 // fold (fsub x, (fma y, z, (fmul u, v)))
7667 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7668 if (N1.getOpcode() == PreferredFusedOpcode &&
7669 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7670 SDValue N20 = N1.getOperand(2).getOperand(0);
7671 SDValue N21 = N1.getOperand(2).getOperand(1);
7672 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7673 DAG.getNode(ISD::FNEG, SL, VT,
7676 DAG.getNode(PreferredFusedOpcode, SL, VT,
7677 DAG.getNode(ISD::FNEG, SL, VT, N20),
7682 if (UnsafeFPMath && LookThroughFPExt) {
7683 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7684 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7685 if (N0.getOpcode() == PreferredFusedOpcode) {
7686 SDValue N02 = N0.getOperand(2);
7687 if (N02.getOpcode() == ISD::FP_EXTEND) {
7688 SDValue N020 = N02.getOperand(0);
7689 if (N020.getOpcode() == ISD::FMUL)
7690 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7691 N0.getOperand(0), N0.getOperand(1),
7692 DAG.getNode(PreferredFusedOpcode, SL, VT,
7693 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7694 N020.getOperand(0)),
7695 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7696 N020.getOperand(1)),
7697 DAG.getNode(ISD::FNEG, SL, VT,
7702 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7703 // -> (fma (fpext x), (fpext y),
7704 // (fma (fpext u), (fpext v), (fneg z)))
7705 // FIXME: This turns two single-precision and one double-precision
7706 // operation into two double-precision operations, which might not be
7707 // interesting for all targets, especially GPUs.
7708 if (N0.getOpcode() == ISD::FP_EXTEND) {
7709 SDValue N00 = N0.getOperand(0);
7710 if (N00.getOpcode() == PreferredFusedOpcode) {
7711 SDValue N002 = N00.getOperand(2);
7712 if (N002.getOpcode() == ISD::FMUL)
7713 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7714 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7716 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7718 DAG.getNode(PreferredFusedOpcode, SL, VT,
7719 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7720 N002.getOperand(0)),
7721 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7722 N002.getOperand(1)),
7723 DAG.getNode(ISD::FNEG, SL, VT,
7728 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7729 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7730 if (N1.getOpcode() == PreferredFusedOpcode &&
7731 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7732 SDValue N120 = N1.getOperand(2).getOperand(0);
7733 if (N120.getOpcode() == ISD::FMUL) {
7734 SDValue N1200 = N120.getOperand(0);
7735 SDValue N1201 = N120.getOperand(1);
7736 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7737 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7739 DAG.getNode(PreferredFusedOpcode, SL, VT,
7740 DAG.getNode(ISD::FNEG, SL, VT,
7741 DAG.getNode(ISD::FP_EXTEND, SL,
7743 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7749 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7750 // -> (fma (fneg (fpext y)), (fpext z),
7751 // (fma (fneg (fpext u)), (fpext v), x))
7752 // FIXME: This turns two single-precision and one double-precision
7753 // operation into two double-precision operations, which might not be
7754 // interesting for all targets, especially GPUs.
7755 if (N1.getOpcode() == ISD::FP_EXTEND &&
7756 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7757 SDValue N100 = N1.getOperand(0).getOperand(0);
7758 SDValue N101 = N1.getOperand(0).getOperand(1);
7759 SDValue N102 = N1.getOperand(0).getOperand(2);
7760 if (N102.getOpcode() == ISD::FMUL) {
7761 SDValue N1020 = N102.getOperand(0);
7762 SDValue N1021 = N102.getOperand(1);
7763 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7764 DAG.getNode(ISD::FNEG, SL, VT,
7765 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7767 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7768 DAG.getNode(PreferredFusedOpcode, SL, VT,
7769 DAG.getNode(ISD::FNEG, SL, VT,
7770 DAG.getNode(ISD::FP_EXTEND, SL,
7772 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7783 SDValue DAGCombiner::visitFADD(SDNode *N) {
7784 SDValue N0 = N->getOperand(0);
7785 SDValue N1 = N->getOperand(1);
7786 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7787 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7788 EVT VT = N->getValueType(0);
7790 const TargetOptions &Options = DAG.getTarget().Options;
7794 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7797 // fold (fadd c1, c2) -> c1 + c2
7799 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7801 // canonicalize constant to RHS
7802 if (N0CFP && !N1CFP)
7803 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7805 // fold (fadd A, (fneg B)) -> (fsub A, B)
7806 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7807 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7808 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7809 GetNegatedExpression(N1, DAG, LegalOperations));
7811 // fold (fadd (fneg A), B) -> (fsub B, A)
7812 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7813 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7814 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7815 GetNegatedExpression(N0, DAG, LegalOperations));
7817 // If 'unsafe math' is enabled, fold lots of things.
7818 if (Options.UnsafeFPMath) {
7819 // No FP constant should be created after legalization as Instruction
7820 // Selection pass has a hard time dealing with FP constants.
7821 bool AllowNewConst = (Level < AfterLegalizeDAG);
7823 // fold (fadd A, 0) -> A
7824 if (N1CFP && N1CFP->getValueAPF().isZero())
7827 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7828 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7829 isa<ConstantFPSDNode>(N0.getOperand(1)))
7830 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7831 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7833 // If allowed, fold (fadd (fneg x), x) -> 0.0
7834 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7835 return DAG.getConstantFP(0.0, DL, VT);
7837 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7838 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7839 return DAG.getConstantFP(0.0, DL, VT);
7841 // We can fold chains of FADD's of the same value into multiplications.
7842 // This transform is not safe in general because we are reducing the number
7843 // of rounding steps.
7844 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7845 if (N0.getOpcode() == ISD::FMUL) {
7846 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7847 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7849 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7850 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7851 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7852 DAG.getConstantFP(1.0, DL, VT));
7853 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7856 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7857 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7858 N1.getOperand(0) == N1.getOperand(1) &&
7859 N0.getOperand(0) == N1.getOperand(0)) {
7860 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7861 DAG.getConstantFP(2.0, DL, VT));
7862 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7866 if (N1.getOpcode() == ISD::FMUL) {
7867 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7868 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7870 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7871 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7872 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7873 DAG.getConstantFP(1.0, DL, VT));
7874 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7877 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7878 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7879 N0.getOperand(0) == N0.getOperand(1) &&
7880 N1.getOperand(0) == N0.getOperand(0)) {
7881 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7882 DAG.getConstantFP(2.0, DL, VT));
7883 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7887 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7888 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7889 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7890 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7891 (N0.getOperand(0) == N1)) {
7892 return DAG.getNode(ISD::FMUL, DL, VT,
7893 N1, DAG.getConstantFP(3.0, DL, VT));
7897 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7898 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7899 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7900 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7901 N1.getOperand(0) == N0) {
7902 return DAG.getNode(ISD::FMUL, DL, VT,
7903 N0, DAG.getConstantFP(3.0, DL, VT));
7907 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7908 if (AllowNewConst &&
7909 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7910 N0.getOperand(0) == N0.getOperand(1) &&
7911 N1.getOperand(0) == N1.getOperand(1) &&
7912 N0.getOperand(0) == N1.getOperand(0)) {
7913 return DAG.getNode(ISD::FMUL, DL, VT,
7914 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7917 } // enable-unsafe-fp-math
7919 // FADD -> FMA combines:
7920 SDValue Fused = visitFADDForFMACombine(N);
7922 AddToWorklist(Fused.getNode());
7929 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7930 SDValue N0 = N->getOperand(0);
7931 SDValue N1 = N->getOperand(1);
7932 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7933 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7934 EVT VT = N->getValueType(0);
7936 const TargetOptions &Options = DAG.getTarget().Options;
7940 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7943 // fold (fsub c1, c2) -> c1-c2
7945 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7947 // fold (fsub A, (fneg B)) -> (fadd A, B)
7948 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7949 return DAG.getNode(ISD::FADD, dl, VT, N0,
7950 GetNegatedExpression(N1, DAG, LegalOperations));
7952 // If 'unsafe math' is enabled, fold lots of things.
7953 if (Options.UnsafeFPMath) {
7955 if (N1CFP && N1CFP->getValueAPF().isZero())
7958 // (fsub 0, B) -> -B
7959 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7960 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7961 return GetNegatedExpression(N1, DAG, LegalOperations);
7962 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7963 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7966 // (fsub x, x) -> 0.0
7968 return DAG.getConstantFP(0.0f, dl, VT);
7970 // (fsub x, (fadd x, y)) -> (fneg y)
7971 // (fsub x, (fadd y, x)) -> (fneg y)
7972 if (N1.getOpcode() == ISD::FADD) {
7973 SDValue N10 = N1->getOperand(0);
7974 SDValue N11 = N1->getOperand(1);
7976 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7977 return GetNegatedExpression(N11, DAG, LegalOperations);
7979 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7980 return GetNegatedExpression(N10, DAG, LegalOperations);
7984 // FSUB -> FMA combines:
7985 SDValue Fused = visitFSUBForFMACombine(N);
7987 AddToWorklist(Fused.getNode());
7994 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7995 SDValue N0 = N->getOperand(0);
7996 SDValue N1 = N->getOperand(1);
7997 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7998 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7999 EVT VT = N->getValueType(0);
8001 const TargetOptions &Options = DAG.getTarget().Options;
8004 if (VT.isVector()) {
8005 // This just handles C1 * C2 for vectors. Other vector folds are below.
8006 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8010 // fold (fmul c1, c2) -> c1*c2
8012 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8014 // canonicalize constant to RHS
8015 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8016 !isConstantFPBuildVectorOrConstantFP(N1))
8017 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8019 // fold (fmul A, 1.0) -> A
8020 if (N1CFP && N1CFP->isExactlyValue(1.0))
8023 if (Options.UnsafeFPMath) {
8024 // fold (fmul A, 0) -> 0
8025 if (N1CFP && N1CFP->getValueAPF().isZero())
8028 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8029 if (N0.getOpcode() == ISD::FMUL) {
8030 // Fold scalars or any vector constants (not just splats).
8031 // This fold is done in general by InstCombine, but extra fmul insts
8032 // may have been generated during lowering.
8033 SDValue N00 = N0.getOperand(0);
8034 SDValue N01 = N0.getOperand(1);
8035 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8036 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8037 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8039 // Check 1: Make sure that the first operand of the inner multiply is NOT
8040 // a constant. Otherwise, we may induce infinite looping.
8041 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8042 // Check 2: Make sure that the second operand of the inner multiply and
8043 // the second operand of the outer multiply are constants.
8044 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8045 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8046 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8047 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8052 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8053 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8054 // during an early run of DAGCombiner can prevent folding with fmuls
8055 // inserted during lowering.
8056 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8057 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8058 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8059 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8063 // fold (fmul X, 2.0) -> (fadd X, X)
8064 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8065 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8067 // fold (fmul X, -1.0) -> (fneg X)
8068 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8069 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8070 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8072 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8073 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8074 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8075 // Both can be negated for free, check to see if at least one is cheaper
8077 if (LHSNeg == 2 || RHSNeg == 2)
8078 return DAG.getNode(ISD::FMUL, DL, VT,
8079 GetNegatedExpression(N0, DAG, LegalOperations),
8080 GetNegatedExpression(N1, DAG, LegalOperations));
8087 SDValue DAGCombiner::visitFMA(SDNode *N) {
8088 SDValue N0 = N->getOperand(0);
8089 SDValue N1 = N->getOperand(1);
8090 SDValue N2 = N->getOperand(2);
8091 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8092 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8093 EVT VT = N->getValueType(0);
8095 const TargetOptions &Options = DAG.getTarget().Options;
8097 // Constant fold FMA.
8098 if (isa<ConstantFPSDNode>(N0) &&
8099 isa<ConstantFPSDNode>(N1) &&
8100 isa<ConstantFPSDNode>(N2)) {
8101 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8104 if (Options.UnsafeFPMath) {
8105 if (N0CFP && N0CFP->isZero())
8107 if (N1CFP && N1CFP->isZero())
8110 if (N0CFP && N0CFP->isExactlyValue(1.0))
8111 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8112 if (N1CFP && N1CFP->isExactlyValue(1.0))
8113 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8115 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8116 if (N0CFP && !N1CFP)
8117 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8119 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8120 if (Options.UnsafeFPMath && N1CFP &&
8121 N2.getOpcode() == ISD::FMUL &&
8122 N0 == N2.getOperand(0) &&
8123 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8124 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8125 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8129 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8130 if (Options.UnsafeFPMath &&
8131 N0.getOpcode() == ISD::FMUL && N1CFP &&
8132 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8133 return DAG.getNode(ISD::FMA, dl, VT,
8135 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8139 // (fma x, 1, y) -> (fadd x, y)
8140 // (fma x, -1, y) -> (fadd (fneg x), y)
8142 if (N1CFP->isExactlyValue(1.0))
8143 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8145 if (N1CFP->isExactlyValue(-1.0) &&
8146 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8147 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8148 AddToWorklist(RHSNeg.getNode());
8149 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8153 // (fma x, c, x) -> (fmul x, (c+1))
8154 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8155 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8156 DAG.getNode(ISD::FADD, dl, VT,
8157 N1, DAG.getConstantFP(1.0, dl, VT)));
8159 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8160 if (Options.UnsafeFPMath && N1CFP &&
8161 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8162 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8163 DAG.getNode(ISD::FADD, dl, VT,
8164 N1, DAG.getConstantFP(-1.0, dl, VT)));
8170 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8171 SDValue N0 = N->getOperand(0);
8172 SDValue N1 = N->getOperand(1);
8173 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8174 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8175 EVT VT = N->getValueType(0);
8177 const TargetOptions &Options = DAG.getTarget().Options;
8181 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8184 // fold (fdiv c1, c2) -> c1/c2
8186 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8188 if (Options.UnsafeFPMath) {
8189 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8191 // Compute the reciprocal 1.0 / c2.
8192 APFloat N1APF = N1CFP->getValueAPF();
8193 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8194 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8195 // Only do the transform if the reciprocal is a legal fp immediate that
8196 // isn't too nasty (eg NaN, denormal, ...).
8197 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8198 (!LegalOperations ||
8199 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8200 // backend)... we should handle this gracefully after Legalize.
8201 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8202 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8203 TLI.isFPImmLegal(Recip, VT)))
8204 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8205 DAG.getConstantFP(Recip, DL, VT));
8208 // If this FDIV is part of a reciprocal square root, it may be folded
8209 // into a target-specific square root estimate instruction.
8210 if (N1.getOpcode() == ISD::FSQRT) {
8211 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8212 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8214 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8215 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8216 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8217 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8218 AddToWorklist(RV.getNode());
8219 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8221 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8222 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8223 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8224 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8225 AddToWorklist(RV.getNode());
8226 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8228 } else if (N1.getOpcode() == ISD::FMUL) {
8229 // Look through an FMUL. Even though this won't remove the FDIV directly,
8230 // it's still worthwhile to get rid of the FSQRT if possible.
8233 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8234 SqrtOp = N1.getOperand(0);
8235 OtherOp = N1.getOperand(1);
8236 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8237 SqrtOp = N1.getOperand(1);
8238 OtherOp = N1.getOperand(0);
8240 if (SqrtOp.getNode()) {
8241 // We found a FSQRT, so try to make this fold:
8242 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8243 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8244 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8245 AddToWorklist(RV.getNode());
8246 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8251 // Fold into a reciprocal estimate and multiply instead of a real divide.
8252 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8253 AddToWorklist(RV.getNode());
8254 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8258 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8259 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8260 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8261 // Both can be negated for free, check to see if at least one is cheaper
8263 if (LHSNeg == 2 || RHSNeg == 2)
8264 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8265 GetNegatedExpression(N0, DAG, LegalOperations),
8266 GetNegatedExpression(N1, DAG, LegalOperations));
8270 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8272 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8273 // Notice that this is not always beneficial. One reason is different target
8274 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8275 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8276 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8277 if (Options.UnsafeFPMath) {
8278 // Skip if current node is a reciprocal.
8279 if (N0CFP && N0CFP->isExactlyValue(1.0))
8282 SmallVector<SDNode *, 4> Users;
8283 // Find all FDIV users of the same divisor.
8284 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8285 UE = N1.getNode()->use_end();
8287 SDNode *User = UI.getUse().getUser();
8288 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8289 Users.push_back(User);
8292 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8294 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8295 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8297 // Dividend / Divisor -> Dividend * Reciprocal
8298 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8299 if ((*I)->getOperand(0) != FPOne) {
8300 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8301 (*I)->getOperand(0), Reciprocal);
8302 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8312 SDValue DAGCombiner::visitFREM(SDNode *N) {
8313 SDValue N0 = N->getOperand(0);
8314 SDValue N1 = N->getOperand(1);
8315 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8316 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8317 EVT VT = N->getValueType(0);
8319 // fold (frem c1, c2) -> fmod(c1,c2)
8321 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8326 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8327 if (DAG.getTarget().Options.UnsafeFPMath &&
8328 !TLI.isFsqrtCheap()) {
8329 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8330 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8331 EVT VT = RV.getValueType();
8333 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8334 AddToWorklist(RV.getNode());
8336 // Unfortunately, RV is now NaN if the input was exactly 0.
8337 // Select out this case and force the answer to 0.
8338 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8340 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8341 N->getOperand(0), Zero, ISD::SETEQ);
8342 AddToWorklist(ZeroCmp.getNode());
8343 AddToWorklist(RV.getNode());
8345 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8346 DL, VT, ZeroCmp, Zero, RV);
8353 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8354 SDValue N0 = N->getOperand(0);
8355 SDValue N1 = N->getOperand(1);
8356 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8357 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8358 EVT VT = N->getValueType(0);
8360 if (N0CFP && N1CFP) // Constant fold
8361 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8364 const APFloat& V = N1CFP->getValueAPF();
8365 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8366 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8367 if (!V.isNegative()) {
8368 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8369 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8371 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8372 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8373 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8377 // copysign(fabs(x), y) -> copysign(x, y)
8378 // copysign(fneg(x), y) -> copysign(x, y)
8379 // copysign(copysign(x,z), y) -> copysign(x, y)
8380 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8381 N0.getOpcode() == ISD::FCOPYSIGN)
8382 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8383 N0.getOperand(0), N1);
8385 // copysign(x, abs(y)) -> abs(x)
8386 if (N1.getOpcode() == ISD::FABS)
8387 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8389 // copysign(x, copysign(y,z)) -> copysign(x, z)
8390 if (N1.getOpcode() == ISD::FCOPYSIGN)
8391 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8392 N0, N1.getOperand(1));
8394 // copysign(x, fp_extend(y)) -> copysign(x, y)
8395 // copysign(x, fp_round(y)) -> copysign(x, y)
8396 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8397 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8398 N0, N1.getOperand(0));
8403 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8404 SDValue N0 = N->getOperand(0);
8405 EVT VT = N->getValueType(0);
8406 EVT OpVT = N0.getValueType();
8408 // fold (sint_to_fp c1) -> c1fp
8409 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8410 // ...but only if the target supports immediate floating-point values
8411 (!LegalOperations ||
8412 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8413 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8415 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8416 // but UINT_TO_FP is legal on this target, try to convert.
8417 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8418 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8419 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8420 if (DAG.SignBitIsZero(N0))
8421 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8424 // The next optimizations are desirable only if SELECT_CC can be lowered.
8425 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8426 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8427 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8429 (!LegalOperations ||
8430 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8433 { N0.getOperand(0), N0.getOperand(1),
8434 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8436 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8439 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8440 // (select_cc x, y, 1.0, 0.0,, cc)
8441 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8442 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8443 (!LegalOperations ||
8444 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8447 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8448 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8449 N0.getOperand(0).getOperand(2) };
8450 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8457 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8458 SDValue N0 = N->getOperand(0);
8459 EVT VT = N->getValueType(0);
8460 EVT OpVT = N0.getValueType();
8462 // fold (uint_to_fp c1) -> c1fp
8463 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8464 // ...but only if the target supports immediate floating-point values
8465 (!LegalOperations ||
8466 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8467 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8469 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8470 // but SINT_TO_FP is legal on this target, try to convert.
8471 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8472 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8473 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8474 if (DAG.SignBitIsZero(N0))
8475 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8478 // The next optimizations are desirable only if SELECT_CC can be lowered.
8479 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8480 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8482 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8483 (!LegalOperations ||
8484 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8487 { N0.getOperand(0), N0.getOperand(1),
8488 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8490 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8497 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8498 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8499 SDValue N0 = N->getOperand(0);
8500 EVT VT = N->getValueType(0);
8502 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8505 SDValue Src = N0.getOperand(0);
8506 EVT SrcVT = Src.getValueType();
8507 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8508 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8510 // We can safely assume the conversion won't overflow the output range,
8511 // because (for example) (uint8_t)18293.f is undefined behavior.
8513 // Since we can assume the conversion won't overflow, our decision as to
8514 // whether the input will fit in the float should depend on the minimum
8515 // of the input range and output range.
8517 // This means this is also safe for a signed input and unsigned output, since
8518 // a negative input would lead to undefined behavior.
8519 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8520 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8521 unsigned ActualSize = std::min(InputSize, OutputSize);
8522 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8524 // We can only fold away the float conversion if the input range can be
8525 // represented exactly in the float range.
8526 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8527 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8528 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8530 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8532 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8533 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8536 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8541 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8542 SDValue N0 = N->getOperand(0);
8543 EVT VT = N->getValueType(0);
8545 // fold (fp_to_sint c1fp) -> c1
8546 if (isConstantFPBuildVectorOrConstantFP(N0))
8547 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8549 return FoldIntToFPToInt(N, DAG);
8552 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8553 SDValue N0 = N->getOperand(0);
8554 EVT VT = N->getValueType(0);
8556 // fold (fp_to_uint c1fp) -> c1
8557 if (isConstantFPBuildVectorOrConstantFP(N0))
8558 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8560 return FoldIntToFPToInt(N, DAG);
8563 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8564 SDValue N0 = N->getOperand(0);
8565 SDValue N1 = N->getOperand(1);
8566 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8567 EVT VT = N->getValueType(0);
8569 // fold (fp_round c1fp) -> c1fp
8571 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8573 // fold (fp_round (fp_extend x)) -> x
8574 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8575 return N0.getOperand(0);
8577 // fold (fp_round (fp_round x)) -> (fp_round x)
8578 if (N0.getOpcode() == ISD::FP_ROUND) {
8579 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8580 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8581 // If the first fp_round isn't a value preserving truncation, it might
8582 // introduce a tie in the second fp_round, that wouldn't occur in the
8583 // single-step fp_round we want to fold to.
8584 // In other words, double rounding isn't the same as rounding.
8585 // Also, this is a value preserving truncation iff both fp_round's are.
8586 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8588 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8589 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8593 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8594 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8595 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8596 N0.getOperand(0), N1);
8597 AddToWorklist(Tmp.getNode());
8598 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8599 Tmp, N0.getOperand(1));
8605 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8606 SDValue N0 = N->getOperand(0);
8607 EVT VT = N->getValueType(0);
8608 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8609 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8611 // fold (fp_round_inreg c1fp) -> c1fp
8612 if (N0CFP && isTypeLegal(EVT)) {
8614 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8615 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8621 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8622 SDValue N0 = N->getOperand(0);
8623 EVT VT = N->getValueType(0);
8625 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8626 if (N->hasOneUse() &&
8627 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8630 // fold (fp_extend c1fp) -> c1fp
8631 if (isConstantFPBuildVectorOrConstantFP(N0))
8632 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8634 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8635 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8636 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8637 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8639 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8641 if (N0.getOpcode() == ISD::FP_ROUND
8642 && N0.getNode()->getConstantOperandVal(1) == 1) {
8643 SDValue In = N0.getOperand(0);
8644 if (In.getValueType() == VT) return In;
8645 if (VT.bitsLT(In.getValueType()))
8646 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8647 In, N0.getOperand(1));
8648 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8651 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8652 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8653 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8654 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8655 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8657 LN0->getBasePtr(), N0.getValueType(),
8658 LN0->getMemOperand());
8659 CombineTo(N, ExtLoad);
8660 CombineTo(N0.getNode(),
8661 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8662 N0.getValueType(), ExtLoad,
8663 DAG.getIntPtrConstant(1, SDLoc(N0))),
8664 ExtLoad.getValue(1));
8665 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8671 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8672 SDValue N0 = N->getOperand(0);
8673 EVT VT = N->getValueType(0);
8675 // fold (fceil c1) -> fceil(c1)
8676 if (isConstantFPBuildVectorOrConstantFP(N0))
8677 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8682 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8683 SDValue N0 = N->getOperand(0);
8684 EVT VT = N->getValueType(0);
8686 // fold (ftrunc c1) -> ftrunc(c1)
8687 if (isConstantFPBuildVectorOrConstantFP(N0))
8688 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8693 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8694 SDValue N0 = N->getOperand(0);
8695 EVT VT = N->getValueType(0);
8697 // fold (ffloor c1) -> ffloor(c1)
8698 if (isConstantFPBuildVectorOrConstantFP(N0))
8699 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8704 // FIXME: FNEG and FABS have a lot in common; refactor.
8705 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8706 SDValue N0 = N->getOperand(0);
8707 EVT VT = N->getValueType(0);
8709 // Constant fold FNEG.
8710 if (isConstantFPBuildVectorOrConstantFP(N0))
8711 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8713 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8714 &DAG.getTarget().Options))
8715 return GetNegatedExpression(N0, DAG, LegalOperations);
8717 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8718 // constant pool values.
8719 if (!TLI.isFNegFree(VT) &&
8720 N0.getOpcode() == ISD::BITCAST &&
8721 N0.getNode()->hasOneUse()) {
8722 SDValue Int = N0.getOperand(0);
8723 EVT IntVT = Int.getValueType();
8724 if (IntVT.isInteger() && !IntVT.isVector()) {
8726 if (N0.getValueType().isVector()) {
8727 // For a vector, get a mask such as 0x80... per scalar element
8729 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8730 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8732 // For a scalar, just generate 0x80...
8733 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8736 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8737 DAG.getConstant(SignMask, DL0, IntVT));
8738 AddToWorklist(Int.getNode());
8739 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8743 // (fneg (fmul c, x)) -> (fmul -c, x)
8744 if (N0.getOpcode() == ISD::FMUL) {
8745 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8747 APFloat CVal = CFP1->getValueAPF();
8749 if (Level >= AfterLegalizeDAG &&
8750 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8751 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8753 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8754 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8761 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8762 SDValue N0 = N->getOperand(0);
8763 SDValue N1 = N->getOperand(1);
8764 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8765 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8767 if (N0CFP && N1CFP) {
8768 const APFloat &C0 = N0CFP->getValueAPF();
8769 const APFloat &C1 = N1CFP->getValueAPF();
8770 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8774 EVT VT = N->getValueType(0);
8775 // Canonicalize to constant on RHS.
8776 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8782 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8783 SDValue N0 = N->getOperand(0);
8784 SDValue N1 = N->getOperand(1);
8785 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8786 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8788 if (N0CFP && N1CFP) {
8789 const APFloat &C0 = N0CFP->getValueAPF();
8790 const APFloat &C1 = N1CFP->getValueAPF();
8791 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8795 EVT VT = N->getValueType(0);
8796 // Canonicalize to constant on RHS.
8797 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8803 SDValue DAGCombiner::visitFABS(SDNode *N) {
8804 SDValue N0 = N->getOperand(0);
8805 EVT VT = N->getValueType(0);
8807 // fold (fabs c1) -> fabs(c1)
8808 if (isConstantFPBuildVectorOrConstantFP(N0))
8809 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8811 // fold (fabs (fabs x)) -> (fabs x)
8812 if (N0.getOpcode() == ISD::FABS)
8813 return N->getOperand(0);
8815 // fold (fabs (fneg x)) -> (fabs x)
8816 // fold (fabs (fcopysign x, y)) -> (fabs x)
8817 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8818 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8820 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8821 // constant pool values.
8822 if (!TLI.isFAbsFree(VT) &&
8823 N0.getOpcode() == ISD::BITCAST &&
8824 N0.getNode()->hasOneUse()) {
8825 SDValue Int = N0.getOperand(0);
8826 EVT IntVT = Int.getValueType();
8827 if (IntVT.isInteger() && !IntVT.isVector()) {
8829 if (N0.getValueType().isVector()) {
8830 // For a vector, get a mask such as 0x7f... per scalar element
8832 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8833 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8835 // For a scalar, just generate 0x7f...
8836 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8839 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8840 DAG.getConstant(SignMask, DL, IntVT));
8841 AddToWorklist(Int.getNode());
8842 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8849 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8850 SDValue Chain = N->getOperand(0);
8851 SDValue N1 = N->getOperand(1);
8852 SDValue N2 = N->getOperand(2);
8854 // If N is a constant we could fold this into a fallthrough or unconditional
8855 // branch. However that doesn't happen very often in normal code, because
8856 // Instcombine/SimplifyCFG should have handled the available opportunities.
8857 // If we did this folding here, it would be necessary to update the
8858 // MachineBasicBlock CFG, which is awkward.
8860 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8862 if (N1.getOpcode() == ISD::SETCC &&
8863 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8864 N1.getOperand(0).getValueType())) {
8865 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8866 Chain, N1.getOperand(2),
8867 N1.getOperand(0), N1.getOperand(1), N2);
8870 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8871 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8872 (N1.getOperand(0).hasOneUse() &&
8873 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8874 SDNode *Trunc = nullptr;
8875 if (N1.getOpcode() == ISD::TRUNCATE) {
8876 // Look pass the truncate.
8877 Trunc = N1.getNode();
8878 N1 = N1.getOperand(0);
8881 // Match this pattern so that we can generate simpler code:
8884 // %b = and i32 %a, 2
8885 // %c = srl i32 %b, 1
8886 // brcond i32 %c ...
8891 // %b = and i32 %a, 2
8892 // %c = setcc eq %b, 0
8895 // This applies only when the AND constant value has one bit set and the
8896 // SRL constant is equal to the log2 of the AND constant. The back-end is
8897 // smart enough to convert the result into a TEST/JMP sequence.
8898 SDValue Op0 = N1.getOperand(0);
8899 SDValue Op1 = N1.getOperand(1);
8901 if (Op0.getOpcode() == ISD::AND &&
8902 Op1.getOpcode() == ISD::Constant) {
8903 SDValue AndOp1 = Op0.getOperand(1);
8905 if (AndOp1.getOpcode() == ISD::Constant) {
8906 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8908 if (AndConst.isPowerOf2() &&
8909 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8913 getSetCCResultType(Op0.getValueType()),
8914 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8917 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8918 MVT::Other, Chain, SetCC, N2);
8919 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8920 // will convert it back to (X & C1) >> C2.
8921 CombineTo(N, NewBRCond, false);
8922 // Truncate is dead.
8924 deleteAndRecombine(Trunc);
8925 // Replace the uses of SRL with SETCC
8926 WorklistRemover DeadNodes(*this);
8927 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8928 deleteAndRecombine(N1.getNode());
8929 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8935 // Restore N1 if the above transformation doesn't match.
8936 N1 = N->getOperand(1);
8939 // Transform br(xor(x, y)) -> br(x != y)
8940 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8941 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8942 SDNode *TheXor = N1.getNode();
8943 SDValue Op0 = TheXor->getOperand(0);
8944 SDValue Op1 = TheXor->getOperand(1);
8945 if (Op0.getOpcode() == Op1.getOpcode()) {
8946 // Avoid missing important xor optimizations.
8947 SDValue Tmp = visitXOR(TheXor);
8948 if (Tmp.getNode()) {
8949 if (Tmp.getNode() != TheXor) {
8950 DEBUG(dbgs() << "\nReplacing.8 ";
8952 dbgs() << "\nWith: ";
8953 Tmp.getNode()->dump(&DAG);
8955 WorklistRemover DeadNodes(*this);
8956 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8957 deleteAndRecombine(TheXor);
8958 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8959 MVT::Other, Chain, Tmp, N2);
8962 // visitXOR has changed XOR's operands or replaced the XOR completely,
8964 return SDValue(N, 0);
8968 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8970 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8971 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8972 Op0.getOpcode() == ISD::XOR) {
8973 TheXor = Op0.getNode();
8977 EVT SetCCVT = N1.getValueType();
8979 SetCCVT = getSetCCResultType(SetCCVT);
8980 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8983 Equal ? ISD::SETEQ : ISD::SETNE);
8984 // Replace the uses of XOR with SETCC
8985 WorklistRemover DeadNodes(*this);
8986 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8987 deleteAndRecombine(N1.getNode());
8988 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8989 MVT::Other, Chain, SetCC, N2);
8996 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8998 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8999 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9000 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9002 // If N is a constant we could fold this into a fallthrough or unconditional
9003 // branch. However that doesn't happen very often in normal code, because
9004 // Instcombine/SimplifyCFG should have handled the available opportunities.
9005 // If we did this folding here, it would be necessary to update the
9006 // MachineBasicBlock CFG, which is awkward.
9008 // Use SimplifySetCC to simplify SETCC's.
9009 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9010 CondLHS, CondRHS, CC->get(), SDLoc(N),
9012 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9014 // fold to a simpler setcc
9015 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9016 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9017 N->getOperand(0), Simp.getOperand(2),
9018 Simp.getOperand(0), Simp.getOperand(1),
9024 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9025 /// and that N may be folded in the load / store addressing mode.
9026 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9028 const TargetLowering &TLI) {
9030 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9031 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9033 VT = LD->getMemoryVT();
9034 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9035 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9037 VT = ST->getMemoryVT();
9041 TargetLowering::AddrMode AM;
9042 if (N->getOpcode() == ISD::ADD) {
9043 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9046 AM.BaseOffs = Offset->getSExtValue();
9050 } else if (N->getOpcode() == ISD::SUB) {
9051 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9054 AM.BaseOffs = -Offset->getSExtValue();
9061 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9064 /// Try turning a load/store into a pre-indexed load/store when the base
9065 /// pointer is an add or subtract and it has other uses besides the load/store.
9066 /// After the transformation, the new indexed load/store has effectively folded
9067 /// the add/subtract in and all of its other uses are redirected to the
9069 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9070 if (Level < AfterLegalizeDAG)
9076 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9077 if (LD->isIndexed())
9079 VT = LD->getMemoryVT();
9080 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9081 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9083 Ptr = LD->getBasePtr();
9084 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9085 if (ST->isIndexed())
9087 VT = ST->getMemoryVT();
9088 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9089 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9091 Ptr = ST->getBasePtr();
9097 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9098 // out. There is no reason to make this a preinc/predec.
9099 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9100 Ptr.getNode()->hasOneUse())
9103 // Ask the target to do addressing mode selection.
9106 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9107 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9110 // Backends without true r+i pre-indexed forms may need to pass a
9111 // constant base with a variable offset so that constant coercion
9112 // will work with the patterns in canonical form.
9113 bool Swapped = false;
9114 if (isa<ConstantSDNode>(BasePtr)) {
9115 std::swap(BasePtr, Offset);
9119 // Don't create a indexed load / store with zero offset.
9120 if (isNullConstant(Offset))
9123 // Try turning it into a pre-indexed load / store except when:
9124 // 1) The new base ptr is a frame index.
9125 // 2) If N is a store and the new base ptr is either the same as or is a
9126 // predecessor of the value being stored.
9127 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9128 // that would create a cycle.
9129 // 4) All uses are load / store ops that use it as old base ptr.
9131 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9132 // (plus the implicit offset) to a register to preinc anyway.
9133 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9138 SDValue Val = cast<StoreSDNode>(N)->getValue();
9139 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9143 // If the offset is a constant, there may be other adds of constants that
9144 // can be folded with this one. We should do this to avoid having to keep
9145 // a copy of the original base pointer.
9146 SmallVector<SDNode *, 16> OtherUses;
9147 if (isa<ConstantSDNode>(Offset))
9148 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9149 UE = BasePtr.getNode()->use_end();
9151 SDUse &Use = UI.getUse();
9152 // Skip the use that is Ptr and uses of other results from BasePtr's
9153 // node (important for nodes that return multiple results).
9154 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9157 if (Use.getUser()->isPredecessorOf(N))
9160 if (Use.getUser()->getOpcode() != ISD::ADD &&
9161 Use.getUser()->getOpcode() != ISD::SUB) {
9166 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9167 if (!isa<ConstantSDNode>(Op1)) {
9172 // FIXME: In some cases, we can be smarter about this.
9173 if (Op1.getValueType() != Offset.getValueType()) {
9178 OtherUses.push_back(Use.getUser());
9182 std::swap(BasePtr, Offset);
9184 // Now check for #3 and #4.
9185 bool RealUse = false;
9187 // Caches for hasPredecessorHelper
9188 SmallPtrSet<const SDNode *, 32> Visited;
9189 SmallVector<const SDNode *, 16> Worklist;
9191 for (SDNode *Use : Ptr.getNode()->uses()) {
9194 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9197 // If Ptr may be folded in addressing mode of other use, then it's
9198 // not profitable to do this transformation.
9199 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9208 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9209 BasePtr, Offset, AM);
9211 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9212 BasePtr, Offset, AM);
9215 DEBUG(dbgs() << "\nReplacing.4 ";
9217 dbgs() << "\nWith: ";
9218 Result.getNode()->dump(&DAG);
9220 WorklistRemover DeadNodes(*this);
9222 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9223 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9225 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9228 // Finally, since the node is now dead, remove it from the graph.
9229 deleteAndRecombine(N);
9232 std::swap(BasePtr, Offset);
9234 // Replace other uses of BasePtr that can be updated to use Ptr
9235 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9236 unsigned OffsetIdx = 1;
9237 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9239 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9240 BasePtr.getNode() && "Expected BasePtr operand");
9242 // We need to replace ptr0 in the following expression:
9243 // x0 * offset0 + y0 * ptr0 = t0
9245 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9247 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9248 // indexed load/store and the expresion that needs to be re-written.
9250 // Therefore, we have:
9251 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9253 ConstantSDNode *CN =
9254 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9256 APInt Offset0 = CN->getAPIntValue();
9257 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9259 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9260 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9261 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9262 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9264 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9266 APInt CNV = Offset0;
9267 if (X0 < 0) CNV = -CNV;
9268 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9269 else CNV = CNV - Offset1;
9271 SDLoc DL(OtherUses[i]);
9273 // We can now generate the new expression.
9274 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9275 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9277 SDValue NewUse = DAG.getNode(Opcode,
9279 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9280 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9281 deleteAndRecombine(OtherUses[i]);
9284 // Replace the uses of Ptr with uses of the updated base value.
9285 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9286 deleteAndRecombine(Ptr.getNode());
9291 /// Try to combine a load/store with a add/sub of the base pointer node into a
9292 /// post-indexed load/store. The transformation folded the add/subtract into the
9293 /// new indexed load/store effectively and all of its uses are redirected to the
9295 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9296 if (Level < AfterLegalizeDAG)
9302 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9303 if (LD->isIndexed())
9305 VT = LD->getMemoryVT();
9306 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9307 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9309 Ptr = LD->getBasePtr();
9310 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9311 if (ST->isIndexed())
9313 VT = ST->getMemoryVT();
9314 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9315 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9317 Ptr = ST->getBasePtr();
9323 if (Ptr.getNode()->hasOneUse())
9326 for (SDNode *Op : Ptr.getNode()->uses()) {
9328 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9333 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9334 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9335 // Don't create a indexed load / store with zero offset.
9336 if (isNullConstant(Offset))
9339 // Try turning it into a post-indexed load / store except when
9340 // 1) All uses are load / store ops that use it as base ptr (and
9341 // it may be folded as addressing mmode).
9342 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9343 // nor a successor of N. Otherwise, if Op is folded that would
9346 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9350 bool TryNext = false;
9351 for (SDNode *Use : BasePtr.getNode()->uses()) {
9352 if (Use == Ptr.getNode())
9355 // If all the uses are load / store addresses, then don't do the
9357 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9358 bool RealUse = false;
9359 for (SDNode *UseUse : Use->uses()) {
9360 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9375 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9376 SDValue Result = isLoad
9377 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9378 BasePtr, Offset, AM)
9379 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9380 BasePtr, Offset, AM);
9383 DEBUG(dbgs() << "\nReplacing.5 ";
9385 dbgs() << "\nWith: ";
9386 Result.getNode()->dump(&DAG);
9388 WorklistRemover DeadNodes(*this);
9390 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9391 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9393 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9396 // Finally, since the node is now dead, remove it from the graph.
9397 deleteAndRecombine(N);
9399 // Replace the uses of Use with uses of the updated base value.
9400 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9401 Result.getValue(isLoad ? 1 : 0));
9402 deleteAndRecombine(Op);
9411 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9412 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9413 ISD::MemIndexedMode AM = LD->getAddressingMode();
9414 assert(AM != ISD::UNINDEXED);
9415 SDValue BP = LD->getOperand(1);
9416 SDValue Inc = LD->getOperand(2);
9418 // Some backends use TargetConstants for load offsets, but don't expect
9419 // TargetConstants in general ADD nodes. We can convert these constants into
9420 // regular Constants (if the constant is not opaque).
9421 assert((Inc.getOpcode() != ISD::TargetConstant ||
9422 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9423 "Cannot split out indexing using opaque target constants");
9424 if (Inc.getOpcode() == ISD::TargetConstant) {
9425 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9426 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9427 ConstInc->getValueType(0));
9431 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9432 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9435 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9436 LoadSDNode *LD = cast<LoadSDNode>(N);
9437 SDValue Chain = LD->getChain();
9438 SDValue Ptr = LD->getBasePtr();
9440 // If load is not volatile and there are no uses of the loaded value (and
9441 // the updated indexed value in case of indexed loads), change uses of the
9442 // chain value into uses of the chain input (i.e. delete the dead load).
9443 if (!LD->isVolatile()) {
9444 if (N->getValueType(1) == MVT::Other) {
9446 if (!N->hasAnyUseOfValue(0)) {
9447 // It's not safe to use the two value CombineTo variant here. e.g.
9448 // v1, chain2 = load chain1, loc
9449 // v2, chain3 = load chain2, loc
9451 // Now we replace use of chain2 with chain1. This makes the second load
9452 // isomorphic to the one we are deleting, and thus makes this load live.
9453 DEBUG(dbgs() << "\nReplacing.6 ";
9455 dbgs() << "\nWith chain: ";
9456 Chain.getNode()->dump(&DAG);
9458 WorklistRemover DeadNodes(*this);
9459 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9462 deleteAndRecombine(N);
9464 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9468 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9470 // If this load has an opaque TargetConstant offset, then we cannot split
9471 // the indexing into an add/sub directly (that TargetConstant may not be
9472 // valid for a different type of node, and we cannot convert an opaque
9473 // target constant into a regular constant).
9474 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9475 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9477 if (!N->hasAnyUseOfValue(0) &&
9478 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9479 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9481 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9482 Index = SplitIndexingFromLoad(LD);
9483 // Try to fold the base pointer arithmetic into subsequent loads and
9485 AddUsersToWorklist(N);
9487 Index = DAG.getUNDEF(N->getValueType(1));
9488 DEBUG(dbgs() << "\nReplacing.7 ";
9490 dbgs() << "\nWith: ";
9491 Undef.getNode()->dump(&DAG);
9492 dbgs() << " and 2 other values\n");
9493 WorklistRemover DeadNodes(*this);
9494 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9495 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9496 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9497 deleteAndRecombine(N);
9498 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9503 // If this load is directly stored, replace the load value with the stored
9505 // TODO: Handle store large -> read small portion.
9506 // TODO: Handle TRUNCSTORE/LOADEXT
9507 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9508 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9509 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9510 if (PrevST->getBasePtr() == Ptr &&
9511 PrevST->getValue().getValueType() == N->getValueType(0))
9512 return CombineTo(N, Chain.getOperand(1), Chain);
9516 // Try to infer better alignment information than the load already has.
9517 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9518 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9519 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9521 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9522 LD->getValueType(0),
9523 Chain, Ptr, LD->getPointerInfo(),
9525 LD->isVolatile(), LD->isNonTemporal(),
9526 LD->isInvariant(), Align, LD->getAAInfo());
9527 if (NewLoad.getNode() != N)
9528 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9533 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9534 : DAG.getSubtarget().useAA();
9536 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9537 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9540 if (UseAA && LD->isUnindexed()) {
9541 // Walk up chain skipping non-aliasing memory nodes.
9542 SDValue BetterChain = FindBetterChain(N, Chain);
9544 // If there is a better chain.
9545 if (Chain != BetterChain) {
9548 // Replace the chain to void dependency.
9549 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9550 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9551 BetterChain, Ptr, LD->getMemOperand());
9553 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9554 LD->getValueType(0),
9555 BetterChain, Ptr, LD->getMemoryVT(),
9556 LD->getMemOperand());
9559 // Create token factor to keep old chain connected.
9560 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9561 MVT::Other, Chain, ReplLoad.getValue(1));
9563 // Make sure the new and old chains are cleaned up.
9564 AddToWorklist(Token.getNode());
9566 // Replace uses with load result and token factor. Don't add users
9568 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9572 // Try transforming N to an indexed load.
9573 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9574 return SDValue(N, 0);
9576 // Try to slice up N to more direct loads if the slices are mapped to
9577 // different register banks or pairing can take place.
9579 return SDValue(N, 0);
9585 /// \brief Helper structure used to slice a load in smaller loads.
9586 /// Basically a slice is obtained from the following sequence:
9587 /// Origin = load Ty1, Base
9588 /// Shift = srl Ty1 Origin, CstTy Amount
9589 /// Inst = trunc Shift to Ty2
9591 /// Then, it will be rewriten into:
9592 /// Slice = load SliceTy, Base + SliceOffset
9593 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9595 /// SliceTy is deduced from the number of bits that are actually used to
9597 struct LoadedSlice {
9598 /// \brief Helper structure used to compute the cost of a slice.
9600 /// Are we optimizing for code size.
9605 unsigned CrossRegisterBanksCopies;
9609 Cost(bool ForCodeSize = false)
9610 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9611 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9613 /// \brief Get the cost of one isolated slice.
9614 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9615 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9616 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9617 EVT TruncType = LS.Inst->getValueType(0);
9618 EVT LoadedType = LS.getLoadedType();
9619 if (TruncType != LoadedType &&
9620 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9624 /// \brief Account for slicing gain in the current cost.
9625 /// Slicing provide a few gains like removing a shift or a
9626 /// truncate. This method allows to grow the cost of the original
9627 /// load with the gain from this slice.
9628 void addSliceGain(const LoadedSlice &LS) {
9629 // Each slice saves a truncate.
9630 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9631 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9632 LS.Inst->getOperand(0).getValueType()))
9634 // If there is a shift amount, this slice gets rid of it.
9637 // If this slice can merge a cross register bank copy, account for it.
9638 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9639 ++CrossRegisterBanksCopies;
9642 Cost &operator+=(const Cost &RHS) {
9644 Truncates += RHS.Truncates;
9645 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9651 bool operator==(const Cost &RHS) const {
9652 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9653 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9654 ZExts == RHS.ZExts && Shift == RHS.Shift;
9657 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9659 bool operator<(const Cost &RHS) const {
9660 // Assume cross register banks copies are as expensive as loads.
9661 // FIXME: Do we want some more target hooks?
9662 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9663 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9664 // Unless we are optimizing for code size, consider the
9665 // expensive operation first.
9666 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9667 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9668 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9669 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9672 bool operator>(const Cost &RHS) const { return RHS < *this; }
9674 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9676 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9678 // The last instruction that represent the slice. This should be a
9679 // truncate instruction.
9681 // The original load instruction.
9683 // The right shift amount in bits from the original load.
9685 // The DAG from which Origin came from.
9686 // This is used to get some contextual information about legal types, etc.
9689 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9690 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9691 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9693 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9694 /// \return Result is \p BitWidth and has used bits set to 1 and
9695 /// not used bits set to 0.
9696 APInt getUsedBits() const {
9697 // Reproduce the trunc(lshr) sequence:
9698 // - Start from the truncated value.
9699 // - Zero extend to the desired bit width.
9701 assert(Origin && "No original load to compare against.");
9702 unsigned BitWidth = Origin->getValueSizeInBits(0);
9703 assert(Inst && "This slice is not bound to an instruction");
9704 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9705 "Extracted slice is bigger than the whole type!");
9706 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9707 UsedBits.setAllBits();
9708 UsedBits = UsedBits.zext(BitWidth);
9713 /// \brief Get the size of the slice to be loaded in bytes.
9714 unsigned getLoadedSize() const {
9715 unsigned SliceSize = getUsedBits().countPopulation();
9716 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9717 return SliceSize / 8;
9720 /// \brief Get the type that will be loaded for this slice.
9721 /// Note: This may not be the final type for the slice.
9722 EVT getLoadedType() const {
9723 assert(DAG && "Missing context");
9724 LLVMContext &Ctxt = *DAG->getContext();
9725 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9728 /// \brief Get the alignment of the load used for this slice.
9729 unsigned getAlignment() const {
9730 unsigned Alignment = Origin->getAlignment();
9731 unsigned Offset = getOffsetFromBase();
9733 Alignment = MinAlign(Alignment, Alignment + Offset);
9737 /// \brief Check if this slice can be rewritten with legal operations.
9738 bool isLegal() const {
9739 // An invalid slice is not legal.
9740 if (!Origin || !Inst || !DAG)
9743 // Offsets are for indexed load only, we do not handle that.
9744 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9747 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9749 // Check that the type is legal.
9750 EVT SliceType = getLoadedType();
9751 if (!TLI.isTypeLegal(SliceType))
9754 // Check that the load is legal for this type.
9755 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9758 // Check that the offset can be computed.
9759 // 1. Check its type.
9760 EVT PtrType = Origin->getBasePtr().getValueType();
9761 if (PtrType == MVT::Untyped || PtrType.isExtended())
9764 // 2. Check that it fits in the immediate.
9765 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9768 // 3. Check that the computation is legal.
9769 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9772 // Check that the zext is legal if it needs one.
9773 EVT TruncateType = Inst->getValueType(0);
9774 if (TruncateType != SliceType &&
9775 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9781 /// \brief Get the offset in bytes of this slice in the original chunk of
9783 /// \pre DAG != nullptr.
9784 uint64_t getOffsetFromBase() const {
9785 assert(DAG && "Missing context.");
9787 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9788 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9789 uint64_t Offset = Shift / 8;
9790 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9791 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9792 "The size of the original loaded type is not a multiple of a"
9794 // If Offset is bigger than TySizeInBytes, it means we are loading all
9795 // zeros. This should have been optimized before in the process.
9796 assert(TySizeInBytes > Offset &&
9797 "Invalid shift amount for given loaded size");
9799 Offset = TySizeInBytes - Offset - getLoadedSize();
9803 /// \brief Generate the sequence of instructions to load the slice
9804 /// represented by this object and redirect the uses of this slice to
9805 /// this new sequence of instructions.
9806 /// \pre this->Inst && this->Origin are valid Instructions and this
9807 /// object passed the legal check: LoadedSlice::isLegal returned true.
9808 /// \return The last instruction of the sequence used to load the slice.
9809 SDValue loadSlice() const {
9810 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9811 const SDValue &OldBaseAddr = Origin->getBasePtr();
9812 SDValue BaseAddr = OldBaseAddr;
9813 // Get the offset in that chunk of bytes w.r.t. the endianess.
9814 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9815 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9817 // BaseAddr = BaseAddr + Offset.
9818 EVT ArithType = BaseAddr.getValueType();
9820 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9821 DAG->getConstant(Offset, DL, ArithType));
9824 // Create the type of the loaded slice according to its size.
9825 EVT SliceType = getLoadedType();
9827 // Create the load for the slice.
9828 SDValue LastInst = DAG->getLoad(
9829 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9830 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9831 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9832 // If the final type is not the same as the loaded type, this means that
9833 // we have to pad with zero. Create a zero extend for that.
9834 EVT FinalType = Inst->getValueType(0);
9835 if (SliceType != FinalType)
9837 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9841 /// \brief Check if this slice can be merged with an expensive cross register
9842 /// bank copy. E.g.,
9844 /// f = bitcast i32 i to float
9845 bool canMergeExpensiveCrossRegisterBankCopy() const {
9846 if (!Inst || !Inst->hasOneUse())
9848 SDNode *Use = *Inst->use_begin();
9849 if (Use->getOpcode() != ISD::BITCAST)
9851 assert(DAG && "Missing context");
9852 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9853 EVT ResVT = Use->getValueType(0);
9854 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9855 const TargetRegisterClass *ArgRC =
9856 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9857 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9860 // At this point, we know that we perform a cross-register-bank copy.
9861 // Check if it is expensive.
9862 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9863 // Assume bitcasts are cheap, unless both register classes do not
9864 // explicitly share a common sub class.
9865 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9868 // Check if it will be merged with the load.
9869 // 1. Check the alignment constraint.
9870 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9871 ResVT.getTypeForEVT(*DAG->getContext()));
9873 if (RequiredAlignment > getAlignment())
9876 // 2. Check that the load is a legal operation for that type.
9877 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9880 // 3. Check that we do not have a zext in the way.
9881 if (Inst->getValueType(0) != getLoadedType())
9889 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9890 /// \p UsedBits looks like 0..0 1..1 0..0.
9891 static bool areUsedBitsDense(const APInt &UsedBits) {
9892 // If all the bits are one, this is dense!
9893 if (UsedBits.isAllOnesValue())
9896 // Get rid of the unused bits on the right.
9897 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9898 // Get rid of the unused bits on the left.
9899 if (NarrowedUsedBits.countLeadingZeros())
9900 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9901 // Check that the chunk of bits is completely used.
9902 return NarrowedUsedBits.isAllOnesValue();
9905 /// \brief Check whether or not \p First and \p Second are next to each other
9906 /// in memory. This means that there is no hole between the bits loaded
9907 /// by \p First and the bits loaded by \p Second.
9908 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9909 const LoadedSlice &Second) {
9910 assert(First.Origin == Second.Origin && First.Origin &&
9911 "Unable to match different memory origins.");
9912 APInt UsedBits = First.getUsedBits();
9913 assert((UsedBits & Second.getUsedBits()) == 0 &&
9914 "Slices are not supposed to overlap.");
9915 UsedBits |= Second.getUsedBits();
9916 return areUsedBitsDense(UsedBits);
9919 /// \brief Adjust the \p GlobalLSCost according to the target
9920 /// paring capabilities and the layout of the slices.
9921 /// \pre \p GlobalLSCost should account for at least as many loads as
9922 /// there is in the slices in \p LoadedSlices.
9923 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9924 LoadedSlice::Cost &GlobalLSCost) {
9925 unsigned NumberOfSlices = LoadedSlices.size();
9926 // If there is less than 2 elements, no pairing is possible.
9927 if (NumberOfSlices < 2)
9930 // Sort the slices so that elements that are likely to be next to each
9931 // other in memory are next to each other in the list.
9932 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9933 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9934 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9935 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9937 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9938 // First (resp. Second) is the first (resp. Second) potentially candidate
9939 // to be placed in a paired load.
9940 const LoadedSlice *First = nullptr;
9941 const LoadedSlice *Second = nullptr;
9942 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9943 // Set the beginning of the pair.
9946 Second = &LoadedSlices[CurrSlice];
9948 // If First is NULL, it means we start a new pair.
9949 // Get to the next slice.
9953 EVT LoadedType = First->getLoadedType();
9955 // If the types of the slices are different, we cannot pair them.
9956 if (LoadedType != Second->getLoadedType())
9959 // Check if the target supplies paired loads for this type.
9960 unsigned RequiredAlignment = 0;
9961 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9962 // move to the next pair, this type is hopeless.
9966 // Check if we meet the alignment requirement.
9967 if (RequiredAlignment > First->getAlignment())
9970 // Check that both loads are next to each other in memory.
9971 if (!areSlicesNextToEachOther(*First, *Second))
9974 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9975 --GlobalLSCost.Loads;
9976 // Move to the next pair.
9981 /// \brief Check the profitability of all involved LoadedSlice.
9982 /// Currently, it is considered profitable if there is exactly two
9983 /// involved slices (1) which are (2) next to each other in memory, and
9984 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9986 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9987 /// the elements themselves.
9989 /// FIXME: When the cost model will be mature enough, we can relax
9990 /// constraints (1) and (2).
9991 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9992 const APInt &UsedBits, bool ForCodeSize) {
9993 unsigned NumberOfSlices = LoadedSlices.size();
9994 if (StressLoadSlicing)
9995 return NumberOfSlices > 1;
9998 if (NumberOfSlices != 2)
10002 if (!areUsedBitsDense(UsedBits))
10006 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10007 // The original code has one big load.
10008 OrigCost.Loads = 1;
10009 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10010 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10011 // Accumulate the cost of all the slices.
10012 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10013 GlobalSlicingCost += SliceCost;
10015 // Account as cost in the original configuration the gain obtained
10016 // with the current slices.
10017 OrigCost.addSliceGain(LS);
10020 // If the target supports paired load, adjust the cost accordingly.
10021 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10022 return OrigCost > GlobalSlicingCost;
10025 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10026 /// operations, split it in the various pieces being extracted.
10028 /// This sort of thing is introduced by SROA.
10029 /// This slicing takes care not to insert overlapping loads.
10030 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10031 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10032 if (Level < AfterLegalizeDAG)
10035 LoadSDNode *LD = cast<LoadSDNode>(N);
10036 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10037 !LD->getValueType(0).isInteger())
10040 // Keep track of already used bits to detect overlapping values.
10041 // In that case, we will just abort the transformation.
10042 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10044 SmallVector<LoadedSlice, 4> LoadedSlices;
10046 // Check if this load is used as several smaller chunks of bits.
10047 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10048 // of computation for each trunc.
10049 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10050 UI != UIEnd; ++UI) {
10051 // Skip the uses of the chain.
10052 if (UI.getUse().getResNo() != 0)
10055 SDNode *User = *UI;
10056 unsigned Shift = 0;
10058 // Check if this is a trunc(lshr).
10059 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10060 isa<ConstantSDNode>(User->getOperand(1))) {
10061 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10062 User = *User->use_begin();
10065 // At this point, User is a Truncate, iff we encountered, trunc or
10067 if (User->getOpcode() != ISD::TRUNCATE)
10070 // The width of the type must be a power of 2 and greater than 8-bits.
10071 // Otherwise the load cannot be represented in LLVM IR.
10072 // Moreover, if we shifted with a non-8-bits multiple, the slice
10073 // will be across several bytes. We do not support that.
10074 unsigned Width = User->getValueSizeInBits(0);
10075 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10078 // Build the slice for this chain of computations.
10079 LoadedSlice LS(User, LD, Shift, &DAG);
10080 APInt CurrentUsedBits = LS.getUsedBits();
10082 // Check if this slice overlaps with another.
10083 if ((CurrentUsedBits & UsedBits) != 0)
10085 // Update the bits used globally.
10086 UsedBits |= CurrentUsedBits;
10088 // Check if the new slice would be legal.
10092 // Record the slice.
10093 LoadedSlices.push_back(LS);
10096 // Abort slicing if it does not seem to be profitable.
10097 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10102 // Rewrite each chain to use an independent load.
10103 // By construction, each chain can be represented by a unique load.
10105 // Prepare the argument for the new token factor for all the slices.
10106 SmallVector<SDValue, 8> ArgChains;
10107 for (SmallVectorImpl<LoadedSlice>::const_iterator
10108 LSIt = LoadedSlices.begin(),
10109 LSItEnd = LoadedSlices.end();
10110 LSIt != LSItEnd; ++LSIt) {
10111 SDValue SliceInst = LSIt->loadSlice();
10112 CombineTo(LSIt->Inst, SliceInst, true);
10113 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10114 SliceInst = SliceInst.getOperand(0);
10115 assert(SliceInst->getOpcode() == ISD::LOAD &&
10116 "It takes more than a zext to get to the loaded slice!!");
10117 ArgChains.push_back(SliceInst.getValue(1));
10120 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10122 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10126 /// Check to see if V is (and load (ptr), imm), where the load is having
10127 /// specific bytes cleared out. If so, return the byte size being masked out
10128 /// and the shift amount.
10129 static std::pair<unsigned, unsigned>
10130 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10131 std::pair<unsigned, unsigned> Result(0, 0);
10133 // Check for the structure we're looking for.
10134 if (V->getOpcode() != ISD::AND ||
10135 !isa<ConstantSDNode>(V->getOperand(1)) ||
10136 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10139 // Check the chain and pointer.
10140 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10141 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10143 // The store should be chained directly to the load or be an operand of a
10145 if (LD == Chain.getNode())
10147 else if (Chain->getOpcode() != ISD::TokenFactor)
10148 return Result; // Fail.
10151 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10152 if (Chain->getOperand(i).getNode() == LD) {
10156 if (!isOk) return Result;
10159 // This only handles simple types.
10160 if (V.getValueType() != MVT::i16 &&
10161 V.getValueType() != MVT::i32 &&
10162 V.getValueType() != MVT::i64)
10165 // Check the constant mask. Invert it so that the bits being masked out are
10166 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10167 // follow the sign bit for uniformity.
10168 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10169 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10170 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10171 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10172 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10173 if (NotMaskLZ == 64) return Result; // All zero mask.
10175 // See if we have a continuous run of bits. If so, we have 0*1+0*
10176 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10179 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10180 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10181 NotMaskLZ -= 64-V.getValueSizeInBits();
10183 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10184 switch (MaskedBytes) {
10188 default: return Result; // All one mask, or 5-byte mask.
10191 // Verify that the first bit starts at a multiple of mask so that the access
10192 // is aligned the same as the access width.
10193 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10195 Result.first = MaskedBytes;
10196 Result.second = NotMaskTZ/8;
10201 /// Check to see if IVal is something that provides a value as specified by
10202 /// MaskInfo. If so, replace the specified store with a narrower store of
10203 /// truncated IVal.
10205 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10206 SDValue IVal, StoreSDNode *St,
10208 unsigned NumBytes = MaskInfo.first;
10209 unsigned ByteShift = MaskInfo.second;
10210 SelectionDAG &DAG = DC->getDAG();
10212 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10213 // that uses this. If not, this is not a replacement.
10214 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10215 ByteShift*8, (ByteShift+NumBytes)*8);
10216 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10218 // Check that it is legal on the target to do this. It is legal if the new
10219 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10221 MVT VT = MVT::getIntegerVT(NumBytes*8);
10222 if (!DC->isTypeLegal(VT))
10225 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10226 // shifted by ByteShift and truncated down to NumBytes.
10229 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10230 DAG.getConstant(ByteShift*8, DL,
10231 DC->getShiftAmountTy(IVal.getValueType())));
10234 // Figure out the offset for the store and the alignment of the access.
10236 unsigned NewAlign = St->getAlignment();
10238 if (DAG.getTargetLoweringInfo().isLittleEndian())
10239 StOffset = ByteShift;
10241 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10243 SDValue Ptr = St->getBasePtr();
10246 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10247 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10248 NewAlign = MinAlign(NewAlign, StOffset);
10251 // Truncate down to the new size.
10252 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10255 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10256 St->getPointerInfo().getWithOffset(StOffset),
10257 false, false, NewAlign).getNode();
10261 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10262 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10263 /// narrowing the load and store if it would end up being a win for performance
10265 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10266 StoreSDNode *ST = cast<StoreSDNode>(N);
10267 if (ST->isVolatile())
10270 SDValue Chain = ST->getChain();
10271 SDValue Value = ST->getValue();
10272 SDValue Ptr = ST->getBasePtr();
10273 EVT VT = Value.getValueType();
10275 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10278 unsigned Opc = Value.getOpcode();
10280 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10281 // is a byte mask indicating a consecutive number of bytes, check to see if
10282 // Y is known to provide just those bytes. If so, we try to replace the
10283 // load + replace + store sequence with a single (narrower) store, which makes
10285 if (Opc == ISD::OR) {
10286 std::pair<unsigned, unsigned> MaskedLoad;
10287 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10288 if (MaskedLoad.first)
10289 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10290 Value.getOperand(1), ST,this))
10291 return SDValue(NewST, 0);
10293 // Or is commutative, so try swapping X and Y.
10294 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10295 if (MaskedLoad.first)
10296 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10297 Value.getOperand(0), ST,this))
10298 return SDValue(NewST, 0);
10301 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10302 Value.getOperand(1).getOpcode() != ISD::Constant)
10305 SDValue N0 = Value.getOperand(0);
10306 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10307 Chain == SDValue(N0.getNode(), 1)) {
10308 LoadSDNode *LD = cast<LoadSDNode>(N0);
10309 if (LD->getBasePtr() != Ptr ||
10310 LD->getPointerInfo().getAddrSpace() !=
10311 ST->getPointerInfo().getAddrSpace())
10314 // Find the type to narrow it the load / op / store to.
10315 SDValue N1 = Value.getOperand(1);
10316 unsigned BitWidth = N1.getValueSizeInBits();
10317 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10318 if (Opc == ISD::AND)
10319 Imm ^= APInt::getAllOnesValue(BitWidth);
10320 if (Imm == 0 || Imm.isAllOnesValue())
10322 unsigned ShAmt = Imm.countTrailingZeros();
10323 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10324 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10325 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10326 // The narrowing should be profitable, the load/store operation should be
10327 // legal (or custom) and the store size should be equal to the NewVT width.
10328 while (NewBW < BitWidth &&
10329 (NewVT.getStoreSizeInBits() != NewBW ||
10330 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10331 !TLI.isNarrowingProfitable(VT, NewVT))) {
10332 NewBW = NextPowerOf2(NewBW);
10333 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10335 if (NewBW >= BitWidth)
10338 // If the lsb changed does not start at the type bitwidth boundary,
10339 // start at the previous one.
10341 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10342 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10343 std::min(BitWidth, ShAmt + NewBW));
10344 if ((Imm & Mask) == Imm) {
10345 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10346 if (Opc == ISD::AND)
10347 NewImm ^= APInt::getAllOnesValue(NewBW);
10348 uint64_t PtrOff = ShAmt / 8;
10349 // For big endian targets, we need to adjust the offset to the pointer to
10350 // load the correct bytes.
10351 if (TLI.isBigEndian())
10352 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10354 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10355 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10356 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10359 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10360 Ptr.getValueType(), Ptr,
10361 DAG.getConstant(PtrOff, SDLoc(LD),
10362 Ptr.getValueType()));
10363 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10364 LD->getChain(), NewPtr,
10365 LD->getPointerInfo().getWithOffset(PtrOff),
10366 LD->isVolatile(), LD->isNonTemporal(),
10367 LD->isInvariant(), NewAlign,
10369 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10370 DAG.getConstant(NewImm, SDLoc(Value),
10372 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10374 ST->getPointerInfo().getWithOffset(PtrOff),
10375 false, false, NewAlign);
10377 AddToWorklist(NewPtr.getNode());
10378 AddToWorklist(NewLD.getNode());
10379 AddToWorklist(NewVal.getNode());
10380 WorklistRemover DeadNodes(*this);
10381 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10390 /// For a given floating point load / store pair, if the load value isn't used
10391 /// by any other operations, then consider transforming the pair to integer
10392 /// load / store operations if the target deems the transformation profitable.
10393 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10394 StoreSDNode *ST = cast<StoreSDNode>(N);
10395 SDValue Chain = ST->getChain();
10396 SDValue Value = ST->getValue();
10397 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10398 Value.hasOneUse() &&
10399 Chain == SDValue(Value.getNode(), 1)) {
10400 LoadSDNode *LD = cast<LoadSDNode>(Value);
10401 EVT VT = LD->getMemoryVT();
10402 if (!VT.isFloatingPoint() ||
10403 VT != ST->getMemoryVT() ||
10404 LD->isNonTemporal() ||
10405 ST->isNonTemporal() ||
10406 LD->getPointerInfo().getAddrSpace() != 0 ||
10407 ST->getPointerInfo().getAddrSpace() != 0)
10410 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10411 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10412 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10413 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10414 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10417 unsigned LDAlign = LD->getAlignment();
10418 unsigned STAlign = ST->getAlignment();
10419 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10420 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10421 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10424 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10425 LD->getChain(), LD->getBasePtr(),
10426 LD->getPointerInfo(),
10427 false, false, false, LDAlign);
10429 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10430 NewLD, ST->getBasePtr(),
10431 ST->getPointerInfo(),
10432 false, false, STAlign);
10434 AddToWorklist(NewLD.getNode());
10435 AddToWorklist(NewST.getNode());
10436 WorklistRemover DeadNodes(*this);
10437 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10446 /// Helper struct to parse and store a memory address as base + index + offset.
10447 /// We ignore sign extensions when it is safe to do so.
10448 /// The following two expressions are not equivalent. To differentiate we need
10449 /// to store whether there was a sign extension involved in the index
10451 /// (load (i64 add (i64 copyfromreg %c)
10452 /// (i64 signextend (add (i8 load %index)
10456 /// (load (i64 add (i64 copyfromreg %c)
10457 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10459 struct BaseIndexOffset {
10463 bool IsIndexSignExt;
10465 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10467 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10468 bool IsIndexSignExt) :
10469 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10471 bool equalBaseIndex(const BaseIndexOffset &Other) {
10472 return Other.Base == Base && Other.Index == Index &&
10473 Other.IsIndexSignExt == IsIndexSignExt;
10476 /// Parses tree in Ptr for base, index, offset addresses.
10477 static BaseIndexOffset match(SDValue Ptr) {
10478 bool IsIndexSignExt = false;
10480 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10481 // instruction, then it could be just the BASE or everything else we don't
10482 // know how to handle. Just use Ptr as BASE and give up.
10483 if (Ptr->getOpcode() != ISD::ADD)
10484 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10486 // We know that we have at least an ADD instruction. Try to pattern match
10487 // the simple case of BASE + OFFSET.
10488 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10489 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10490 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10494 // Inside a loop the current BASE pointer is calculated using an ADD and a
10495 // MUL instruction. In this case Ptr is the actual BASE pointer.
10496 // (i64 add (i64 %array_ptr)
10497 // (i64 mul (i64 %induction_var)
10498 // (i64 %element_size)))
10499 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10500 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10502 // Look at Base + Index + Offset cases.
10503 SDValue Base = Ptr->getOperand(0);
10504 SDValue IndexOffset = Ptr->getOperand(1);
10506 // Skip signextends.
10507 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10508 IndexOffset = IndexOffset->getOperand(0);
10509 IsIndexSignExt = true;
10512 // Either the case of Base + Index (no offset) or something else.
10513 if (IndexOffset->getOpcode() != ISD::ADD)
10514 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10516 // Now we have the case of Base + Index + offset.
10517 SDValue Index = IndexOffset->getOperand(0);
10518 SDValue Offset = IndexOffset->getOperand(1);
10520 if (!isa<ConstantSDNode>(Offset))
10521 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10523 // Ignore signextends.
10524 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10525 Index = Index->getOperand(0);
10526 IsIndexSignExt = true;
10527 } else IsIndexSignExt = false;
10529 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10530 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10535 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10536 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10537 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10538 // Make sure we have something to merge.
10542 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10543 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10544 unsigned LatestNodeUsed = 0;
10546 for (unsigned i=0; i < NumElem; ++i) {
10547 // Find a chain for the new wide-store operand. Notice that some
10548 // of the store nodes that we found may not be selected for inclusion
10549 // in the wide store. The chain we use needs to be the chain of the
10550 // latest store node which is *used* and replaced by the wide store.
10551 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10552 LatestNodeUsed = i;
10555 // The latest Node in the DAG.
10556 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10557 SDLoc DL(StoreNodes[0].MemNode);
10561 // Find a legal type for the vector store.
10562 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10563 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10564 if (IsConstantSrc) {
10565 // A vector store with a constant source implies that the constant is
10566 // zero; we only handle merging stores of constant zeros because the zero
10567 // can be materialized without a load.
10568 // It may be beneficial to loosen this restriction to allow non-zero
10570 StoredVal = DAG.getConstant(0, DL, Ty);
10572 SmallVector<SDValue, 8> Ops;
10573 for (unsigned i = 0; i < NumElem ; ++i) {
10574 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10575 SDValue Val = St->getValue();
10576 // All of the operands of a BUILD_VECTOR must have the same type.
10577 if (Val.getValueType() != MemVT)
10579 Ops.push_back(Val);
10582 // Build the extracted vector elements back into a vector.
10583 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10586 // We should always use a vector store when merging extracted vector
10587 // elements, so this path implies a store of constants.
10588 assert(IsConstantSrc && "Merged vector elements should use vector store");
10590 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10591 APInt StoreInt(StoreBW, 0);
10593 // Construct a single integer constant which is made of the smaller
10594 // constant inputs.
10595 bool IsLE = TLI.isLittleEndian();
10596 for (unsigned i = 0; i < NumElem ; ++i) {
10597 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10598 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10599 SDValue Val = St->getValue();
10600 StoreInt <<= ElementSizeBytes*8;
10601 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10602 StoreInt |= C->getAPIntValue().zext(StoreBW);
10603 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10604 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10606 llvm_unreachable("Invalid constant element type");
10610 // Create the new Load and Store operations.
10611 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10612 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10615 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10616 FirstInChain->getBasePtr(),
10617 FirstInChain->getPointerInfo(),
10619 FirstInChain->getAlignment());
10621 // Replace the last store with the new store
10622 CombineTo(LatestOp, NewStore);
10623 // Erase all other stores.
10624 for (unsigned i = 0; i < NumElem ; ++i) {
10625 if (StoreNodes[i].MemNode == LatestOp)
10627 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10628 // ReplaceAllUsesWith will replace all uses that existed when it was
10629 // called, but graph optimizations may cause new ones to appear. For
10630 // example, the case in pr14333 looks like
10632 // St's chain -> St -> another store -> X
10634 // And the only difference from St to the other store is the chain.
10635 // When we change it's chain to be St's chain they become identical,
10636 // get CSEed and the net result is that X is now a use of St.
10637 // Since we know that St is redundant, just iterate.
10638 while (!St->use_empty())
10639 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10640 deleteAndRecombine(St);
10646 static bool allowableAlignment(const SelectionDAG &DAG,
10647 const TargetLowering &TLI, EVT EVTTy,
10648 unsigned AS, unsigned Align) {
10649 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10652 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10653 unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10654 return (Align >= ABIAlignment);
10657 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10658 if (OptLevel == CodeGenOpt::None)
10661 EVT MemVT = St->getMemoryVT();
10662 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10663 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10664 Attribute::NoImplicitFloat);
10666 // This function cannot currently deal with non-byte-sized memory sizes.
10667 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10670 // Don't merge vectors into wider inputs.
10671 if (MemVT.isVector() || !MemVT.isSimple())
10674 // Perform an early exit check. Do not bother looking at stored values that
10675 // are not constants, loads, or extracted vector elements.
10676 SDValue StoredVal = St->getValue();
10677 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10678 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10679 isa<ConstantFPSDNode>(StoredVal);
10680 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10682 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10685 // Only look at ends of store sequences.
10686 SDValue Chain = SDValue(St, 0);
10687 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10690 // This holds the base pointer, index, and the offset in bytes from the base
10692 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10694 // We must have a base and an offset.
10695 if (!BasePtr.Base.getNode())
10698 // Do not handle stores to undef base pointers.
10699 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10702 // Save the LoadSDNodes that we find in the chain.
10703 // We need to make sure that these nodes do not interfere with
10704 // any of the store nodes.
10705 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10707 // Save the StoreSDNodes that we find in the chain.
10708 SmallVector<MemOpLink, 8> StoreNodes;
10710 // Walk up the chain and look for nodes with offsets from the same
10711 // base pointer. Stop when reaching an instruction with a different kind
10712 // or instruction which has a different base pointer.
10714 StoreSDNode *Index = St;
10716 // If the chain has more than one use, then we can't reorder the mem ops.
10717 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10720 // Find the base pointer and offset for this memory node.
10721 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10723 // Check that the base pointer is the same as the original one.
10724 if (!Ptr.equalBaseIndex(BasePtr))
10727 // The memory operands must not be volatile.
10728 if (Index->isVolatile() || Index->isIndexed())
10732 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10733 if (St->isTruncatingStore())
10736 // The stored memory type must be the same.
10737 if (Index->getMemoryVT() != MemVT)
10740 // We found a potential memory operand to merge.
10741 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10743 // Find the next memory operand in the chain. If the next operand in the
10744 // chain is a store then move up and continue the scan with the next
10745 // memory operand. If the next operand is a load save it and use alias
10746 // information to check if it interferes with anything.
10747 SDNode *NextInChain = Index->getChain().getNode();
10749 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10750 // We found a store node. Use it for the next iteration.
10753 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10754 if (Ldn->isVolatile()) {
10759 // Save the load node for later. Continue the scan.
10760 AliasLoadNodes.push_back(Ldn);
10761 NextInChain = Ldn->getChain().getNode();
10770 // Check if there is anything to merge.
10771 if (StoreNodes.size() < 2)
10774 // Sort the memory operands according to their distance from the base pointer.
10775 std::sort(StoreNodes.begin(), StoreNodes.end(),
10776 [](MemOpLink LHS, MemOpLink RHS) {
10777 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10778 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10779 LHS.SequenceNum > RHS.SequenceNum);
10782 // Scan the memory operations on the chain and find the first non-consecutive
10783 // store memory address.
10784 unsigned LastConsecutiveStore = 0;
10785 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10786 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10788 // Check that the addresses are consecutive starting from the second
10789 // element in the list of stores.
10791 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10792 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10796 bool Alias = false;
10797 // Check if this store interferes with any of the loads that we found.
10798 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10799 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10803 // We found a load that alias with this store. Stop the sequence.
10807 // Mark this node as useful.
10808 LastConsecutiveStore = i;
10811 // The node with the lowest store address.
10812 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10813 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10814 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10816 // Store the constants into memory as one consecutive store.
10817 if (IsConstantSrc) {
10818 unsigned LastLegalType = 0;
10819 unsigned LastLegalVectorType = 0;
10820 bool NonZero = false;
10821 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10822 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10823 SDValue StoredVal = St->getValue();
10825 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10826 NonZero |= !C->isNullValue();
10827 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10828 NonZero |= !C->getConstantFPValue()->isNullValue();
10834 // Find a legal type for the constant store.
10835 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10836 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10837 if (TLI.isTypeLegal(StoreTy) &&
10838 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10839 FirstStoreAlign)) {
10840 LastLegalType = i+1;
10841 // Or check whether a truncstore is legal.
10842 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10843 TargetLowering::TypePromoteInteger) {
10844 EVT LegalizedStoredValueTy =
10845 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10846 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10847 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10848 FirstStoreAlign)) {
10849 LastLegalType = i + 1;
10853 // Find a legal type for the vector store.
10854 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10855 if (TLI.isTypeLegal(Ty) &&
10856 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10857 LastLegalVectorType = i + 1;
10861 // We only use vectors if the constant is known to be zero and the
10862 // function is not marked with the noimplicitfloat attribute.
10863 if (NonZero || NoVectors)
10864 LastLegalVectorType = 0;
10866 // Check if we found a legal integer type to store.
10867 if (LastLegalType == 0 && LastLegalVectorType == 0)
10870 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10871 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10873 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10877 // When extracting multiple vector elements, try to store them
10878 // in one vector store rather than a sequence of scalar stores.
10879 if (IsExtractVecEltSrc) {
10880 unsigned NumElem = 0;
10881 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10882 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10883 SDValue StoredVal = St->getValue();
10884 // This restriction could be loosened.
10885 // Bail out if any stored values are not elements extracted from a vector.
10886 // It should be possible to handle mixed sources, but load sources need
10887 // more careful handling (see the block of code below that handles
10888 // consecutive loads).
10889 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10892 // Find a legal type for the vector store.
10893 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10894 if (TLI.isTypeLegal(Ty) &&
10895 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10899 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10903 // Below we handle the case of multiple consecutive stores that
10904 // come from multiple consecutive loads. We merge them into a single
10905 // wide load and a single wide store.
10907 // Look for load nodes which are used by the stored values.
10908 SmallVector<MemOpLink, 8> LoadNodes;
10910 // Find acceptable loads. Loads need to have the same chain (token factor),
10911 // must not be zext, volatile, indexed, and they must be consecutive.
10912 BaseIndexOffset LdBasePtr;
10913 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10914 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10915 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10918 // Loads must only have one use.
10919 if (!Ld->hasNUsesOfValue(1, 0))
10922 // The memory operands must not be volatile.
10923 if (Ld->isVolatile() || Ld->isIndexed())
10926 // We do not accept ext loads.
10927 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10930 // The stored memory type must be the same.
10931 if (Ld->getMemoryVT() != MemVT)
10934 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10935 // If this is not the first ptr that we check.
10936 if (LdBasePtr.Base.getNode()) {
10937 // The base ptr must be the same.
10938 if (!LdPtr.equalBaseIndex(LdBasePtr))
10941 // Check that all other base pointers are the same as this one.
10945 // We found a potential memory operand to merge.
10946 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10949 if (LoadNodes.size() < 2)
10952 // If we have load/store pair instructions and we only have two values,
10954 unsigned RequiredAlignment;
10955 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10956 St->getAlignment() >= RequiredAlignment)
10959 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10960 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
10961 unsigned FirstLoadAlign = FirstLoad->getAlignment();
10963 // Scan the memory operations on the chain and find the first non-consecutive
10964 // load memory address. These variables hold the index in the store node
10966 unsigned LastConsecutiveLoad = 0;
10967 // This variable refers to the size and not index in the array.
10968 unsigned LastLegalVectorType = 0;
10969 unsigned LastLegalIntegerType = 0;
10970 StartAddress = LoadNodes[0].OffsetFromBase;
10971 SDValue FirstChain = FirstLoad->getChain();
10972 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10973 // All loads much share the same chain.
10974 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10977 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10978 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10980 LastConsecutiveLoad = i;
10982 // Find a legal type for the vector store.
10983 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10984 if (TLI.isTypeLegal(StoreTy) &&
10985 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10986 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
10987 LastLegalVectorType = i + 1;
10990 // Find a legal type for the integer store.
10991 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10992 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10993 if (TLI.isTypeLegal(StoreTy) &&
10994 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10995 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
10996 LastLegalIntegerType = i + 1;
10997 // Or check whether a truncstore and extload is legal.
10998 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10999 TargetLowering::TypePromoteInteger) {
11000 EVT LegalizedStoredValueTy =
11001 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11002 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11003 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11004 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11005 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11006 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11007 FirstStoreAlign) &&
11008 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11010 LastLegalIntegerType = i+1;
11014 // Only use vector types if the vector type is larger than the integer type.
11015 // If they are the same, use integers.
11016 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11017 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11019 // We add +1 here because the LastXXX variables refer to location while
11020 // the NumElem refers to array/index size.
11021 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11022 NumElem = std::min(LastLegalType, NumElem);
11027 // The latest Node in the DAG.
11028 unsigned LatestNodeUsed = 0;
11029 for (unsigned i=1; i<NumElem; ++i) {
11030 // Find a chain for the new wide-store operand. Notice that some
11031 // of the store nodes that we found may not be selected for inclusion
11032 // in the wide store. The chain we use needs to be the chain of the
11033 // latest store node which is *used* and replaced by the wide store.
11034 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11035 LatestNodeUsed = i;
11038 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11040 // Find if it is better to use vectors or integers to load and store
11044 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11046 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11047 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11050 SDLoc LoadDL(LoadNodes[0].MemNode);
11051 SDLoc StoreDL(StoreNodes[0].MemNode);
11053 SDValue NewLoad = DAG.getLoad(
11054 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11055 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11057 SDValue NewStore = DAG.getStore(
11058 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11059 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11061 // Replace one of the loads with the new load.
11062 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11063 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11064 SDValue(NewLoad.getNode(), 1));
11066 // Remove the rest of the load chains.
11067 for (unsigned i = 1; i < NumElem ; ++i) {
11068 // Replace all chain users of the old load nodes with the chain of the new
11070 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11071 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11074 // Replace the last store with the new store.
11075 CombineTo(LatestOp, NewStore);
11076 // Erase all other stores.
11077 for (unsigned i = 0; i < NumElem ; ++i) {
11078 // Remove all Store nodes.
11079 if (StoreNodes[i].MemNode == LatestOp)
11081 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11082 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11083 deleteAndRecombine(St);
11089 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11090 StoreSDNode *ST = cast<StoreSDNode>(N);
11091 SDValue Chain = ST->getChain();
11092 SDValue Value = ST->getValue();
11093 SDValue Ptr = ST->getBasePtr();
11095 // If this is a store of a bit convert, store the input value if the
11096 // resultant store does not need a higher alignment than the original.
11097 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11098 ST->isUnindexed()) {
11099 unsigned OrigAlign = ST->getAlignment();
11100 EVT SVT = Value.getOperand(0).getValueType();
11101 unsigned Align = TLI.getDataLayout()->
11102 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11103 if (Align <= OrigAlign &&
11104 ((!LegalOperations && !ST->isVolatile()) ||
11105 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11106 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11107 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11108 ST->isNonTemporal(), OrigAlign,
11112 // Turn 'store undef, Ptr' -> nothing.
11113 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11116 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11117 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11118 // NOTE: If the original store is volatile, this transform must not increase
11119 // the number of stores. For example, on x86-32 an f64 can be stored in one
11120 // processor operation but an i64 (which is not legal) requires two. So the
11121 // transform should not be done in this case.
11122 if (Value.getOpcode() != ISD::TargetConstantFP) {
11124 switch (CFP->getSimpleValueType(0).SimpleTy) {
11125 default: llvm_unreachable("Unknown FP type");
11126 case MVT::f16: // We don't do this for these yet.
11132 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11133 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11135 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11136 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11138 return DAG.getStore(Chain, SDLoc(N), Tmp,
11139 Ptr, ST->getMemOperand());
11143 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11144 !ST->isVolatile()) ||
11145 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11147 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11148 getZExtValue(), SDLoc(CFP), MVT::i64);
11149 return DAG.getStore(Chain, SDLoc(N), Tmp,
11150 Ptr, ST->getMemOperand());
11153 if (!ST->isVolatile() &&
11154 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11155 // Many FP stores are not made apparent until after legalize, e.g. for
11156 // argument passing. Since this is so common, custom legalize the
11157 // 64-bit integer store into two 32-bit stores.
11158 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11159 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11160 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11161 if (TLI.isBigEndian()) std::swap(Lo, Hi);
11163 unsigned Alignment = ST->getAlignment();
11164 bool isVolatile = ST->isVolatile();
11165 bool isNonTemporal = ST->isNonTemporal();
11166 AAMDNodes AAInfo = ST->getAAInfo();
11170 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11171 Ptr, ST->getPointerInfo(),
11172 isVolatile, isNonTemporal,
11173 ST->getAlignment(), AAInfo);
11174 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11175 DAG.getConstant(4, DL, Ptr.getValueType()));
11176 Alignment = MinAlign(Alignment, 4U);
11177 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11178 Ptr, ST->getPointerInfo().getWithOffset(4),
11179 isVolatile, isNonTemporal,
11180 Alignment, AAInfo);
11181 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11190 // Try to infer better alignment information than the store already has.
11191 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11192 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11193 if (Align > ST->getAlignment()) {
11195 DAG.getTruncStore(Chain, SDLoc(N), Value,
11196 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11197 ST->isVolatile(), ST->isNonTemporal(), Align,
11199 if (NewStore.getNode() != N)
11200 return CombineTo(ST, NewStore, true);
11205 // Try transforming a pair floating point load / store ops to integer
11206 // load / store ops.
11207 SDValue NewST = TransformFPLoadStorePair(N);
11208 if (NewST.getNode())
11211 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11212 : DAG.getSubtarget().useAA();
11214 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11215 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11218 if (UseAA && ST->isUnindexed()) {
11219 // Walk up chain skipping non-aliasing memory nodes.
11220 SDValue BetterChain = FindBetterChain(N, Chain);
11222 // If there is a better chain.
11223 if (Chain != BetterChain) {
11226 // Replace the chain to avoid dependency.
11227 if (ST->isTruncatingStore()) {
11228 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11229 ST->getMemoryVT(), ST->getMemOperand());
11231 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11232 ST->getMemOperand());
11235 // Create token to keep both nodes around.
11236 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11237 MVT::Other, Chain, ReplStore);
11239 // Make sure the new and old chains are cleaned up.
11240 AddToWorklist(Token.getNode());
11242 // Don't add users to work list.
11243 return CombineTo(N, Token, false);
11247 // Try transforming N to an indexed store.
11248 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11249 return SDValue(N, 0);
11251 // FIXME: is there such a thing as a truncating indexed store?
11252 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11253 Value.getValueType().isInteger()) {
11254 // See if we can simplify the input to this truncstore with knowledge that
11255 // only the low bits are being used. For example:
11256 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11258 GetDemandedBits(Value,
11259 APInt::getLowBitsSet(
11260 Value.getValueType().getScalarType().getSizeInBits(),
11261 ST->getMemoryVT().getScalarType().getSizeInBits()));
11262 AddToWorklist(Value.getNode());
11263 if (Shorter.getNode())
11264 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11265 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11267 // Otherwise, see if we can simplify the operation with
11268 // SimplifyDemandedBits, which only works if the value has a single use.
11269 if (SimplifyDemandedBits(Value,
11270 APInt::getLowBitsSet(
11271 Value.getValueType().getScalarType().getSizeInBits(),
11272 ST->getMemoryVT().getScalarType().getSizeInBits())))
11273 return SDValue(N, 0);
11276 // If this is a load followed by a store to the same location, then the store
11278 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11279 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11280 ST->isUnindexed() && !ST->isVolatile() &&
11281 // There can't be any side effects between the load and store, such as
11282 // a call or store.
11283 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11284 // The store is dead, remove it.
11289 // If this is a store followed by a store with the same value to the same
11290 // location, then the store is dead/noop.
11291 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11292 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11293 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11294 ST1->isUnindexed() && !ST1->isVolatile()) {
11295 // The store is dead, remove it.
11300 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11301 // truncating store. We can do this even if this is already a truncstore.
11302 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11303 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11304 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11305 ST->getMemoryVT())) {
11306 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11307 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11310 // Only perform this optimization before the types are legal, because we
11311 // don't want to perform this optimization on every DAGCombine invocation.
11313 bool EverChanged = false;
11316 // There can be multiple store sequences on the same chain.
11317 // Keep trying to merge store sequences until we are unable to do so
11318 // or until we merge the last store on the chain.
11319 bool Changed = MergeConsecutiveStores(ST);
11320 EverChanged |= Changed;
11321 if (!Changed) break;
11322 } while (ST->getOpcode() != ISD::DELETED_NODE);
11325 return SDValue(N, 0);
11328 return ReduceLoadOpStoreWidth(N);
11331 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11332 SDValue InVec = N->getOperand(0);
11333 SDValue InVal = N->getOperand(1);
11334 SDValue EltNo = N->getOperand(2);
11337 // If the inserted element is an UNDEF, just use the input vector.
11338 if (InVal.getOpcode() == ISD::UNDEF)
11341 EVT VT = InVec.getValueType();
11343 // If we can't generate a legal BUILD_VECTOR, exit
11344 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11347 // Check that we know which element is being inserted
11348 if (!isa<ConstantSDNode>(EltNo))
11350 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11352 // Canonicalize insert_vector_elt dag nodes.
11354 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11355 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11357 // Do this only if the child insert_vector node has one use; also
11358 // do this only if indices are both constants and Idx1 < Idx0.
11359 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11360 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11361 unsigned OtherElt =
11362 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11363 if (Elt < OtherElt) {
11365 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11366 InVec.getOperand(0), InVal, EltNo);
11367 AddToWorklist(NewOp.getNode());
11368 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11369 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11373 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11374 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11375 // vector elements.
11376 SmallVector<SDValue, 8> Ops;
11377 // Do not combine these two vectors if the output vector will not replace
11378 // the input vector.
11379 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11380 Ops.append(InVec.getNode()->op_begin(),
11381 InVec.getNode()->op_end());
11382 } else if (InVec.getOpcode() == ISD::UNDEF) {
11383 unsigned NElts = VT.getVectorNumElements();
11384 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11389 // Insert the element
11390 if (Elt < Ops.size()) {
11391 // All the operands of BUILD_VECTOR must have the same type;
11392 // we enforce that here.
11393 EVT OpVT = Ops[0].getValueType();
11394 if (InVal.getValueType() != OpVT)
11395 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11396 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11397 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11401 // Return the new vector
11402 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11405 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11406 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11407 EVT ResultVT = EVE->getValueType(0);
11408 EVT VecEltVT = InVecVT.getVectorElementType();
11409 unsigned Align = OriginalLoad->getAlignment();
11410 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11411 VecEltVT.getTypeForEVT(*DAG.getContext()));
11413 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11418 SDValue NewPtr = OriginalLoad->getBasePtr();
11420 EVT PtrType = NewPtr.getValueType();
11421 MachinePointerInfo MPI;
11423 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11424 int Elt = ConstEltNo->getZExtValue();
11425 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11426 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11427 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11429 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11430 Offset = DAG.getNode(
11431 ISD::MUL, DL, PtrType, Offset,
11432 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11433 MPI = OriginalLoad->getPointerInfo();
11435 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11437 // The replacement we need to do here is a little tricky: we need to
11438 // replace an extractelement of a load with a load.
11439 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11440 // Note that this replacement assumes that the extractvalue is the only
11441 // use of the load; that's okay because we don't want to perform this
11442 // transformation in other cases anyway.
11445 if (ResultVT.bitsGT(VecEltVT)) {
11446 // If the result type of vextract is wider than the load, then issue an
11447 // extending load instead.
11448 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11452 Load = DAG.getExtLoad(
11453 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11454 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11455 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11456 Chain = Load.getValue(1);
11458 Load = DAG.getLoad(
11459 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11460 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11461 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11462 Chain = Load.getValue(1);
11463 if (ResultVT.bitsLT(VecEltVT))
11464 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11466 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11468 WorklistRemover DeadNodes(*this);
11469 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11470 SDValue To[] = { Load, Chain };
11471 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11472 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11473 // worklist explicitly as well.
11474 AddToWorklist(Load.getNode());
11475 AddUsersToWorklist(Load.getNode()); // Add users too
11476 // Make sure to revisit this node to clean it up; it will usually be dead.
11477 AddToWorklist(EVE);
11479 return SDValue(EVE, 0);
11482 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11483 // (vextract (scalar_to_vector val, 0) -> val
11484 SDValue InVec = N->getOperand(0);
11485 EVT VT = InVec.getValueType();
11486 EVT NVT = N->getValueType(0);
11488 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11489 // Check if the result type doesn't match the inserted element type. A
11490 // SCALAR_TO_VECTOR may truncate the inserted element and the
11491 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11492 SDValue InOp = InVec.getOperand(0);
11493 if (InOp.getValueType() != NVT) {
11494 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11495 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11500 SDValue EltNo = N->getOperand(1);
11501 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11503 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11504 // We only perform this optimization before the op legalization phase because
11505 // we may introduce new vector instructions which are not backed by TD
11506 // patterns. For example on AVX, extracting elements from a wide vector
11507 // without using extract_subvector. However, if we can find an underlying
11508 // scalar value, then we can always use that.
11509 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11511 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11512 int NumElem = VT.getVectorNumElements();
11513 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11514 // Find the new index to extract from.
11515 int OrigElt = SVOp->getMaskElt(Elt);
11517 // Extracting an undef index is undef.
11519 return DAG.getUNDEF(NVT);
11521 // Select the right vector half to extract from.
11523 if (OrigElt < NumElem) {
11524 SVInVec = InVec->getOperand(0);
11526 SVInVec = InVec->getOperand(1);
11527 OrigElt -= NumElem;
11530 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11531 SDValue InOp = SVInVec.getOperand(OrigElt);
11532 if (InOp.getValueType() != NVT) {
11533 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11534 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11540 // FIXME: We should handle recursing on other vector shuffles and
11541 // scalar_to_vector here as well.
11543 if (!LegalOperations) {
11544 EVT IndexTy = TLI.getVectorIdxTy();
11545 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11546 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11550 bool BCNumEltsChanged = false;
11551 EVT ExtVT = VT.getVectorElementType();
11554 // If the result of load has to be truncated, then it's not necessarily
11556 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11559 if (InVec.getOpcode() == ISD::BITCAST) {
11560 // Don't duplicate a load with other uses.
11561 if (!InVec.hasOneUse())
11564 EVT BCVT = InVec.getOperand(0).getValueType();
11565 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11567 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11568 BCNumEltsChanged = true;
11569 InVec = InVec.getOperand(0);
11570 ExtVT = BCVT.getVectorElementType();
11573 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11574 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11575 ISD::isNormalLoad(InVec.getNode()) &&
11576 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11577 SDValue Index = N->getOperand(1);
11578 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11579 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11583 // Perform only after legalization to ensure build_vector / vector_shuffle
11584 // optimizations have already been done.
11585 if (!LegalOperations) return SDValue();
11587 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11588 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11589 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11592 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11594 LoadSDNode *LN0 = nullptr;
11595 const ShuffleVectorSDNode *SVN = nullptr;
11596 if (ISD::isNormalLoad(InVec.getNode())) {
11597 LN0 = cast<LoadSDNode>(InVec);
11598 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11599 InVec.getOperand(0).getValueType() == ExtVT &&
11600 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11601 // Don't duplicate a load with other uses.
11602 if (!InVec.hasOneUse())
11605 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11606 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11607 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11609 // (load $addr+1*size)
11611 // Don't duplicate a load with other uses.
11612 if (!InVec.hasOneUse())
11615 // If the bit convert changed the number of elements, it is unsafe
11616 // to examine the mask.
11617 if (BCNumEltsChanged)
11620 // Select the input vector, guarding against out of range extract vector.
11621 unsigned NumElems = VT.getVectorNumElements();
11622 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11623 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11625 if (InVec.getOpcode() == ISD::BITCAST) {
11626 // Don't duplicate a load with other uses.
11627 if (!InVec.hasOneUse())
11630 InVec = InVec.getOperand(0);
11632 if (ISD::isNormalLoad(InVec.getNode())) {
11633 LN0 = cast<LoadSDNode>(InVec);
11634 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11635 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11639 // Make sure we found a non-volatile load and the extractelement is
11641 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11644 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11646 return DAG.getUNDEF(LVT);
11648 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11654 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11655 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11656 // We perform this optimization post type-legalization because
11657 // the type-legalizer often scalarizes integer-promoted vectors.
11658 // Performing this optimization before may create bit-casts which
11659 // will be type-legalized to complex code sequences.
11660 // We perform this optimization only before the operation legalizer because we
11661 // may introduce illegal operations.
11662 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11665 unsigned NumInScalars = N->getNumOperands();
11667 EVT VT = N->getValueType(0);
11669 // Check to see if this is a BUILD_VECTOR of a bunch of values
11670 // which come from any_extend or zero_extend nodes. If so, we can create
11671 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11672 // optimizations. We do not handle sign-extend because we can't fill the sign
11674 EVT SourceType = MVT::Other;
11675 bool AllAnyExt = true;
11677 for (unsigned i = 0; i != NumInScalars; ++i) {
11678 SDValue In = N->getOperand(i);
11679 // Ignore undef inputs.
11680 if (In.getOpcode() == ISD::UNDEF) continue;
11682 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11683 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11685 // Abort if the element is not an extension.
11686 if (!ZeroExt && !AnyExt) {
11687 SourceType = MVT::Other;
11691 // The input is a ZeroExt or AnyExt. Check the original type.
11692 EVT InTy = In.getOperand(0).getValueType();
11694 // Check that all of the widened source types are the same.
11695 if (SourceType == MVT::Other)
11698 else if (InTy != SourceType) {
11699 // Multiple income types. Abort.
11700 SourceType = MVT::Other;
11704 // Check if all of the extends are ANY_EXTENDs.
11705 AllAnyExt &= AnyExt;
11708 // In order to have valid types, all of the inputs must be extended from the
11709 // same source type and all of the inputs must be any or zero extend.
11710 // Scalar sizes must be a power of two.
11711 EVT OutScalarTy = VT.getScalarType();
11712 bool ValidTypes = SourceType != MVT::Other &&
11713 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11714 isPowerOf2_32(SourceType.getSizeInBits());
11716 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11717 // turn into a single shuffle instruction.
11721 bool isLE = TLI.isLittleEndian();
11722 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11723 assert(ElemRatio > 1 && "Invalid element size ratio");
11724 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11725 DAG.getConstant(0, SDLoc(N), SourceType);
11727 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11728 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11730 // Populate the new build_vector
11731 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11732 SDValue Cast = N->getOperand(i);
11733 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11734 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11735 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11737 if (Cast.getOpcode() == ISD::UNDEF)
11738 In = DAG.getUNDEF(SourceType);
11740 In = Cast->getOperand(0);
11741 unsigned Index = isLE ? (i * ElemRatio) :
11742 (i * ElemRatio + (ElemRatio - 1));
11744 assert(Index < Ops.size() && "Invalid index");
11748 // The type of the new BUILD_VECTOR node.
11749 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11750 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11751 "Invalid vector size");
11752 // Check if the new vector type is legal.
11753 if (!isTypeLegal(VecVT)) return SDValue();
11755 // Make the new BUILD_VECTOR.
11756 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11758 // The new BUILD_VECTOR node has the potential to be further optimized.
11759 AddToWorklist(BV.getNode());
11760 // Bitcast to the desired type.
11761 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11764 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11765 EVT VT = N->getValueType(0);
11767 unsigned NumInScalars = N->getNumOperands();
11770 EVT SrcVT = MVT::Other;
11771 unsigned Opcode = ISD::DELETED_NODE;
11772 unsigned NumDefs = 0;
11774 for (unsigned i = 0; i != NumInScalars; ++i) {
11775 SDValue In = N->getOperand(i);
11776 unsigned Opc = In.getOpcode();
11778 if (Opc == ISD::UNDEF)
11781 // If all scalar values are floats and converted from integers.
11782 if (Opcode == ISD::DELETED_NODE &&
11783 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11790 EVT InVT = In.getOperand(0).getValueType();
11792 // If all scalar values are typed differently, bail out. It's chosen to
11793 // simplify BUILD_VECTOR of integer types.
11794 if (SrcVT == MVT::Other)
11801 // If the vector has just one element defined, it's not worth to fold it into
11802 // a vectorized one.
11806 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11807 && "Should only handle conversion from integer to float.");
11808 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11810 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11812 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11815 // Just because the floating-point vector type is legal does not necessarily
11816 // mean that the corresponding integer vector type is.
11817 if (!isTypeLegal(NVT))
11820 SmallVector<SDValue, 8> Opnds;
11821 for (unsigned i = 0; i != NumInScalars; ++i) {
11822 SDValue In = N->getOperand(i);
11824 if (In.getOpcode() == ISD::UNDEF)
11825 Opnds.push_back(DAG.getUNDEF(SrcVT));
11827 Opnds.push_back(In.getOperand(0));
11829 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11830 AddToWorklist(BV.getNode());
11832 return DAG.getNode(Opcode, dl, VT, BV);
11835 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11836 unsigned NumInScalars = N->getNumOperands();
11838 EVT VT = N->getValueType(0);
11840 // A vector built entirely of undefs is undef.
11841 if (ISD::allOperandsUndef(N))
11842 return DAG.getUNDEF(VT);
11844 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11847 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11850 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11851 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11852 // at most two distinct vectors, turn this into a shuffle node.
11854 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11855 if (!isTypeLegal(VT))
11858 // May only combine to shuffle after legalize if shuffle is legal.
11859 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11862 SDValue VecIn1, VecIn2;
11863 bool UsesZeroVector = false;
11864 for (unsigned i = 0; i != NumInScalars; ++i) {
11865 SDValue Op = N->getOperand(i);
11866 // Ignore undef inputs.
11867 if (Op.getOpcode() == ISD::UNDEF) continue;
11869 // See if we can combine this build_vector into a blend with a zero vector.
11870 if (!VecIn2.getNode() && (isNullConstant(Op) ||
11871 (Op.getOpcode() == ISD::ConstantFP &&
11872 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11873 UsesZeroVector = true;
11877 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11878 // constant index, bail out.
11879 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11880 !isa<ConstantSDNode>(Op.getOperand(1))) {
11881 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11885 // We allow up to two distinct input vectors.
11886 SDValue ExtractedFromVec = Op.getOperand(0);
11887 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11890 if (!VecIn1.getNode()) {
11891 VecIn1 = ExtractedFromVec;
11892 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11893 VecIn2 = ExtractedFromVec;
11895 // Too many inputs.
11896 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11901 // If everything is good, we can make a shuffle operation.
11902 if (VecIn1.getNode()) {
11903 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11904 SmallVector<int, 8> Mask;
11905 for (unsigned i = 0; i != NumInScalars; ++i) {
11906 unsigned Opcode = N->getOperand(i).getOpcode();
11907 if (Opcode == ISD::UNDEF) {
11908 Mask.push_back(-1);
11912 // Operands can also be zero.
11913 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11914 assert(UsesZeroVector &&
11915 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11916 "Unexpected node found!");
11917 Mask.push_back(NumInScalars+i);
11921 // If extracting from the first vector, just use the index directly.
11922 SDValue Extract = N->getOperand(i);
11923 SDValue ExtVal = Extract.getOperand(1);
11924 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11925 if (Extract.getOperand(0) == VecIn1) {
11926 Mask.push_back(ExtIndex);
11930 // Otherwise, use InIdx + InputVecSize
11931 Mask.push_back(InNumElements + ExtIndex);
11934 // Avoid introducing illegal shuffles with zero.
11935 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11938 // We can't generate a shuffle node with mismatched input and output types.
11939 // Attempt to transform a single input vector to the correct type.
11940 if ((VT != VecIn1.getValueType())) {
11941 // If the input vector type has a different base type to the output
11942 // vector type, bail out.
11943 EVT VTElemType = VT.getVectorElementType();
11944 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11945 (VecIn2.getNode() &&
11946 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11949 // If the input vector is too small, widen it.
11950 // We only support widening of vectors which are half the size of the
11951 // output registers. For example XMM->YMM widening on X86 with AVX.
11952 EVT VecInT = VecIn1.getValueType();
11953 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11954 // If we only have one small input, widen it by adding undef values.
11955 if (!VecIn2.getNode())
11956 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11957 DAG.getUNDEF(VecIn1.getValueType()));
11958 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11959 // If we have two small inputs of the same type, try to concat them.
11960 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11961 VecIn2 = SDValue(nullptr, 0);
11964 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11965 // If the input vector is too large, try to split it.
11966 // We don't support having two input vectors that are too large.
11967 // If the zero vector was used, we can not split the vector,
11968 // since we'd need 3 inputs.
11969 if (UsesZeroVector || VecIn2.getNode())
11972 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11975 // Try to replace VecIn1 with two extract_subvectors
11976 // No need to update the masks, they should still be correct.
11977 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11978 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11979 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11980 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11985 if (UsesZeroVector)
11986 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11987 DAG.getConstantFP(0.0, dl, VT);
11989 // If VecIn2 is unused then change it to undef.
11990 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11992 // Check that we were able to transform all incoming values to the same
11994 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11995 VecIn1.getValueType() != VT)
11998 // Return the new VECTOR_SHUFFLE node.
12002 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12008 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12009 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12010 EVT OpVT = N->getOperand(0).getValueType();
12012 // If the operands are legal vectors, leave them alone.
12013 if (TLI.isTypeLegal(OpVT))
12017 EVT VT = N->getValueType(0);
12018 SmallVector<SDValue, 8> Ops;
12020 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12021 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12023 // Keep track of what we encounter.
12024 bool AnyInteger = false;
12025 bool AnyFP = false;
12026 for (const SDValue &Op : N->ops()) {
12027 if (ISD::BITCAST == Op.getOpcode() &&
12028 !Op.getOperand(0).getValueType().isVector())
12029 Ops.push_back(Op.getOperand(0));
12030 else if (ISD::UNDEF == Op.getOpcode())
12031 Ops.push_back(ScalarUndef);
12035 // Note whether we encounter an integer or floating point scalar.
12036 // If it's neither, bail out, it could be something weird like x86mmx.
12037 EVT LastOpVT = Ops.back().getValueType();
12038 if (LastOpVT.isFloatingPoint())
12040 else if (LastOpVT.isInteger())
12046 // If any of the operands is a floating point scalar bitcast to a vector,
12047 // use floating point types throughout, and bitcast everything.
12048 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12050 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12051 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12053 for (SDValue &Op : Ops) {
12054 if (Op.getValueType() == SVT)
12056 if (Op.getOpcode() == ISD::UNDEF)
12059 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12064 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12065 VT.getSizeInBits() / SVT.getSizeInBits());
12066 return DAG.getNode(ISD::BITCAST, DL, VT,
12067 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12070 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12071 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12072 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12073 // inputs come from at most two distinct vectors, turn this into a shuffle
12076 // If we only have one input vector, we don't need to do any concatenation.
12077 if (N->getNumOperands() == 1)
12078 return N->getOperand(0);
12080 // Check if all of the operands are undefs.
12081 EVT VT = N->getValueType(0);
12082 if (ISD::allOperandsUndef(N))
12083 return DAG.getUNDEF(VT);
12085 // Optimize concat_vectors where all but the first of the vectors are undef.
12086 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12087 return Op.getOpcode() == ISD::UNDEF;
12089 SDValue In = N->getOperand(0);
12090 assert(In.getValueType().isVector() && "Must concat vectors");
12092 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12093 if (In->getOpcode() == ISD::BITCAST &&
12094 !In->getOperand(0)->getValueType(0).isVector()) {
12095 SDValue Scalar = In->getOperand(0);
12097 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12098 // look through the trunc so we can still do the transform:
12099 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12100 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12101 !TLI.isTypeLegal(Scalar.getValueType()) &&
12102 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12103 Scalar = Scalar->getOperand(0);
12105 EVT SclTy = Scalar->getValueType(0);
12107 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12110 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12111 VT.getSizeInBits() / SclTy.getSizeInBits());
12112 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12115 SDLoc dl = SDLoc(N);
12116 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12117 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12121 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12122 // We have already tested above for an UNDEF only concatenation.
12123 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12124 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12125 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12126 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12128 bool AllBuildVectorsOrUndefs =
12129 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12130 if (AllBuildVectorsOrUndefs) {
12131 SmallVector<SDValue, 8> Opnds;
12132 EVT SVT = VT.getScalarType();
12135 if (!SVT.isFloatingPoint()) {
12136 // If BUILD_VECTOR are from built from integer, they may have different
12137 // operand types. Get the smallest type and truncate all operands to it.
12138 bool FoundMinVT = false;
12139 for (const SDValue &Op : N->ops())
12140 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12141 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12142 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12145 assert(FoundMinVT && "Concat vector type mismatch");
12148 for (const SDValue &Op : N->ops()) {
12149 EVT OpVT = Op.getValueType();
12150 unsigned NumElts = OpVT.getVectorNumElements();
12152 if (ISD::UNDEF == Op.getOpcode())
12153 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12155 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12156 if (SVT.isFloatingPoint()) {
12157 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12158 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12160 for (unsigned i = 0; i != NumElts; ++i)
12162 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12167 assert(VT.getVectorNumElements() == Opnds.size() &&
12168 "Concat vector type mismatch");
12169 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12172 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12173 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12176 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12177 // nodes often generate nop CONCAT_VECTOR nodes.
12178 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12179 // place the incoming vectors at the exact same location.
12180 SDValue SingleSource = SDValue();
12181 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12183 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12184 SDValue Op = N->getOperand(i);
12186 if (Op.getOpcode() == ISD::UNDEF)
12189 // Check if this is the identity extract:
12190 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12193 // Find the single incoming vector for the extract_subvector.
12194 if (SingleSource.getNode()) {
12195 if (Op.getOperand(0) != SingleSource)
12198 SingleSource = Op.getOperand(0);
12200 // Check the source type is the same as the type of the result.
12201 // If not, this concat may extend the vector, so we can not
12202 // optimize it away.
12203 if (SingleSource.getValueType() != N->getValueType(0))
12207 unsigned IdentityIndex = i * PartNumElem;
12208 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12209 // The extract index must be constant.
12213 // Check that we are reading from the identity index.
12214 if (CS->getZExtValue() != IdentityIndex)
12218 if (SingleSource.getNode())
12219 return SingleSource;
12224 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12225 EVT NVT = N->getValueType(0);
12226 SDValue V = N->getOperand(0);
12228 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12230 // (extract_subvec (concat V1, V2, ...), i)
12233 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12235 if (V->getOperand(0).getValueType() != NVT)
12237 unsigned Idx = N->getConstantOperandVal(1);
12238 unsigned NumElems = NVT.getVectorNumElements();
12239 assert((Idx % NumElems) == 0 &&
12240 "IDX in concat is not a multiple of the result vector length.");
12241 return V->getOperand(Idx / NumElems);
12245 if (V->getOpcode() == ISD::BITCAST)
12246 V = V.getOperand(0);
12248 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12250 // Handle only simple case where vector being inserted and vector
12251 // being extracted are of same type, and are half size of larger vectors.
12252 EVT BigVT = V->getOperand(0).getValueType();
12253 EVT SmallVT = V->getOperand(1).getValueType();
12254 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12257 // Only handle cases where both indexes are constants with the same type.
12258 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12259 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12261 if (InsIdx && ExtIdx &&
12262 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12263 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12265 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12267 // indices are equal or bit offsets are equal => V1
12268 // otherwise => (extract_subvec V1, ExtIdx)
12269 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12270 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12271 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12272 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12273 DAG.getNode(ISD::BITCAST, dl,
12274 N->getOperand(0).getValueType(),
12275 V->getOperand(0)), N->getOperand(1));
12282 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12283 SDValue V, SelectionDAG &DAG) {
12285 EVT VT = V.getValueType();
12287 switch (V.getOpcode()) {
12291 case ISD::CONCAT_VECTORS: {
12292 EVT OpVT = V->getOperand(0).getValueType();
12293 int OpSize = OpVT.getVectorNumElements();
12294 SmallBitVector OpUsedElements(OpSize, false);
12295 bool FoundSimplification = false;
12296 SmallVector<SDValue, 4> NewOps;
12297 NewOps.reserve(V->getNumOperands());
12298 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12299 SDValue Op = V->getOperand(i);
12300 bool OpUsed = false;
12301 for (int j = 0; j < OpSize; ++j)
12302 if (UsedElements[i * OpSize + j]) {
12303 OpUsedElements[j] = true;
12307 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12308 : DAG.getUNDEF(OpVT));
12309 FoundSimplification |= Op == NewOps.back();
12310 OpUsedElements.reset();
12312 if (FoundSimplification)
12313 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12317 case ISD::INSERT_SUBVECTOR: {
12318 SDValue BaseV = V->getOperand(0);
12319 SDValue SubV = V->getOperand(1);
12320 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12324 int SubSize = SubV.getValueType().getVectorNumElements();
12325 int Idx = IdxN->getZExtValue();
12326 bool SubVectorUsed = false;
12327 SmallBitVector SubUsedElements(SubSize, false);
12328 for (int i = 0; i < SubSize; ++i)
12329 if (UsedElements[i + Idx]) {
12330 SubVectorUsed = true;
12331 SubUsedElements[i] = true;
12332 UsedElements[i + Idx] = false;
12335 // Now recurse on both the base and sub vectors.
12336 SDValue SimplifiedSubV =
12338 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12339 : DAG.getUNDEF(SubV.getValueType());
12340 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12341 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12342 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12343 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12349 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12350 SDValue N1, SelectionDAG &DAG) {
12351 EVT VT = SVN->getValueType(0);
12352 int NumElts = VT.getVectorNumElements();
12353 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12354 for (int M : SVN->getMask())
12355 if (M >= 0 && M < NumElts)
12356 N0UsedElements[M] = true;
12357 else if (M >= NumElts)
12358 N1UsedElements[M - NumElts] = true;
12360 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12361 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12362 if (S0 == N0 && S1 == N1)
12365 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12368 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12369 // or turn a shuffle of a single concat into simpler shuffle then concat.
12370 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12371 EVT VT = N->getValueType(0);
12372 unsigned NumElts = VT.getVectorNumElements();
12374 SDValue N0 = N->getOperand(0);
12375 SDValue N1 = N->getOperand(1);
12376 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12378 SmallVector<SDValue, 4> Ops;
12379 EVT ConcatVT = N0.getOperand(0).getValueType();
12380 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12381 unsigned NumConcats = NumElts / NumElemsPerConcat;
12383 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12384 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12385 // half vector elements.
12386 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12387 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12388 SVN->getMask().end(), [](int i) { return i == -1; })) {
12389 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12390 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12391 N1 = DAG.getUNDEF(ConcatVT);
12392 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12395 // Look at every vector that's inserted. We're looking for exact
12396 // subvector-sized copies from a concatenated vector
12397 for (unsigned I = 0; I != NumConcats; ++I) {
12398 // Make sure we're dealing with a copy.
12399 unsigned Begin = I * NumElemsPerConcat;
12400 bool AllUndef = true, NoUndef = true;
12401 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12402 if (SVN->getMaskElt(J) >= 0)
12409 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12412 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12413 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12416 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12417 if (FirstElt < N0.getNumOperands())
12418 Ops.push_back(N0.getOperand(FirstElt));
12420 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12422 } else if (AllUndef) {
12423 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12424 } else { // Mixed with general masks and undefs, can't do optimization.
12429 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12432 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12433 EVT VT = N->getValueType(0);
12434 unsigned NumElts = VT.getVectorNumElements();
12436 SDValue N0 = N->getOperand(0);
12437 SDValue N1 = N->getOperand(1);
12439 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12441 // Canonicalize shuffle undef, undef -> undef
12442 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12443 return DAG.getUNDEF(VT);
12445 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12447 // Canonicalize shuffle v, v -> v, undef
12449 SmallVector<int, 8> NewMask;
12450 for (unsigned i = 0; i != NumElts; ++i) {
12451 int Idx = SVN->getMaskElt(i);
12452 if (Idx >= (int)NumElts) Idx -= NumElts;
12453 NewMask.push_back(Idx);
12455 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12459 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12460 if (N0.getOpcode() == ISD::UNDEF) {
12461 SmallVector<int, 8> NewMask;
12462 for (unsigned i = 0; i != NumElts; ++i) {
12463 int Idx = SVN->getMaskElt(i);
12465 if (Idx >= (int)NumElts)
12468 Idx = -1; // remove reference to lhs
12470 NewMask.push_back(Idx);
12472 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12476 // Remove references to rhs if it is undef
12477 if (N1.getOpcode() == ISD::UNDEF) {
12478 bool Changed = false;
12479 SmallVector<int, 8> NewMask;
12480 for (unsigned i = 0; i != NumElts; ++i) {
12481 int Idx = SVN->getMaskElt(i);
12482 if (Idx >= (int)NumElts) {
12486 NewMask.push_back(Idx);
12489 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12492 // If it is a splat, check if the argument vector is another splat or a
12494 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12495 SDNode *V = N0.getNode();
12497 // If this is a bit convert that changes the element type of the vector but
12498 // not the number of vector elements, look through it. Be careful not to
12499 // look though conversions that change things like v4f32 to v2f64.
12500 if (V->getOpcode() == ISD::BITCAST) {
12501 SDValue ConvInput = V->getOperand(0);
12502 if (ConvInput.getValueType().isVector() &&
12503 ConvInput.getValueType().getVectorNumElements() == NumElts)
12504 V = ConvInput.getNode();
12507 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12508 assert(V->getNumOperands() == NumElts &&
12509 "BUILD_VECTOR has wrong number of operands");
12511 bool AllSame = true;
12512 for (unsigned i = 0; i != NumElts; ++i) {
12513 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12514 Base = V->getOperand(i);
12518 // Splat of <u, u, u, u>, return <u, u, u, u>
12519 if (!Base.getNode())
12521 for (unsigned i = 0; i != NumElts; ++i) {
12522 if (V->getOperand(i) != Base) {
12527 // Splat of <x, x, x, x>, return <x, x, x, x>
12531 // Canonicalize any other splat as a build_vector.
12532 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12533 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12534 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12535 V->getValueType(0), Ops);
12537 // We may have jumped through bitcasts, so the type of the
12538 // BUILD_VECTOR may not match the type of the shuffle.
12539 if (V->getValueType(0) != VT)
12540 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12545 // There are various patterns used to build up a vector from smaller vectors,
12546 // subvectors, or elements. Scan chains of these and replace unused insertions
12547 // or components with undef.
12548 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12551 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12552 Level < AfterLegalizeVectorOps &&
12553 (N1.getOpcode() == ISD::UNDEF ||
12554 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12555 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12556 SDValue V = partitionShuffleOfConcats(N, DAG);
12562 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12563 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12564 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12565 SmallVector<SDValue, 8> Ops;
12566 for (int M : SVN->getMask()) {
12567 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12569 int Idx = M % NumElts;
12570 SDValue &S = (M < (int)NumElts ? N0 : N1);
12571 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12572 Op = S.getOperand(Idx);
12573 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12575 Op = S.getOperand(0);
12577 // Operand can't be combined - bail out.
12583 if (Ops.size() == VT.getVectorNumElements()) {
12584 // BUILD_VECTOR requires all inputs to be of the same type, find the
12585 // maximum type and extend them all.
12586 EVT SVT = VT.getScalarType();
12587 if (SVT.isInteger())
12588 for (SDValue &Op : Ops)
12589 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12590 if (SVT != VT.getScalarType())
12591 for (SDValue &Op : Ops)
12592 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12593 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12594 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12595 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12599 // If this shuffle only has a single input that is a bitcasted shuffle,
12600 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12601 // back to their original types.
12602 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12603 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12604 TLI.isTypeLegal(VT)) {
12606 // Peek through the bitcast only if there is one user.
12608 while (BC0.getOpcode() == ISD::BITCAST) {
12609 if (!BC0.hasOneUse())
12611 BC0 = BC0.getOperand(0);
12614 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12616 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12618 SmallVector<int, 8> NewMask;
12620 for (int s = 0; s != Scale; ++s)
12621 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12625 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12626 EVT SVT = VT.getScalarType();
12627 EVT InnerVT = BC0->getValueType(0);
12628 EVT InnerSVT = InnerVT.getScalarType();
12630 // Determine which shuffle works with the smaller scalar type.
12631 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12632 EVT ScaleSVT = ScaleVT.getScalarType();
12634 if (TLI.isTypeLegal(ScaleVT) &&
12635 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12636 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12638 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12639 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12641 // Scale the shuffle masks to the smaller scalar type.
12642 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12643 SmallVector<int, 8> InnerMask =
12644 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12645 SmallVector<int, 8> OuterMask =
12646 ScaleShuffleMask(SVN->getMask(), OuterScale);
12648 // Merge the shuffle masks.
12649 SmallVector<int, 8> NewMask;
12650 for (int M : OuterMask)
12651 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12653 // Test for shuffle mask legality over both commutations.
12654 SDValue SV0 = BC0->getOperand(0);
12655 SDValue SV1 = BC0->getOperand(1);
12656 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12658 std::swap(SV0, SV1);
12659 ShuffleVectorSDNode::commuteMask(NewMask);
12660 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12664 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12665 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12666 return DAG.getNode(
12667 ISD::BITCAST, SDLoc(N), VT,
12668 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12674 // Canonicalize shuffles according to rules:
12675 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12676 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12677 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12678 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12679 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12680 TLI.isTypeLegal(VT)) {
12681 // The incoming shuffle must be of the same type as the result of the
12682 // current shuffle.
12683 assert(N1->getOperand(0).getValueType() == VT &&
12684 "Shuffle types don't match");
12686 SDValue SV0 = N1->getOperand(0);
12687 SDValue SV1 = N1->getOperand(1);
12688 bool HasSameOp0 = N0 == SV0;
12689 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12690 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12691 // Commute the operands of this shuffle so that next rule
12693 return DAG.getCommutedVectorShuffle(*SVN);
12696 // Try to fold according to rules:
12697 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12698 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12699 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12700 // Don't try to fold shuffles with illegal type.
12701 // Only fold if this shuffle is the only user of the other shuffle.
12702 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12703 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12704 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12706 // The incoming shuffle must be of the same type as the result of the
12707 // current shuffle.
12708 assert(OtherSV->getOperand(0).getValueType() == VT &&
12709 "Shuffle types don't match");
12712 SmallVector<int, 4> Mask;
12713 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12714 // operand, and SV1 as the second operand.
12715 for (unsigned i = 0; i != NumElts; ++i) {
12716 int Idx = SVN->getMaskElt(i);
12718 // Propagate Undef.
12719 Mask.push_back(Idx);
12723 SDValue CurrentVec;
12724 if (Idx < (int)NumElts) {
12725 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12726 // shuffle mask to identify which vector is actually referenced.
12727 Idx = OtherSV->getMaskElt(Idx);
12729 // Propagate Undef.
12730 Mask.push_back(Idx);
12734 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12735 : OtherSV->getOperand(1);
12737 // This shuffle index references an element within N1.
12741 // Simple case where 'CurrentVec' is UNDEF.
12742 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12743 Mask.push_back(-1);
12747 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12748 // will be the first or second operand of the combined shuffle.
12749 Idx = Idx % NumElts;
12750 if (!SV0.getNode() || SV0 == CurrentVec) {
12751 // Ok. CurrentVec is the left hand side.
12752 // Update the mask accordingly.
12754 Mask.push_back(Idx);
12758 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12759 if (SV1.getNode() && SV1 != CurrentVec)
12762 // Ok. CurrentVec is the right hand side.
12763 // Update the mask accordingly.
12765 Mask.push_back(Idx + NumElts);
12768 // Check if all indices in Mask are Undef. In case, propagate Undef.
12769 bool isUndefMask = true;
12770 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12771 isUndefMask &= Mask[i] < 0;
12774 return DAG.getUNDEF(VT);
12776 if (!SV0.getNode())
12777 SV0 = DAG.getUNDEF(VT);
12778 if (!SV1.getNode())
12779 SV1 = DAG.getUNDEF(VT);
12781 // Avoid introducing shuffles with illegal mask.
12782 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12783 ShuffleVectorSDNode::commuteMask(Mask);
12785 if (!TLI.isShuffleMaskLegal(Mask, VT))
12788 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12789 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12790 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12791 std::swap(SV0, SV1);
12794 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12795 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12796 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12797 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12803 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12804 SDValue InVal = N->getOperand(0);
12805 EVT VT = N->getValueType(0);
12807 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12808 // with a VECTOR_SHUFFLE.
12809 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12810 SDValue InVec = InVal->getOperand(0);
12811 SDValue EltNo = InVal->getOperand(1);
12813 // FIXME: We could support implicit truncation if the shuffle can be
12814 // scaled to a smaller vector scalar type.
12815 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12816 if (C0 && VT == InVec.getValueType() &&
12817 VT.getScalarType() == InVal.getValueType()) {
12818 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12819 int Elt = C0->getZExtValue();
12822 if (TLI.isShuffleMaskLegal(NewMask, VT))
12823 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12831 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12832 SDValue N0 = N->getOperand(0);
12833 SDValue N2 = N->getOperand(2);
12835 // If the input vector is a concatenation, and the insert replaces
12836 // one of the halves, we can optimize into a single concat_vectors.
12837 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12838 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12839 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12840 EVT VT = N->getValueType(0);
12842 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12843 // (concat_vectors Z, Y)
12845 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12846 N->getOperand(1), N0.getOperand(1));
12848 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12849 // (concat_vectors X, Z)
12850 if (InsIdx == VT.getVectorNumElements()/2)
12851 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12852 N0.getOperand(0), N->getOperand(1));
12858 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12859 SDValue N0 = N->getOperand(0);
12861 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12862 if (N0->getOpcode() == ISD::FP16_TO_FP)
12863 return N0->getOperand(0);
12868 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12869 /// with the destination vector and a zero vector.
12870 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12871 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12872 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12873 EVT VT = N->getValueType(0);
12874 SDValue LHS = N->getOperand(0);
12875 SDValue RHS = N->getOperand(1);
12878 // Make sure we're not running after operation legalization where it
12879 // may have custom lowered the vector shuffles.
12880 if (LegalOperations)
12883 if (N->getOpcode() != ISD::AND)
12886 if (RHS.getOpcode() == ISD::BITCAST)
12887 RHS = RHS.getOperand(0);
12889 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12890 SmallVector<int, 8> Indices;
12891 unsigned NumElts = RHS.getNumOperands();
12893 for (unsigned i = 0; i != NumElts; ++i) {
12894 SDValue Elt = RHS.getOperand(i);
12895 if (const ConstantSDNode *EltC = dyn_cast<const ConstantSDNode>(Elt)) {
12896 if (EltC->isAllOnesValue())
12897 Indices.push_back(i);
12898 else if (EltC->isNullValue())
12899 Indices.push_back(NumElts+i);
12907 // Let's see if the target supports this vector_shuffle.
12908 EVT RVT = RHS.getValueType();
12909 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12912 // Return the new VECTOR_SHUFFLE node.
12913 EVT EltVT = RVT.getVectorElementType();
12914 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12915 DAG.getConstant(0, dl, EltVT));
12916 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12917 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12918 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12919 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12925 /// Visit a binary vector operation, like ADD.
12926 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12927 assert(N->getValueType(0).isVector() &&
12928 "SimplifyVBinOp only works on vectors!");
12930 SDValue LHS = N->getOperand(0);
12931 SDValue RHS = N->getOperand(1);
12933 if (SDValue Shuffle = XformToShuffleWithZero(N))
12936 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12938 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12939 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12940 // Check if both vectors are constants. If not bail out.
12941 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12942 cast<BuildVectorSDNode>(RHS)->isConstant()))
12945 SmallVector<SDValue, 8> Ops;
12946 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12947 SDValue LHSOp = LHS.getOperand(i);
12948 SDValue RHSOp = RHS.getOperand(i);
12950 // Can't fold divide by zero.
12951 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12952 N->getOpcode() == ISD::FDIV) {
12953 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
12954 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12958 EVT VT = LHSOp.getValueType();
12959 EVT RVT = RHSOp.getValueType();
12961 // Integer BUILD_VECTOR operands may have types larger than the element
12962 // size (e.g., when the element type is not legal). Prior to type
12963 // legalization, the types may not match between the two BUILD_VECTORS.
12964 // Truncate one of the operands to make them match.
12965 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12966 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12968 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12972 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12974 if (FoldOp.getOpcode() != ISD::UNDEF &&
12975 FoldOp.getOpcode() != ISD::Constant &&
12976 FoldOp.getOpcode() != ISD::ConstantFP)
12978 Ops.push_back(FoldOp);
12979 AddToWorklist(FoldOp.getNode());
12982 if (Ops.size() == LHS.getNumOperands())
12983 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12986 // Type legalization might introduce new shuffles in the DAG.
12987 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12988 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12989 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12990 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12991 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12992 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12993 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12994 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12996 if (SVN0->getMask().equals(SVN1->getMask())) {
12997 EVT VT = N->getValueType(0);
12998 SDValue UndefVector = LHS.getOperand(1);
12999 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13000 LHS.getOperand(0), RHS.getOperand(0));
13001 AddUsersToWorklist(N);
13002 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13003 &SVN0->getMask()[0]);
13010 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13011 SDValue N1, SDValue N2){
13012 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13014 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13015 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13017 // If we got a simplified select_cc node back from SimplifySelectCC, then
13018 // break it down into a new SETCC node, and a new SELECT node, and then return
13019 // the SELECT node, since we were called with a SELECT node.
13020 if (SCC.getNode()) {
13021 // Check to see if we got a select_cc back (to turn into setcc/select).
13022 // Otherwise, just return whatever node we got back, like fabs.
13023 if (SCC.getOpcode() == ISD::SELECT_CC) {
13024 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13026 SCC.getOperand(0), SCC.getOperand(1),
13027 SCC.getOperand(4));
13028 AddToWorklist(SETCC.getNode());
13029 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13030 SCC.getOperand(2), SCC.getOperand(3));
13038 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13039 /// being selected between, see if we can simplify the select. Callers of this
13040 /// should assume that TheSelect is deleted if this returns true. As such, they
13041 /// should return the appropriate thing (e.g. the node) back to the top-level of
13042 /// the DAG combiner loop to avoid it being looked at.
13043 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13046 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13047 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13048 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13049 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13050 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13051 SDValue Sqrt = RHS;
13054 const ConstantFPSDNode *NegZero = nullptr;
13056 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13057 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13058 CmpLHS = TheSelect->getOperand(0);
13059 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13061 // SELECT or VSELECT
13062 SDValue Cmp = TheSelect->getOperand(0);
13063 if (Cmp.getOpcode() == ISD::SETCC) {
13064 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13065 CmpLHS = Cmp.getOperand(0);
13066 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13069 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13070 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13071 CC == ISD::SETULT || CC == ISD::SETLT)) {
13072 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13073 CombineTo(TheSelect, Sqrt);
13078 // Cannot simplify select with vector condition
13079 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13081 // If this is a select from two identical things, try to pull the operation
13082 // through the select.
13083 if (LHS.getOpcode() != RHS.getOpcode() ||
13084 !LHS.hasOneUse() || !RHS.hasOneUse())
13087 // If this is a load and the token chain is identical, replace the select
13088 // of two loads with a load through a select of the address to load from.
13089 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13090 // constants have been dropped into the constant pool.
13091 if (LHS.getOpcode() == ISD::LOAD) {
13092 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13093 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13095 // Token chains must be identical.
13096 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13097 // Do not let this transformation reduce the number of volatile loads.
13098 LLD->isVolatile() || RLD->isVolatile() ||
13099 // FIXME: If either is a pre/post inc/dec load,
13100 // we'd need to split out the address adjustment.
13101 LLD->isIndexed() || RLD->isIndexed() ||
13102 // If this is an EXTLOAD, the VT's must match.
13103 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13104 // If this is an EXTLOAD, the kind of extension must match.
13105 (LLD->getExtensionType() != RLD->getExtensionType() &&
13106 // The only exception is if one of the extensions is anyext.
13107 LLD->getExtensionType() != ISD::EXTLOAD &&
13108 RLD->getExtensionType() != ISD::EXTLOAD) ||
13109 // FIXME: this discards src value information. This is
13110 // over-conservative. It would be beneficial to be able to remember
13111 // both potential memory locations. Since we are discarding
13112 // src value info, don't do the transformation if the memory
13113 // locations are not in the default address space.
13114 LLD->getPointerInfo().getAddrSpace() != 0 ||
13115 RLD->getPointerInfo().getAddrSpace() != 0 ||
13116 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13117 LLD->getBasePtr().getValueType()))
13120 // Check that the select condition doesn't reach either load. If so,
13121 // folding this will induce a cycle into the DAG. If not, this is safe to
13122 // xform, so create a select of the addresses.
13124 if (TheSelect->getOpcode() == ISD::SELECT) {
13125 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13126 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13127 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13129 // The loads must not depend on one another.
13130 if (LLD->isPredecessorOf(RLD) ||
13131 RLD->isPredecessorOf(LLD))
13133 Addr = DAG.getSelect(SDLoc(TheSelect),
13134 LLD->getBasePtr().getValueType(),
13135 TheSelect->getOperand(0), LLD->getBasePtr(),
13136 RLD->getBasePtr());
13137 } else { // Otherwise SELECT_CC
13138 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13139 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13141 if ((LLD->hasAnyUseOfValue(1) &&
13142 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13143 (RLD->hasAnyUseOfValue(1) &&
13144 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13147 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13148 LLD->getBasePtr().getValueType(),
13149 TheSelect->getOperand(0),
13150 TheSelect->getOperand(1),
13151 LLD->getBasePtr(), RLD->getBasePtr(),
13152 TheSelect->getOperand(4));
13156 // It is safe to replace the two loads if they have different alignments,
13157 // but the new load must be the minimum (most restrictive) alignment of the
13159 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13160 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13161 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13162 Load = DAG.getLoad(TheSelect->getValueType(0),
13164 // FIXME: Discards pointer and AA info.
13165 LLD->getChain(), Addr, MachinePointerInfo(),
13166 LLD->isVolatile(), LLD->isNonTemporal(),
13167 isInvariant, Alignment);
13169 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13170 RLD->getExtensionType() : LLD->getExtensionType(),
13172 TheSelect->getValueType(0),
13173 // FIXME: Discards pointer and AA info.
13174 LLD->getChain(), Addr, MachinePointerInfo(),
13175 LLD->getMemoryVT(), LLD->isVolatile(),
13176 LLD->isNonTemporal(), isInvariant, Alignment);
13179 // Users of the select now use the result of the load.
13180 CombineTo(TheSelect, Load);
13182 // Users of the old loads now use the new load's chain. We know the
13183 // old-load value is dead now.
13184 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13185 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13192 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13193 /// where 'cond' is the comparison specified by CC.
13194 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13195 SDValue N2, SDValue N3,
13196 ISD::CondCode CC, bool NotExtCompare) {
13197 // (x ? y : y) -> y.
13198 if (N2 == N3) return N2;
13200 EVT VT = N2.getValueType();
13201 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13202 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13204 // Determine if the condition we're dealing with is constant
13205 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13206 N0, N1, CC, DL, false);
13207 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13209 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13210 // fold select_cc true, x, y -> x
13211 // fold select_cc false, x, y -> y
13212 return !SCCC->isNullValue() ? N2 : N3;
13215 // Check to see if we can simplify the select into an fabs node
13216 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13217 // Allow either -0.0 or 0.0
13218 if (CFP->getValueAPF().isZero()) {
13219 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13220 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13221 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13222 N2 == N3.getOperand(0))
13223 return DAG.getNode(ISD::FABS, DL, VT, N0);
13225 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13226 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13227 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13228 N2.getOperand(0) == N3)
13229 return DAG.getNode(ISD::FABS, DL, VT, N3);
13233 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13234 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13235 // in it. This is a win when the constant is not otherwise available because
13236 // it replaces two constant pool loads with one. We only do this if the FP
13237 // type is known to be legal, because if it isn't, then we are before legalize
13238 // types an we want the other legalization to happen first (e.g. to avoid
13239 // messing with soft float) and if the ConstantFP is not legal, because if
13240 // it is legal, we may not need to store the FP constant in a constant pool.
13241 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13242 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13243 if (TLI.isTypeLegal(N2.getValueType()) &&
13244 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13245 TargetLowering::Legal &&
13246 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13247 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13248 // If both constants have multiple uses, then we won't need to do an
13249 // extra load, they are likely around in registers for other users.
13250 (TV->hasOneUse() || FV->hasOneUse())) {
13251 Constant *Elts[] = {
13252 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13253 const_cast<ConstantFP*>(TV->getConstantFPValue())
13255 Type *FPTy = Elts[0]->getType();
13256 const DataLayout &TD = *TLI.getDataLayout();
13258 // Create a ConstantArray of the two constants.
13259 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13260 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13261 TD.getPrefTypeAlignment(FPTy));
13262 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13264 // Get the offsets to the 0 and 1 element of the array so that we can
13265 // select between them.
13266 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13267 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13268 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13270 SDValue Cond = DAG.getSetCC(DL,
13271 getSetCCResultType(N0.getValueType()),
13273 AddToWorklist(Cond.getNode());
13274 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13276 AddToWorklist(CstOffset.getNode());
13277 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13279 AddToWorklist(CPIdx.getNode());
13280 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13281 MachinePointerInfo::getConstantPool(), false,
13282 false, false, Alignment);
13286 // Check to see if we can perform the "gzip trick", transforming
13287 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13288 if (N1C && isNullConstant(N3) && CC == ISD::SETLT &&
13289 (N1C->isNullValue() || // (a < 0) ? b : 0
13290 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
13291 EVT XType = N0.getValueType();
13292 EVT AType = N2.getValueType();
13293 if (XType.bitsGE(AType)) {
13294 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13295 // single-bit constant.
13296 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13297 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13298 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13299 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13300 getShiftAmountTy(N0.getValueType()));
13301 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13303 AddToWorklist(Shift.getNode());
13305 if (XType.bitsGT(AType)) {
13306 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13307 AddToWorklist(Shift.getNode());
13310 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13313 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13315 DAG.getConstant(XType.getSizeInBits() - 1,
13317 getShiftAmountTy(N0.getValueType())));
13318 AddToWorklist(Shift.getNode());
13320 if (XType.bitsGT(AType)) {
13321 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13322 AddToWorklist(Shift.getNode());
13325 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13329 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13330 // where y is has a single bit set.
13331 // A plaintext description would be, we can turn the SELECT_CC into an AND
13332 // when the condition can be materialized as an all-ones register. Any
13333 // single bit-test can be materialized as an all-ones register with
13334 // shift-left and shift-right-arith.
13335 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13336 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13337 SDValue AndLHS = N0->getOperand(0);
13338 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13339 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13340 // Shift the tested bit over the sign bit.
13341 APInt AndMask = ConstAndRHS->getAPIntValue();
13343 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13344 getShiftAmountTy(AndLHS.getValueType()));
13345 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13347 // Now arithmetic right shift it all the way over, so the result is either
13348 // all-ones, or zero.
13350 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13351 getShiftAmountTy(Shl.getValueType()));
13352 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13354 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13358 // fold select C, 16, 0 -> shl C, 4
13359 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13360 TLI.getBooleanContents(N0.getValueType()) ==
13361 TargetLowering::ZeroOrOneBooleanContent) {
13363 // If the caller doesn't want us to simplify this into a zext of a compare,
13365 if (NotExtCompare && N2C->getAPIntValue() == 1)
13368 // Get a SetCC of the condition
13369 // NOTE: Don't create a SETCC if it's not legal on this target.
13370 if (!LegalOperations ||
13371 TLI.isOperationLegal(ISD::SETCC,
13372 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13374 // cast from setcc result type to select result type
13376 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13378 if (N2.getValueType().bitsLT(SCC.getValueType()))
13379 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13380 N2.getValueType());
13382 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13383 N2.getValueType(), SCC);
13385 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13386 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13387 N2.getValueType(), SCC);
13390 AddToWorklist(SCC.getNode());
13391 AddToWorklist(Temp.getNode());
13393 if (N2C->getAPIntValue() == 1)
13396 // shl setcc result by log2 n2c
13397 return DAG.getNode(
13398 ISD::SHL, DL, N2.getValueType(), Temp,
13399 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13400 getShiftAmountTy(Temp.getValueType())));
13404 // Check to see if this is the equivalent of setcc
13405 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13406 // otherwise, go ahead with the folds.
13407 if (0 && isNullConstant(N3) && N2C && (N2C->getAPIntValue() == 1ULL)) {
13408 EVT XType = N0.getValueType();
13409 if (!LegalOperations ||
13410 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13411 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13412 if (Res.getValueType() != VT)
13413 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13417 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13418 if (isNullConstant(N1) && CC == ISD::SETEQ &&
13419 (!LegalOperations ||
13420 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13421 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13422 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13423 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13425 getShiftAmountTy(Ctlz.getValueType())));
13427 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13428 if (isNullConstant(N1) && CC == ISD::SETGT) {
13430 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13431 XType, DAG.getConstant(0, DL, XType), N0);
13432 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13433 return DAG.getNode(ISD::SRL, DL, XType,
13434 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13435 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13436 getShiftAmountTy(XType)));
13438 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13439 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13441 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13442 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13443 getShiftAmountTy(N0.getValueType())));
13444 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13449 // Check to see if this is an integer abs.
13450 // select_cc setg[te] X, 0, X, -X ->
13451 // select_cc setgt X, -1, X, -X ->
13452 // select_cc setl[te] X, 0, -X, X ->
13453 // select_cc setlt X, 1, -X, X ->
13454 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13456 ConstantSDNode *SubC = nullptr;
13457 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13458 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13459 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13460 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13461 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13462 (N1C->isOne() && CC == ISD::SETLT)) &&
13463 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13464 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13466 EVT XType = N0.getValueType();
13467 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13469 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13471 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13472 getShiftAmountTy(N0.getValueType())));
13473 SDValue Add = DAG.getNode(ISD::ADD, DL,
13475 AddToWorklist(Shift.getNode());
13476 AddToWorklist(Add.getNode());
13477 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13484 /// This is a stub for TargetLowering::SimplifySetCC.
13485 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13486 SDValue N1, ISD::CondCode Cond,
13487 SDLoc DL, bool foldBooleans) {
13488 TargetLowering::DAGCombinerInfo
13489 DagCombineInfo(DAG, Level, false, this);
13490 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13493 /// Given an ISD::SDIV node expressing a divide by constant, return
13494 /// a DAG expression to select that will generate the same value by multiplying
13495 /// by a magic number.
13496 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13497 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13498 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13502 // Avoid division by zero.
13503 if (C->isNullValue())
13506 std::vector<SDNode*> Built;
13508 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13510 for (SDNode *N : Built)
13515 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13516 /// DAG expression that will generate the same value by right shifting.
13517 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13518 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13522 // Avoid division by zero.
13523 if (C->isNullValue())
13526 std::vector<SDNode *> Built;
13527 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13529 for (SDNode *N : Built)
13534 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13535 /// expression that will generate the same value by multiplying by a magic
13537 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13538 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13539 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13543 // Avoid division by zero.
13544 if (C->isNullValue())
13547 std::vector<SDNode*> Built;
13549 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13551 for (SDNode *N : Built)
13556 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13557 if (Level >= AfterLegalizeDAG)
13560 // Expose the DAG combiner to the target combiner implementations.
13561 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13563 unsigned Iterations = 0;
13564 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13566 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13567 // For the reciprocal, we need to find the zero of the function:
13568 // F(X) = A X - 1 [which has a zero at X = 1/A]
13570 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13571 // does not require additional intermediate precision]
13572 EVT VT = Op.getValueType();
13574 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13576 AddToWorklist(Est.getNode());
13578 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13579 for (unsigned i = 0; i < Iterations; ++i) {
13580 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13581 AddToWorklist(NewEst.getNode());
13583 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13584 AddToWorklist(NewEst.getNode());
13586 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13587 AddToWorklist(NewEst.getNode());
13589 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13590 AddToWorklist(Est.getNode());
13599 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13600 /// For the reciprocal sqrt, we need to find the zero of the function:
13601 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13603 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13604 /// As a result, we precompute A/2 prior to the iteration loop.
13605 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13606 unsigned Iterations) {
13607 EVT VT = Arg.getValueType();
13609 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13611 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13612 // this entire sequence requires only one FP constant.
13613 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13614 AddToWorklist(HalfArg.getNode());
13616 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13617 AddToWorklist(HalfArg.getNode());
13619 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13620 for (unsigned i = 0; i < Iterations; ++i) {
13621 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13622 AddToWorklist(NewEst.getNode());
13624 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13625 AddToWorklist(NewEst.getNode());
13627 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13628 AddToWorklist(NewEst.getNode());
13630 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13631 AddToWorklist(Est.getNode());
13636 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13637 /// For the reciprocal sqrt, we need to find the zero of the function:
13638 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13640 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13641 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13642 unsigned Iterations) {
13643 EVT VT = Arg.getValueType();
13645 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13646 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13648 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13649 for (unsigned i = 0; i < Iterations; ++i) {
13650 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13651 AddToWorklist(HalfEst.getNode());
13653 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13654 AddToWorklist(Est.getNode());
13656 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13657 AddToWorklist(Est.getNode());
13659 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13660 AddToWorklist(Est.getNode());
13662 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13663 AddToWorklist(Est.getNode());
13668 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13669 if (Level >= AfterLegalizeDAG)
13672 // Expose the DAG combiner to the target combiner implementations.
13673 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13674 unsigned Iterations = 0;
13675 bool UseOneConstNR = false;
13676 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13677 AddToWorklist(Est.getNode());
13679 Est = UseOneConstNR ?
13680 BuildRsqrtNROneConst(Op, Est, Iterations) :
13681 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13689 /// Return true if base is a frame index, which is known not to alias with
13690 /// anything but itself. Provides base object and offset as results.
13691 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13692 const GlobalValue *&GV, const void *&CV) {
13693 // Assume it is a primitive operation.
13694 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13696 // If it's an adding a simple constant then integrate the offset.
13697 if (Base.getOpcode() == ISD::ADD) {
13698 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13699 Base = Base.getOperand(0);
13700 Offset += C->getZExtValue();
13704 // Return the underlying GlobalValue, and update the Offset. Return false
13705 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13706 // by multiple nodes with different offsets.
13707 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13708 GV = G->getGlobal();
13709 Offset += G->getOffset();
13713 // Return the underlying Constant value, and update the Offset. Return false
13714 // for ConstantSDNodes since the same constant pool entry may be represented
13715 // by multiple nodes with different offsets.
13716 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13717 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13718 : (const void *)C->getConstVal();
13719 Offset += C->getOffset();
13722 // If it's any of the following then it can't alias with anything but itself.
13723 return isa<FrameIndexSDNode>(Base);
13726 /// Return true if there is any possibility that the two addresses overlap.
13727 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13728 // If they are the same then they must be aliases.
13729 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13731 // If they are both volatile then they cannot be reordered.
13732 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13734 // Gather base node and offset information.
13735 SDValue Base1, Base2;
13736 int64_t Offset1, Offset2;
13737 const GlobalValue *GV1, *GV2;
13738 const void *CV1, *CV2;
13739 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13740 Base1, Offset1, GV1, CV1);
13741 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13742 Base2, Offset2, GV2, CV2);
13744 // If they have a same base address then check to see if they overlap.
13745 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13746 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13747 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13749 // It is possible for different frame indices to alias each other, mostly
13750 // when tail call optimization reuses return address slots for arguments.
13751 // To catch this case, look up the actual index of frame indices to compute
13752 // the real alias relationship.
13753 if (isFrameIndex1 && isFrameIndex2) {
13754 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13755 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13756 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13757 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13758 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13761 // Otherwise, if we know what the bases are, and they aren't identical, then
13762 // we know they cannot alias.
13763 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13766 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13767 // compared to the size and offset of the access, we may be able to prove they
13768 // do not alias. This check is conservative for now to catch cases created by
13769 // splitting vector types.
13770 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13771 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13772 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13773 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13774 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13775 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13776 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13778 // There is no overlap between these relatively aligned accesses of similar
13779 // size, return no alias.
13780 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13781 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13785 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13787 : DAG.getSubtarget().useAA();
13789 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13790 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13794 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13795 // Use alias analysis information.
13796 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13797 Op1->getSrcValueOffset());
13798 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13799 Op0->getSrcValueOffset() - MinOffset;
13800 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13801 Op1->getSrcValueOffset() - MinOffset;
13802 AliasAnalysis::AliasResult AAResult =
13803 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13805 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13806 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13808 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13809 if (AAResult == AliasAnalysis::NoAlias)
13813 // Otherwise we have to assume they alias.
13817 /// Walk up chain skipping non-aliasing memory nodes,
13818 /// looking for aliasing nodes and adding them to the Aliases vector.
13819 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13820 SmallVectorImpl<SDValue> &Aliases) {
13821 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13822 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13824 // Get alias information for node.
13825 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13828 Chains.push_back(OriginalChain);
13829 unsigned Depth = 0;
13831 // Look at each chain and determine if it is an alias. If so, add it to the
13832 // aliases list. If not, then continue up the chain looking for the next
13834 while (!Chains.empty()) {
13835 SDValue Chain = Chains.back();
13838 // For TokenFactor nodes, look at each operand and only continue up the
13839 // chain until we find two aliases. If we've seen two aliases, assume we'll
13840 // find more and revert to original chain since the xform is unlikely to be
13843 // FIXME: The depth check could be made to return the last non-aliasing
13844 // chain we found before we hit a tokenfactor rather than the original
13846 if (Depth > 6 || Aliases.size() == 2) {
13848 Aliases.push_back(OriginalChain);
13852 // Don't bother if we've been before.
13853 if (!Visited.insert(Chain.getNode()).second)
13856 switch (Chain.getOpcode()) {
13857 case ISD::EntryToken:
13858 // Entry token is ideal chain operand, but handled in FindBetterChain.
13863 // Get alias information for Chain.
13864 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13865 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13867 // If chain is alias then stop here.
13868 if (!(IsLoad && IsOpLoad) &&
13869 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13870 Aliases.push_back(Chain);
13872 // Look further up the chain.
13873 Chains.push_back(Chain.getOperand(0));
13879 case ISD::TokenFactor:
13880 // We have to check each of the operands of the token factor for "small"
13881 // token factors, so we queue them up. Adding the operands to the queue
13882 // (stack) in reverse order maintains the original order and increases the
13883 // likelihood that getNode will find a matching token factor (CSE.)
13884 if (Chain.getNumOperands() > 16) {
13885 Aliases.push_back(Chain);
13888 for (unsigned n = Chain.getNumOperands(); n;)
13889 Chains.push_back(Chain.getOperand(--n));
13894 // For all other instructions we will just have to take what we can get.
13895 Aliases.push_back(Chain);
13900 // We need to be careful here to also search for aliases through the
13901 // value operand of a store, etc. Consider the following situation:
13903 // L1 = load Token1, %52
13904 // S1 = store Token1, L1, %51
13905 // L2 = load Token1, %52+8
13906 // S2 = store Token1, L2, %51+8
13907 // Token2 = Token(S1, S2)
13908 // L3 = load Token2, %53
13909 // S3 = store Token2, L3, %52
13910 // L4 = load Token2, %53+8
13911 // S4 = store Token2, L4, %52+8
13912 // If we search for aliases of S3 (which loads address %52), and we look
13913 // only through the chain, then we'll miss the trivial dependence on L1
13914 // (which also loads from %52). We then might change all loads and
13915 // stores to use Token1 as their chain operand, which could result in
13916 // copying %53 into %52 before copying %52 into %51 (which should
13919 // The problem is, however, that searching for such data dependencies
13920 // can become expensive, and the cost is not directly related to the
13921 // chain depth. Instead, we'll rule out such configurations here by
13922 // insisting that we've visited all chain users (except for users
13923 // of the original chain, which is not necessary). When doing this,
13924 // we need to look through nodes we don't care about (otherwise, things
13925 // like register copies will interfere with trivial cases).
13927 SmallVector<const SDNode *, 16> Worklist;
13928 for (const SDNode *N : Visited)
13929 if (N != OriginalChain.getNode())
13930 Worklist.push_back(N);
13932 while (!Worklist.empty()) {
13933 const SDNode *M = Worklist.pop_back_val();
13935 // We have already visited M, and want to make sure we've visited any uses
13936 // of M that we care about. For uses that we've not visisted, and don't
13937 // care about, queue them to the worklist.
13939 for (SDNode::use_iterator UI = M->use_begin(),
13940 UIE = M->use_end(); UI != UIE; ++UI)
13941 if (UI.getUse().getValueType() == MVT::Other &&
13942 Visited.insert(*UI).second) {
13943 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13944 // We've not visited this use, and we care about it (it could have an
13945 // ordering dependency with the original node).
13947 Aliases.push_back(OriginalChain);
13951 // We've not visited this use, but we don't care about it. Mark it as
13952 // visited and enqueue it to the worklist.
13953 Worklist.push_back(*UI);
13958 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13959 /// (aliasing node.)
13960 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13961 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13963 // Accumulate all the aliases to this node.
13964 GatherAllAliases(N, OldChain, Aliases);
13966 // If no operands then chain to entry token.
13967 if (Aliases.size() == 0)
13968 return DAG.getEntryNode();
13970 // If a single operand then chain to it. We don't need to revisit it.
13971 if (Aliases.size() == 1)
13974 // Construct a custom tailored token factor.
13975 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13978 /// This is the entry point for the file.
13979 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13980 CodeGenOpt::Level OptLevel) {
13981 /// This is the main entry point to this class.
13982 DAGCombiner(*this, AA, OptLevel).Run(Level);