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/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SetVector.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/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
44 #define DEBUG_TYPE "dagcombine"
46 STATISTIC(NodesCombined , "Number of dag nodes combined");
47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
49 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
50 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
51 STATISTIC(SlicedLoads, "Number of load sliced");
55 CombinerAA("combiner-alias-analysis", cl::Hidden,
56 cl::desc("Enable DAG combiner alias-analysis heuristics"));
59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60 cl::desc("Enable DAG combiner's use of IR alias analysis"));
63 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
64 cl::desc("Enable DAG combiner's use of TBAA"));
67 static cl::opt<std::string>
68 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
69 cl::desc("Only use DAG-combiner alias analysis in this"
73 /// Hidden option to stress test load slicing, i.e., when this option
74 /// is enabled, load slicing bypasses most of its profitability guards.
76 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
77 cl::desc("Bypass the profitability model of load "
82 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
83 cl::desc("DAG combiner may split indexing from loads"));
85 //------------------------------ DAGCombiner ---------------------------------//
89 const TargetLowering &TLI;
91 CodeGenOpt::Level OptLevel;
96 /// \brief Worklist of all of the nodes that need to be simplified.
98 /// This must behave as a stack -- new nodes to process are pushed onto the
99 /// back and when processing we pop off of the back.
101 /// The worklist will not contain duplicates but may contain null entries
102 /// due to nodes being deleted from the underlying DAG.
103 SmallVector<SDNode *, 64> Worklist;
105 /// \brief Mapping from an SDNode to its position on the worklist.
107 /// This is used to find and remove nodes from the worklist (by nulling
108 /// them) when they are deleted from the underlying DAG. It relies on
109 /// stable indices of nodes within the worklist.
110 DenseMap<SDNode *, unsigned> WorklistMap;
112 /// \brief Set of nodes which have been combined (at least once).
114 /// This is used to allow us to reliably add any operands of a DAG node
115 /// which have not yet been combined to the worklist.
116 SmallPtrSet<SDNode *, 64> CombinedNodes;
118 // AA - Used for DAG load/store alias analysis.
121 /// When an instruction is simplified, add all users of the instruction to
122 /// the work lists because they might get more simplified now.
123 void AddUsersToWorklist(SDNode *N) {
124 for (SDNode *Node : N->uses())
128 /// Call the node-specific routine that folds each particular type of node.
129 SDValue visit(SDNode *N);
132 /// Add to the worklist making sure its instance is at the back (next to be
134 void AddToWorklist(SDNode *N) {
135 // Skip handle nodes as they can't usefully be combined and confuse the
136 // zero-use deletion strategy.
137 if (N->getOpcode() == ISD::HANDLENODE)
140 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141 Worklist.push_back(N);
144 /// Remove all instances of N from the worklist.
145 void removeFromWorklist(SDNode *N) {
146 CombinedNodes.erase(N);
148 auto It = WorklistMap.find(N);
149 if (It == WorklistMap.end())
150 return; // Not in the worklist.
152 // Null out the entry rather than erasing it to avoid a linear operation.
153 Worklist[It->second] = nullptr;
154 WorklistMap.erase(It);
157 void deleteAndRecombine(SDNode *N);
158 bool recursivelyDeleteUnusedNodes(SDNode *N);
160 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
163 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
164 return CombineTo(N, &Res, 1, AddTo);
167 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
169 SDValue To[] = { Res0, Res1 };
170 return CombineTo(N, To, 2, AddTo);
173 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
177 /// Check the specified integer node value to see if it can be simplified or
178 /// if things it uses can be simplified by bit propagation.
179 /// If so, return true.
180 bool SimplifyDemandedBits(SDValue Op) {
181 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
182 APInt Demanded = APInt::getAllOnesValue(BitWidth);
183 return SimplifyDemandedBits(Op, Demanded);
186 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
188 bool CombineToPreIndexedLoadStore(SDNode *N);
189 bool CombineToPostIndexedLoadStore(SDNode *N);
190 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
191 bool SliceUpLoad(SDNode *N);
193 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
196 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
197 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
198 /// \param EltNo index of the vector element to load.
199 /// \param OriginalLoad load that EVE came from to be replaced.
200 /// \returns EVE on success SDValue() on failure.
201 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
202 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
203 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
204 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
205 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
207 SDValue PromoteIntBinOp(SDValue Op);
208 SDValue PromoteIntShiftOp(SDValue Op);
209 SDValue PromoteExtend(SDValue Op);
210 bool PromoteLoad(SDValue Op);
212 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
213 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
214 ISD::NodeType ExtType);
216 /// Call the node-specific routine that knows how to fold each
217 /// particular type of node. If that doesn't do anything, try the
218 /// target-specific DAG combines.
219 SDValue combine(SDNode *N);
221 // Visitation implementation - Implement dag node combining for different
222 // node types. The semantics are as follows:
224 // SDValue.getNode() == 0 - No change was made
225 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
226 // otherwise - N should be replaced by the returned Operand.
228 SDValue visitTokenFactor(SDNode *N);
229 SDValue visitMERGE_VALUES(SDNode *N);
230 SDValue visitADD(SDNode *N);
231 SDValue visitSUB(SDNode *N);
232 SDValue visitADDC(SDNode *N);
233 SDValue visitSUBC(SDNode *N);
234 SDValue visitADDE(SDNode *N);
235 SDValue visitSUBE(SDNode *N);
236 SDValue visitMUL(SDNode *N);
237 SDValue visitSDIV(SDNode *N);
238 SDValue visitUDIV(SDNode *N);
239 SDValue visitSREM(SDNode *N);
240 SDValue visitUREM(SDNode *N);
241 SDValue visitMULHU(SDNode *N);
242 SDValue visitMULHS(SDNode *N);
243 SDValue visitSMUL_LOHI(SDNode *N);
244 SDValue visitUMUL_LOHI(SDNode *N);
245 SDValue visitSMULO(SDNode *N);
246 SDValue visitUMULO(SDNode *N);
247 SDValue visitSDIVREM(SDNode *N);
248 SDValue visitUDIVREM(SDNode *N);
249 SDValue visitAND(SDNode *N);
250 SDValue visitOR(SDNode *N);
251 SDValue visitXOR(SDNode *N);
252 SDValue SimplifyVBinOp(SDNode *N);
253 SDValue SimplifyVUnaryOp(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 visitBRCOND(SDNode *N);
295 SDValue visitBR_CC(SDNode *N);
296 SDValue visitLOAD(SDNode *N);
297 SDValue visitSTORE(SDNode *N);
298 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
299 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
300 SDValue visitBUILD_VECTOR(SDNode *N);
301 SDValue visitCONCAT_VECTORS(SDNode *N);
302 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
303 SDValue visitVECTOR_SHUFFLE(SDNode *N);
304 SDValue visitINSERT_SUBVECTOR(SDNode *N);
306 SDValue XformToShuffleWithZero(SDNode *N);
307 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
309 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
311 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
312 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
313 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
314 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
315 SDValue N3, ISD::CondCode CC,
316 bool NotExtCompare = false);
317 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
318 SDLoc DL, bool foldBooleans = true);
320 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
322 bool isOneUseSetCC(SDValue N) const;
324 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
326 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
327 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
328 SDValue BuildSDIV(SDNode *N);
329 SDValue BuildSDIVPow2(SDNode *N);
330 SDValue BuildUDIV(SDNode *N);
331 SDValue BuildReciprocalEstimate(SDValue Op);
332 SDValue BuildRsqrtEstimate(SDValue Op);
333 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
334 bool DemandHighBits = true);
335 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
336 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
337 SDValue InnerPos, SDValue InnerNeg,
338 unsigned PosOpcode, unsigned NegOpcode,
340 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
341 SDValue ReduceLoadWidth(SDNode *N);
342 SDValue ReduceLoadOpStoreWidth(SDNode *N);
343 SDValue TransformFPLoadStorePair(SDNode *N);
344 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
345 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
347 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
349 /// Walk up chain skipping non-aliasing memory nodes,
350 /// looking for aliasing nodes and adding them to the Aliases vector.
351 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
352 SmallVectorImpl<SDValue> &Aliases);
354 /// Return true if there is any possibility that the two addresses overlap.
355 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
357 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
358 /// chain (aliasing node.)
359 SDValue FindBetterChain(SDNode *N, SDValue Chain);
361 /// Merge consecutive store operations into a wide store.
362 /// This optimization uses wide integers or vectors when possible.
363 /// \return True if some memory operations were changed.
364 bool MergeConsecutiveStores(StoreSDNode *N);
366 /// \brief Try to transform a truncation where C is a constant:
367 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
369 /// \p N needs to be a truncation and its first operand an AND. Other
370 /// requirements are checked by the function (e.g. that trunc is
371 /// single-use) and if missed an empty SDValue is returned.
372 SDValue distributeTruncateThroughAnd(SDNode *N);
375 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
376 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
377 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
378 AttributeSet FnAttrs =
379 DAG.getMachineFunction().getFunction()->getAttributes();
381 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
382 Attribute::OptimizeForSize) ||
383 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
386 /// Runs the dag combiner on all nodes in the work list
387 void Run(CombineLevel AtLevel);
389 SelectionDAG &getDAG() const { return DAG; }
391 /// Returns a type large enough to hold any valid shift amount - before type
392 /// legalization these can be huge.
393 EVT getShiftAmountTy(EVT LHSTy) {
394 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
395 if (LHSTy.isVector())
397 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
398 : TLI.getPointerTy();
401 /// This method returns true if we are running before type legalization or
402 /// if the specified VT is legal.
403 bool isTypeLegal(const EVT &VT) {
404 if (!LegalTypes) return true;
405 return TLI.isTypeLegal(VT);
408 /// Convenience wrapper around TargetLowering::getSetCCResultType
409 EVT getSetCCResultType(EVT VT) const {
410 return TLI.getSetCCResultType(*DAG.getContext(), VT);
417 /// This class is a DAGUpdateListener that removes any deleted
418 /// nodes from the worklist.
419 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
422 explicit WorklistRemover(DAGCombiner &dc)
423 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
425 void NodeDeleted(SDNode *N, SDNode *E) override {
426 DC.removeFromWorklist(N);
431 //===----------------------------------------------------------------------===//
432 // TargetLowering::DAGCombinerInfo implementation
433 //===----------------------------------------------------------------------===//
435 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
436 ((DAGCombiner*)DC)->AddToWorklist(N);
439 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
440 ((DAGCombiner*)DC)->removeFromWorklist(N);
443 SDValue TargetLowering::DAGCombinerInfo::
444 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
445 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
448 SDValue TargetLowering::DAGCombinerInfo::
449 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
450 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
454 SDValue TargetLowering::DAGCombinerInfo::
455 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
456 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
459 void TargetLowering::DAGCombinerInfo::
460 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
461 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
464 //===----------------------------------------------------------------------===//
466 //===----------------------------------------------------------------------===//
468 void DAGCombiner::deleteAndRecombine(SDNode *N) {
469 removeFromWorklist(N);
471 // If the operands of this node are only used by the node, they will now be
472 // dead. Make sure to re-visit them and recursively delete dead nodes.
473 for (const SDValue &Op : N->ops())
474 // For an operand generating multiple values, one of the values may
475 // become dead allowing further simplification (e.g. split index
476 // arithmetic from an indexed load).
477 if (Op->hasOneUse() || Op->getNumValues() > 1)
478 AddToWorklist(Op.getNode());
483 /// Return 1 if we can compute the negated form of the specified expression for
484 /// the same cost as the expression itself, or 2 if we can compute the negated
485 /// form more cheaply than the expression itself.
486 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
487 const TargetLowering &TLI,
488 const TargetOptions *Options,
489 unsigned Depth = 0) {
490 // fneg is removable even if it has multiple uses.
491 if (Op.getOpcode() == ISD::FNEG) return 2;
493 // Don't allow anything with multiple uses.
494 if (!Op.hasOneUse()) return 0;
496 // Don't recurse exponentially.
497 if (Depth > 6) return 0;
499 switch (Op.getOpcode()) {
500 default: return false;
501 case ISD::ConstantFP:
502 // Don't invert constant FP values after legalize. The negated constant
503 // isn't necessarily legal.
504 return LegalOperations ? 0 : 1;
506 // FIXME: determine better conditions for this xform.
507 if (!Options->UnsafeFPMath) return 0;
509 // After operation legalization, it might not be legal to create new FSUBs.
510 if (LegalOperations &&
511 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
514 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
515 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
518 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
519 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
522 // We can't turn -(A-B) into B-A when we honor signed zeros.
523 if (!Options->UnsafeFPMath) return 0;
525 // fold (fneg (fsub A, B)) -> (fsub B, A)
530 if (Options->HonorSignDependentRoundingFPMath()) return 0;
532 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
533 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
537 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
543 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
548 /// If isNegatibleForFree returns true, return the newly negated expression.
549 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
550 bool LegalOperations, unsigned Depth = 0) {
551 const TargetOptions &Options = DAG.getTarget().Options;
552 // fneg is removable even if it has multiple uses.
553 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
555 // Don't allow anything with multiple uses.
556 assert(Op.hasOneUse() && "Unknown reuse!");
558 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
559 switch (Op.getOpcode()) {
560 default: llvm_unreachable("Unknown code");
561 case ISD::ConstantFP: {
562 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
564 return DAG.getConstantFP(V, Op.getValueType());
567 // FIXME: determine better conditions for this xform.
568 assert(Options.UnsafeFPMath);
570 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
571 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
572 DAG.getTargetLoweringInfo(), &Options, Depth+1))
573 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(0), DAG,
575 LegalOperations, Depth+1),
577 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
578 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
579 GetNegatedExpression(Op.getOperand(1), DAG,
580 LegalOperations, Depth+1),
583 // We can't turn -(A-B) into B-A when we honor signed zeros.
584 assert(Options.UnsafeFPMath);
586 // fold (fneg (fsub 0, B)) -> B
587 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
588 if (N0CFP->getValueAPF().isZero())
589 return Op.getOperand(1);
591 // fold (fneg (fsub A, B)) -> (fsub B, A)
592 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
593 Op.getOperand(1), Op.getOperand(0));
597 assert(!Options.HonorSignDependentRoundingFPMath());
599 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
600 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
601 DAG.getTargetLoweringInfo(), &Options, Depth+1))
602 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
603 GetNegatedExpression(Op.getOperand(0), DAG,
604 LegalOperations, Depth+1),
607 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
608 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
610 GetNegatedExpression(Op.getOperand(1), DAG,
611 LegalOperations, Depth+1));
615 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
616 GetNegatedExpression(Op.getOperand(0), DAG,
617 LegalOperations, Depth+1));
619 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
620 GetNegatedExpression(Op.getOperand(0), DAG,
621 LegalOperations, Depth+1),
626 // Return true if this node is a setcc, or is a select_cc
627 // that selects between the target values used for true and false, making it
628 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
629 // the appropriate nodes based on the type of node we are checking. This
630 // simplifies life a bit for the callers.
631 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
633 if (N.getOpcode() == ISD::SETCC) {
634 LHS = N.getOperand(0);
635 RHS = N.getOperand(1);
636 CC = N.getOperand(2);
640 if (N.getOpcode() != ISD::SELECT_CC ||
641 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
642 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
645 LHS = N.getOperand(0);
646 RHS = N.getOperand(1);
647 CC = N.getOperand(4);
651 /// Return true if this is a SetCC-equivalent operation with only one use.
652 /// If this is true, it allows the users to invert the operation for free when
653 /// it is profitable to do so.
654 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
656 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
661 /// Returns true if N is a BUILD_VECTOR node whose
662 /// elements are all the same constant or undefined.
663 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
664 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
669 unsigned SplatBitSize;
671 EVT EltVT = N->getValueType(0).getVectorElementType();
672 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
674 EltVT.getSizeInBits() >= SplatBitSize);
677 // \brief Returns the SDNode if it is a constant BuildVector or constant.
678 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
679 if (isa<ConstantSDNode>(N))
681 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
682 if (BV && BV->isConstant())
687 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
689 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
690 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
693 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
694 BitVector UndefElements;
695 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
697 // BuildVectors can truncate their operands. Ignore that case here.
698 // FIXME: We blindly ignore splats which include undef which is overly
700 if (CN && UndefElements.none() &&
701 CN->getValueType(0) == N.getValueType().getScalarType())
708 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
710 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
711 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
714 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
715 BitVector UndefElements;
716 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
718 if (CN && UndefElements.none())
725 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
726 SDValue N0, SDValue N1) {
727 EVT VT = N0.getValueType();
728 if (N0.getOpcode() == Opc) {
729 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
730 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
731 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
732 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
733 if (!OpNode.getNode())
735 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
737 if (N0.hasOneUse()) {
738 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
740 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
741 if (!OpNode.getNode())
743 AddToWorklist(OpNode.getNode());
744 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
749 if (N1.getOpcode() == Opc) {
750 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
751 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
752 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
753 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
754 if (!OpNode.getNode())
756 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
758 if (N1.hasOneUse()) {
759 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
761 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
762 if (!OpNode.getNode())
764 AddToWorklist(OpNode.getNode());
765 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
773 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
775 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
777 DEBUG(dbgs() << "\nReplacing.1 ";
779 dbgs() << "\nWith: ";
780 To[0].getNode()->dump(&DAG);
781 dbgs() << " and " << NumTo-1 << " other values\n";
782 for (unsigned i = 0, e = NumTo; i != e; ++i)
783 assert((!To[i].getNode() ||
784 N->getValueType(i) == To[i].getValueType()) &&
785 "Cannot combine value to value of different type!"));
786 WorklistRemover DeadNodes(*this);
787 DAG.ReplaceAllUsesWith(N, To);
789 // Push the new nodes and any users onto the worklist
790 for (unsigned i = 0, e = NumTo; i != e; ++i) {
791 if (To[i].getNode()) {
792 AddToWorklist(To[i].getNode());
793 AddUsersToWorklist(To[i].getNode());
798 // Finally, if the node is now dead, remove it from the graph. The node
799 // may not be dead if the replacement process recursively simplified to
800 // something else needing this node.
802 deleteAndRecombine(N);
803 return SDValue(N, 0);
807 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
808 // Replace all uses. If any nodes become isomorphic to other nodes and
809 // are deleted, make sure to remove them from our worklist.
810 WorklistRemover DeadNodes(*this);
811 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
813 // Push the new node and any (possibly new) users onto the worklist.
814 AddToWorklist(TLO.New.getNode());
815 AddUsersToWorklist(TLO.New.getNode());
817 // Finally, if the node is now dead, remove it from the graph. The node
818 // may not be dead if the replacement process recursively simplified to
819 // something else needing this node.
820 if (TLO.Old.getNode()->use_empty())
821 deleteAndRecombine(TLO.Old.getNode());
824 /// Check the specified integer node value to see if it can be simplified or if
825 /// things it uses can be simplified by bit propagation. If so, return true.
826 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
827 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
828 APInt KnownZero, KnownOne;
829 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
833 AddToWorklist(Op.getNode());
835 // Replace the old value with the new one.
837 DEBUG(dbgs() << "\nReplacing.2 ";
838 TLO.Old.getNode()->dump(&DAG);
839 dbgs() << "\nWith: ";
840 TLO.New.getNode()->dump(&DAG);
843 CommitTargetLoweringOpt(TLO);
847 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
849 EVT VT = Load->getValueType(0);
850 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
852 DEBUG(dbgs() << "\nReplacing.9 ";
854 dbgs() << "\nWith: ";
855 Trunc.getNode()->dump(&DAG);
857 WorklistRemover DeadNodes(*this);
858 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
859 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
860 deleteAndRecombine(Load);
861 AddToWorklist(Trunc.getNode());
864 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
867 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
868 EVT MemVT = LD->getMemoryVT();
869 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
870 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
872 : LD->getExtensionType();
874 return DAG.getExtLoad(ExtType, dl, PVT,
875 LD->getChain(), LD->getBasePtr(),
876 MemVT, LD->getMemOperand());
879 unsigned Opc = Op.getOpcode();
882 case ISD::AssertSext:
883 return DAG.getNode(ISD::AssertSext, dl, PVT,
884 SExtPromoteOperand(Op.getOperand(0), PVT),
886 case ISD::AssertZext:
887 return DAG.getNode(ISD::AssertZext, dl, PVT,
888 ZExtPromoteOperand(Op.getOperand(0), PVT),
890 case ISD::Constant: {
892 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
893 return DAG.getNode(ExtOpc, dl, PVT, Op);
897 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
899 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
902 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
903 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
905 EVT OldVT = Op.getValueType();
907 bool Replace = false;
908 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
909 if (!NewOp.getNode())
911 AddToWorklist(NewOp.getNode());
914 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
915 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
916 DAG.getValueType(OldVT));
919 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
920 EVT OldVT = Op.getValueType();
922 bool Replace = false;
923 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
924 if (!NewOp.getNode())
926 AddToWorklist(NewOp.getNode());
929 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
930 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
933 /// Promote the specified integer binary operation if the target indicates it is
934 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
935 /// i32 since i16 instructions are longer.
936 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
937 if (!LegalOperations)
940 EVT VT = Op.getValueType();
941 if (VT.isVector() || !VT.isInteger())
944 // If operation type is 'undesirable', e.g. i16 on x86, consider
946 unsigned Opc = Op.getOpcode();
947 if (TLI.isTypeDesirableForOp(Opc, VT))
951 // Consult target whether it is a good idea to promote this operation and
952 // what's the right type to promote it to.
953 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
954 assert(PVT != VT && "Don't know what type to promote to!");
956 bool Replace0 = false;
957 SDValue N0 = Op.getOperand(0);
958 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
962 bool Replace1 = false;
963 SDValue N1 = Op.getOperand(1);
968 NN1 = PromoteOperand(N1, PVT, Replace1);
973 AddToWorklist(NN0.getNode());
975 AddToWorklist(NN1.getNode());
978 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
980 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
982 DEBUG(dbgs() << "\nPromoting ";
983 Op.getNode()->dump(&DAG));
985 return DAG.getNode(ISD::TRUNCATE, dl, VT,
986 DAG.getNode(Opc, dl, PVT, NN0, NN1));
991 /// Promote the specified integer shift operation if the target indicates it is
992 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
993 /// i32 since i16 instructions are longer.
994 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
995 if (!LegalOperations)
998 EVT VT = Op.getValueType();
999 if (VT.isVector() || !VT.isInteger())
1002 // If operation type is 'undesirable', e.g. i16 on x86, consider
1004 unsigned Opc = Op.getOpcode();
1005 if (TLI.isTypeDesirableForOp(Opc, VT))
1009 // Consult target whether it is a good idea to promote this operation and
1010 // what's the right type to promote it to.
1011 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1012 assert(PVT != VT && "Don't know what type to promote to!");
1014 bool Replace = false;
1015 SDValue N0 = Op.getOperand(0);
1016 if (Opc == ISD::SRA)
1017 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1018 else if (Opc == ISD::SRL)
1019 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1021 N0 = PromoteOperand(N0, PVT, Replace);
1025 AddToWorklist(N0.getNode());
1027 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1029 DEBUG(dbgs() << "\nPromoting ";
1030 Op.getNode()->dump(&DAG));
1032 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1033 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1038 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1039 if (!LegalOperations)
1042 EVT VT = Op.getValueType();
1043 if (VT.isVector() || !VT.isInteger())
1046 // If operation type is 'undesirable', e.g. i16 on x86, consider
1048 unsigned Opc = Op.getOpcode();
1049 if (TLI.isTypeDesirableForOp(Opc, VT))
1053 // Consult target whether it is a good idea to promote this operation and
1054 // what's the right type to promote it to.
1055 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056 assert(PVT != VT && "Don't know what type to promote to!");
1057 // fold (aext (aext x)) -> (aext x)
1058 // fold (aext (zext x)) -> (zext x)
1059 // fold (aext (sext x)) -> (sext x)
1060 DEBUG(dbgs() << "\nPromoting ";
1061 Op.getNode()->dump(&DAG));
1062 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1067 bool DAGCombiner::PromoteLoad(SDValue Op) {
1068 if (!LegalOperations)
1071 EVT VT = Op.getValueType();
1072 if (VT.isVector() || !VT.isInteger())
1075 // If operation type is 'undesirable', e.g. i16 on x86, consider
1077 unsigned Opc = Op.getOpcode();
1078 if (TLI.isTypeDesirableForOp(Opc, VT))
1082 // Consult target whether it is a good idea to promote this operation and
1083 // what's the right type to promote it to.
1084 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1085 assert(PVT != VT && "Don't know what type to promote to!");
1088 SDNode *N = Op.getNode();
1089 LoadSDNode *LD = cast<LoadSDNode>(N);
1090 EVT MemVT = LD->getMemoryVT();
1091 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1092 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1094 : LD->getExtensionType();
1095 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1096 LD->getChain(), LD->getBasePtr(),
1097 MemVT, LD->getMemOperand());
1098 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1100 DEBUG(dbgs() << "\nPromoting ";
1103 Result.getNode()->dump(&DAG);
1105 WorklistRemover DeadNodes(*this);
1106 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1107 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1108 deleteAndRecombine(N);
1109 AddToWorklist(Result.getNode());
1115 /// \brief Recursively delete a node which has no uses and any operands for
1116 /// which it is the only use.
1118 /// Note that this both deletes the nodes and removes them from the worklist.
1119 /// It also adds any nodes who have had a user deleted to the worklist as they
1120 /// may now have only one use and subject to other combines.
1121 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1122 if (!N->use_empty())
1125 SmallSetVector<SDNode *, 16> Nodes;
1128 N = Nodes.pop_back_val();
1132 if (N->use_empty()) {
1133 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1134 Nodes.insert(N->getOperand(i).getNode());
1136 removeFromWorklist(N);
1141 } while (!Nodes.empty());
1145 //===----------------------------------------------------------------------===//
1146 // Main DAG Combiner implementation
1147 //===----------------------------------------------------------------------===//
1149 void DAGCombiner::Run(CombineLevel AtLevel) {
1150 // set the instance variables, so that the various visit routines may use it.
1152 LegalOperations = Level >= AfterLegalizeVectorOps;
1153 LegalTypes = Level >= AfterLegalizeTypes;
1155 // Add all the dag nodes to the worklist.
1156 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1157 E = DAG.allnodes_end(); I != E; ++I)
1160 // Create a dummy node (which is not added to allnodes), that adds a reference
1161 // to the root node, preventing it from being deleted, and tracking any
1162 // changes of the root.
1163 HandleSDNode Dummy(DAG.getRoot());
1165 // while the worklist isn't empty, find a node and
1166 // try and combine it.
1167 while (!WorklistMap.empty()) {
1169 // The Worklist holds the SDNodes in order, but it may contain null entries.
1171 N = Worklist.pop_back_val();
1174 bool GoodWorklistEntry = WorklistMap.erase(N);
1175 (void)GoodWorklistEntry;
1176 assert(GoodWorklistEntry &&
1177 "Found a worklist entry without a corresponding map entry!");
1179 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1180 // N is deleted from the DAG, since they too may now be dead or may have a
1181 // reduced number of uses, allowing other xforms.
1182 if (recursivelyDeleteUnusedNodes(N))
1185 WorklistRemover DeadNodes(*this);
1187 // If this combine is running after legalizing the DAG, re-legalize any
1188 // nodes pulled off the worklist.
1189 if (Level == AfterLegalizeDAG) {
1190 SmallSetVector<SDNode *, 16> UpdatedNodes;
1191 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1193 for (SDNode *LN : UpdatedNodes) {
1195 AddUsersToWorklist(LN);
1201 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1203 // Add any operands of the new node which have not yet been combined to the
1204 // worklist as well. Because the worklist uniques things already, this
1205 // won't repeatedly process the same operand.
1206 CombinedNodes.insert(N);
1207 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1208 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1209 AddToWorklist(N->getOperand(i).getNode());
1211 SDValue RV = combine(N);
1218 // If we get back the same node we passed in, rather than a new node or
1219 // zero, we know that the node must have defined multiple values and
1220 // CombineTo was used. Since CombineTo takes care of the worklist
1221 // mechanics for us, we have no work to do in this case.
1222 if (RV.getNode() == N)
1225 assert(N->getOpcode() != ISD::DELETED_NODE &&
1226 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1227 "Node was deleted but visit returned new node!");
1229 DEBUG(dbgs() << " ... into: ";
1230 RV.getNode()->dump(&DAG));
1232 // Transfer debug value.
1233 DAG.TransferDbgValues(SDValue(N, 0), RV);
1234 if (N->getNumValues() == RV.getNode()->getNumValues())
1235 DAG.ReplaceAllUsesWith(N, RV.getNode());
1237 assert(N->getValueType(0) == RV.getValueType() &&
1238 N->getNumValues() == 1 && "Type mismatch");
1240 DAG.ReplaceAllUsesWith(N, &OpV);
1243 // Push the new node and any users onto the worklist
1244 AddToWorklist(RV.getNode());
1245 AddUsersToWorklist(RV.getNode());
1247 // Finally, if the node is now dead, remove it from the graph. The node
1248 // may not be dead if the replacement process recursively simplified to
1249 // something else needing this node. This will also take care of adding any
1250 // operands which have lost a user to the worklist.
1251 recursivelyDeleteUnusedNodes(N);
1254 // If the root changed (e.g. it was a dead load, update the root).
1255 DAG.setRoot(Dummy.getValue());
1256 DAG.RemoveDeadNodes();
1259 SDValue DAGCombiner::visit(SDNode *N) {
1260 switch (N->getOpcode()) {
1262 case ISD::TokenFactor: return visitTokenFactor(N);
1263 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1264 case ISD::ADD: return visitADD(N);
1265 case ISD::SUB: return visitSUB(N);
1266 case ISD::ADDC: return visitADDC(N);
1267 case ISD::SUBC: return visitSUBC(N);
1268 case ISD::ADDE: return visitADDE(N);
1269 case ISD::SUBE: return visitSUBE(N);
1270 case ISD::MUL: return visitMUL(N);
1271 case ISD::SDIV: return visitSDIV(N);
1272 case ISD::UDIV: return visitUDIV(N);
1273 case ISD::SREM: return visitSREM(N);
1274 case ISD::UREM: return visitUREM(N);
1275 case ISD::MULHU: return visitMULHU(N);
1276 case ISD::MULHS: return visitMULHS(N);
1277 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1278 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1279 case ISD::SMULO: return visitSMULO(N);
1280 case ISD::UMULO: return visitUMULO(N);
1281 case ISD::SDIVREM: return visitSDIVREM(N);
1282 case ISD::UDIVREM: return visitUDIVREM(N);
1283 case ISD::AND: return visitAND(N);
1284 case ISD::OR: return visitOR(N);
1285 case ISD::XOR: return visitXOR(N);
1286 case ISD::SHL: return visitSHL(N);
1287 case ISD::SRA: return visitSRA(N);
1288 case ISD::SRL: return visitSRL(N);
1290 case ISD::ROTL: return visitRotate(N);
1291 case ISD::CTLZ: return visitCTLZ(N);
1292 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1293 case ISD::CTTZ: return visitCTTZ(N);
1294 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1295 case ISD::CTPOP: return visitCTPOP(N);
1296 case ISD::SELECT: return visitSELECT(N);
1297 case ISD::VSELECT: return visitVSELECT(N);
1298 case ISD::SELECT_CC: return visitSELECT_CC(N);
1299 case ISD::SETCC: return visitSETCC(N);
1300 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1301 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1302 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1303 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1304 case ISD::TRUNCATE: return visitTRUNCATE(N);
1305 case ISD::BITCAST: return visitBITCAST(N);
1306 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1307 case ISD::FADD: return visitFADD(N);
1308 case ISD::FSUB: return visitFSUB(N);
1309 case ISD::FMUL: return visitFMUL(N);
1310 case ISD::FMA: return visitFMA(N);
1311 case ISD::FDIV: return visitFDIV(N);
1312 case ISD::FREM: return visitFREM(N);
1313 case ISD::FSQRT: return visitFSQRT(N);
1314 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1315 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1316 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1317 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1318 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1319 case ISD::FP_ROUND: return visitFP_ROUND(N);
1320 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1321 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1322 case ISD::FNEG: return visitFNEG(N);
1323 case ISD::FABS: return visitFABS(N);
1324 case ISD::FFLOOR: return visitFFLOOR(N);
1325 case ISD::FCEIL: return visitFCEIL(N);
1326 case ISD::FTRUNC: return visitFTRUNC(N);
1327 case ISD::BRCOND: return visitBRCOND(N);
1328 case ISD::BR_CC: return visitBR_CC(N);
1329 case ISD::LOAD: return visitLOAD(N);
1330 case ISD::STORE: return visitSTORE(N);
1331 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1332 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1333 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1334 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1335 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1336 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1337 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1342 SDValue DAGCombiner::combine(SDNode *N) {
1343 SDValue RV = visit(N);
1345 // If nothing happened, try a target-specific DAG combine.
1346 if (!RV.getNode()) {
1347 assert(N->getOpcode() != ISD::DELETED_NODE &&
1348 "Node was deleted but visit returned NULL!");
1350 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1351 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1353 // Expose the DAG combiner to the target combiner impls.
1354 TargetLowering::DAGCombinerInfo
1355 DagCombineInfo(DAG, Level, false, this);
1357 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1361 // If nothing happened still, try promoting the operation.
1362 if (!RV.getNode()) {
1363 switch (N->getOpcode()) {
1371 RV = PromoteIntBinOp(SDValue(N, 0));
1376 RV = PromoteIntShiftOp(SDValue(N, 0));
1378 case ISD::SIGN_EXTEND:
1379 case ISD::ZERO_EXTEND:
1380 case ISD::ANY_EXTEND:
1381 RV = PromoteExtend(SDValue(N, 0));
1384 if (PromoteLoad(SDValue(N, 0)))
1390 // If N is a commutative binary node, try commuting it to enable more
1392 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1393 N->getNumValues() == 1) {
1394 SDValue N0 = N->getOperand(0);
1395 SDValue N1 = N->getOperand(1);
1397 // Constant operands are canonicalized to RHS.
1398 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1399 SDValue Ops[] = {N1, N0};
1401 if (const BinaryWithFlagsSDNode *BinNode =
1402 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1403 CSENode = DAG.getNodeIfExists(
1404 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1405 BinNode->hasNoSignedWrap(), BinNode->isExact());
1407 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1410 return SDValue(CSENode, 0);
1417 /// Given a node, return its input chain if it has one, otherwise return a null
1419 static SDValue getInputChainForNode(SDNode *N) {
1420 if (unsigned NumOps = N->getNumOperands()) {
1421 if (N->getOperand(0).getValueType() == MVT::Other)
1422 return N->getOperand(0);
1423 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1424 return N->getOperand(NumOps-1);
1425 for (unsigned i = 1; i < NumOps-1; ++i)
1426 if (N->getOperand(i).getValueType() == MVT::Other)
1427 return N->getOperand(i);
1432 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1433 // If N has two operands, where one has an input chain equal to the other,
1434 // the 'other' chain is redundant.
1435 if (N->getNumOperands() == 2) {
1436 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1437 return N->getOperand(0);
1438 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1439 return N->getOperand(1);
1442 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1443 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1444 SmallPtrSet<SDNode*, 16> SeenOps;
1445 bool Changed = false; // If we should replace this token factor.
1447 // Start out with this token factor.
1450 // Iterate through token factors. The TFs grows when new token factors are
1452 for (unsigned i = 0; i < TFs.size(); ++i) {
1453 SDNode *TF = TFs[i];
1455 // Check each of the operands.
1456 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1457 SDValue Op = TF->getOperand(i);
1459 switch (Op.getOpcode()) {
1460 case ISD::EntryToken:
1461 // Entry tokens don't need to be added to the list. They are
1466 case ISD::TokenFactor:
1467 if (Op.hasOneUse() &&
1468 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1469 // Queue up for processing.
1470 TFs.push_back(Op.getNode());
1471 // Clean up in case the token factor is removed.
1472 AddToWorklist(Op.getNode());
1479 // Only add if it isn't already in the list.
1480 if (SeenOps.insert(Op.getNode()))
1491 // If we've change things around then replace token factor.
1494 // The entry token is the only possible outcome.
1495 Result = DAG.getEntryNode();
1497 // New and improved token factor.
1498 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1501 // Don't add users to work list.
1502 return CombineTo(N, Result, false);
1508 /// MERGE_VALUES can always be eliminated.
1509 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1510 WorklistRemover DeadNodes(*this);
1511 // Replacing results may cause a different MERGE_VALUES to suddenly
1512 // be CSE'd with N, and carry its uses with it. Iterate until no
1513 // uses remain, to ensure that the node can be safely deleted.
1514 // First add the users of this node to the work list so that they
1515 // can be tried again once they have new operands.
1516 AddUsersToWorklist(N);
1518 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1519 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1520 } while (!N->use_empty());
1521 deleteAndRecombine(N);
1522 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1525 SDValue DAGCombiner::visitADD(SDNode *N) {
1526 SDValue N0 = N->getOperand(0);
1527 SDValue N1 = N->getOperand(1);
1528 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1529 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1530 EVT VT = N0.getValueType();
1533 if (VT.isVector()) {
1534 SDValue FoldedVOp = SimplifyVBinOp(N);
1535 if (FoldedVOp.getNode()) return FoldedVOp;
1537 // fold (add x, 0) -> x, vector edition
1538 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1540 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1544 // fold (add x, undef) -> undef
1545 if (N0.getOpcode() == ISD::UNDEF)
1547 if (N1.getOpcode() == ISD::UNDEF)
1549 // fold (add c1, c2) -> c1+c2
1551 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1552 // canonicalize constant to RHS
1554 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1555 // fold (add x, 0) -> x
1556 if (N1C && N1C->isNullValue())
1558 // fold (add Sym, c) -> Sym+c
1559 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1560 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1561 GA->getOpcode() == ISD::GlobalAddress)
1562 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1564 (uint64_t)N1C->getSExtValue());
1565 // fold ((c1-A)+c2) -> (c1+c2)-A
1566 if (N1C && N0.getOpcode() == ISD::SUB)
1567 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1568 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1569 DAG.getConstant(N1C->getAPIntValue()+
1570 N0C->getAPIntValue(), VT),
1573 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1576 // fold ((0-A) + B) -> B-A
1577 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1578 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1579 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1580 // fold (A + (0-B)) -> A-B
1581 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1582 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1583 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1584 // fold (A+(B-A)) -> B
1585 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1586 return N1.getOperand(0);
1587 // fold ((B-A)+A) -> B
1588 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1589 return N0.getOperand(0);
1590 // fold (A+(B-(A+C))) to (B-C)
1591 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1592 N0 == N1.getOperand(1).getOperand(0))
1593 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1594 N1.getOperand(1).getOperand(1));
1595 // fold (A+(B-(C+A))) to (B-C)
1596 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1597 N0 == N1.getOperand(1).getOperand(1))
1598 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1599 N1.getOperand(1).getOperand(0));
1600 // fold (A+((B-A)+or-C)) to (B+or-C)
1601 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1602 N1.getOperand(0).getOpcode() == ISD::SUB &&
1603 N0 == N1.getOperand(0).getOperand(1))
1604 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1605 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1607 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1608 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1609 SDValue N00 = N0.getOperand(0);
1610 SDValue N01 = N0.getOperand(1);
1611 SDValue N10 = N1.getOperand(0);
1612 SDValue N11 = N1.getOperand(1);
1614 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1615 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1616 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1617 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1620 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1621 return SDValue(N, 0);
1623 // fold (a+b) -> (a|b) iff a and b share no bits.
1624 if (VT.isInteger() && !VT.isVector()) {
1625 APInt LHSZero, LHSOne;
1626 APInt RHSZero, RHSOne;
1627 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1629 if (LHSZero.getBoolValue()) {
1630 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1632 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1633 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1634 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1635 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1636 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1641 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1642 if (N1.getOpcode() == ISD::SHL &&
1643 N1.getOperand(0).getOpcode() == ISD::SUB)
1644 if (ConstantSDNode *C =
1645 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1646 if (C->getAPIntValue() == 0)
1647 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1648 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1649 N1.getOperand(0).getOperand(1),
1651 if (N0.getOpcode() == ISD::SHL &&
1652 N0.getOperand(0).getOpcode() == ISD::SUB)
1653 if (ConstantSDNode *C =
1654 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1655 if (C->getAPIntValue() == 0)
1656 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1657 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1658 N0.getOperand(0).getOperand(1),
1661 if (N1.getOpcode() == ISD::AND) {
1662 SDValue AndOp0 = N1.getOperand(0);
1663 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1664 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1665 unsigned DestBits = VT.getScalarType().getSizeInBits();
1667 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1668 // and similar xforms where the inner op is either ~0 or 0.
1669 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1671 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1675 // add (sext i1), X -> sub X, (zext i1)
1676 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1677 N0.getOperand(0).getValueType() == MVT::i1 &&
1678 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1680 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1681 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1687 SDValue DAGCombiner::visitADDC(SDNode *N) {
1688 SDValue N0 = N->getOperand(0);
1689 SDValue N1 = N->getOperand(1);
1690 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1691 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1692 EVT VT = N0.getValueType();
1694 // If the flag result is dead, turn this into an ADD.
1695 if (!N->hasAnyUseOfValue(1))
1696 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1697 DAG.getNode(ISD::CARRY_FALSE,
1698 SDLoc(N), MVT::Glue));
1700 // canonicalize constant to RHS.
1702 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1704 // fold (addc x, 0) -> x + no carry out
1705 if (N1C && N1C->isNullValue())
1706 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1707 SDLoc(N), MVT::Glue));
1709 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1710 APInt LHSZero, LHSOne;
1711 APInt RHSZero, RHSOne;
1712 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1714 if (LHSZero.getBoolValue()) {
1715 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1717 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1718 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1719 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1720 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1721 DAG.getNode(ISD::CARRY_FALSE,
1722 SDLoc(N), MVT::Glue));
1728 SDValue DAGCombiner::visitADDE(SDNode *N) {
1729 SDValue N0 = N->getOperand(0);
1730 SDValue N1 = N->getOperand(1);
1731 SDValue CarryIn = N->getOperand(2);
1732 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1733 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1735 // canonicalize constant to RHS
1737 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1740 // fold (adde x, y, false) -> (addc x, y)
1741 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1742 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1747 // Since it may not be valid to emit a fold to zero for vector initializers
1748 // check if we can before folding.
1749 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1751 bool LegalOperations, bool LegalTypes) {
1753 return DAG.getConstant(0, VT);
1754 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1755 return DAG.getConstant(0, VT);
1759 SDValue DAGCombiner::visitSUB(SDNode *N) {
1760 SDValue N0 = N->getOperand(0);
1761 SDValue N1 = N->getOperand(1);
1762 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1763 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1764 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1765 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1766 EVT VT = N0.getValueType();
1769 if (VT.isVector()) {
1770 SDValue FoldedVOp = SimplifyVBinOp(N);
1771 if (FoldedVOp.getNode()) return FoldedVOp;
1773 // fold (sub x, 0) -> x, vector edition
1774 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1778 // fold (sub x, x) -> 0
1779 // FIXME: Refactor this and xor and other similar operations together.
1781 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1782 // fold (sub c1, c2) -> c1-c2
1784 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1785 // fold (sub x, c) -> (add x, -c)
1787 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1788 DAG.getConstant(-N1C->getAPIntValue(), VT));
1789 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1790 if (N0C && N0C->isAllOnesValue())
1791 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1792 // fold A-(A-B) -> B
1793 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1794 return N1.getOperand(1);
1795 // fold (A+B)-A -> B
1796 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1797 return N0.getOperand(1);
1798 // fold (A+B)-B -> A
1799 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1800 return N0.getOperand(0);
1801 // fold C2-(A+C1) -> (C2-C1)-A
1802 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1803 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1805 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1808 // fold ((A+(B+or-C))-B) -> A+or-C
1809 if (N0.getOpcode() == ISD::ADD &&
1810 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1811 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1812 N0.getOperand(1).getOperand(0) == N1)
1813 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1814 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1815 // fold ((A+(C+B))-B) -> A+C
1816 if (N0.getOpcode() == ISD::ADD &&
1817 N0.getOperand(1).getOpcode() == ISD::ADD &&
1818 N0.getOperand(1).getOperand(1) == N1)
1819 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1820 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1821 // fold ((A-(B-C))-C) -> A-B
1822 if (N0.getOpcode() == ISD::SUB &&
1823 N0.getOperand(1).getOpcode() == ISD::SUB &&
1824 N0.getOperand(1).getOperand(1) == N1)
1825 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1826 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1828 // If either operand of a sub is undef, the result is undef
1829 if (N0.getOpcode() == ISD::UNDEF)
1831 if (N1.getOpcode() == ISD::UNDEF)
1834 // If the relocation model supports it, consider symbol offsets.
1835 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1836 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1837 // fold (sub Sym, c) -> Sym-c
1838 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1839 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1841 (uint64_t)N1C->getSExtValue());
1842 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1843 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1844 if (GA->getGlobal() == GB->getGlobal())
1845 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1852 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1853 SDValue N0 = N->getOperand(0);
1854 SDValue N1 = N->getOperand(1);
1855 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1856 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1857 EVT VT = N0.getValueType();
1859 // If the flag result is dead, turn this into an SUB.
1860 if (!N->hasAnyUseOfValue(1))
1861 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1862 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1865 // fold (subc x, x) -> 0 + no borrow
1867 return CombineTo(N, DAG.getConstant(0, VT),
1868 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1871 // fold (subc x, 0) -> x + no borrow
1872 if (N1C && N1C->isNullValue())
1873 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1876 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1877 if (N0C && N0C->isAllOnesValue())
1878 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1879 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1885 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1886 SDValue N0 = N->getOperand(0);
1887 SDValue N1 = N->getOperand(1);
1888 SDValue CarryIn = N->getOperand(2);
1890 // fold (sube x, y, false) -> (subc x, y)
1891 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1892 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1897 SDValue DAGCombiner::visitMUL(SDNode *N) {
1898 SDValue N0 = N->getOperand(0);
1899 SDValue N1 = N->getOperand(1);
1900 EVT VT = N0.getValueType();
1902 // fold (mul x, undef) -> 0
1903 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1904 return DAG.getConstant(0, VT);
1906 bool N0IsConst = false;
1907 bool N1IsConst = false;
1908 APInt ConstValue0, ConstValue1;
1910 if (VT.isVector()) {
1911 SDValue FoldedVOp = SimplifyVBinOp(N);
1912 if (FoldedVOp.getNode()) return FoldedVOp;
1914 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1915 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1917 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1918 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1920 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1921 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1925 // fold (mul c1, c2) -> c1*c2
1926 if (N0IsConst && N1IsConst)
1927 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1929 // canonicalize constant to RHS
1930 if (N0IsConst && !N1IsConst)
1931 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1932 // fold (mul x, 0) -> 0
1933 if (N1IsConst && ConstValue1 == 0)
1935 // We require a splat of the entire scalar bit width for non-contiguous
1938 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1939 // fold (mul x, 1) -> x
1940 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1942 // fold (mul x, -1) -> 0-x
1943 if (N1IsConst && ConstValue1.isAllOnesValue())
1944 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1945 DAG.getConstant(0, VT), N0);
1946 // fold (mul x, (1 << c)) -> x << c
1947 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1948 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1949 DAG.getConstant(ConstValue1.logBase2(),
1950 getShiftAmountTy(N0.getValueType())));
1951 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1952 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1953 unsigned Log2Val = (-ConstValue1).logBase2();
1954 // FIXME: If the input is something that is easily negated (e.g. a
1955 // single-use add), we should put the negate there.
1956 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1957 DAG.getConstant(0, VT),
1958 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1959 DAG.getConstant(Log2Val,
1960 getShiftAmountTy(N0.getValueType()))));
1964 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1965 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1966 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1967 isa<ConstantSDNode>(N0.getOperand(1)))) {
1968 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1969 N1, N0.getOperand(1));
1970 AddToWorklist(C3.getNode());
1971 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1972 N0.getOperand(0), C3);
1975 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1978 SDValue Sh(nullptr,0), Y(nullptr,0);
1979 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1980 if (N0.getOpcode() == ISD::SHL &&
1981 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1982 isa<ConstantSDNode>(N0.getOperand(1))) &&
1983 N0.getNode()->hasOneUse()) {
1985 } else if (N1.getOpcode() == ISD::SHL &&
1986 isa<ConstantSDNode>(N1.getOperand(1)) &&
1987 N1.getNode()->hasOneUse()) {
1992 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1993 Sh.getOperand(0), Y);
1994 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1995 Mul, Sh.getOperand(1));
1999 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2000 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2001 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2002 isa<ConstantSDNode>(N0.getOperand(1))))
2003 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2004 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2005 N0.getOperand(0), N1),
2006 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2007 N0.getOperand(1), N1));
2010 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2017 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2018 SDValue N0 = N->getOperand(0);
2019 SDValue N1 = N->getOperand(1);
2020 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2021 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2022 EVT VT = N->getValueType(0);
2025 if (VT.isVector()) {
2026 SDValue FoldedVOp = SimplifyVBinOp(N);
2027 if (FoldedVOp.getNode()) return FoldedVOp;
2030 // fold (sdiv c1, c2) -> c1/c2
2031 if (N0C && N1C && !N1C->isNullValue())
2032 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2033 // fold (sdiv X, 1) -> X
2034 if (N1C && N1C->getAPIntValue() == 1LL)
2036 // fold (sdiv X, -1) -> 0-X
2037 if (N1C && N1C->isAllOnesValue())
2038 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2039 DAG.getConstant(0, VT), N0);
2040 // If we know the sign bits of both operands are zero, strength reduce to a
2041 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2042 if (!VT.isVector()) {
2043 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2044 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2048 // fold (sdiv X, pow2) -> simple ops after legalize
2049 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2050 (-N1C->getAPIntValue()).isPowerOf2())) {
2051 // If dividing by powers of two is cheap, then don't perform the following
2053 if (TLI.isPow2SDivCheap())
2056 // Target-specific implementation of sdiv x, pow2.
2057 SDValue Res = BuildSDIVPow2(N);
2061 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2063 // Splat the sign bit into the register
2065 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2066 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2067 getShiftAmountTy(N0.getValueType())));
2068 AddToWorklist(SGN.getNode());
2070 // Add (N0 < 0) ? abs2 - 1 : 0;
2072 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2073 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2074 getShiftAmountTy(SGN.getValueType())));
2075 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2076 AddToWorklist(SRL.getNode());
2077 AddToWorklist(ADD.getNode()); // Divide by pow2
2078 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2079 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2081 // If we're dividing by a positive value, we're done. Otherwise, we must
2082 // negate the result.
2083 if (N1C->getAPIntValue().isNonNegative())
2086 AddToWorklist(SRA.getNode());
2087 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2090 // if integer divide is expensive and we satisfy the requirements, emit an
2091 // alternate sequence.
2092 if (N1C && !TLI.isIntDivCheap()) {
2093 SDValue Op = BuildSDIV(N);
2094 if (Op.getNode()) return Op;
2098 if (N0.getOpcode() == ISD::UNDEF)
2099 return DAG.getConstant(0, VT);
2100 // X / undef -> undef
2101 if (N1.getOpcode() == ISD::UNDEF)
2107 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2108 SDValue N0 = N->getOperand(0);
2109 SDValue N1 = N->getOperand(1);
2110 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2111 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2112 EVT VT = N->getValueType(0);
2115 if (VT.isVector()) {
2116 SDValue FoldedVOp = SimplifyVBinOp(N);
2117 if (FoldedVOp.getNode()) return FoldedVOp;
2120 // fold (udiv c1, c2) -> c1/c2
2121 if (N0C && N1C && !N1C->isNullValue())
2122 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2123 // fold (udiv x, (1 << c)) -> x >>u c
2124 if (N1C && N1C->getAPIntValue().isPowerOf2())
2125 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2126 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2127 getShiftAmountTy(N0.getValueType())));
2128 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2129 if (N1.getOpcode() == ISD::SHL) {
2130 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2131 if (SHC->getAPIntValue().isPowerOf2()) {
2132 EVT ADDVT = N1.getOperand(1).getValueType();
2133 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2135 DAG.getConstant(SHC->getAPIntValue()
2138 AddToWorklist(Add.getNode());
2139 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2143 // fold (udiv x, c) -> alternate
2144 if (N1C && !TLI.isIntDivCheap()) {
2145 SDValue Op = BuildUDIV(N);
2146 if (Op.getNode()) return Op;
2150 if (N0.getOpcode() == ISD::UNDEF)
2151 return DAG.getConstant(0, VT);
2152 // X / undef -> undef
2153 if (N1.getOpcode() == ISD::UNDEF)
2159 SDValue DAGCombiner::visitSREM(SDNode *N) {
2160 SDValue N0 = N->getOperand(0);
2161 SDValue N1 = N->getOperand(1);
2162 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2163 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2164 EVT VT = N->getValueType(0);
2166 // fold (srem c1, c2) -> c1%c2
2167 if (N0C && N1C && !N1C->isNullValue())
2168 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2169 // If we know the sign bits of both operands are zero, strength reduce to a
2170 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2171 if (!VT.isVector()) {
2172 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2173 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2176 // If X/C can be simplified by the division-by-constant logic, lower
2177 // X%C to the equivalent of X-X/C*C.
2178 if (N1C && !N1C->isNullValue()) {
2179 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2180 AddToWorklist(Div.getNode());
2181 SDValue OptimizedDiv = combine(Div.getNode());
2182 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2183 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2185 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2186 AddToWorklist(Mul.getNode());
2192 if (N0.getOpcode() == ISD::UNDEF)
2193 return DAG.getConstant(0, VT);
2194 // X % undef -> undef
2195 if (N1.getOpcode() == ISD::UNDEF)
2201 SDValue DAGCombiner::visitUREM(SDNode *N) {
2202 SDValue N0 = N->getOperand(0);
2203 SDValue N1 = N->getOperand(1);
2204 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2205 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2206 EVT VT = N->getValueType(0);
2208 // fold (urem c1, c2) -> c1%c2
2209 if (N0C && N1C && !N1C->isNullValue())
2210 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2211 // fold (urem x, pow2) -> (and x, pow2-1)
2212 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2213 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2214 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2215 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2216 if (N1.getOpcode() == ISD::SHL) {
2217 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2218 if (SHC->getAPIntValue().isPowerOf2()) {
2220 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2221 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2223 AddToWorklist(Add.getNode());
2224 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2229 // If X/C can be simplified by the division-by-constant logic, lower
2230 // X%C to the equivalent of X-X/C*C.
2231 if (N1C && !N1C->isNullValue()) {
2232 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2233 AddToWorklist(Div.getNode());
2234 SDValue OptimizedDiv = combine(Div.getNode());
2235 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2236 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2238 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2239 AddToWorklist(Mul.getNode());
2245 if (N0.getOpcode() == ISD::UNDEF)
2246 return DAG.getConstant(0, VT);
2247 // X % undef -> undef
2248 if (N1.getOpcode() == ISD::UNDEF)
2254 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2255 SDValue N0 = N->getOperand(0);
2256 SDValue N1 = N->getOperand(1);
2257 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2258 EVT VT = N->getValueType(0);
2261 // fold (mulhs x, 0) -> 0
2262 if (N1C && N1C->isNullValue())
2264 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2265 if (N1C && N1C->getAPIntValue() == 1)
2266 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2267 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2268 getShiftAmountTy(N0.getValueType())));
2269 // fold (mulhs x, undef) -> 0
2270 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2271 return DAG.getConstant(0, VT);
2273 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2275 if (VT.isSimple() && !VT.isVector()) {
2276 MVT Simple = VT.getSimpleVT();
2277 unsigned SimpleSize = Simple.getSizeInBits();
2278 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2279 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2280 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2281 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2282 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2283 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2284 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2285 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2292 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2293 SDValue N0 = N->getOperand(0);
2294 SDValue N1 = N->getOperand(1);
2295 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2296 EVT VT = N->getValueType(0);
2299 // fold (mulhu x, 0) -> 0
2300 if (N1C && N1C->isNullValue())
2302 // fold (mulhu x, 1) -> 0
2303 if (N1C && N1C->getAPIntValue() == 1)
2304 return DAG.getConstant(0, N0.getValueType());
2305 // fold (mulhu x, undef) -> 0
2306 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2307 return DAG.getConstant(0, VT);
2309 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2311 if (VT.isSimple() && !VT.isVector()) {
2312 MVT Simple = VT.getSimpleVT();
2313 unsigned SimpleSize = Simple.getSizeInBits();
2314 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2315 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2316 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2317 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2318 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2319 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2320 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2321 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2328 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2329 /// give the opcodes for the two computations that are being performed. Return
2330 /// true if a simplification was made.
2331 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2333 // If the high half is not needed, just compute the low half.
2334 bool HiExists = N->hasAnyUseOfValue(1);
2336 (!LegalOperations ||
2337 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2338 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2339 return CombineTo(N, Res, Res);
2342 // If the low half is not needed, just compute the high half.
2343 bool LoExists = N->hasAnyUseOfValue(0);
2345 (!LegalOperations ||
2346 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2347 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2348 return CombineTo(N, Res, Res);
2351 // If both halves are used, return as it is.
2352 if (LoExists && HiExists)
2355 // If the two computed results can be simplified separately, separate them.
2357 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2358 AddToWorklist(Lo.getNode());
2359 SDValue LoOpt = combine(Lo.getNode());
2360 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2361 (!LegalOperations ||
2362 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2363 return CombineTo(N, LoOpt, LoOpt);
2367 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2368 AddToWorklist(Hi.getNode());
2369 SDValue HiOpt = combine(Hi.getNode());
2370 if (HiOpt.getNode() && HiOpt != Hi &&
2371 (!LegalOperations ||
2372 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2373 return CombineTo(N, HiOpt, HiOpt);
2379 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2380 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2381 if (Res.getNode()) return Res;
2383 EVT VT = N->getValueType(0);
2386 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2388 if (VT.isSimple() && !VT.isVector()) {
2389 MVT Simple = VT.getSimpleVT();
2390 unsigned SimpleSize = Simple.getSizeInBits();
2391 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2392 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2393 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2394 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2395 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2396 // Compute the high part as N1.
2397 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2398 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2399 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2400 // Compute the low part as N0.
2401 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2402 return CombineTo(N, Lo, Hi);
2409 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2410 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2411 if (Res.getNode()) return Res;
2413 EVT VT = N->getValueType(0);
2416 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2418 if (VT.isSimple() && !VT.isVector()) {
2419 MVT Simple = VT.getSimpleVT();
2420 unsigned SimpleSize = Simple.getSizeInBits();
2421 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2422 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2423 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2424 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2425 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2426 // Compute the high part as N1.
2427 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2428 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2429 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2430 // Compute the low part as N0.
2431 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2432 return CombineTo(N, Lo, Hi);
2439 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2440 // (smulo x, 2) -> (saddo x, x)
2441 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2442 if (C2->getAPIntValue() == 2)
2443 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2444 N->getOperand(0), N->getOperand(0));
2449 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2450 // (umulo x, 2) -> (uaddo x, x)
2451 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2452 if (C2->getAPIntValue() == 2)
2453 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2454 N->getOperand(0), N->getOperand(0));
2459 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2460 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2461 if (Res.getNode()) return Res;
2466 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2467 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2468 if (Res.getNode()) return Res;
2473 /// If this is a binary operator with two operands of the same opcode, try to
2475 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2476 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2477 EVT VT = N0.getValueType();
2478 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2480 // Bail early if none of these transforms apply.
2481 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2483 // For each of OP in AND/OR/XOR:
2484 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2485 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2486 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2487 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2489 // do not sink logical op inside of a vector extend, since it may combine
2491 EVT Op0VT = N0.getOperand(0).getValueType();
2492 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2493 N0.getOpcode() == ISD::SIGN_EXTEND ||
2494 // Avoid infinite looping with PromoteIntBinOp.
2495 (N0.getOpcode() == ISD::ANY_EXTEND &&
2496 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2497 (N0.getOpcode() == ISD::TRUNCATE &&
2498 (!TLI.isZExtFree(VT, Op0VT) ||
2499 !TLI.isTruncateFree(Op0VT, VT)) &&
2500 TLI.isTypeLegal(Op0VT))) &&
2502 Op0VT == N1.getOperand(0).getValueType() &&
2503 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2504 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2505 N0.getOperand(0).getValueType(),
2506 N0.getOperand(0), N1.getOperand(0));
2507 AddToWorklist(ORNode.getNode());
2508 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2511 // For each of OP in SHL/SRL/SRA/AND...
2512 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2513 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2514 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2515 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2516 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2517 N0.getOperand(1) == N1.getOperand(1)) {
2518 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2519 N0.getOperand(0).getValueType(),
2520 N0.getOperand(0), N1.getOperand(0));
2521 AddToWorklist(ORNode.getNode());
2522 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2523 ORNode, N0.getOperand(1));
2526 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2527 // Only perform this optimization after type legalization and before
2528 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2529 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2530 // we don't want to undo this promotion.
2531 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2533 if ((N0.getOpcode() == ISD::BITCAST ||
2534 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2535 Level == AfterLegalizeTypes) {
2536 SDValue In0 = N0.getOperand(0);
2537 SDValue In1 = N1.getOperand(0);
2538 EVT In0Ty = In0.getValueType();
2539 EVT In1Ty = In1.getValueType();
2541 // If both incoming values are integers, and the original types are the
2543 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2544 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2545 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2546 AddToWorklist(Op.getNode());
2551 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2552 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2553 // If both shuffles use the same mask, and both shuffle within a single
2554 // vector, then it is worthwhile to move the swizzle after the operation.
2555 // The type-legalizer generates this pattern when loading illegal
2556 // vector types from memory. In many cases this allows additional shuffle
2558 // There are other cases where moving the shuffle after the xor/and/or
2559 // is profitable even if shuffles don't perform a swizzle.
2560 // If both shuffles use the same mask, and both shuffles have the same first
2561 // or second operand, then it might still be profitable to move the shuffle
2562 // after the xor/and/or operation.
2563 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2564 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2565 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2567 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2568 "Inputs to shuffles are not the same type");
2570 // Check that both shuffles use the same mask. The masks are known to be of
2571 // the same length because the result vector type is the same.
2572 // Check also that shuffles have only one use to avoid introducing extra
2574 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2575 SVN0->getMask().equals(SVN1->getMask())) {
2576 SDValue ShOp = N0->getOperand(1);
2578 // Don't try to fold this node if it requires introducing a
2579 // build vector of all zeros that might be illegal at this stage.
2580 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2582 ShOp = DAG.getConstant(0, VT);
2587 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2588 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2589 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2590 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2591 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2592 N0->getOperand(0), N1->getOperand(0));
2593 AddToWorklist(NewNode.getNode());
2594 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2595 &SVN0->getMask()[0]);
2598 // Don't try to fold this node if it requires introducing a
2599 // build vector of all zeros that might be illegal at this stage.
2600 ShOp = N0->getOperand(0);
2601 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2603 ShOp = DAG.getConstant(0, VT);
2608 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2609 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2610 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2611 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2612 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2613 N0->getOperand(1), N1->getOperand(1));
2614 AddToWorklist(NewNode.getNode());
2615 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2616 &SVN0->getMask()[0]);
2624 SDValue DAGCombiner::visitAND(SDNode *N) {
2625 SDValue N0 = N->getOperand(0);
2626 SDValue N1 = N->getOperand(1);
2627 SDValue LL, LR, RL, RR, CC0, CC1;
2628 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2629 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2630 EVT VT = N1.getValueType();
2631 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2634 if (VT.isVector()) {
2635 SDValue FoldedVOp = SimplifyVBinOp(N);
2636 if (FoldedVOp.getNode()) return FoldedVOp;
2638 // fold (and x, 0) -> 0, vector edition
2639 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2640 // do not return N0, because undef node may exist in N0
2641 return DAG.getConstant(
2642 APInt::getNullValue(
2643 N0.getValueType().getScalarType().getSizeInBits()),
2645 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2646 // do not return N1, because undef node may exist in N1
2647 return DAG.getConstant(
2648 APInt::getNullValue(
2649 N1.getValueType().getScalarType().getSizeInBits()),
2652 // fold (and x, -1) -> x, vector edition
2653 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2655 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2659 // fold (and x, undef) -> 0
2660 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2661 return DAG.getConstant(0, VT);
2662 // fold (and c1, c2) -> c1&c2
2664 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2665 // canonicalize constant to RHS
2667 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2668 // fold (and x, -1) -> x
2669 if (N1C && N1C->isAllOnesValue())
2671 // if (and x, c) is known to be zero, return 0
2672 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2673 APInt::getAllOnesValue(BitWidth)))
2674 return DAG.getConstant(0, VT);
2676 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2679 // fold (and (or x, C), D) -> D if (C & D) == D
2680 if (N1C && N0.getOpcode() == ISD::OR)
2681 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2682 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2684 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2685 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2686 SDValue N0Op0 = N0.getOperand(0);
2687 APInt Mask = ~N1C->getAPIntValue();
2688 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2689 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2690 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2691 N0.getValueType(), N0Op0);
2693 // Replace uses of the AND with uses of the Zero extend node.
2696 // We actually want to replace all uses of the any_extend with the
2697 // zero_extend, to avoid duplicating things. This will later cause this
2698 // AND to be folded.
2699 CombineTo(N0.getNode(), Zext);
2700 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2703 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2704 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2705 // already be zero by virtue of the width of the base type of the load.
2707 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2709 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2710 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2711 N0.getOpcode() == ISD::LOAD) {
2712 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2713 N0 : N0.getOperand(0) );
2715 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2716 // This can be a pure constant or a vector splat, in which case we treat the
2717 // vector as a scalar and use the splat value.
2718 APInt Constant = APInt::getNullValue(1);
2719 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2720 Constant = C->getAPIntValue();
2721 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2722 APInt SplatValue, SplatUndef;
2723 unsigned SplatBitSize;
2725 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2726 SplatBitSize, HasAnyUndefs);
2728 // Undef bits can contribute to a possible optimisation if set, so
2730 SplatValue |= SplatUndef;
2732 // The splat value may be something like "0x00FFFFFF", which means 0 for
2733 // the first vector value and FF for the rest, repeating. We need a mask
2734 // that will apply equally to all members of the vector, so AND all the
2735 // lanes of the constant together.
2736 EVT VT = Vector->getValueType(0);
2737 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2739 // If the splat value has been compressed to a bitlength lower
2740 // than the size of the vector lane, we need to re-expand it to
2742 if (BitWidth > SplatBitSize)
2743 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2744 SplatBitSize < BitWidth;
2745 SplatBitSize = SplatBitSize * 2)
2746 SplatValue |= SplatValue.shl(SplatBitSize);
2748 Constant = APInt::getAllOnesValue(BitWidth);
2749 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2750 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2754 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2755 // actually legal and isn't going to get expanded, else this is a false
2757 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2758 Load->getMemoryVT());
2760 // Resize the constant to the same size as the original memory access before
2761 // extension. If it is still the AllOnesValue then this AND is completely
2764 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2767 switch (Load->getExtensionType()) {
2768 default: B = false; break;
2769 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2771 case ISD::NON_EXTLOAD: B = true; break;
2774 if (B && Constant.isAllOnesValue()) {
2775 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2776 // preserve semantics once we get rid of the AND.
2777 SDValue NewLoad(Load, 0);
2778 if (Load->getExtensionType() == ISD::EXTLOAD) {
2779 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2780 Load->getValueType(0), SDLoc(Load),
2781 Load->getChain(), Load->getBasePtr(),
2782 Load->getOffset(), Load->getMemoryVT(),
2783 Load->getMemOperand());
2784 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2785 if (Load->getNumValues() == 3) {
2786 // PRE/POST_INC loads have 3 values.
2787 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2788 NewLoad.getValue(2) };
2789 CombineTo(Load, To, 3, true);
2791 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2795 // Fold the AND away, taking care not to fold to the old load node if we
2797 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2799 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2802 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2803 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2804 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2805 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2807 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2808 LL.getValueType().isInteger()) {
2809 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2810 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2811 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2812 LR.getValueType(), LL, RL);
2813 AddToWorklist(ORNode.getNode());
2814 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2816 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2817 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2818 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2819 LR.getValueType(), LL, RL);
2820 AddToWorklist(ANDNode.getNode());
2821 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2823 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2824 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2825 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2826 LR.getValueType(), LL, RL);
2827 AddToWorklist(ORNode.getNode());
2828 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2831 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2832 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2833 Op0 == Op1 && LL.getValueType().isInteger() &&
2834 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2835 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2836 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2837 cast<ConstantSDNode>(RR)->isNullValue()))) {
2838 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2839 LL, DAG.getConstant(1, LL.getValueType()));
2840 AddToWorklist(ADDNode.getNode());
2841 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2842 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2844 // canonicalize equivalent to ll == rl
2845 if (LL == RR && LR == RL) {
2846 Op1 = ISD::getSetCCSwappedOperands(Op1);
2849 if (LL == RL && LR == RR) {
2850 bool isInteger = LL.getValueType().isInteger();
2851 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2852 if (Result != ISD::SETCC_INVALID &&
2853 (!LegalOperations ||
2854 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2855 TLI.isOperationLegal(ISD::SETCC,
2856 getSetCCResultType(N0.getSimpleValueType())))))
2857 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2862 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2863 if (N0.getOpcode() == N1.getOpcode()) {
2864 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2865 if (Tmp.getNode()) return Tmp;
2868 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2869 // fold (and (sra)) -> (and (srl)) when possible.
2870 if (!VT.isVector() &&
2871 SimplifyDemandedBits(SDValue(N, 0)))
2872 return SDValue(N, 0);
2874 // fold (zext_inreg (extload x)) -> (zextload x)
2875 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2876 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2877 EVT MemVT = LN0->getMemoryVT();
2878 // If we zero all the possible extended bits, then we can turn this into
2879 // a zextload if we are running before legalize or the operation is legal.
2880 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2881 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2882 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2883 ((!LegalOperations && !LN0->isVolatile()) ||
2884 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2885 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2886 LN0->getChain(), LN0->getBasePtr(),
2887 MemVT, LN0->getMemOperand());
2889 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2890 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2893 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2894 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2896 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2897 EVT MemVT = LN0->getMemoryVT();
2898 // If we zero all the possible extended bits, then we can turn this into
2899 // a zextload if we are running before legalize or the operation is legal.
2900 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2901 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2902 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2903 ((!LegalOperations && !LN0->isVolatile()) ||
2904 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2905 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2906 LN0->getChain(), LN0->getBasePtr(),
2907 MemVT, LN0->getMemOperand());
2909 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2910 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2914 // fold (and (load x), 255) -> (zextload x, i8)
2915 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2916 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2917 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2918 (N0.getOpcode() == ISD::ANY_EXTEND &&
2919 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2920 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2921 LoadSDNode *LN0 = HasAnyExt
2922 ? cast<LoadSDNode>(N0.getOperand(0))
2923 : cast<LoadSDNode>(N0);
2924 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2925 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2926 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2927 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2928 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2929 EVT LoadedVT = LN0->getMemoryVT();
2931 if (ExtVT == LoadedVT &&
2932 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2933 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2936 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2937 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2938 LN0->getMemOperand());
2940 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2941 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2944 // Do not change the width of a volatile load.
2945 // Do not generate loads of non-round integer types since these can
2946 // be expensive (and would be wrong if the type is not byte sized).
2947 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2948 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2949 EVT PtrType = LN0->getOperand(1).getValueType();
2951 unsigned Alignment = LN0->getAlignment();
2952 SDValue NewPtr = LN0->getBasePtr();
2954 // For big endian targets, we need to add an offset to the pointer
2955 // to load the correct bytes. For little endian systems, we merely
2956 // need to read fewer bytes from the same pointer.
2957 if (TLI.isBigEndian()) {
2958 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2959 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2960 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2961 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2962 NewPtr, DAG.getConstant(PtrOff, PtrType));
2963 Alignment = MinAlign(Alignment, PtrOff);
2966 AddToWorklist(NewPtr.getNode());
2968 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2970 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2971 LN0->getChain(), NewPtr,
2972 LN0->getPointerInfo(),
2973 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2974 LN0->isInvariant(), Alignment, LN0->getAAInfo());
2976 CombineTo(LN0, Load, Load.getValue(1));
2977 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2983 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2984 VT.getSizeInBits() <= 64) {
2985 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2986 APInt ADDC = ADDI->getAPIntValue();
2987 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2988 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2989 // immediate for an add, but it is legal if its top c2 bits are set,
2990 // transform the ADD so the immediate doesn't need to be materialized
2992 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2993 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2994 SRLI->getZExtValue());
2995 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2997 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2999 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3000 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3001 CombineTo(N0.getNode(), NewAdd);
3002 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3010 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3011 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3012 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3013 N0.getOperand(1), false);
3014 if (BSwap.getNode())
3021 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3022 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3023 bool DemandHighBits) {
3024 if (!LegalOperations)
3027 EVT VT = N->getValueType(0);
3028 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3030 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3033 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3034 bool LookPassAnd0 = false;
3035 bool LookPassAnd1 = false;
3036 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3038 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3040 if (N0.getOpcode() == ISD::AND) {
3041 if (!N0.getNode()->hasOneUse())
3043 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3044 if (!N01C || N01C->getZExtValue() != 0xFF00)
3046 N0 = N0.getOperand(0);
3047 LookPassAnd0 = true;
3050 if (N1.getOpcode() == ISD::AND) {
3051 if (!N1.getNode()->hasOneUse())
3053 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3054 if (!N11C || N11C->getZExtValue() != 0xFF)
3056 N1 = N1.getOperand(0);
3057 LookPassAnd1 = true;
3060 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3062 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3064 if (!N0.getNode()->hasOneUse() ||
3065 !N1.getNode()->hasOneUse())
3068 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3069 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3072 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3075 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3076 SDValue N00 = N0->getOperand(0);
3077 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3078 if (!N00.getNode()->hasOneUse())
3080 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3081 if (!N001C || N001C->getZExtValue() != 0xFF)
3083 N00 = N00.getOperand(0);
3084 LookPassAnd0 = true;
3087 SDValue N10 = N1->getOperand(0);
3088 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3089 if (!N10.getNode()->hasOneUse())
3091 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3092 if (!N101C || N101C->getZExtValue() != 0xFF00)
3094 N10 = N10.getOperand(0);
3095 LookPassAnd1 = true;
3101 // Make sure everything beyond the low halfword gets set to zero since the SRL
3102 // 16 will clear the top bits.
3103 unsigned OpSizeInBits = VT.getSizeInBits();
3104 if (DemandHighBits && OpSizeInBits > 16) {
3105 // If the left-shift isn't masked out then the only way this is a bswap is
3106 // if all bits beyond the low 8 are 0. In that case the entire pattern
3107 // reduces to a left shift anyway: leave it for other parts of the combiner.
3111 // However, if the right shift isn't masked out then it might be because
3112 // it's not needed. See if we can spot that too.
3113 if (!LookPassAnd1 &&
3114 !DAG.MaskedValueIsZero(
3115 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3119 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3120 if (OpSizeInBits > 16)
3121 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3122 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3126 /// Return true if the specified node is an element that makes up a 32-bit
3127 /// packed halfword byteswap.
3128 /// ((x & 0x000000ff) << 8) |
3129 /// ((x & 0x0000ff00) >> 8) |
3130 /// ((x & 0x00ff0000) << 8) |
3131 /// ((x & 0xff000000) >> 8)
3132 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3133 if (!N.getNode()->hasOneUse())
3136 unsigned Opc = N.getOpcode();
3137 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3140 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3145 switch (N1C->getZExtValue()) {
3148 case 0xFF: Num = 0; break;
3149 case 0xFF00: Num = 1; break;
3150 case 0xFF0000: Num = 2; break;
3151 case 0xFF000000: Num = 3; break;
3154 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3155 SDValue N0 = N.getOperand(0);
3156 if (Opc == ISD::AND) {
3157 if (Num == 0 || Num == 2) {
3159 // (x >> 8) & 0xff0000
3160 if (N0.getOpcode() != ISD::SRL)
3162 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3163 if (!C || C->getZExtValue() != 8)
3166 // (x << 8) & 0xff00
3167 // (x << 8) & 0xff000000
3168 if (N0.getOpcode() != ISD::SHL)
3170 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3171 if (!C || C->getZExtValue() != 8)
3174 } else if (Opc == ISD::SHL) {
3176 // (x & 0xff0000) << 8
3177 if (Num != 0 && Num != 2)
3179 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3180 if (!C || C->getZExtValue() != 8)
3182 } else { // Opc == ISD::SRL
3183 // (x & 0xff00) >> 8
3184 // (x & 0xff000000) >> 8
3185 if (Num != 1 && Num != 3)
3187 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3188 if (!C || C->getZExtValue() != 8)
3195 Parts[Num] = N0.getOperand(0).getNode();
3199 /// Match a 32-bit packed halfword bswap. That is
3200 /// ((x & 0x000000ff) << 8) |
3201 /// ((x & 0x0000ff00) >> 8) |
3202 /// ((x & 0x00ff0000) << 8) |
3203 /// ((x & 0xff000000) >> 8)
3204 /// => (rotl (bswap x), 16)
3205 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3206 if (!LegalOperations)
3209 EVT VT = N->getValueType(0);
3212 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3215 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3217 // (or (or (and), (and)), (or (and), (and)))
3218 // (or (or (or (and), (and)), (and)), (and))
3219 if (N0.getOpcode() != ISD::OR)
3221 SDValue N00 = N0.getOperand(0);
3222 SDValue N01 = N0.getOperand(1);
3224 if (N1.getOpcode() == ISD::OR &&
3225 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3226 // (or (or (and), (and)), (or (and), (and)))
3227 SDValue N000 = N00.getOperand(0);
3228 if (!isBSwapHWordElement(N000, Parts))
3231 SDValue N001 = N00.getOperand(1);
3232 if (!isBSwapHWordElement(N001, Parts))
3234 SDValue N010 = N01.getOperand(0);
3235 if (!isBSwapHWordElement(N010, Parts))
3237 SDValue N011 = N01.getOperand(1);
3238 if (!isBSwapHWordElement(N011, Parts))
3241 // (or (or (or (and), (and)), (and)), (and))
3242 if (!isBSwapHWordElement(N1, Parts))
3244 if (!isBSwapHWordElement(N01, Parts))
3246 if (N00.getOpcode() != ISD::OR)
3248 SDValue N000 = N00.getOperand(0);
3249 if (!isBSwapHWordElement(N000, Parts))
3251 SDValue N001 = N00.getOperand(1);
3252 if (!isBSwapHWordElement(N001, Parts))
3256 // Make sure the parts are all coming from the same node.
3257 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3260 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3261 SDValue(Parts[0],0));
3263 // Result of the bswap should be rotated by 16. If it's not legal, then
3264 // do (x << 16) | (x >> 16).
3265 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3266 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3267 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3268 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3269 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3270 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3271 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3272 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3275 SDValue DAGCombiner::visitOR(SDNode *N) {
3276 SDValue N0 = N->getOperand(0);
3277 SDValue N1 = N->getOperand(1);
3278 SDValue LL, LR, RL, RR, CC0, CC1;
3279 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3280 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3281 EVT VT = N1.getValueType();
3284 if (VT.isVector()) {
3285 SDValue FoldedVOp = SimplifyVBinOp(N);
3286 if (FoldedVOp.getNode()) return FoldedVOp;
3288 // fold (or x, 0) -> x, vector edition
3289 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3291 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3294 // fold (or x, -1) -> -1, vector edition
3295 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3296 // do not return N0, because undef node may exist in N0
3297 return DAG.getConstant(
3298 APInt::getAllOnesValue(
3299 N0.getValueType().getScalarType().getSizeInBits()),
3301 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3302 // do not return N1, because undef node may exist in N1
3303 return DAG.getConstant(
3304 APInt::getAllOnesValue(
3305 N1.getValueType().getScalarType().getSizeInBits()),
3308 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3309 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3310 // Do this only if the resulting shuffle is legal.
3311 if (isa<ShuffleVectorSDNode>(N0) &&
3312 isa<ShuffleVectorSDNode>(N1) &&
3313 // Avoid folding a node with illegal type.
3314 TLI.isTypeLegal(VT) &&
3315 N0->getOperand(1) == N1->getOperand(1) &&
3316 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3317 bool CanFold = true;
3318 unsigned NumElts = VT.getVectorNumElements();
3319 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3320 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3321 // We construct two shuffle masks:
3322 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3323 // and N1 as the second operand.
3324 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3325 // and N0 as the second operand.
3326 // We do this because OR is commutable and therefore there might be
3327 // two ways to fold this node into a shuffle.
3328 SmallVector<int,4> Mask1;
3329 SmallVector<int,4> Mask2;
3331 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3332 int M0 = SV0->getMaskElt(i);
3333 int M1 = SV1->getMaskElt(i);
3335 // Both shuffle indexes are undef. Propagate Undef.
3336 if (M0 < 0 && M1 < 0) {
3337 Mask1.push_back(M0);
3338 Mask2.push_back(M0);
3342 if (M0 < 0 || M1 < 0 ||
3343 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3344 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3349 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3350 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3354 // Fold this sequence only if the resulting shuffle is 'legal'.
3355 if (TLI.isShuffleMaskLegal(Mask1, VT))
3356 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3357 N1->getOperand(0), &Mask1[0]);
3358 if (TLI.isShuffleMaskLegal(Mask2, VT))
3359 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3360 N0->getOperand(0), &Mask2[0]);
3365 // fold (or x, undef) -> -1
3366 if (!LegalOperations &&
3367 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3368 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3369 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3371 // fold (or c1, c2) -> c1|c2
3373 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3374 // canonicalize constant to RHS
3376 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3377 // fold (or x, 0) -> x
3378 if (N1C && N1C->isNullValue())
3380 // fold (or x, -1) -> -1
3381 if (N1C && N1C->isAllOnesValue())
3383 // fold (or x, c) -> c iff (x & ~c) == 0
3384 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3387 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3388 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3389 if (BSwap.getNode())
3391 BSwap = MatchBSwapHWordLow(N, N0, N1);
3392 if (BSwap.getNode())
3396 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3399 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3400 // iff (c1 & c2) == 0.
3401 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3402 isa<ConstantSDNode>(N0.getOperand(1))) {
3403 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3404 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3405 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3408 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3409 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3410 N0.getOperand(0), N1), COR);
3413 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3414 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3415 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3416 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3418 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3419 LL.getValueType().isInteger()) {
3420 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3421 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3422 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3423 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3424 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3425 LR.getValueType(), LL, RL);
3426 AddToWorklist(ORNode.getNode());
3427 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3429 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3430 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3431 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3432 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3433 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3434 LR.getValueType(), LL, RL);
3435 AddToWorklist(ANDNode.getNode());
3436 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3439 // canonicalize equivalent to ll == rl
3440 if (LL == RR && LR == RL) {
3441 Op1 = ISD::getSetCCSwappedOperands(Op1);
3444 if (LL == RL && LR == RR) {
3445 bool isInteger = LL.getValueType().isInteger();
3446 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3447 if (Result != ISD::SETCC_INVALID &&
3448 (!LegalOperations ||
3449 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3450 TLI.isOperationLegal(ISD::SETCC,
3451 getSetCCResultType(N0.getValueType())))))
3452 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3457 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3458 if (N0.getOpcode() == N1.getOpcode()) {
3459 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3460 if (Tmp.getNode()) return Tmp;
3463 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3464 if (N0.getOpcode() == ISD::AND &&
3465 N1.getOpcode() == ISD::AND &&
3466 N0.getOperand(1).getOpcode() == ISD::Constant &&
3467 N1.getOperand(1).getOpcode() == ISD::Constant &&
3468 // Don't increase # computations.
3469 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3470 // We can only do this xform if we know that bits from X that are set in C2
3471 // but not in C1 are already zero. Likewise for Y.
3472 const APInt &LHSMask =
3473 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3474 const APInt &RHSMask =
3475 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3477 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3478 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3479 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3480 N0.getOperand(0), N1.getOperand(0));
3481 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3482 DAG.getConstant(LHSMask | RHSMask, VT));
3486 // See if this is some rotate idiom.
3487 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3488 return SDValue(Rot, 0);
3490 // Simplify the operands using demanded-bits information.
3491 if (!VT.isVector() &&
3492 SimplifyDemandedBits(SDValue(N, 0)))
3493 return SDValue(N, 0);
3498 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3499 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3500 if (Op.getOpcode() == ISD::AND) {
3501 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3502 Mask = Op.getOperand(1);
3503 Op = Op.getOperand(0);
3509 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3517 // Return true if we can prove that, whenever Neg and Pos are both in the
3518 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3519 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3521 // (or (shift1 X, Neg), (shift2 X, Pos))
3523 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3524 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3525 // to consider shift amounts with defined behavior.
3526 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3527 // If OpSize is a power of 2 then:
3529 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3530 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3532 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3533 // for the stronger condition:
3535 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3537 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3538 // we can just replace Neg with Neg' for the rest of the function.
3540 // In other cases we check for the even stronger condition:
3542 // Neg == OpSize - Pos [B]
3544 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3545 // behavior if Pos == 0 (and consequently Neg == OpSize).
3547 // We could actually use [A] whenever OpSize is a power of 2, but the
3548 // only extra cases that it would match are those uninteresting ones
3549 // where Neg and Pos are never in range at the same time. E.g. for
3550 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3551 // as well as (sub 32, Pos), but:
3553 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3555 // always invokes undefined behavior for 32-bit X.
3557 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3558 unsigned MaskLoBits = 0;
3559 if (Neg.getOpcode() == ISD::AND &&
3560 isPowerOf2_64(OpSize) &&
3561 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3562 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3563 Neg = Neg.getOperand(0);
3564 MaskLoBits = Log2_64(OpSize);
3567 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3568 if (Neg.getOpcode() != ISD::SUB)
3570 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3573 SDValue NegOp1 = Neg.getOperand(1);
3575 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3576 // Pos'. The truncation is redundant for the purpose of the equality.
3578 Pos.getOpcode() == ISD::AND &&
3579 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3580 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3581 Pos = Pos.getOperand(0);
3583 // The condition we need is now:
3585 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3587 // If NegOp1 == Pos then we need:
3589 // OpSize & Mask == NegC & Mask
3591 // (because "x & Mask" is a truncation and distributes through subtraction).
3594 Width = NegC->getAPIntValue();
3595 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3596 // Then the condition we want to prove becomes:
3598 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3600 // which, again because "x & Mask" is a truncation, becomes:
3602 // NegC & Mask == (OpSize - PosC) & Mask
3603 // OpSize & Mask == (NegC + PosC) & Mask
3604 else if (Pos.getOpcode() == ISD::ADD &&
3605 Pos.getOperand(0) == NegOp1 &&
3606 Pos.getOperand(1).getOpcode() == ISD::Constant)
3607 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3608 NegC->getAPIntValue());
3612 // Now we just need to check that OpSize & Mask == Width & Mask.
3614 // Opsize & Mask is 0 since Mask is Opsize - 1.
3615 return Width.getLoBits(MaskLoBits) == 0;
3616 return Width == OpSize;
3619 // A subroutine of MatchRotate used once we have found an OR of two opposite
3620 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3621 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3622 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3623 // Neg with outer conversions stripped away.
3624 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3625 SDValue Neg, SDValue InnerPos,
3626 SDValue InnerNeg, unsigned PosOpcode,
3627 unsigned NegOpcode, SDLoc DL) {
3628 // fold (or (shl x, (*ext y)),
3629 // (srl x, (*ext (sub 32, y)))) ->
3630 // (rotl x, y) or (rotr x, (sub 32, y))
3632 // fold (or (shl x, (*ext (sub 32, y))),
3633 // (srl x, (*ext y))) ->
3634 // (rotr x, y) or (rotl x, (sub 32, y))
3635 EVT VT = Shifted.getValueType();
3636 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3637 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3638 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3639 HasPos ? Pos : Neg).getNode();
3645 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3646 // idioms for rotate, and if the target supports rotation instructions, generate
3648 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3649 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3650 EVT VT = LHS.getValueType();
3651 if (!TLI.isTypeLegal(VT)) return nullptr;
3653 // The target must have at least one rotate flavor.
3654 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3655 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3656 if (!HasROTL && !HasROTR) return nullptr;
3658 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3659 SDValue LHSShift; // The shift.
3660 SDValue LHSMask; // AND value if any.
3661 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3662 return nullptr; // Not part of a rotate.
3664 SDValue RHSShift; // The shift.
3665 SDValue RHSMask; // AND value if any.
3666 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3667 return nullptr; // Not part of a rotate.
3669 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3670 return nullptr; // Not shifting the same value.
3672 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3673 return nullptr; // Shifts must disagree.
3675 // Canonicalize shl to left side in a shl/srl pair.
3676 if (RHSShift.getOpcode() == ISD::SHL) {
3677 std::swap(LHS, RHS);
3678 std::swap(LHSShift, RHSShift);
3679 std::swap(LHSMask , RHSMask );
3682 unsigned OpSizeInBits = VT.getSizeInBits();
3683 SDValue LHSShiftArg = LHSShift.getOperand(0);
3684 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3685 SDValue RHSShiftArg = RHSShift.getOperand(0);
3686 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3688 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3689 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3690 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3691 RHSShiftAmt.getOpcode() == ISD::Constant) {
3692 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3693 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3694 if ((LShVal + RShVal) != OpSizeInBits)
3697 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3698 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3700 // If there is an AND of either shifted operand, apply it to the result.
3701 if (LHSMask.getNode() || RHSMask.getNode()) {
3702 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3704 if (LHSMask.getNode()) {
3705 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3706 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3708 if (RHSMask.getNode()) {
3709 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3710 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3713 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3716 return Rot.getNode();
3719 // If there is a mask here, and we have a variable shift, we can't be sure
3720 // that we're masking out the right stuff.
3721 if (LHSMask.getNode() || RHSMask.getNode())
3724 // If the shift amount is sign/zext/any-extended just peel it off.
3725 SDValue LExtOp0 = LHSShiftAmt;
3726 SDValue RExtOp0 = RHSShiftAmt;
3727 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3728 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3729 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3730 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3731 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3732 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3733 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3734 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3735 LExtOp0 = LHSShiftAmt.getOperand(0);
3736 RExtOp0 = RHSShiftAmt.getOperand(0);
3739 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3740 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3744 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3745 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3752 SDValue DAGCombiner::visitXOR(SDNode *N) {
3753 SDValue N0 = N->getOperand(0);
3754 SDValue N1 = N->getOperand(1);
3755 SDValue LHS, RHS, CC;
3756 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3757 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3758 EVT VT = N0.getValueType();
3761 if (VT.isVector()) {
3762 SDValue FoldedVOp = SimplifyVBinOp(N);
3763 if (FoldedVOp.getNode()) return FoldedVOp;
3765 // fold (xor x, 0) -> x, vector edition
3766 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3768 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3772 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3773 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3774 return DAG.getConstant(0, VT);
3775 // fold (xor x, undef) -> undef
3776 if (N0.getOpcode() == ISD::UNDEF)
3778 if (N1.getOpcode() == ISD::UNDEF)
3780 // fold (xor c1, c2) -> c1^c2
3782 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3783 // canonicalize constant to RHS
3785 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3786 // fold (xor x, 0) -> x
3787 if (N1C && N1C->isNullValue())
3790 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3794 // fold !(x cc y) -> (x !cc y)
3795 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3796 bool isInt = LHS.getValueType().isInteger();
3797 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3800 if (!LegalOperations ||
3801 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3802 switch (N0.getOpcode()) {
3804 llvm_unreachable("Unhandled SetCC Equivalent!");
3806 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3807 case ISD::SELECT_CC:
3808 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3809 N0.getOperand(3), NotCC);
3814 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3815 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3816 N0.getNode()->hasOneUse() &&
3817 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3818 SDValue V = N0.getOperand(0);
3819 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3820 DAG.getConstant(1, V.getValueType()));
3821 AddToWorklist(V.getNode());
3822 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3825 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3826 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3827 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3828 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3829 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3830 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3831 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3832 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3833 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3834 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3837 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3838 if (N1C && N1C->isAllOnesValue() &&
3839 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3840 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3841 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3842 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3843 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3844 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3845 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3846 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3849 // fold (xor (and x, y), y) -> (and (not x), y)
3850 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3851 N0->getOperand(1) == N1) {
3852 SDValue X = N0->getOperand(0);
3853 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3854 AddToWorklist(NotX.getNode());
3855 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3857 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3858 if (N1C && N0.getOpcode() == ISD::XOR) {
3859 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3860 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3862 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3863 DAG.getConstant(N1C->getAPIntValue() ^
3864 N00C->getAPIntValue(), VT));
3866 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3867 DAG.getConstant(N1C->getAPIntValue() ^
3868 N01C->getAPIntValue(), VT));
3870 // fold (xor x, x) -> 0
3872 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3874 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3875 if (N0.getOpcode() == N1.getOpcode()) {
3876 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3877 if (Tmp.getNode()) return Tmp;
3880 // Simplify the expression using non-local knowledge.
3881 if (!VT.isVector() &&
3882 SimplifyDemandedBits(SDValue(N, 0)))
3883 return SDValue(N, 0);
3888 /// Handle transforms common to the three shifts, when the shift amount is a
3890 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3891 // We can't and shouldn't fold opaque constants.
3892 if (Amt->isOpaque())
3895 SDNode *LHS = N->getOperand(0).getNode();
3896 if (!LHS->hasOneUse()) return SDValue();
3898 // We want to pull some binops through shifts, so that we have (and (shift))
3899 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3900 // thing happens with address calculations, so it's important to canonicalize
3902 bool HighBitSet = false; // Can we transform this if the high bit is set?
3904 switch (LHS->getOpcode()) {
3905 default: return SDValue();
3908 HighBitSet = false; // We can only transform sra if the high bit is clear.
3911 HighBitSet = true; // We can only transform sra if the high bit is set.
3914 if (N->getOpcode() != ISD::SHL)
3915 return SDValue(); // only shl(add) not sr[al](add).
3916 HighBitSet = false; // We can only transform sra if the high bit is clear.
3920 // We require the RHS of the binop to be a constant and not opaque as well.
3921 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3922 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3924 // FIXME: disable this unless the input to the binop is a shift by a constant.
3925 // If it is not a shift, it pessimizes some common cases like:
3927 // void foo(int *X, int i) { X[i & 1235] = 1; }
3928 // int bar(int *X, int i) { return X[i & 255]; }
3929 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3930 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3931 BinOpLHSVal->getOpcode() != ISD::SRA &&
3932 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3933 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3936 EVT VT = N->getValueType(0);
3938 // If this is a signed shift right, and the high bit is modified by the
3939 // logical operation, do not perform the transformation. The highBitSet
3940 // boolean indicates the value of the high bit of the constant which would
3941 // cause it to be modified for this operation.
3942 if (N->getOpcode() == ISD::SRA) {
3943 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3944 if (BinOpRHSSignSet != HighBitSet)
3948 if (!TLI.isDesirableToCommuteWithShift(LHS))
3951 // Fold the constants, shifting the binop RHS by the shift amount.
3952 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3954 LHS->getOperand(1), N->getOperand(1));
3955 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3957 // Create the new shift.
3958 SDValue NewShift = DAG.getNode(N->getOpcode(),
3959 SDLoc(LHS->getOperand(0)),
3960 VT, LHS->getOperand(0), N->getOperand(1));
3962 // Create the new binop.
3963 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3966 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3967 assert(N->getOpcode() == ISD::TRUNCATE);
3968 assert(N->getOperand(0).getOpcode() == ISD::AND);
3970 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3971 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3972 SDValue N01 = N->getOperand(0).getOperand(1);
3974 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3975 EVT TruncVT = N->getValueType(0);
3976 SDValue N00 = N->getOperand(0).getOperand(0);
3977 APInt TruncC = N01C->getAPIntValue();
3978 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3980 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3981 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3982 DAG.getConstant(TruncC, TruncVT));
3989 SDValue DAGCombiner::visitRotate(SDNode *N) {
3990 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3991 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3992 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3993 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3994 if (NewOp1.getNode())
3995 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3996 N->getOperand(0), NewOp1);
4001 SDValue DAGCombiner::visitSHL(SDNode *N) {
4002 SDValue N0 = N->getOperand(0);
4003 SDValue N1 = N->getOperand(1);
4004 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4005 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4006 EVT VT = N0.getValueType();
4007 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4010 if (VT.isVector()) {
4011 SDValue FoldedVOp = SimplifyVBinOp(N);
4012 if (FoldedVOp.getNode()) return FoldedVOp;
4014 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4015 // If setcc produces all-one true value then:
4016 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4017 if (N1CV && N1CV->isConstant()) {
4018 if (N0.getOpcode() == ISD::AND) {
4019 SDValue N00 = N0->getOperand(0);
4020 SDValue N01 = N0->getOperand(1);
4021 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4023 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4024 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4025 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4026 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4028 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4031 N1C = isConstOrConstSplat(N1);
4036 // fold (shl c1, c2) -> c1<<c2
4038 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4039 // fold (shl 0, x) -> 0
4040 if (N0C && N0C->isNullValue())
4042 // fold (shl x, c >= size(x)) -> undef
4043 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4044 return DAG.getUNDEF(VT);
4045 // fold (shl x, 0) -> x
4046 if (N1C && N1C->isNullValue())
4048 // fold (shl undef, x) -> 0
4049 if (N0.getOpcode() == ISD::UNDEF)
4050 return DAG.getConstant(0, VT);
4051 // if (shl x, c) is known to be zero, return 0
4052 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4053 APInt::getAllOnesValue(OpSizeInBits)))
4054 return DAG.getConstant(0, VT);
4055 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4056 if (N1.getOpcode() == ISD::TRUNCATE &&
4057 N1.getOperand(0).getOpcode() == ISD::AND) {
4058 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4059 if (NewOp1.getNode())
4060 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4063 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4064 return SDValue(N, 0);
4066 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4067 if (N1C && N0.getOpcode() == ISD::SHL) {
4068 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4069 uint64_t c1 = N0C1->getZExtValue();
4070 uint64_t c2 = N1C->getZExtValue();
4071 if (c1 + c2 >= OpSizeInBits)
4072 return DAG.getConstant(0, VT);
4073 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4074 DAG.getConstant(c1 + c2, N1.getValueType()));
4078 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4079 // For this to be valid, the second form must not preserve any of the bits
4080 // that are shifted out by the inner shift in the first form. This means
4081 // the outer shift size must be >= the number of bits added by the ext.
4082 // As a corollary, we don't care what kind of ext it is.
4083 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4084 N0.getOpcode() == ISD::ANY_EXTEND ||
4085 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4086 N0.getOperand(0).getOpcode() == ISD::SHL) {
4087 SDValue N0Op0 = N0.getOperand(0);
4088 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4089 uint64_t c1 = N0Op0C1->getZExtValue();
4090 uint64_t c2 = N1C->getZExtValue();
4091 EVT InnerShiftVT = N0Op0.getValueType();
4092 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4093 if (c2 >= OpSizeInBits - InnerShiftSize) {
4094 if (c1 + c2 >= OpSizeInBits)
4095 return DAG.getConstant(0, VT);
4096 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4097 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4098 N0Op0->getOperand(0)),
4099 DAG.getConstant(c1 + c2, N1.getValueType()));
4104 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4105 // Only fold this if the inner zext has no other uses to avoid increasing
4106 // the total number of instructions.
4107 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4108 N0.getOperand(0).getOpcode() == ISD::SRL) {
4109 SDValue N0Op0 = N0.getOperand(0);
4110 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4111 uint64_t c1 = N0Op0C1->getZExtValue();
4112 if (c1 < VT.getScalarSizeInBits()) {
4113 uint64_t c2 = N1C->getZExtValue();
4115 SDValue NewOp0 = N0.getOperand(0);
4116 EVT CountVT = NewOp0.getOperand(1).getValueType();
4117 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4118 NewOp0, DAG.getConstant(c2, CountVT));
4119 AddToWorklist(NewSHL.getNode());
4120 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4126 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4127 // (and (srl x, (sub c1, c2), MASK)
4128 // Only fold this if the inner shift has no other uses -- if it does, folding
4129 // this will increase the total number of instructions.
4130 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4131 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4132 uint64_t c1 = N0C1->getZExtValue();
4133 if (c1 < OpSizeInBits) {
4134 uint64_t c2 = N1C->getZExtValue();
4135 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4138 Mask = Mask.shl(c2 - c1);
4139 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4140 DAG.getConstant(c2 - c1, N1.getValueType()));
4142 Mask = Mask.lshr(c1 - c2);
4143 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4144 DAG.getConstant(c1 - c2, N1.getValueType()));
4146 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4147 DAG.getConstant(Mask, VT));
4151 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4152 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4153 unsigned BitSize = VT.getScalarSizeInBits();
4154 SDValue HiBitsMask =
4155 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4156 BitSize - N1C->getZExtValue()), VT);
4157 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4161 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4162 // Variant of version done on multiply, except mul by a power of 2 is turned
4165 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4166 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4167 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4168 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4169 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4170 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4174 SDValue NewSHL = visitShiftByConstant(N, N1C);
4175 if (NewSHL.getNode())
4182 SDValue DAGCombiner::visitSRA(SDNode *N) {
4183 SDValue N0 = N->getOperand(0);
4184 SDValue N1 = N->getOperand(1);
4185 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4186 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4187 EVT VT = N0.getValueType();
4188 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4191 if (VT.isVector()) {
4192 SDValue FoldedVOp = SimplifyVBinOp(N);
4193 if (FoldedVOp.getNode()) return FoldedVOp;
4195 N1C = isConstOrConstSplat(N1);
4198 // fold (sra c1, c2) -> (sra c1, c2)
4200 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4201 // fold (sra 0, x) -> 0
4202 if (N0C && N0C->isNullValue())
4204 // fold (sra -1, x) -> -1
4205 if (N0C && N0C->isAllOnesValue())
4207 // fold (sra x, (setge c, size(x))) -> undef
4208 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4209 return DAG.getUNDEF(VT);
4210 // fold (sra x, 0) -> x
4211 if (N1C && N1C->isNullValue())
4213 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4215 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4216 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4217 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4219 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4220 ExtVT, VT.getVectorNumElements());
4221 if ((!LegalOperations ||
4222 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4223 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4224 N0.getOperand(0), DAG.getValueType(ExtVT));
4227 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4228 if (N1C && N0.getOpcode() == ISD::SRA) {
4229 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4230 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4231 if (Sum >= OpSizeInBits)
4232 Sum = OpSizeInBits - 1;
4233 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4234 DAG.getConstant(Sum, N1.getValueType()));
4238 // fold (sra (shl X, m), (sub result_size, n))
4239 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4240 // result_size - n != m.
4241 // If truncate is free for the target sext(shl) is likely to result in better
4243 if (N0.getOpcode() == ISD::SHL && N1C) {
4244 // Get the two constanst of the shifts, CN0 = m, CN = n.
4245 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4247 LLVMContext &Ctx = *DAG.getContext();
4248 // Determine what the truncate's result bitsize and type would be.
4249 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4252 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4254 // Determine the residual right-shift amount.
4255 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4257 // If the shift is not a no-op (in which case this should be just a sign
4258 // extend already), the truncated to type is legal, sign_extend is legal
4259 // on that type, and the truncate to that type is both legal and free,
4260 // perform the transform.
4261 if ((ShiftAmt > 0) &&
4262 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4263 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4264 TLI.isTruncateFree(VT, TruncVT)) {
4266 SDValue Amt = DAG.getConstant(ShiftAmt,
4267 getShiftAmountTy(N0.getOperand(0).getValueType()));
4268 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4269 N0.getOperand(0), Amt);
4270 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4272 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4273 N->getValueType(0), Trunc);
4278 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4279 if (N1.getOpcode() == ISD::TRUNCATE &&
4280 N1.getOperand(0).getOpcode() == ISD::AND) {
4281 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4282 if (NewOp1.getNode())
4283 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4286 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4287 // if c1 is equal to the number of bits the trunc removes
4288 if (N0.getOpcode() == ISD::TRUNCATE &&
4289 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4290 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4291 N0.getOperand(0).hasOneUse() &&
4292 N0.getOperand(0).getOperand(1).hasOneUse() &&
4294 SDValue N0Op0 = N0.getOperand(0);
4295 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4296 unsigned LargeShiftVal = LargeShift->getZExtValue();
4297 EVT LargeVT = N0Op0.getValueType();
4299 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4301 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4302 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4303 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4304 N0Op0.getOperand(0), Amt);
4305 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4310 // Simplify, based on bits shifted out of the LHS.
4311 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4312 return SDValue(N, 0);
4315 // If the sign bit is known to be zero, switch this to a SRL.
4316 if (DAG.SignBitIsZero(N0))
4317 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4320 SDValue NewSRA = visitShiftByConstant(N, N1C);
4321 if (NewSRA.getNode())
4328 SDValue DAGCombiner::visitSRL(SDNode *N) {
4329 SDValue N0 = N->getOperand(0);
4330 SDValue N1 = N->getOperand(1);
4331 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4332 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4333 EVT VT = N0.getValueType();
4334 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4337 if (VT.isVector()) {
4338 SDValue FoldedVOp = SimplifyVBinOp(N);
4339 if (FoldedVOp.getNode()) return FoldedVOp;
4341 N1C = isConstOrConstSplat(N1);
4344 // fold (srl c1, c2) -> c1 >>u c2
4346 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4347 // fold (srl 0, x) -> 0
4348 if (N0C && N0C->isNullValue())
4350 // fold (srl x, c >= size(x)) -> undef
4351 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4352 return DAG.getUNDEF(VT);
4353 // fold (srl x, 0) -> x
4354 if (N1C && N1C->isNullValue())
4356 // if (srl x, c) is known to be zero, return 0
4357 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4358 APInt::getAllOnesValue(OpSizeInBits)))
4359 return DAG.getConstant(0, VT);
4361 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4362 if (N1C && N0.getOpcode() == ISD::SRL) {
4363 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4364 uint64_t c1 = N01C->getZExtValue();
4365 uint64_t c2 = N1C->getZExtValue();
4366 if (c1 + c2 >= OpSizeInBits)
4367 return DAG.getConstant(0, VT);
4368 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4369 DAG.getConstant(c1 + c2, N1.getValueType()));
4373 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4374 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4375 N0.getOperand(0).getOpcode() == ISD::SRL &&
4376 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4378 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4379 uint64_t c2 = N1C->getZExtValue();
4380 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4381 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4382 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4383 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4384 if (c1 + OpSizeInBits == InnerShiftSize) {
4385 if (c1 + c2 >= InnerShiftSize)
4386 return DAG.getConstant(0, VT);
4387 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4388 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4389 N0.getOperand(0)->getOperand(0),
4390 DAG.getConstant(c1 + c2, ShiftCountVT)));
4394 // fold (srl (shl x, c), c) -> (and x, cst2)
4395 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4396 unsigned BitSize = N0.getScalarValueSizeInBits();
4397 if (BitSize <= 64) {
4398 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4399 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4400 DAG.getConstant(~0ULL >> ShAmt, VT));
4404 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4405 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4406 // Shifting in all undef bits?
4407 EVT SmallVT = N0.getOperand(0).getValueType();
4408 unsigned BitSize = SmallVT.getScalarSizeInBits();
4409 if (N1C->getZExtValue() >= BitSize)
4410 return DAG.getUNDEF(VT);
4412 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4413 uint64_t ShiftAmt = N1C->getZExtValue();
4414 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4416 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4417 AddToWorklist(SmallShift.getNode());
4418 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4419 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4420 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4421 DAG.getConstant(Mask, VT));
4425 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4426 // bit, which is unmodified by sra.
4427 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4428 if (N0.getOpcode() == ISD::SRA)
4429 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4432 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4433 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4434 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4435 APInt KnownZero, KnownOne;
4436 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4438 // If any of the input bits are KnownOne, then the input couldn't be all
4439 // zeros, thus the result of the srl will always be zero.
4440 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4442 // If all of the bits input the to ctlz node are known to be zero, then
4443 // the result of the ctlz is "32" and the result of the shift is one.
4444 APInt UnknownBits = ~KnownZero;
4445 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4447 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4448 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4449 // Okay, we know that only that the single bit specified by UnknownBits
4450 // could be set on input to the CTLZ node. If this bit is set, the SRL
4451 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4452 // to an SRL/XOR pair, which is likely to simplify more.
4453 unsigned ShAmt = UnknownBits.countTrailingZeros();
4454 SDValue Op = N0.getOperand(0);
4457 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4458 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4459 AddToWorklist(Op.getNode());
4462 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4463 Op, DAG.getConstant(1, VT));
4467 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4468 if (N1.getOpcode() == ISD::TRUNCATE &&
4469 N1.getOperand(0).getOpcode() == ISD::AND) {
4470 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4471 if (NewOp1.getNode())
4472 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4475 // fold operands of srl based on knowledge that the low bits are not
4477 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4478 return SDValue(N, 0);
4481 SDValue NewSRL = visitShiftByConstant(N, N1C);
4482 if (NewSRL.getNode())
4486 // Attempt to convert a srl of a load into a narrower zero-extending load.
4487 SDValue NarrowLoad = ReduceLoadWidth(N);
4488 if (NarrowLoad.getNode())
4491 // Here is a common situation. We want to optimize:
4494 // %b = and i32 %a, 2
4495 // %c = srl i32 %b, 1
4496 // brcond i32 %c ...
4502 // %c = setcc eq %b, 0
4505 // However when after the source operand of SRL is optimized into AND, the SRL
4506 // itself may not be optimized further. Look for it and add the BRCOND into
4508 if (N->hasOneUse()) {
4509 SDNode *Use = *N->use_begin();
4510 if (Use->getOpcode() == ISD::BRCOND)
4512 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4513 // Also look pass the truncate.
4514 Use = *Use->use_begin();
4515 if (Use->getOpcode() == ISD::BRCOND)
4523 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4524 SDValue N0 = N->getOperand(0);
4525 EVT VT = N->getValueType(0);
4527 // fold (ctlz c1) -> c2
4528 if (isa<ConstantSDNode>(N0))
4529 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4533 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4534 SDValue N0 = N->getOperand(0);
4535 EVT VT = N->getValueType(0);
4537 // fold (ctlz_zero_undef c1) -> c2
4538 if (isa<ConstantSDNode>(N0))
4539 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4543 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4544 SDValue N0 = N->getOperand(0);
4545 EVT VT = N->getValueType(0);
4547 // fold (cttz c1) -> c2
4548 if (isa<ConstantSDNode>(N0))
4549 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4553 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4554 SDValue N0 = N->getOperand(0);
4555 EVT VT = N->getValueType(0);
4557 // fold (cttz_zero_undef c1) -> c2
4558 if (isa<ConstantSDNode>(N0))
4559 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4563 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4564 SDValue N0 = N->getOperand(0);
4565 EVT VT = N->getValueType(0);
4567 // fold (ctpop c1) -> c2
4568 if (isa<ConstantSDNode>(N0))
4569 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4573 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4574 SDValue N0 = N->getOperand(0);
4575 SDValue N1 = N->getOperand(1);
4576 SDValue N2 = N->getOperand(2);
4577 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4578 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4579 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4580 EVT VT = N->getValueType(0);
4581 EVT VT0 = N0.getValueType();
4583 // fold (select C, X, X) -> X
4586 // fold (select true, X, Y) -> X
4587 if (N0C && !N0C->isNullValue())
4589 // fold (select false, X, Y) -> Y
4590 if (N0C && N0C->isNullValue())
4592 // fold (select C, 1, X) -> (or C, X)
4593 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4594 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4595 // fold (select C, 0, 1) -> (xor C, 1)
4596 // We can't do this reliably if integer based booleans have different contents
4597 // to floating point based booleans. This is because we can't tell whether we
4598 // have an integer-based boolean or a floating-point-based boolean unless we
4599 // can find the SETCC that produced it and inspect its operands. This is
4600 // fairly easy if C is the SETCC node, but it can potentially be
4601 // undiscoverable (or not reasonably discoverable). For example, it could be
4602 // in another basic block or it could require searching a complicated
4604 if (VT.isInteger() &&
4605 (VT0 == MVT::i1 || (VT0.isInteger() &&
4606 TLI.getBooleanContents(false, false) ==
4607 TLI.getBooleanContents(false, true) &&
4608 TLI.getBooleanContents(false, false) ==
4609 TargetLowering::ZeroOrOneBooleanContent)) &&
4610 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4613 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4614 N0, DAG.getConstant(1, VT0));
4615 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4616 N0, DAG.getConstant(1, VT0));
4617 AddToWorklist(XORNode.getNode());
4619 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4620 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4622 // fold (select C, 0, X) -> (and (not C), X)
4623 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4624 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4625 AddToWorklist(NOTNode.getNode());
4626 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4628 // fold (select C, X, 1) -> (or (not C), X)
4629 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4630 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4631 AddToWorklist(NOTNode.getNode());
4632 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4634 // fold (select C, X, 0) -> (and C, X)
4635 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4636 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4637 // fold (select X, X, Y) -> (or X, Y)
4638 // fold (select X, 1, Y) -> (or X, Y)
4639 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4640 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4641 // fold (select X, Y, X) -> (and X, Y)
4642 // fold (select X, Y, 0) -> (and X, Y)
4643 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4644 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4646 // If we can fold this based on the true/false value, do so.
4647 if (SimplifySelectOps(N, N1, N2))
4648 return SDValue(N, 0); // Don't revisit N.
4650 // fold selects based on a setcc into other things, such as min/max/abs
4651 if (N0.getOpcode() == ISD::SETCC) {
4652 if ((!LegalOperations &&
4653 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4654 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4655 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4656 N0.getOperand(0), N0.getOperand(1),
4657 N1, N2, N0.getOperand(2));
4658 return SimplifySelect(SDLoc(N), N0, N1, N2);
4665 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4668 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4670 // Split the inputs.
4671 SDValue Lo, Hi, LL, LH, RL, RH;
4672 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4673 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4675 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4676 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4678 return std::make_pair(Lo, Hi);
4681 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4682 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4683 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4685 SDValue Cond = N->getOperand(0);
4686 SDValue LHS = N->getOperand(1);
4687 SDValue RHS = N->getOperand(2);
4688 EVT VT = N->getValueType(0);
4689 int NumElems = VT.getVectorNumElements();
4690 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4691 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4692 Cond.getOpcode() == ISD::BUILD_VECTOR);
4694 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4695 // binary ones here.
4696 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4699 // We're sure we have an even number of elements due to the
4700 // concat_vectors we have as arguments to vselect.
4701 // Skip BV elements until we find one that's not an UNDEF
4702 // After we find an UNDEF element, keep looping until we get to half the
4703 // length of the BV and see if all the non-undef nodes are the same.
4704 ConstantSDNode *BottomHalf = nullptr;
4705 for (int i = 0; i < NumElems / 2; ++i) {
4706 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4709 if (BottomHalf == nullptr)
4710 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4711 else if (Cond->getOperand(i).getNode() != BottomHalf)
4715 // Do the same for the second half of the BuildVector
4716 ConstantSDNode *TopHalf = nullptr;
4717 for (int i = NumElems / 2; i < NumElems; ++i) {
4718 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4721 if (TopHalf == nullptr)
4722 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4723 else if (Cond->getOperand(i).getNode() != TopHalf)
4727 assert(TopHalf && BottomHalf &&
4728 "One half of the selector was all UNDEFs and the other was all the "
4729 "same value. This should have been addressed before this function.");
4731 ISD::CONCAT_VECTORS, dl, VT,
4732 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4733 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4736 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4737 SDValue N0 = N->getOperand(0);
4738 SDValue N1 = N->getOperand(1);
4739 SDValue N2 = N->getOperand(2);
4742 // Canonicalize integer abs.
4743 // vselect (setg[te] X, 0), X, -X ->
4744 // vselect (setgt X, -1), X, -X ->
4745 // vselect (setl[te] X, 0), -X, X ->
4746 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4747 if (N0.getOpcode() == ISD::SETCC) {
4748 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4749 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4751 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4753 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4754 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4755 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4756 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4757 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4758 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4759 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4762 EVT VT = LHS.getValueType();
4763 SDValue Shift = DAG.getNode(
4764 ISD::SRA, DL, VT, LHS,
4765 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4766 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4767 AddToWorklist(Shift.getNode());
4768 AddToWorklist(Add.getNode());
4769 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4773 // If the VSELECT result requires splitting and the mask is provided by a
4774 // SETCC, then split both nodes and its operands before legalization. This
4775 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4776 // and enables future optimizations (e.g. min/max pattern matching on X86).
4777 if (N0.getOpcode() == ISD::SETCC) {
4778 EVT VT = N->getValueType(0);
4780 // Check if any splitting is required.
4781 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4782 TargetLowering::TypeSplitVector)
4785 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4786 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4787 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4788 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4790 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4791 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4793 // Add the new VSELECT nodes to the work list in case they need to be split
4795 AddToWorklist(Lo.getNode());
4796 AddToWorklist(Hi.getNode());
4798 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4801 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4802 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4804 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4805 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4808 // The ConvertSelectToConcatVector function is assuming both the above
4809 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4811 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4812 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4813 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4814 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4822 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4823 SDValue N0 = N->getOperand(0);
4824 SDValue N1 = N->getOperand(1);
4825 SDValue N2 = N->getOperand(2);
4826 SDValue N3 = N->getOperand(3);
4827 SDValue N4 = N->getOperand(4);
4828 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4830 // fold select_cc lhs, rhs, x, x, cc -> x
4834 // Determine if the condition we're dealing with is constant
4835 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4836 N0, N1, CC, SDLoc(N), false);
4837 if (SCC.getNode()) {
4838 AddToWorklist(SCC.getNode());
4840 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4841 if (!SCCC->isNullValue())
4842 return N2; // cond always true -> true val
4844 return N3; // cond always false -> false val
4847 // Fold to a simpler select_cc
4848 if (SCC.getOpcode() == ISD::SETCC)
4849 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4850 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4854 // If we can fold this based on the true/false value, do so.
4855 if (SimplifySelectOps(N, N2, N3))
4856 return SDValue(N, 0); // Don't revisit N.
4858 // fold select_cc into other things, such as min/max/abs
4859 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4862 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4863 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4864 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4868 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4869 // dag node into a ConstantSDNode or a build_vector of constants.
4870 // This function is called by the DAGCombiner when visiting sext/zext/aext
4871 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4872 // Vector extends are not folded if operations are legal; this is to
4873 // avoid introducing illegal build_vector dag nodes.
4874 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4875 SelectionDAG &DAG, bool LegalTypes,
4876 bool LegalOperations) {
4877 unsigned Opcode = N->getOpcode();
4878 SDValue N0 = N->getOperand(0);
4879 EVT VT = N->getValueType(0);
4881 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4882 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4884 // fold (sext c1) -> c1
4885 // fold (zext c1) -> c1
4886 // fold (aext c1) -> c1
4887 if (isa<ConstantSDNode>(N0))
4888 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4890 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4891 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4892 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4893 EVT SVT = VT.getScalarType();
4894 if (!(VT.isVector() &&
4895 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4896 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4899 // We can fold this node into a build_vector.
4900 unsigned VTBits = SVT.getSizeInBits();
4901 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4902 unsigned ShAmt = VTBits - EVTBits;
4903 SmallVector<SDValue, 8> Elts;
4904 unsigned NumElts = N0->getNumOperands();
4907 for (unsigned i=0; i != NumElts; ++i) {
4908 SDValue Op = N0->getOperand(i);
4909 if (Op->getOpcode() == ISD::UNDEF) {
4910 Elts.push_back(DAG.getUNDEF(SVT));
4914 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4915 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4916 if (Opcode == ISD::SIGN_EXTEND)
4917 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4920 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4924 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4927 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4928 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4929 // transformation. Returns true if extension are possible and the above
4930 // mentioned transformation is profitable.
4931 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4933 SmallVectorImpl<SDNode *> &ExtendNodes,
4934 const TargetLowering &TLI) {
4935 bool HasCopyToRegUses = false;
4936 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4937 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4938 UE = N0.getNode()->use_end();
4943 if (UI.getUse().getResNo() != N0.getResNo())
4945 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4946 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4947 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4948 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4949 // Sign bits will be lost after a zext.
4952 for (unsigned i = 0; i != 2; ++i) {
4953 SDValue UseOp = User->getOperand(i);
4956 if (!isa<ConstantSDNode>(UseOp))
4961 ExtendNodes.push_back(User);
4964 // If truncates aren't free and there are users we can't
4965 // extend, it isn't worthwhile.
4968 // Remember if this value is live-out.
4969 if (User->getOpcode() == ISD::CopyToReg)
4970 HasCopyToRegUses = true;
4973 if (HasCopyToRegUses) {
4974 bool BothLiveOut = false;
4975 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4977 SDUse &Use = UI.getUse();
4978 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4984 // Both unextended and extended values are live out. There had better be
4985 // a good reason for the transformation.
4986 return ExtendNodes.size();
4991 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4992 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4993 ISD::NodeType ExtType) {
4994 // Extend SetCC uses if necessary.
4995 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4996 SDNode *SetCC = SetCCs[i];
4997 SmallVector<SDValue, 4> Ops;
4999 for (unsigned j = 0; j != 2; ++j) {
5000 SDValue SOp = SetCC->getOperand(j);
5002 Ops.push_back(ExtLoad);
5004 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5007 Ops.push_back(SetCC->getOperand(2));
5008 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5012 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5013 SDValue N0 = N->getOperand(0);
5014 EVT VT = N->getValueType(0);
5016 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5018 return SDValue(Res, 0);
5020 // fold (sext (sext x)) -> (sext x)
5021 // fold (sext (aext x)) -> (sext x)
5022 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5023 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5026 if (N0.getOpcode() == ISD::TRUNCATE) {
5027 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5028 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5029 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5030 if (NarrowLoad.getNode()) {
5031 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5032 if (NarrowLoad.getNode() != N0.getNode()) {
5033 CombineTo(N0.getNode(), NarrowLoad);
5034 // CombineTo deleted the truncate, if needed, but not what's under it.
5037 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5040 // See if the value being truncated is already sign extended. If so, just
5041 // eliminate the trunc/sext pair.
5042 SDValue Op = N0.getOperand(0);
5043 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5044 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5045 unsigned DestBits = VT.getScalarType().getSizeInBits();
5046 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5048 if (OpBits == DestBits) {
5049 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5050 // bits, it is already ready.
5051 if (NumSignBits > DestBits-MidBits)
5053 } else if (OpBits < DestBits) {
5054 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5055 // bits, just sext from i32.
5056 if (NumSignBits > OpBits-MidBits)
5057 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5059 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5060 // bits, just truncate to i32.
5061 if (NumSignBits > OpBits-MidBits)
5062 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5065 // fold (sext (truncate x)) -> (sextinreg x).
5066 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5067 N0.getValueType())) {
5068 if (OpBits < DestBits)
5069 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5070 else if (OpBits > DestBits)
5071 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5072 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5073 DAG.getValueType(N0.getValueType()));
5077 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5078 // None of the supported targets knows how to perform load and sign extend
5079 // on vectors in one instruction. We only perform this transformation on
5081 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5082 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5083 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5084 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5085 bool DoXform = true;
5086 SmallVector<SDNode*, 4> SetCCs;
5087 if (!N0.hasOneUse())
5088 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5090 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5091 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5093 LN0->getBasePtr(), N0.getValueType(),
5094 LN0->getMemOperand());
5095 CombineTo(N, ExtLoad);
5096 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5097 N0.getValueType(), ExtLoad);
5098 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5099 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5101 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5105 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5106 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5107 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5108 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5109 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5110 EVT MemVT = LN0->getMemoryVT();
5111 if ((!LegalOperations && !LN0->isVolatile()) ||
5112 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5113 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5115 LN0->getBasePtr(), MemVT,
5116 LN0->getMemOperand());
5117 CombineTo(N, ExtLoad);
5118 CombineTo(N0.getNode(),
5119 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5120 N0.getValueType(), ExtLoad),
5121 ExtLoad.getValue(1));
5122 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5126 // fold (sext (and/or/xor (load x), cst)) ->
5127 // (and/or/xor (sextload x), (sext cst))
5128 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5129 N0.getOpcode() == ISD::XOR) &&
5130 isa<LoadSDNode>(N0.getOperand(0)) &&
5131 N0.getOperand(1).getOpcode() == ISD::Constant &&
5132 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5133 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5134 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5135 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5136 bool DoXform = true;
5137 SmallVector<SDNode*, 4> SetCCs;
5138 if (!N0.hasOneUse())
5139 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5142 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5143 LN0->getChain(), LN0->getBasePtr(),
5145 LN0->getMemOperand());
5146 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5147 Mask = Mask.sext(VT.getSizeInBits());
5148 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5149 ExtLoad, DAG.getConstant(Mask, VT));
5150 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5151 SDLoc(N0.getOperand(0)),
5152 N0.getOperand(0).getValueType(), ExtLoad);
5154 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5155 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5157 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5162 if (N0.getOpcode() == ISD::SETCC) {
5163 EVT N0VT = N0.getOperand(0).getValueType();
5164 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5165 // Only do this before legalize for now.
5166 if (VT.isVector() && !LegalOperations &&
5167 TLI.getBooleanContents(N0VT) ==
5168 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5169 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5170 // of the same size as the compared operands. Only optimize sext(setcc())
5171 // if this is the case.
5172 EVT SVT = getSetCCResultType(N0VT);
5174 // We know that the # elements of the results is the same as the
5175 // # elements of the compare (and the # elements of the compare result
5176 // for that matter). Check to see that they are the same size. If so,
5177 // we know that the element size of the sext'd result matches the
5178 // element size of the compare operands.
5179 if (VT.getSizeInBits() == SVT.getSizeInBits())
5180 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5182 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5184 // If the desired elements are smaller or larger than the source
5185 // elements we can use a matching integer vector type and then
5186 // truncate/sign extend
5187 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5188 if (SVT == MatchingVectorType) {
5189 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5190 N0.getOperand(0), N0.getOperand(1),
5191 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5192 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5196 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5197 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5199 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5201 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5202 NegOne, DAG.getConstant(0, VT),
5203 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5204 if (SCC.getNode()) return SCC;
5206 if (!VT.isVector()) {
5207 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5208 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5210 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5211 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5212 N0.getOperand(0), N0.getOperand(1), CC);
5213 return DAG.getSelect(DL, VT, SetCC,
5214 NegOne, DAG.getConstant(0, VT));
5219 // fold (sext x) -> (zext x) if the sign bit is known zero.
5220 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5221 DAG.SignBitIsZero(N0))
5222 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5227 // isTruncateOf - If N is a truncate of some other value, return true, record
5228 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5229 // This function computes KnownZero to avoid a duplicated call to
5230 // computeKnownBits in the caller.
5231 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5234 if (N->getOpcode() == ISD::TRUNCATE) {
5235 Op = N->getOperand(0);
5236 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5240 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5241 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5244 SDValue Op0 = N->getOperand(0);
5245 SDValue Op1 = N->getOperand(1);
5246 assert(Op0.getValueType() == Op1.getValueType());
5248 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5249 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5250 if (COp0 && COp0->isNullValue())
5252 else if (COp1 && COp1->isNullValue())
5257 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5259 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5265 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5266 SDValue N0 = N->getOperand(0);
5267 EVT VT = N->getValueType(0);
5269 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5271 return SDValue(Res, 0);
5273 // fold (zext (zext x)) -> (zext x)
5274 // fold (zext (aext x)) -> (zext x)
5275 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5276 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5279 // fold (zext (truncate x)) -> (zext x) or
5280 // (zext (truncate x)) -> (truncate x)
5281 // This is valid when the truncated bits of x are already zero.
5282 // FIXME: We should extend this to work for vectors too.
5285 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5286 APInt TruncatedBits =
5287 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5288 APInt(Op.getValueSizeInBits(), 0) :
5289 APInt::getBitsSet(Op.getValueSizeInBits(),
5290 N0.getValueSizeInBits(),
5291 std::min(Op.getValueSizeInBits(),
5292 VT.getSizeInBits()));
5293 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5294 if (VT.bitsGT(Op.getValueType()))
5295 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5296 if (VT.bitsLT(Op.getValueType()))
5297 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5303 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5304 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5305 if (N0.getOpcode() == ISD::TRUNCATE) {
5306 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5307 if (NarrowLoad.getNode()) {
5308 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5309 if (NarrowLoad.getNode() != N0.getNode()) {
5310 CombineTo(N0.getNode(), NarrowLoad);
5311 // CombineTo deleted the truncate, if needed, but not what's under it.
5314 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5318 // fold (zext (truncate x)) -> (and x, mask)
5319 if (N0.getOpcode() == ISD::TRUNCATE &&
5320 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5322 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5323 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5324 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5325 if (NarrowLoad.getNode()) {
5326 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5327 if (NarrowLoad.getNode() != N0.getNode()) {
5328 CombineTo(N0.getNode(), NarrowLoad);
5329 // CombineTo deleted the truncate, if needed, but not what's under it.
5332 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5335 SDValue Op = N0.getOperand(0);
5336 if (Op.getValueType().bitsLT(VT)) {
5337 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5338 AddToWorklist(Op.getNode());
5339 } else if (Op.getValueType().bitsGT(VT)) {
5340 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5341 AddToWorklist(Op.getNode());
5343 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5344 N0.getValueType().getScalarType());
5347 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5348 // if either of the casts is not free.
5349 if (N0.getOpcode() == ISD::AND &&
5350 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5351 N0.getOperand(1).getOpcode() == ISD::Constant &&
5352 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5353 N0.getValueType()) ||
5354 !TLI.isZExtFree(N0.getValueType(), VT))) {
5355 SDValue X = N0.getOperand(0).getOperand(0);
5356 if (X.getValueType().bitsLT(VT)) {
5357 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5358 } else if (X.getValueType().bitsGT(VT)) {
5359 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5361 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5362 Mask = Mask.zext(VT.getSizeInBits());
5363 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5364 X, DAG.getConstant(Mask, VT));
5367 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5368 // None of the supported targets knows how to perform load and vector_zext
5369 // on vectors in one instruction. We only perform this transformation on
5371 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5372 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5373 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5374 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5375 bool DoXform = true;
5376 SmallVector<SDNode*, 4> SetCCs;
5377 if (!N0.hasOneUse())
5378 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5380 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5381 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5383 LN0->getBasePtr(), N0.getValueType(),
5384 LN0->getMemOperand());
5385 CombineTo(N, ExtLoad);
5386 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5387 N0.getValueType(), ExtLoad);
5388 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5390 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5392 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5396 // fold (zext (and/or/xor (load x), cst)) ->
5397 // (and/or/xor (zextload x), (zext cst))
5398 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5399 N0.getOpcode() == ISD::XOR) &&
5400 isa<LoadSDNode>(N0.getOperand(0)) &&
5401 N0.getOperand(1).getOpcode() == ISD::Constant &&
5402 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5403 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5404 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5405 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5406 bool DoXform = true;
5407 SmallVector<SDNode*, 4> SetCCs;
5408 if (!N0.hasOneUse())
5409 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5412 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5413 LN0->getChain(), LN0->getBasePtr(),
5415 LN0->getMemOperand());
5416 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5417 Mask = Mask.zext(VT.getSizeInBits());
5418 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5419 ExtLoad, DAG.getConstant(Mask, VT));
5420 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5421 SDLoc(N0.getOperand(0)),
5422 N0.getOperand(0).getValueType(), ExtLoad);
5424 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5425 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5427 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5432 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5433 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5434 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5435 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5436 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5437 EVT MemVT = LN0->getMemoryVT();
5438 if ((!LegalOperations && !LN0->isVolatile()) ||
5439 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5440 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5442 LN0->getBasePtr(), MemVT,
5443 LN0->getMemOperand());
5444 CombineTo(N, ExtLoad);
5445 CombineTo(N0.getNode(),
5446 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5448 ExtLoad.getValue(1));
5449 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5453 if (N0.getOpcode() == ISD::SETCC) {
5454 if (!LegalOperations && VT.isVector() &&
5455 N0.getValueType().getVectorElementType() == MVT::i1) {
5456 EVT N0VT = N0.getOperand(0).getValueType();
5457 if (getSetCCResultType(N0VT) == N0.getValueType())
5460 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5461 // Only do this before legalize for now.
5462 EVT EltVT = VT.getVectorElementType();
5463 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5464 DAG.getConstant(1, EltVT));
5465 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5466 // We know that the # elements of the results is the same as the
5467 // # elements of the compare (and the # elements of the compare result
5468 // for that matter). Check to see that they are the same size. If so,
5469 // we know that the element size of the sext'd result matches the
5470 // element size of the compare operands.
5471 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5472 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5474 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5475 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5478 // If the desired elements are smaller or larger than the source
5479 // elements we can use a matching integer vector type and then
5480 // truncate/sign extend
5481 EVT MatchingElementType =
5482 EVT::getIntegerVT(*DAG.getContext(),
5483 N0VT.getScalarType().getSizeInBits());
5484 EVT MatchingVectorType =
5485 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5486 N0VT.getVectorNumElements());
5488 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5490 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5491 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5492 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5493 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5496 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5498 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5499 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5500 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5501 if (SCC.getNode()) return SCC;
5504 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5505 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5506 isa<ConstantSDNode>(N0.getOperand(1)) &&
5507 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5509 SDValue ShAmt = N0.getOperand(1);
5510 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5511 if (N0.getOpcode() == ISD::SHL) {
5512 SDValue InnerZExt = N0.getOperand(0);
5513 // If the original shl may be shifting out bits, do not perform this
5515 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5516 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5517 if (ShAmtVal > KnownZeroBits)
5523 // Ensure that the shift amount is wide enough for the shifted value.
5524 if (VT.getSizeInBits() >= 256)
5525 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5527 return DAG.getNode(N0.getOpcode(), DL, VT,
5528 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5535 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5536 SDValue N0 = N->getOperand(0);
5537 EVT VT = N->getValueType(0);
5539 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5541 return SDValue(Res, 0);
5543 // fold (aext (aext x)) -> (aext x)
5544 // fold (aext (zext x)) -> (zext x)
5545 // fold (aext (sext x)) -> (sext x)
5546 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5547 N0.getOpcode() == ISD::ZERO_EXTEND ||
5548 N0.getOpcode() == ISD::SIGN_EXTEND)
5549 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5551 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5552 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5553 if (N0.getOpcode() == ISD::TRUNCATE) {
5554 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5555 if (NarrowLoad.getNode()) {
5556 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5557 if (NarrowLoad.getNode() != N0.getNode()) {
5558 CombineTo(N0.getNode(), NarrowLoad);
5559 // CombineTo deleted the truncate, if needed, but not what's under it.
5562 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5566 // fold (aext (truncate x))
5567 if (N0.getOpcode() == ISD::TRUNCATE) {
5568 SDValue TruncOp = N0.getOperand(0);
5569 if (TruncOp.getValueType() == VT)
5570 return TruncOp; // x iff x size == zext size.
5571 if (TruncOp.getValueType().bitsGT(VT))
5572 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5573 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5576 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5577 // if the trunc is not free.
5578 if (N0.getOpcode() == ISD::AND &&
5579 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5580 N0.getOperand(1).getOpcode() == ISD::Constant &&
5581 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5582 N0.getValueType())) {
5583 SDValue X = N0.getOperand(0).getOperand(0);
5584 if (X.getValueType().bitsLT(VT)) {
5585 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5586 } else if (X.getValueType().bitsGT(VT)) {
5587 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5589 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5590 Mask = Mask.zext(VT.getSizeInBits());
5591 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5592 X, DAG.getConstant(Mask, VT));
5595 // fold (aext (load x)) -> (aext (truncate (extload x)))
5596 // None of the supported targets knows how to perform load and any_ext
5597 // on vectors in one instruction. We only perform this transformation on
5599 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5600 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5601 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5602 bool DoXform = true;
5603 SmallVector<SDNode*, 4> SetCCs;
5604 if (!N0.hasOneUse())
5605 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5607 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5608 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5610 LN0->getBasePtr(), N0.getValueType(),
5611 LN0->getMemOperand());
5612 CombineTo(N, ExtLoad);
5613 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5614 N0.getValueType(), ExtLoad);
5615 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5616 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5618 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5622 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5623 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5624 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5625 if (N0.getOpcode() == ISD::LOAD &&
5626 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5628 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5629 ISD::LoadExtType ExtType = LN0->getExtensionType();
5630 EVT MemVT = LN0->getMemoryVT();
5631 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5632 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5633 VT, LN0->getChain(), LN0->getBasePtr(),
5634 MemVT, LN0->getMemOperand());
5635 CombineTo(N, ExtLoad);
5636 CombineTo(N0.getNode(),
5637 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5638 N0.getValueType(), ExtLoad),
5639 ExtLoad.getValue(1));
5640 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5644 if (N0.getOpcode() == ISD::SETCC) {
5646 // aext(setcc) -> vsetcc
5647 // aext(setcc) -> truncate(vsetcc)
5648 // aext(setcc) -> aext(vsetcc)
5649 // Only do this before legalize for now.
5650 if (VT.isVector() && !LegalOperations) {
5651 EVT N0VT = N0.getOperand(0).getValueType();
5652 // We know that the # elements of the results is the same as the
5653 // # elements of the compare (and the # elements of the compare result
5654 // for that matter). Check to see that they are the same size. If so,
5655 // we know that the element size of the sext'd result matches the
5656 // element size of the compare operands.
5657 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5658 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5660 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5661 // If the desired elements are smaller or larger than the source
5662 // elements we can use a matching integer vector type and then
5663 // truncate/any extend
5665 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5667 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5669 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5670 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5674 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5676 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5677 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5678 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5686 /// See if the specified operand can be simplified with the knowledge that only
5687 /// the bits specified by Mask are used. If so, return the simpler operand,
5688 /// otherwise return a null SDValue.
5689 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5690 switch (V.getOpcode()) {
5692 case ISD::Constant: {
5693 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5694 assert(CV && "Const value should be ConstSDNode.");
5695 const APInt &CVal = CV->getAPIntValue();
5696 APInt NewVal = CVal & Mask;
5698 return DAG.getConstant(NewVal, V.getValueType());
5703 // If the LHS or RHS don't contribute bits to the or, drop them.
5704 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5705 return V.getOperand(1);
5706 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5707 return V.getOperand(0);
5710 // Only look at single-use SRLs.
5711 if (!V.getNode()->hasOneUse())
5713 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5714 // See if we can recursively simplify the LHS.
5715 unsigned Amt = RHSC->getZExtValue();
5717 // Watch out for shift count overflow though.
5718 if (Amt >= Mask.getBitWidth()) break;
5719 APInt NewMask = Mask << Amt;
5720 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5721 if (SimplifyLHS.getNode())
5722 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5723 SimplifyLHS, V.getOperand(1));
5729 /// If the result of a wider load is shifted to right of N bits and then
5730 /// truncated to a narrower type and where N is a multiple of number of bits of
5731 /// the narrower type, transform it to a narrower load from address + N / num of
5732 /// bits of new type. If the result is to be extended, also fold the extension
5733 /// to form a extending load.
5734 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5735 unsigned Opc = N->getOpcode();
5737 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5738 SDValue N0 = N->getOperand(0);
5739 EVT VT = N->getValueType(0);
5742 // This transformation isn't valid for vector loads.
5746 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5748 if (Opc == ISD::SIGN_EXTEND_INREG) {
5749 ExtType = ISD::SEXTLOAD;
5750 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5751 } else if (Opc == ISD::SRL) {
5752 // Another special-case: SRL is basically zero-extending a narrower value.
5753 ExtType = ISD::ZEXTLOAD;
5755 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5756 if (!N01) return SDValue();
5757 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5758 VT.getSizeInBits() - N01->getZExtValue());
5760 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5763 unsigned EVTBits = ExtVT.getSizeInBits();
5765 // Do not generate loads of non-round integer types since these can
5766 // be expensive (and would be wrong if the type is not byte sized).
5767 if (!ExtVT.isRound())
5771 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5772 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5773 ShAmt = N01->getZExtValue();
5774 // Is the shift amount a multiple of size of VT?
5775 if ((ShAmt & (EVTBits-1)) == 0) {
5776 N0 = N0.getOperand(0);
5777 // Is the load width a multiple of size of VT?
5778 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5782 // At this point, we must have a load or else we can't do the transform.
5783 if (!isa<LoadSDNode>(N0)) return SDValue();
5785 // Because a SRL must be assumed to *need* to zero-extend the high bits
5786 // (as opposed to anyext the high bits), we can't combine the zextload
5787 // lowering of SRL and an sextload.
5788 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5791 // If the shift amount is larger than the input type then we're not
5792 // accessing any of the loaded bytes. If the load was a zextload/extload
5793 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5794 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5799 // If the load is shifted left (and the result isn't shifted back right),
5800 // we can fold the truncate through the shift.
5801 unsigned ShLeftAmt = 0;
5802 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5803 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5804 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5805 ShLeftAmt = N01->getZExtValue();
5806 N0 = N0.getOperand(0);
5810 // If we haven't found a load, we can't narrow it. Don't transform one with
5811 // multiple uses, this would require adding a new load.
5812 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5815 // Don't change the width of a volatile load.
5816 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5817 if (LN0->isVolatile())
5820 // Verify that we are actually reducing a load width here.
5821 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5824 // For the transform to be legal, the load must produce only two values
5825 // (the value loaded and the chain). Don't transform a pre-increment
5826 // load, for example, which produces an extra value. Otherwise the
5827 // transformation is not equivalent, and the downstream logic to replace
5828 // uses gets things wrong.
5829 if (LN0->getNumValues() > 2)
5832 // If the load that we're shrinking is an extload and we're not just
5833 // discarding the extension we can't simply shrink the load. Bail.
5834 // TODO: It would be possible to merge the extensions in some cases.
5835 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5836 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5839 EVT PtrType = N0.getOperand(1).getValueType();
5841 if (PtrType == MVT::Untyped || PtrType.isExtended())
5842 // It's not possible to generate a constant of extended or untyped type.
5845 // For big endian targets, we need to adjust the offset to the pointer to
5846 // load the correct bytes.
5847 if (TLI.isBigEndian()) {
5848 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5849 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5850 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5853 uint64_t PtrOff = ShAmt / 8;
5854 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5855 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5856 PtrType, LN0->getBasePtr(),
5857 DAG.getConstant(PtrOff, PtrType));
5858 AddToWorklist(NewPtr.getNode());
5861 if (ExtType == ISD::NON_EXTLOAD)
5862 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5863 LN0->getPointerInfo().getWithOffset(PtrOff),
5864 LN0->isVolatile(), LN0->isNonTemporal(),
5865 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5867 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5868 LN0->getPointerInfo().getWithOffset(PtrOff),
5869 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5870 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5872 // Replace the old load's chain with the new load's chain.
5873 WorklistRemover DeadNodes(*this);
5874 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5876 // Shift the result left, if we've swallowed a left shift.
5877 SDValue Result = Load;
5878 if (ShLeftAmt != 0) {
5879 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5880 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5882 // If the shift amount is as large as the result size (but, presumably,
5883 // no larger than the source) then the useful bits of the result are
5884 // zero; we can't simply return the shortened shift, because the result
5885 // of that operation is undefined.
5886 if (ShLeftAmt >= VT.getSizeInBits())
5887 Result = DAG.getConstant(0, VT);
5889 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5890 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5893 // Return the new loaded value.
5897 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5898 SDValue N0 = N->getOperand(0);
5899 SDValue N1 = N->getOperand(1);
5900 EVT VT = N->getValueType(0);
5901 EVT EVT = cast<VTSDNode>(N1)->getVT();
5902 unsigned VTBits = VT.getScalarType().getSizeInBits();
5903 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5905 // fold (sext_in_reg c1) -> c1
5906 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5907 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5909 // If the input is already sign extended, just drop the extension.
5910 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5913 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5914 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5915 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5916 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5917 N0.getOperand(0), N1);
5919 // fold (sext_in_reg (sext x)) -> (sext x)
5920 // fold (sext_in_reg (aext x)) -> (sext x)
5921 // if x is small enough.
5922 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5923 SDValue N00 = N0.getOperand(0);
5924 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5925 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5926 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5929 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5930 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5931 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5933 // fold operands of sext_in_reg based on knowledge that the top bits are not
5935 if (SimplifyDemandedBits(SDValue(N, 0)))
5936 return SDValue(N, 0);
5938 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5939 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5940 SDValue NarrowLoad = ReduceLoadWidth(N);
5941 if (NarrowLoad.getNode())
5944 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5945 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5946 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5947 if (N0.getOpcode() == ISD::SRL) {
5948 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5949 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5950 // We can turn this into an SRA iff the input to the SRL is already sign
5952 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5953 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5954 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5955 N0.getOperand(0), N0.getOperand(1));
5959 // fold (sext_inreg (extload x)) -> (sextload x)
5960 if (ISD::isEXTLoad(N0.getNode()) &&
5961 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5962 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5963 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5964 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5965 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5966 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5968 LN0->getBasePtr(), EVT,
5969 LN0->getMemOperand());
5970 CombineTo(N, ExtLoad);
5971 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5972 AddToWorklist(ExtLoad.getNode());
5973 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5975 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5976 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5978 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5979 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5980 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5981 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5982 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5984 LN0->getBasePtr(), EVT,
5985 LN0->getMemOperand());
5986 CombineTo(N, ExtLoad);
5987 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5988 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5991 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5992 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5993 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5994 N0.getOperand(1), false);
5995 if (BSwap.getNode())
5996 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6000 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6001 // into a build_vector.
6002 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6003 SmallVector<SDValue, 8> Elts;
6004 unsigned NumElts = N0->getNumOperands();
6005 unsigned ShAmt = VTBits - EVTBits;
6007 for (unsigned i = 0; i != NumElts; ++i) {
6008 SDValue Op = N0->getOperand(i);
6009 if (Op->getOpcode() == ISD::UNDEF) {
6014 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6015 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6016 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6017 Op.getValueType()));
6020 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6026 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6027 SDValue N0 = N->getOperand(0);
6028 EVT VT = N->getValueType(0);
6029 bool isLE = TLI.isLittleEndian();
6032 if (N0.getValueType() == N->getValueType(0))
6034 // fold (truncate c1) -> c1
6035 if (isa<ConstantSDNode>(N0))
6036 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6037 // fold (truncate (truncate x)) -> (truncate x)
6038 if (N0.getOpcode() == ISD::TRUNCATE)
6039 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6040 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6041 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6042 N0.getOpcode() == ISD::SIGN_EXTEND ||
6043 N0.getOpcode() == ISD::ANY_EXTEND) {
6044 if (N0.getOperand(0).getValueType().bitsLT(VT))
6045 // if the source is smaller than the dest, we still need an extend
6046 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6048 if (N0.getOperand(0).getValueType().bitsGT(VT))
6049 // if the source is larger than the dest, than we just need the truncate
6050 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6051 // if the source and dest are the same type, we can drop both the extend
6052 // and the truncate.
6053 return N0.getOperand(0);
6056 // Fold extract-and-trunc into a narrow extract. For example:
6057 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6058 // i32 y = TRUNCATE(i64 x)
6060 // v16i8 b = BITCAST (v2i64 val)
6061 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6063 // Note: We only run this optimization after type legalization (which often
6064 // creates this pattern) and before operation legalization after which
6065 // we need to be more careful about the vector instructions that we generate.
6066 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6067 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6069 EVT VecTy = N0.getOperand(0).getValueType();
6070 EVT ExTy = N0.getValueType();
6071 EVT TrTy = N->getValueType(0);
6073 unsigned NumElem = VecTy.getVectorNumElements();
6074 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6076 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6077 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6079 SDValue EltNo = N0->getOperand(1);
6080 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6081 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6082 EVT IndexTy = TLI.getVectorIdxTy();
6083 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6085 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6086 NVT, N0.getOperand(0));
6088 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6090 DAG.getConstant(Index, IndexTy));
6094 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6095 if (N0.getOpcode() == ISD::SELECT) {
6096 EVT SrcVT = N0.getValueType();
6097 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6098 TLI.isTruncateFree(SrcVT, VT)) {
6100 SDValue Cond = N0.getOperand(0);
6101 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6102 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6103 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6107 // Fold a series of buildvector, bitcast, and truncate if possible.
6109 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6110 // (2xi32 (buildvector x, y)).
6111 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6112 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6113 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6114 N0.getOperand(0).hasOneUse()) {
6116 SDValue BuildVect = N0.getOperand(0);
6117 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6118 EVT TruncVecEltTy = VT.getVectorElementType();
6120 // Check that the element types match.
6121 if (BuildVectEltTy == TruncVecEltTy) {
6122 // Now we only need to compute the offset of the truncated elements.
6123 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6124 unsigned TruncVecNumElts = VT.getVectorNumElements();
6125 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6127 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6128 "Invalid number of elements");
6130 SmallVector<SDValue, 8> Opnds;
6131 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6132 Opnds.push_back(BuildVect.getOperand(i));
6134 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6138 // See if we can simplify the input to this truncate through knowledge that
6139 // only the low bits are being used.
6140 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6141 // Currently we only perform this optimization on scalars because vectors
6142 // may have different active low bits.
6143 if (!VT.isVector()) {
6145 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6146 VT.getSizeInBits()));
6147 if (Shorter.getNode())
6148 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6150 // fold (truncate (load x)) -> (smaller load x)
6151 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6152 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6153 SDValue Reduced = ReduceLoadWidth(N);
6154 if (Reduced.getNode())
6156 // Handle the case where the load remains an extending load even
6157 // after truncation.
6158 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6159 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6160 if (!LN0->isVolatile() &&
6161 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6162 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6163 VT, LN0->getChain(), LN0->getBasePtr(),
6165 LN0->getMemOperand());
6166 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6171 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6172 // where ... are all 'undef'.
6173 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6174 SmallVector<EVT, 8> VTs;
6177 unsigned NumDefs = 0;
6179 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6180 SDValue X = N0.getOperand(i);
6181 if (X.getOpcode() != ISD::UNDEF) {
6186 // Stop if more than one members are non-undef.
6189 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6190 VT.getVectorElementType(),
6191 X.getValueType().getVectorNumElements()));
6195 return DAG.getUNDEF(VT);
6198 assert(V.getNode() && "The single defined operand is empty!");
6199 SmallVector<SDValue, 8> Opnds;
6200 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6202 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6205 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6206 AddToWorklist(NV.getNode());
6207 Opnds.push_back(NV);
6209 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6213 // Simplify the operands using demanded-bits information.
6214 if (!VT.isVector() &&
6215 SimplifyDemandedBits(SDValue(N, 0)))
6216 return SDValue(N, 0);
6221 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6222 SDValue Elt = N->getOperand(i);
6223 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6224 return Elt.getNode();
6225 return Elt.getOperand(Elt.getResNo()).getNode();
6228 /// build_pair (load, load) -> load
6229 /// if load locations are consecutive.
6230 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6231 assert(N->getOpcode() == ISD::BUILD_PAIR);
6233 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6234 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6235 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6236 LD1->getAddressSpace() != LD2->getAddressSpace())
6238 EVT LD1VT = LD1->getValueType(0);
6240 if (ISD::isNON_EXTLoad(LD2) &&
6242 // If both are volatile this would reduce the number of volatile loads.
6243 // If one is volatile it might be ok, but play conservative and bail out.
6244 !LD1->isVolatile() &&
6245 !LD2->isVolatile() &&
6246 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6247 unsigned Align = LD1->getAlignment();
6248 unsigned NewAlign = TLI.getDataLayout()->
6249 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6251 if (NewAlign <= Align &&
6252 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6253 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6254 LD1->getBasePtr(), LD1->getPointerInfo(),
6255 false, false, false, Align);
6261 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6262 SDValue N0 = N->getOperand(0);
6263 EVT VT = N->getValueType(0);
6265 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6266 // Only do this before legalize, since afterward the target may be depending
6267 // on the bitconvert.
6268 // First check to see if this is all constant.
6270 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6272 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6274 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6275 assert(!DestEltVT.isVector() &&
6276 "Element type of vector ValueType must not be vector!");
6278 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6281 // If the input is a constant, let getNode fold it.
6282 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6283 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6284 if (Res.getNode() != N) {
6285 if (!LegalOperations ||
6286 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6289 // Folding it resulted in an illegal node, and it's too late to
6290 // do that. Clean up the old node and forego the transformation.
6291 // Ideally this won't happen very often, because instcombine
6292 // and the earlier dagcombine runs (where illegal nodes are
6293 // permitted) should have folded most of them already.
6294 deleteAndRecombine(Res.getNode());
6298 // (conv (conv x, t1), t2) -> (conv x, t2)
6299 if (N0.getOpcode() == ISD::BITCAST)
6300 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6303 // fold (conv (load x)) -> (load (conv*)x)
6304 // If the resultant load doesn't need a higher alignment than the original!
6305 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6306 // Do not change the width of a volatile load.
6307 !cast<LoadSDNode>(N0)->isVolatile() &&
6308 // Do not remove the cast if the types differ in endian layout.
6309 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6310 TLI.hasBigEndianPartOrdering(VT) &&
6311 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6312 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6313 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6314 unsigned Align = TLI.getDataLayout()->
6315 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6316 unsigned OrigAlign = LN0->getAlignment();
6318 if (Align <= OrigAlign) {
6319 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6320 LN0->getBasePtr(), LN0->getPointerInfo(),
6321 LN0->isVolatile(), LN0->isNonTemporal(),
6322 LN0->isInvariant(), OrigAlign,
6324 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6329 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6330 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6331 // This often reduces constant pool loads.
6332 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6333 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6334 N0.getNode()->hasOneUse() && VT.isInteger() &&
6335 !VT.isVector() && !N0.getValueType().isVector()) {
6336 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6338 AddToWorklist(NewConv.getNode());
6340 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6341 if (N0.getOpcode() == ISD::FNEG)
6342 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6343 NewConv, DAG.getConstant(SignBit, VT));
6344 assert(N0.getOpcode() == ISD::FABS);
6345 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6346 NewConv, DAG.getConstant(~SignBit, VT));
6349 // fold (bitconvert (fcopysign cst, x)) ->
6350 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6351 // Note that we don't handle (copysign x, cst) because this can always be
6352 // folded to an fneg or fabs.
6353 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6354 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6355 VT.isInteger() && !VT.isVector()) {
6356 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6357 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6358 if (isTypeLegal(IntXVT)) {
6359 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6360 IntXVT, N0.getOperand(1));
6361 AddToWorklist(X.getNode());
6363 // If X has a different width than the result/lhs, sext it or truncate it.
6364 unsigned VTWidth = VT.getSizeInBits();
6365 if (OrigXWidth < VTWidth) {
6366 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6367 AddToWorklist(X.getNode());
6368 } else if (OrigXWidth > VTWidth) {
6369 // To get the sign bit in the right place, we have to shift it right
6370 // before truncating.
6371 X = DAG.getNode(ISD::SRL, SDLoc(X),
6372 X.getValueType(), X,
6373 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6374 AddToWorklist(X.getNode());
6375 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6376 AddToWorklist(X.getNode());
6379 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6380 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6381 X, DAG.getConstant(SignBit, VT));
6382 AddToWorklist(X.getNode());
6384 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6385 VT, N0.getOperand(0));
6386 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6387 Cst, DAG.getConstant(~SignBit, VT));
6388 AddToWorklist(Cst.getNode());
6390 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6394 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6395 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6396 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6397 if (CombineLD.getNode())
6404 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6405 EVT VT = N->getValueType(0);
6406 return CombineConsecutiveLoads(N, VT);
6409 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6410 /// operands. DstEltVT indicates the destination element value type.
6411 SDValue DAGCombiner::
6412 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6413 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6415 // If this is already the right type, we're done.
6416 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6418 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6419 unsigned DstBitSize = DstEltVT.getSizeInBits();
6421 // If this is a conversion of N elements of one type to N elements of another
6422 // type, convert each element. This handles FP<->INT cases.
6423 if (SrcBitSize == DstBitSize) {
6424 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6425 BV->getValueType(0).getVectorNumElements());
6427 // Due to the FP element handling below calling this routine recursively,
6428 // we can end up with a scalar-to-vector node here.
6429 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6430 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6431 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6432 DstEltVT, BV->getOperand(0)));
6434 SmallVector<SDValue, 8> Ops;
6435 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6436 SDValue Op = BV->getOperand(i);
6437 // If the vector element type is not legal, the BUILD_VECTOR operands
6438 // are promoted and implicitly truncated. Make that explicit here.
6439 if (Op.getValueType() != SrcEltVT)
6440 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6441 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6443 AddToWorklist(Ops.back().getNode());
6445 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6448 // Otherwise, we're growing or shrinking the elements. To avoid having to
6449 // handle annoying details of growing/shrinking FP values, we convert them to
6451 if (SrcEltVT.isFloatingPoint()) {
6452 // Convert the input float vector to a int vector where the elements are the
6454 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6455 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6456 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6460 // Now we know the input is an integer vector. If the output is a FP type,
6461 // convert to integer first, then to FP of the right size.
6462 if (DstEltVT.isFloatingPoint()) {
6463 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6464 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6465 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6467 // Next, convert to FP elements of the same size.
6468 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6471 // Okay, we know the src/dst types are both integers of differing types.
6472 // Handling growing first.
6473 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6474 if (SrcBitSize < DstBitSize) {
6475 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6477 SmallVector<SDValue, 8> Ops;
6478 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6479 i += NumInputsPerOutput) {
6480 bool isLE = TLI.isLittleEndian();
6481 APInt NewBits = APInt(DstBitSize, 0);
6482 bool EltIsUndef = true;
6483 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6484 // Shift the previously computed bits over.
6485 NewBits <<= SrcBitSize;
6486 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6487 if (Op.getOpcode() == ISD::UNDEF) continue;
6490 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6491 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6495 Ops.push_back(DAG.getUNDEF(DstEltVT));
6497 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6500 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6501 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6504 // Finally, this must be the case where we are shrinking elements: each input
6505 // turns into multiple outputs.
6506 bool isS2V = ISD::isScalarToVector(BV);
6507 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6508 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6509 NumOutputsPerInput*BV->getNumOperands());
6510 SmallVector<SDValue, 8> Ops;
6512 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6513 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6514 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6515 Ops.push_back(DAG.getUNDEF(DstEltVT));
6519 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6520 getAPIntValue().zextOrTrunc(SrcBitSize);
6522 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6523 APInt ThisVal = OpVal.trunc(DstBitSize);
6524 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6525 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6526 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6527 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6529 OpVal = OpVal.lshr(DstBitSize);
6532 // For big endian targets, swap the order of the pieces of each element.
6533 if (TLI.isBigEndian())
6534 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6537 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6540 SDValue DAGCombiner::visitFADD(SDNode *N) {
6541 SDValue N0 = N->getOperand(0);
6542 SDValue N1 = N->getOperand(1);
6543 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6544 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6545 EVT VT = N->getValueType(0);
6546 const TargetOptions &Options = DAG.getTarget().Options;
6549 if (VT.isVector()) {
6550 SDValue FoldedVOp = SimplifyVBinOp(N);
6551 if (FoldedVOp.getNode()) return FoldedVOp;
6554 // fold (fadd c1, c2) -> c1 + c2
6556 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6558 // canonicalize constant to RHS
6559 if (N0CFP && !N1CFP)
6560 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6562 // fold (fadd A, (fneg B)) -> (fsub A, B)
6563 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6564 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6565 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6566 GetNegatedExpression(N1, DAG, LegalOperations));
6568 // fold (fadd (fneg A), B) -> (fsub B, A)
6569 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6570 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6571 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6572 GetNegatedExpression(N0, DAG, LegalOperations));
6574 // If 'unsafe math' is enabled, fold lots of things.
6575 if (Options.UnsafeFPMath) {
6576 // No FP constant should be created after legalization as Instruction
6577 // Selection pass has a hard time dealing with FP constants.
6578 bool AllowNewConst = (Level < AfterLegalizeDAG);
6580 // fold (fadd A, 0) -> A
6581 if (N1CFP && N1CFP->getValueAPF().isZero())
6584 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6585 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6586 isa<ConstantFPSDNode>(N0.getOperand(1)))
6587 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6588 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6589 N0.getOperand(1), N1));
6591 // If allowed, fold (fadd (fneg x), x) -> 0.0
6592 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6593 return DAG.getConstantFP(0.0, VT);
6595 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6596 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6597 return DAG.getConstantFP(0.0, VT);
6599 // We can fold chains of FADD's of the same value into multiplications.
6600 // This transform is not safe in general because we are reducing the number
6601 // of rounding steps.
6602 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6603 if (N0.getOpcode() == ISD::FMUL) {
6604 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6605 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6607 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6608 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6609 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6611 DAG.getConstantFP(1.0, VT));
6612 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6615 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6616 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6617 N1.getOperand(0) == N1.getOperand(1) &&
6618 N0.getOperand(0) == N1.getOperand(0)) {
6619 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6621 DAG.getConstantFP(2.0, VT));
6622 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6623 N0.getOperand(0), NewCFP);
6627 if (N1.getOpcode() == ISD::FMUL) {
6628 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6629 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6631 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6632 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6633 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6635 DAG.getConstantFP(1.0, VT));
6636 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6639 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6640 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6641 N0.getOperand(0) == N0.getOperand(1) &&
6642 N1.getOperand(0) == N0.getOperand(0)) {
6643 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6645 DAG.getConstantFP(2.0, VT));
6646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6650 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6651 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6652 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6653 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6654 (N0.getOperand(0) == N1))
6655 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6656 N1, DAG.getConstantFP(3.0, VT));
6659 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6660 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6661 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6662 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6663 N1.getOperand(0) == N0)
6664 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6665 N0, DAG.getConstantFP(3.0, VT));
6668 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6669 if (AllowNewConst &&
6670 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6671 N0.getOperand(0) == N0.getOperand(1) &&
6672 N1.getOperand(0) == N1.getOperand(1) &&
6673 N0.getOperand(0) == N1.getOperand(0))
6674 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6675 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6677 } // enable-unsafe-fp-math
6679 // FADD -> FMA combines:
6680 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6681 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6682 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6684 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6685 if (N0.getOpcode() == ISD::FMUL &&
6686 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6687 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6688 N0.getOperand(0), N0.getOperand(1), N1);
6690 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6691 // Note: Commutes FADD operands.
6692 if (N1.getOpcode() == ISD::FMUL &&
6693 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6694 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6695 N1.getOperand(0), N1.getOperand(1), N0);
6701 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6702 SDValue N0 = N->getOperand(0);
6703 SDValue N1 = N->getOperand(1);
6704 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6705 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6706 EVT VT = N->getValueType(0);
6708 const TargetOptions &Options = DAG.getTarget().Options;
6711 if (VT.isVector()) {
6712 SDValue FoldedVOp = SimplifyVBinOp(N);
6713 if (FoldedVOp.getNode()) return FoldedVOp;
6716 // fold (fsub c1, c2) -> c1-c2
6718 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6720 // fold (fsub A, (fneg B)) -> (fadd A, B)
6721 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6722 return DAG.getNode(ISD::FADD, dl, VT, N0,
6723 GetNegatedExpression(N1, DAG, LegalOperations));
6725 // If 'unsafe math' is enabled, fold lots of things.
6726 if (Options.UnsafeFPMath) {
6728 if (N1CFP && N1CFP->getValueAPF().isZero())
6731 // (fsub 0, B) -> -B
6732 if (N0CFP && N0CFP->getValueAPF().isZero()) {
6733 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6734 return GetNegatedExpression(N1, DAG, LegalOperations);
6735 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6736 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6739 // (fsub x, x) -> 0.0
6741 return DAG.getConstantFP(0.0f, VT);
6743 // (fsub x, (fadd x, y)) -> (fneg y)
6744 // (fsub x, (fadd y, x)) -> (fneg y)
6745 if (N1.getOpcode() == ISD::FADD) {
6746 SDValue N10 = N1->getOperand(0);
6747 SDValue N11 = N1->getOperand(1);
6749 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6750 return GetNegatedExpression(N11, DAG, LegalOperations);
6752 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6753 return GetNegatedExpression(N10, DAG, LegalOperations);
6757 // FSUB -> FMA combines:
6758 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6759 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6760 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6762 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6763 if (N0.getOpcode() == ISD::FMUL &&
6764 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6765 return DAG.getNode(ISD::FMA, dl, VT,
6766 N0.getOperand(0), N0.getOperand(1),
6767 DAG.getNode(ISD::FNEG, dl, VT, N1));
6769 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6770 // Note: Commutes FSUB operands.
6771 if (N1.getOpcode() == ISD::FMUL &&
6772 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6773 return DAG.getNode(ISD::FMA, dl, VT,
6774 DAG.getNode(ISD::FNEG, dl, VT,
6776 N1.getOperand(1), N0);
6778 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6779 if (N0.getOpcode() == ISD::FNEG &&
6780 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6781 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6782 TLI.enableAggressiveFMAFusion(VT))) {
6783 SDValue N00 = N0.getOperand(0).getOperand(0);
6784 SDValue N01 = N0.getOperand(0).getOperand(1);
6785 return DAG.getNode(ISD::FMA, dl, VT,
6786 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6787 DAG.getNode(ISD::FNEG, dl, VT, N1));
6794 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6795 SDValue N0 = N->getOperand(0);
6796 SDValue N1 = N->getOperand(1);
6797 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6798 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6799 EVT VT = N->getValueType(0);
6800 const TargetOptions &Options = DAG.getTarget().Options;
6803 if (VT.isVector()) {
6804 // This just handles C1 * C2 for vectors. Other vector folds are below.
6805 SDValue FoldedVOp = SimplifyVBinOp(N);
6806 if (FoldedVOp.getNode())
6808 // Canonicalize vector constant to RHS.
6809 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6810 N1.getOpcode() != ISD::BUILD_VECTOR)
6811 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6812 if (BV0->isConstant())
6813 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6816 // fold (fmul c1, c2) -> c1*c2
6818 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6820 // canonicalize constant to RHS
6821 if (N0CFP && !N1CFP)
6822 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6824 // fold (fmul A, 1.0) -> A
6825 if (N1CFP && N1CFP->isExactlyValue(1.0))
6828 if (Options.UnsafeFPMath) {
6829 // fold (fmul A, 0) -> 0
6830 if (N1CFP && N1CFP->getValueAPF().isZero())
6833 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6834 if (N0.getOpcode() == ISD::FMUL) {
6835 // Fold scalars or any vector constants (not just splats).
6836 // This fold is done in general by InstCombine, but extra fmul insts
6837 // may have been generated during lowering.
6838 SDValue N01 = N0.getOperand(1);
6839 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6840 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6841 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6842 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6844 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6845 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6849 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6850 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6851 // during an early run of DAGCombiner can prevent folding with fmuls
6852 // inserted during lowering.
6853 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6855 const SDValue Two = DAG.getConstantFP(2.0, VT);
6856 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6857 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6861 // fold (fmul X, 2.0) -> (fadd X, X)
6862 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6863 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6865 // fold (fmul X, -1.0) -> (fneg X)
6866 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6867 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6868 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6870 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6871 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6872 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6873 // Both can be negated for free, check to see if at least one is cheaper
6875 if (LHSNeg == 2 || RHSNeg == 2)
6876 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6877 GetNegatedExpression(N0, DAG, LegalOperations),
6878 GetNegatedExpression(N1, DAG, LegalOperations));
6885 SDValue DAGCombiner::visitFMA(SDNode *N) {
6886 SDValue N0 = N->getOperand(0);
6887 SDValue N1 = N->getOperand(1);
6888 SDValue N2 = N->getOperand(2);
6889 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6890 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6891 EVT VT = N->getValueType(0);
6893 const TargetOptions &Options = DAG.getTarget().Options;
6895 // Constant fold FMA.
6896 if (isa<ConstantFPSDNode>(N0) &&
6897 isa<ConstantFPSDNode>(N1) &&
6898 isa<ConstantFPSDNode>(N2)) {
6899 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6902 if (Options.UnsafeFPMath) {
6903 if (N0CFP && N0CFP->isZero())
6905 if (N1CFP && N1CFP->isZero())
6908 if (N0CFP && N0CFP->isExactlyValue(1.0))
6909 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6910 if (N1CFP && N1CFP->isExactlyValue(1.0))
6911 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6913 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6914 if (N0CFP && !N1CFP)
6915 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6917 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6918 if (Options.UnsafeFPMath && N1CFP &&
6919 N2.getOpcode() == ISD::FMUL &&
6920 N0 == N2.getOperand(0) &&
6921 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6922 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6923 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6927 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6928 if (Options.UnsafeFPMath &&
6929 N0.getOpcode() == ISD::FMUL && N1CFP &&
6930 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6931 return DAG.getNode(ISD::FMA, dl, VT,
6933 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6937 // (fma x, 1, y) -> (fadd x, y)
6938 // (fma x, -1, y) -> (fadd (fneg x), y)
6940 if (N1CFP->isExactlyValue(1.0))
6941 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6943 if (N1CFP->isExactlyValue(-1.0) &&
6944 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6945 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6946 AddToWorklist(RHSNeg.getNode());
6947 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6951 // (fma x, c, x) -> (fmul x, (c+1))
6952 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6953 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6954 DAG.getNode(ISD::FADD, dl, VT,
6955 N1, DAG.getConstantFP(1.0, VT)));
6957 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6958 if (Options.UnsafeFPMath && N1CFP &&
6959 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6960 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6961 DAG.getNode(ISD::FADD, dl, VT,
6962 N1, DAG.getConstantFP(-1.0, VT)));
6968 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6969 SDValue N0 = N->getOperand(0);
6970 SDValue N1 = N->getOperand(1);
6971 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6972 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6973 EVT VT = N->getValueType(0);
6975 const TargetOptions &Options = DAG.getTarget().Options;
6978 if (VT.isVector()) {
6979 SDValue FoldedVOp = SimplifyVBinOp(N);
6980 if (FoldedVOp.getNode()) return FoldedVOp;
6983 // fold (fdiv c1, c2) -> c1/c2
6985 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6987 if (Options.UnsafeFPMath) {
6988 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6990 // Compute the reciprocal 1.0 / c2.
6991 APFloat N1APF = N1CFP->getValueAPF();
6992 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6993 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6994 // Only do the transform if the reciprocal is a legal fp immediate that
6995 // isn't too nasty (eg NaN, denormal, ...).
6996 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6997 (!LegalOperations ||
6998 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6999 // backend)... we should handle this gracefully after Legalize.
7000 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7001 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7002 TLI.isFPImmLegal(Recip, VT)))
7003 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7004 DAG.getConstantFP(Recip, VT));
7007 // If this FDIV is part of a reciprocal square root, it may be folded
7008 // into a target-specific square root estimate instruction.
7009 if (N1.getOpcode() == ISD::FSQRT) {
7010 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7011 AddToWorklist(RV.getNode());
7012 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7014 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7015 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7016 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7017 AddToWorklist(RV.getNode());
7018 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7019 AddToWorklist(RV.getNode());
7020 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7022 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7023 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7024 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7025 AddToWorklist(RV.getNode());
7026 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7027 AddToWorklist(RV.getNode());
7028 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7030 } else if (N1.getOpcode() == ISD::FMUL) {
7031 // Look through an FMUL. Even though this won't remove the FDIV directly,
7032 // it's still worthwhile to get rid of the FSQRT if possible.
7035 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7036 SqrtOp = N1.getOperand(0);
7037 OtherOp = N1.getOperand(1);
7038 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7039 SqrtOp = N1.getOperand(1);
7040 OtherOp = N1.getOperand(0);
7042 if (SqrtOp.getNode()) {
7043 // We found a FSQRT, so try to make this fold:
7044 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7045 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7046 AddToWorklist(RV.getNode());
7047 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7048 AddToWorklist(RV.getNode());
7049 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7054 // Fold into a reciprocal estimate and multiply instead of a real divide.
7055 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7056 AddToWorklist(RV.getNode());
7057 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7061 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7062 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7063 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7064 // Both can be negated for free, check to see if at least one is cheaper
7066 if (LHSNeg == 2 || RHSNeg == 2)
7067 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7068 GetNegatedExpression(N0, DAG, LegalOperations),
7069 GetNegatedExpression(N1, DAG, LegalOperations));
7076 SDValue DAGCombiner::visitFREM(SDNode *N) {
7077 SDValue N0 = N->getOperand(0);
7078 SDValue N1 = N->getOperand(1);
7079 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7080 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7081 EVT VT = N->getValueType(0);
7083 // fold (frem c1, c2) -> fmod(c1,c2)
7085 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7090 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7091 if (DAG.getTarget().Options.UnsafeFPMath) {
7092 // Compute this as 1/(1/sqrt(X)): the reciprocal of the reciprocal sqrt.
7093 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7094 AddToWorklist(RV.getNode());
7095 RV = BuildReciprocalEstimate(RV);
7097 // Unfortunately, RV is now NaN if the input was exactly 0.
7098 // Select out this case and force the answer to 0.
7099 EVT VT = RV.getValueType();
7101 SDValue Zero = DAG.getConstantFP(0.0, VT);
7103 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7104 N->getOperand(0), Zero, ISD::SETEQ);
7105 AddToWorklist(ZeroCmp.getNode());
7106 AddToWorklist(RV.getNode());
7108 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7109 SDLoc(N), VT, ZeroCmp, Zero, RV);
7117 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7118 SDValue N0 = N->getOperand(0);
7119 SDValue N1 = N->getOperand(1);
7120 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7121 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7122 EVT VT = N->getValueType(0);
7124 if (N0CFP && N1CFP) // Constant fold
7125 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7128 const APFloat& V = N1CFP->getValueAPF();
7129 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7130 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7131 if (!V.isNegative()) {
7132 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7133 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7135 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7136 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7137 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7141 // copysign(fabs(x), y) -> copysign(x, y)
7142 // copysign(fneg(x), y) -> copysign(x, y)
7143 // copysign(copysign(x,z), y) -> copysign(x, y)
7144 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7145 N0.getOpcode() == ISD::FCOPYSIGN)
7146 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7147 N0.getOperand(0), N1);
7149 // copysign(x, abs(y)) -> abs(x)
7150 if (N1.getOpcode() == ISD::FABS)
7151 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7153 // copysign(x, copysign(y,z)) -> copysign(x, z)
7154 if (N1.getOpcode() == ISD::FCOPYSIGN)
7155 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7156 N0, N1.getOperand(1));
7158 // copysign(x, fp_extend(y)) -> copysign(x, y)
7159 // copysign(x, fp_round(y)) -> copysign(x, y)
7160 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7161 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7162 N0, N1.getOperand(0));
7167 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7168 SDValue N0 = N->getOperand(0);
7169 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7170 EVT VT = N->getValueType(0);
7171 EVT OpVT = N0.getValueType();
7173 // fold (sint_to_fp c1) -> c1fp
7175 // ...but only if the target supports immediate floating-point values
7176 (!LegalOperations ||
7177 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7178 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7180 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7181 // but UINT_TO_FP is legal on this target, try to convert.
7182 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7183 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7184 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7185 if (DAG.SignBitIsZero(N0))
7186 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7189 // The next optimizations are desirable only if SELECT_CC can be lowered.
7190 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7191 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7192 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7194 (!LegalOperations ||
7195 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7197 { N0.getOperand(0), N0.getOperand(1),
7198 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7200 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7203 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7204 // (select_cc x, y, 1.0, 0.0,, cc)
7205 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7206 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7207 (!LegalOperations ||
7208 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7210 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7211 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7212 N0.getOperand(0).getOperand(2) };
7213 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7220 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7221 SDValue N0 = N->getOperand(0);
7222 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7223 EVT VT = N->getValueType(0);
7224 EVT OpVT = N0.getValueType();
7226 // fold (uint_to_fp c1) -> c1fp
7228 // ...but only if the target supports immediate floating-point values
7229 (!LegalOperations ||
7230 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7231 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7233 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7234 // but SINT_TO_FP is legal on this target, try to convert.
7235 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7236 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7237 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7238 if (DAG.SignBitIsZero(N0))
7239 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7242 // The next optimizations are desirable only if SELECT_CC can be lowered.
7243 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7244 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7246 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7247 (!LegalOperations ||
7248 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7250 { N0.getOperand(0), N0.getOperand(1),
7251 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7253 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7260 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7261 SDValue N0 = N->getOperand(0);
7262 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7263 EVT VT = N->getValueType(0);
7265 // fold (fp_to_sint c1fp) -> c1
7267 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7272 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7273 SDValue N0 = N->getOperand(0);
7274 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7275 EVT VT = N->getValueType(0);
7277 // fold (fp_to_uint c1fp) -> c1
7279 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7284 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7285 SDValue N0 = N->getOperand(0);
7286 SDValue N1 = N->getOperand(1);
7287 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7288 EVT VT = N->getValueType(0);
7290 // fold (fp_round c1fp) -> c1fp
7292 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7294 // fold (fp_round (fp_extend x)) -> x
7295 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7296 return N0.getOperand(0);
7298 // fold (fp_round (fp_round x)) -> (fp_round x)
7299 if (N0.getOpcode() == ISD::FP_ROUND) {
7300 // This is a value preserving truncation if both round's are.
7301 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7302 N0.getNode()->getConstantOperandVal(1) == 1;
7303 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7304 DAG.getIntPtrConstant(IsTrunc));
7307 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7308 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7309 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7310 N0.getOperand(0), N1);
7311 AddToWorklist(Tmp.getNode());
7312 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7313 Tmp, N0.getOperand(1));
7319 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7320 SDValue N0 = N->getOperand(0);
7321 EVT VT = N->getValueType(0);
7322 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7323 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7325 // fold (fp_round_inreg c1fp) -> c1fp
7326 if (N0CFP && isTypeLegal(EVT)) {
7327 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7328 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7334 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7335 SDValue N0 = N->getOperand(0);
7336 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7337 EVT VT = N->getValueType(0);
7339 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7340 if (N->hasOneUse() &&
7341 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7344 // fold (fp_extend c1fp) -> c1fp
7346 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7348 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7350 if (N0.getOpcode() == ISD::FP_ROUND
7351 && N0.getNode()->getConstantOperandVal(1) == 1) {
7352 SDValue In = N0.getOperand(0);
7353 if (In.getValueType() == VT) return In;
7354 if (VT.bitsLT(In.getValueType()))
7355 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7356 In, N0.getOperand(1));
7357 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7360 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7361 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7362 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7363 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7364 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7366 LN0->getBasePtr(), N0.getValueType(),
7367 LN0->getMemOperand());
7368 CombineTo(N, ExtLoad);
7369 CombineTo(N0.getNode(),
7370 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7371 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7372 ExtLoad.getValue(1));
7373 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7379 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7380 SDValue N0 = N->getOperand(0);
7381 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7382 EVT VT = N->getValueType(0);
7384 // fold (fceil c1) -> fceil(c1)
7386 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7391 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7392 SDValue N0 = N->getOperand(0);
7393 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7394 EVT VT = N->getValueType(0);
7396 // fold (ftrunc c1) -> ftrunc(c1)
7398 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7403 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7404 SDValue N0 = N->getOperand(0);
7405 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7406 EVT VT = N->getValueType(0);
7408 // fold (ffloor c1) -> ffloor(c1)
7410 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7415 // FIXME: FNEG and FABS have a lot in common; refactor.
7416 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7417 SDValue N0 = N->getOperand(0);
7418 EVT VT = N->getValueType(0);
7420 if (VT.isVector()) {
7421 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7422 if (FoldedVOp.getNode()) return FoldedVOp;
7425 // Constant fold FNEG.
7426 if (isa<ConstantFPSDNode>(N0))
7427 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7429 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7430 &DAG.getTarget().Options))
7431 return GetNegatedExpression(N0, DAG, LegalOperations);
7433 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7434 // constant pool values.
7435 if (!TLI.isFNegFree(VT) &&
7436 N0.getOpcode() == ISD::BITCAST &&
7437 N0.getNode()->hasOneUse()) {
7438 SDValue Int = N0.getOperand(0);
7439 EVT IntVT = Int.getValueType();
7440 if (IntVT.isInteger() && !IntVT.isVector()) {
7442 if (N0.getValueType().isVector()) {
7443 // For a vector, get a mask such as 0x80... per scalar element
7445 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7446 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7448 // For a scalar, just generate 0x80...
7449 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7451 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7452 DAG.getConstant(SignMask, IntVT));
7453 AddToWorklist(Int.getNode());
7454 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7458 // (fneg (fmul c, x)) -> (fmul -c, x)
7459 if (N0.getOpcode() == ISD::FMUL) {
7460 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7462 APFloat CVal = CFP1->getValueAPF();
7464 if (Level >= AfterLegalizeDAG &&
7465 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7466 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7468 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7469 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7476 SDValue DAGCombiner::visitFABS(SDNode *N) {
7477 SDValue N0 = N->getOperand(0);
7478 EVT VT = N->getValueType(0);
7480 if (VT.isVector()) {
7481 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7482 if (FoldedVOp.getNode()) return FoldedVOp;
7485 // fold (fabs c1) -> fabs(c1)
7486 if (isa<ConstantFPSDNode>(N0))
7487 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7489 // fold (fabs (fabs x)) -> (fabs x)
7490 if (N0.getOpcode() == ISD::FABS)
7491 return N->getOperand(0);
7493 // fold (fabs (fneg x)) -> (fabs x)
7494 // fold (fabs (fcopysign x, y)) -> (fabs x)
7495 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7496 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7498 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7499 // constant pool values.
7500 if (!TLI.isFAbsFree(VT) &&
7501 N0.getOpcode() == ISD::BITCAST &&
7502 N0.getNode()->hasOneUse()) {
7503 SDValue Int = N0.getOperand(0);
7504 EVT IntVT = Int.getValueType();
7505 if (IntVT.isInteger() && !IntVT.isVector()) {
7507 if (N0.getValueType().isVector()) {
7508 // For a vector, get a mask such as 0x7f... per scalar element
7510 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7511 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7513 // For a scalar, just generate 0x7f...
7514 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7516 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7517 DAG.getConstant(SignMask, IntVT));
7518 AddToWorklist(Int.getNode());
7519 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7526 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7527 SDValue Chain = N->getOperand(0);
7528 SDValue N1 = N->getOperand(1);
7529 SDValue N2 = N->getOperand(2);
7531 // If N is a constant we could fold this into a fallthrough or unconditional
7532 // branch. However that doesn't happen very often in normal code, because
7533 // Instcombine/SimplifyCFG should have handled the available opportunities.
7534 // If we did this folding here, it would be necessary to update the
7535 // MachineBasicBlock CFG, which is awkward.
7537 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7539 if (N1.getOpcode() == ISD::SETCC &&
7540 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7541 N1.getOperand(0).getValueType())) {
7542 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7543 Chain, N1.getOperand(2),
7544 N1.getOperand(0), N1.getOperand(1), N2);
7547 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7548 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7549 (N1.getOperand(0).hasOneUse() &&
7550 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7551 SDNode *Trunc = nullptr;
7552 if (N1.getOpcode() == ISD::TRUNCATE) {
7553 // Look pass the truncate.
7554 Trunc = N1.getNode();
7555 N1 = N1.getOperand(0);
7558 // Match this pattern so that we can generate simpler code:
7561 // %b = and i32 %a, 2
7562 // %c = srl i32 %b, 1
7563 // brcond i32 %c ...
7568 // %b = and i32 %a, 2
7569 // %c = setcc eq %b, 0
7572 // This applies only when the AND constant value has one bit set and the
7573 // SRL constant is equal to the log2 of the AND constant. The back-end is
7574 // smart enough to convert the result into a TEST/JMP sequence.
7575 SDValue Op0 = N1.getOperand(0);
7576 SDValue Op1 = N1.getOperand(1);
7578 if (Op0.getOpcode() == ISD::AND &&
7579 Op1.getOpcode() == ISD::Constant) {
7580 SDValue AndOp1 = Op0.getOperand(1);
7582 if (AndOp1.getOpcode() == ISD::Constant) {
7583 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7585 if (AndConst.isPowerOf2() &&
7586 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7588 DAG.getSetCC(SDLoc(N),
7589 getSetCCResultType(Op0.getValueType()),
7590 Op0, DAG.getConstant(0, Op0.getValueType()),
7593 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7594 MVT::Other, Chain, SetCC, N2);
7595 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7596 // will convert it back to (X & C1) >> C2.
7597 CombineTo(N, NewBRCond, false);
7598 // Truncate is dead.
7600 deleteAndRecombine(Trunc);
7601 // Replace the uses of SRL with SETCC
7602 WorklistRemover DeadNodes(*this);
7603 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7604 deleteAndRecombine(N1.getNode());
7605 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7611 // Restore N1 if the above transformation doesn't match.
7612 N1 = N->getOperand(1);
7615 // Transform br(xor(x, y)) -> br(x != y)
7616 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7617 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7618 SDNode *TheXor = N1.getNode();
7619 SDValue Op0 = TheXor->getOperand(0);
7620 SDValue Op1 = TheXor->getOperand(1);
7621 if (Op0.getOpcode() == Op1.getOpcode()) {
7622 // Avoid missing important xor optimizations.
7623 SDValue Tmp = visitXOR(TheXor);
7624 if (Tmp.getNode()) {
7625 if (Tmp.getNode() != TheXor) {
7626 DEBUG(dbgs() << "\nReplacing.8 ";
7628 dbgs() << "\nWith: ";
7629 Tmp.getNode()->dump(&DAG);
7631 WorklistRemover DeadNodes(*this);
7632 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7633 deleteAndRecombine(TheXor);
7634 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7635 MVT::Other, Chain, Tmp, N2);
7638 // visitXOR has changed XOR's operands or replaced the XOR completely,
7640 return SDValue(N, 0);
7644 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7646 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7647 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7648 Op0.getOpcode() == ISD::XOR) {
7649 TheXor = Op0.getNode();
7653 EVT SetCCVT = N1.getValueType();
7655 SetCCVT = getSetCCResultType(SetCCVT);
7656 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7659 Equal ? ISD::SETEQ : ISD::SETNE);
7660 // Replace the uses of XOR with SETCC
7661 WorklistRemover DeadNodes(*this);
7662 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7663 deleteAndRecombine(N1.getNode());
7664 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7665 MVT::Other, Chain, SetCC, N2);
7672 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7674 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7675 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7676 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7678 // If N is a constant we could fold this into a fallthrough or unconditional
7679 // branch. However that doesn't happen very often in normal code, because
7680 // Instcombine/SimplifyCFG should have handled the available opportunities.
7681 // If we did this folding here, it would be necessary to update the
7682 // MachineBasicBlock CFG, which is awkward.
7684 // Use SimplifySetCC to simplify SETCC's.
7685 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7686 CondLHS, CondRHS, CC->get(), SDLoc(N),
7688 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7690 // fold to a simpler setcc
7691 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7692 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7693 N->getOperand(0), Simp.getOperand(2),
7694 Simp.getOperand(0), Simp.getOperand(1),
7700 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7701 /// and that N may be folded in the load / store addressing mode.
7702 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7704 const TargetLowering &TLI) {
7706 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7707 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7709 VT = Use->getValueType(0);
7710 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7711 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7713 VT = ST->getValue().getValueType();
7717 TargetLowering::AddrMode AM;
7718 if (N->getOpcode() == ISD::ADD) {
7719 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7722 AM.BaseOffs = Offset->getSExtValue();
7726 } else if (N->getOpcode() == ISD::SUB) {
7727 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7730 AM.BaseOffs = -Offset->getSExtValue();
7737 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7740 /// Try turning a load/store into a pre-indexed load/store when the base
7741 /// pointer is an add or subtract and it has other uses besides the load/store.
7742 /// After the transformation, the new indexed load/store has effectively folded
7743 /// the add/subtract in and all of its other uses are redirected to the
7745 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7746 if (Level < AfterLegalizeDAG)
7752 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7753 if (LD->isIndexed())
7755 VT = LD->getMemoryVT();
7756 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7757 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7759 Ptr = LD->getBasePtr();
7760 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7761 if (ST->isIndexed())
7763 VT = ST->getMemoryVT();
7764 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7765 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7767 Ptr = ST->getBasePtr();
7773 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7774 // out. There is no reason to make this a preinc/predec.
7775 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7776 Ptr.getNode()->hasOneUse())
7779 // Ask the target to do addressing mode selection.
7782 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7783 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7786 // Backends without true r+i pre-indexed forms may need to pass a
7787 // constant base with a variable offset so that constant coercion
7788 // will work with the patterns in canonical form.
7789 bool Swapped = false;
7790 if (isa<ConstantSDNode>(BasePtr)) {
7791 std::swap(BasePtr, Offset);
7795 // Don't create a indexed load / store with zero offset.
7796 if (isa<ConstantSDNode>(Offset) &&
7797 cast<ConstantSDNode>(Offset)->isNullValue())
7800 // Try turning it into a pre-indexed load / store except when:
7801 // 1) The new base ptr is a frame index.
7802 // 2) If N is a store and the new base ptr is either the same as or is a
7803 // predecessor of the value being stored.
7804 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7805 // that would create a cycle.
7806 // 4) All uses are load / store ops that use it as old base ptr.
7808 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7809 // (plus the implicit offset) to a register to preinc anyway.
7810 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7815 SDValue Val = cast<StoreSDNode>(N)->getValue();
7816 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7820 // If the offset is a constant, there may be other adds of constants that
7821 // can be folded with this one. We should do this to avoid having to keep
7822 // a copy of the original base pointer.
7823 SmallVector<SDNode *, 16> OtherUses;
7824 if (isa<ConstantSDNode>(Offset))
7825 for (SDNode *Use : BasePtr.getNode()->uses()) {
7826 if (Use == Ptr.getNode())
7829 if (Use->isPredecessorOf(N))
7832 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7837 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7838 if (Op1.getNode() == BasePtr.getNode())
7839 std::swap(Op0, Op1);
7840 assert(Op0.getNode() == BasePtr.getNode() &&
7841 "Use of ADD/SUB but not an operand");
7843 if (!isa<ConstantSDNode>(Op1)) {
7848 // FIXME: In some cases, we can be smarter about this.
7849 if (Op1.getValueType() != Offset.getValueType()) {
7854 OtherUses.push_back(Use);
7858 std::swap(BasePtr, Offset);
7860 // Now check for #3 and #4.
7861 bool RealUse = false;
7863 // Caches for hasPredecessorHelper
7864 SmallPtrSet<const SDNode *, 32> Visited;
7865 SmallVector<const SDNode *, 16> Worklist;
7867 for (SDNode *Use : Ptr.getNode()->uses()) {
7870 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7873 // If Ptr may be folded in addressing mode of other use, then it's
7874 // not profitable to do this transformation.
7875 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7884 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7885 BasePtr, Offset, AM);
7887 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7888 BasePtr, Offset, AM);
7891 DEBUG(dbgs() << "\nReplacing.4 ";
7893 dbgs() << "\nWith: ";
7894 Result.getNode()->dump(&DAG);
7896 WorklistRemover DeadNodes(*this);
7898 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7899 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7901 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7904 // Finally, since the node is now dead, remove it from the graph.
7905 deleteAndRecombine(N);
7908 std::swap(BasePtr, Offset);
7910 // Replace other uses of BasePtr that can be updated to use Ptr
7911 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7912 unsigned OffsetIdx = 1;
7913 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7915 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7916 BasePtr.getNode() && "Expected BasePtr operand");
7918 // We need to replace ptr0 in the following expression:
7919 // x0 * offset0 + y0 * ptr0 = t0
7921 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7923 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7924 // indexed load/store and the expresion that needs to be re-written.
7926 // Therefore, we have:
7927 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7929 ConstantSDNode *CN =
7930 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7932 APInt Offset0 = CN->getAPIntValue();
7933 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7935 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7936 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7937 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7938 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7940 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7942 APInt CNV = Offset0;
7943 if (X0 < 0) CNV = -CNV;
7944 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7945 else CNV = CNV - Offset1;
7947 // We can now generate the new expression.
7948 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7949 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7951 SDValue NewUse = DAG.getNode(Opcode,
7952 SDLoc(OtherUses[i]),
7953 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7954 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7955 deleteAndRecombine(OtherUses[i]);
7958 // Replace the uses of Ptr with uses of the updated base value.
7959 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7960 deleteAndRecombine(Ptr.getNode());
7965 /// Try to combine a load/store with a add/sub of the base pointer node into a
7966 /// post-indexed load/store. The transformation folded the add/subtract into the
7967 /// new indexed load/store effectively and all of its uses are redirected to the
7969 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7970 if (Level < AfterLegalizeDAG)
7976 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7977 if (LD->isIndexed())
7979 VT = LD->getMemoryVT();
7980 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7981 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7983 Ptr = LD->getBasePtr();
7984 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7985 if (ST->isIndexed())
7987 VT = ST->getMemoryVT();
7988 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7989 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7991 Ptr = ST->getBasePtr();
7997 if (Ptr.getNode()->hasOneUse())
8000 for (SDNode *Op : Ptr.getNode()->uses()) {
8002 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8007 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8008 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8009 // Don't create a indexed load / store with zero offset.
8010 if (isa<ConstantSDNode>(Offset) &&
8011 cast<ConstantSDNode>(Offset)->isNullValue())
8014 // Try turning it into a post-indexed load / store except when
8015 // 1) All uses are load / store ops that use it as base ptr (and
8016 // it may be folded as addressing mmode).
8017 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8018 // nor a successor of N. Otherwise, if Op is folded that would
8021 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8025 bool TryNext = false;
8026 for (SDNode *Use : BasePtr.getNode()->uses()) {
8027 if (Use == Ptr.getNode())
8030 // If all the uses are load / store addresses, then don't do the
8032 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8033 bool RealUse = false;
8034 for (SDNode *UseUse : Use->uses()) {
8035 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8050 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8051 SDValue Result = isLoad
8052 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8053 BasePtr, Offset, AM)
8054 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8055 BasePtr, Offset, AM);
8058 DEBUG(dbgs() << "\nReplacing.5 ";
8060 dbgs() << "\nWith: ";
8061 Result.getNode()->dump(&DAG);
8063 WorklistRemover DeadNodes(*this);
8065 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8066 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8068 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8071 // Finally, since the node is now dead, remove it from the graph.
8072 deleteAndRecombine(N);
8074 // Replace the uses of Use with uses of the updated base value.
8075 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8076 Result.getValue(isLoad ? 1 : 0));
8077 deleteAndRecombine(Op);
8086 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8087 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8088 ISD::MemIndexedMode AM = LD->getAddressingMode();
8089 assert(AM != ISD::UNINDEXED);
8090 SDValue BP = LD->getOperand(1);
8091 SDValue Inc = LD->getOperand(2);
8093 // Some backends use TargetConstants for load offsets, but don't expect
8094 // TargetConstants in general ADD nodes. We can convert these constants into
8095 // regular Constants (if the constant is not opaque).
8096 assert((Inc.getOpcode() != ISD::TargetConstant ||
8097 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8098 "Cannot split out indexing using opaque target constants");
8099 if (Inc.getOpcode() == ISD::TargetConstant) {
8100 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8101 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8102 ConstInc->getValueType(0));
8106 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8107 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8110 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8111 LoadSDNode *LD = cast<LoadSDNode>(N);
8112 SDValue Chain = LD->getChain();
8113 SDValue Ptr = LD->getBasePtr();
8115 // If load is not volatile and there are no uses of the loaded value (and
8116 // the updated indexed value in case of indexed loads), change uses of the
8117 // chain value into uses of the chain input (i.e. delete the dead load).
8118 if (!LD->isVolatile()) {
8119 if (N->getValueType(1) == MVT::Other) {
8121 if (!N->hasAnyUseOfValue(0)) {
8122 // It's not safe to use the two value CombineTo variant here. e.g.
8123 // v1, chain2 = load chain1, loc
8124 // v2, chain3 = load chain2, loc
8126 // Now we replace use of chain2 with chain1. This makes the second load
8127 // isomorphic to the one we are deleting, and thus makes this load live.
8128 DEBUG(dbgs() << "\nReplacing.6 ";
8130 dbgs() << "\nWith chain: ";
8131 Chain.getNode()->dump(&DAG);
8133 WorklistRemover DeadNodes(*this);
8134 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8137 deleteAndRecombine(N);
8139 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8143 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8145 // If this load has an opaque TargetConstant offset, then we cannot split
8146 // the indexing into an add/sub directly (that TargetConstant may not be
8147 // valid for a different type of node, and we cannot convert an opaque
8148 // target constant into a regular constant).
8149 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8150 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8152 if (!N->hasAnyUseOfValue(0) &&
8153 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8154 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8156 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8157 Index = SplitIndexingFromLoad(LD);
8158 // Try to fold the base pointer arithmetic into subsequent loads and
8160 AddUsersToWorklist(N);
8162 Index = DAG.getUNDEF(N->getValueType(1));
8163 DEBUG(dbgs() << "\nReplacing.7 ";
8165 dbgs() << "\nWith: ";
8166 Undef.getNode()->dump(&DAG);
8167 dbgs() << " and 2 other values\n");
8168 WorklistRemover DeadNodes(*this);
8169 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8170 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8171 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8172 deleteAndRecombine(N);
8173 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8178 // If this load is directly stored, replace the load value with the stored
8180 // TODO: Handle store large -> read small portion.
8181 // TODO: Handle TRUNCSTORE/LOADEXT
8182 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8183 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8184 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8185 if (PrevST->getBasePtr() == Ptr &&
8186 PrevST->getValue().getValueType() == N->getValueType(0))
8187 return CombineTo(N, Chain.getOperand(1), Chain);
8191 // Try to infer better alignment information than the load already has.
8192 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8193 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8194 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8196 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8197 LD->getValueType(0),
8198 Chain, Ptr, LD->getPointerInfo(),
8200 LD->isVolatile(), LD->isNonTemporal(),
8201 LD->isInvariant(), Align, LD->getAAInfo());
8202 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8207 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8208 : DAG.getSubtarget().useAA();
8210 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8211 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8214 if (UseAA && LD->isUnindexed()) {
8215 // Walk up chain skipping non-aliasing memory nodes.
8216 SDValue BetterChain = FindBetterChain(N, Chain);
8218 // If there is a better chain.
8219 if (Chain != BetterChain) {
8222 // Replace the chain to void dependency.
8223 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8224 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8225 BetterChain, Ptr, LD->getMemOperand());
8227 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8228 LD->getValueType(0),
8229 BetterChain, Ptr, LD->getMemoryVT(),
8230 LD->getMemOperand());
8233 // Create token factor to keep old chain connected.
8234 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8235 MVT::Other, Chain, ReplLoad.getValue(1));
8237 // Make sure the new and old chains are cleaned up.
8238 AddToWorklist(Token.getNode());
8240 // Replace uses with load result and token factor. Don't add users
8242 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8246 // Try transforming N to an indexed load.
8247 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8248 return SDValue(N, 0);
8250 // Try to slice up N to more direct loads if the slices are mapped to
8251 // different register banks or pairing can take place.
8253 return SDValue(N, 0);
8259 /// \brief Helper structure used to slice a load in smaller loads.
8260 /// Basically a slice is obtained from the following sequence:
8261 /// Origin = load Ty1, Base
8262 /// Shift = srl Ty1 Origin, CstTy Amount
8263 /// Inst = trunc Shift to Ty2
8265 /// Then, it will be rewriten into:
8266 /// Slice = load SliceTy, Base + SliceOffset
8267 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8269 /// SliceTy is deduced from the number of bits that are actually used to
8271 struct LoadedSlice {
8272 /// \brief Helper structure used to compute the cost of a slice.
8274 /// Are we optimizing for code size.
8279 unsigned CrossRegisterBanksCopies;
8283 Cost(bool ForCodeSize = false)
8284 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8285 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8287 /// \brief Get the cost of one isolated slice.
8288 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8289 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8290 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8291 EVT TruncType = LS.Inst->getValueType(0);
8292 EVT LoadedType = LS.getLoadedType();
8293 if (TruncType != LoadedType &&
8294 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8298 /// \brief Account for slicing gain in the current cost.
8299 /// Slicing provide a few gains like removing a shift or a
8300 /// truncate. This method allows to grow the cost of the original
8301 /// load with the gain from this slice.
8302 void addSliceGain(const LoadedSlice &LS) {
8303 // Each slice saves a truncate.
8304 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8305 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8306 LS.Inst->getOperand(0).getValueType()))
8308 // If there is a shift amount, this slice gets rid of it.
8311 // If this slice can merge a cross register bank copy, account for it.
8312 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8313 ++CrossRegisterBanksCopies;
8316 Cost &operator+=(const Cost &RHS) {
8318 Truncates += RHS.Truncates;
8319 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8325 bool operator==(const Cost &RHS) const {
8326 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8327 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8328 ZExts == RHS.ZExts && Shift == RHS.Shift;
8331 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8333 bool operator<(const Cost &RHS) const {
8334 // Assume cross register banks copies are as expensive as loads.
8335 // FIXME: Do we want some more target hooks?
8336 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8337 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8338 // Unless we are optimizing for code size, consider the
8339 // expensive operation first.
8340 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8341 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8342 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8343 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8346 bool operator>(const Cost &RHS) const { return RHS < *this; }
8348 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8350 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8352 // The last instruction that represent the slice. This should be a
8353 // truncate instruction.
8355 // The original load instruction.
8357 // The right shift amount in bits from the original load.
8359 // The DAG from which Origin came from.
8360 // This is used to get some contextual information about legal types, etc.
8363 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8364 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8365 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8367 LoadedSlice(const LoadedSlice &LS)
8368 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8370 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8371 /// \return Result is \p BitWidth and has used bits set to 1 and
8372 /// not used bits set to 0.
8373 APInt getUsedBits() const {
8374 // Reproduce the trunc(lshr) sequence:
8375 // - Start from the truncated value.
8376 // - Zero extend to the desired bit width.
8378 assert(Origin && "No original load to compare against.");
8379 unsigned BitWidth = Origin->getValueSizeInBits(0);
8380 assert(Inst && "This slice is not bound to an instruction");
8381 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8382 "Extracted slice is bigger than the whole type!");
8383 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8384 UsedBits.setAllBits();
8385 UsedBits = UsedBits.zext(BitWidth);
8390 /// \brief Get the size of the slice to be loaded in bytes.
8391 unsigned getLoadedSize() const {
8392 unsigned SliceSize = getUsedBits().countPopulation();
8393 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8394 return SliceSize / 8;
8397 /// \brief Get the type that will be loaded for this slice.
8398 /// Note: This may not be the final type for the slice.
8399 EVT getLoadedType() const {
8400 assert(DAG && "Missing context");
8401 LLVMContext &Ctxt = *DAG->getContext();
8402 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8405 /// \brief Get the alignment of the load used for this slice.
8406 unsigned getAlignment() const {
8407 unsigned Alignment = Origin->getAlignment();
8408 unsigned Offset = getOffsetFromBase();
8410 Alignment = MinAlign(Alignment, Alignment + Offset);
8414 /// \brief Check if this slice can be rewritten with legal operations.
8415 bool isLegal() const {
8416 // An invalid slice is not legal.
8417 if (!Origin || !Inst || !DAG)
8420 // Offsets are for indexed load only, we do not handle that.
8421 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8424 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8426 // Check that the type is legal.
8427 EVT SliceType = getLoadedType();
8428 if (!TLI.isTypeLegal(SliceType))
8431 // Check that the load is legal for this type.
8432 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8435 // Check that the offset can be computed.
8436 // 1. Check its type.
8437 EVT PtrType = Origin->getBasePtr().getValueType();
8438 if (PtrType == MVT::Untyped || PtrType.isExtended())
8441 // 2. Check that it fits in the immediate.
8442 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8445 // 3. Check that the computation is legal.
8446 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8449 // Check that the zext is legal if it needs one.
8450 EVT TruncateType = Inst->getValueType(0);
8451 if (TruncateType != SliceType &&
8452 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8458 /// \brief Get the offset in bytes of this slice in the original chunk of
8460 /// \pre DAG != nullptr.
8461 uint64_t getOffsetFromBase() const {
8462 assert(DAG && "Missing context.");
8464 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8465 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8466 uint64_t Offset = Shift / 8;
8467 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8468 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8469 "The size of the original loaded type is not a multiple of a"
8471 // If Offset is bigger than TySizeInBytes, it means we are loading all
8472 // zeros. This should have been optimized before in the process.
8473 assert(TySizeInBytes > Offset &&
8474 "Invalid shift amount for given loaded size");
8476 Offset = TySizeInBytes - Offset - getLoadedSize();
8480 /// \brief Generate the sequence of instructions to load the slice
8481 /// represented by this object and redirect the uses of this slice to
8482 /// this new sequence of instructions.
8483 /// \pre this->Inst && this->Origin are valid Instructions and this
8484 /// object passed the legal check: LoadedSlice::isLegal returned true.
8485 /// \return The last instruction of the sequence used to load the slice.
8486 SDValue loadSlice() const {
8487 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8488 const SDValue &OldBaseAddr = Origin->getBasePtr();
8489 SDValue BaseAddr = OldBaseAddr;
8490 // Get the offset in that chunk of bytes w.r.t. the endianess.
8491 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8492 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8494 // BaseAddr = BaseAddr + Offset.
8495 EVT ArithType = BaseAddr.getValueType();
8496 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8497 DAG->getConstant(Offset, ArithType));
8500 // Create the type of the loaded slice according to its size.
8501 EVT SliceType = getLoadedType();
8503 // Create the load for the slice.
8504 SDValue LastInst = DAG->getLoad(
8505 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8506 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8507 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8508 // If the final type is not the same as the loaded type, this means that
8509 // we have to pad with zero. Create a zero extend for that.
8510 EVT FinalType = Inst->getValueType(0);
8511 if (SliceType != FinalType)
8513 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8517 /// \brief Check if this slice can be merged with an expensive cross register
8518 /// bank copy. E.g.,
8520 /// f = bitcast i32 i to float
8521 bool canMergeExpensiveCrossRegisterBankCopy() const {
8522 if (!Inst || !Inst->hasOneUse())
8524 SDNode *Use = *Inst->use_begin();
8525 if (Use->getOpcode() != ISD::BITCAST)
8527 assert(DAG && "Missing context");
8528 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8529 EVT ResVT = Use->getValueType(0);
8530 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8531 const TargetRegisterClass *ArgRC =
8532 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8533 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8536 // At this point, we know that we perform a cross-register-bank copy.
8537 // Check if it is expensive.
8538 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8539 // Assume bitcasts are cheap, unless both register classes do not
8540 // explicitly share a common sub class.
8541 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8544 // Check if it will be merged with the load.
8545 // 1. Check the alignment constraint.
8546 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8547 ResVT.getTypeForEVT(*DAG->getContext()));
8549 if (RequiredAlignment > getAlignment())
8552 // 2. Check that the load is a legal operation for that type.
8553 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8556 // 3. Check that we do not have a zext in the way.
8557 if (Inst->getValueType(0) != getLoadedType())
8565 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8566 /// \p UsedBits looks like 0..0 1..1 0..0.
8567 static bool areUsedBitsDense(const APInt &UsedBits) {
8568 // If all the bits are one, this is dense!
8569 if (UsedBits.isAllOnesValue())
8572 // Get rid of the unused bits on the right.
8573 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8574 // Get rid of the unused bits on the left.
8575 if (NarrowedUsedBits.countLeadingZeros())
8576 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8577 // Check that the chunk of bits is completely used.
8578 return NarrowedUsedBits.isAllOnesValue();
8581 /// \brief Check whether or not \p First and \p Second are next to each other
8582 /// in memory. This means that there is no hole between the bits loaded
8583 /// by \p First and the bits loaded by \p Second.
8584 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8585 const LoadedSlice &Second) {
8586 assert(First.Origin == Second.Origin && First.Origin &&
8587 "Unable to match different memory origins.");
8588 APInt UsedBits = First.getUsedBits();
8589 assert((UsedBits & Second.getUsedBits()) == 0 &&
8590 "Slices are not supposed to overlap.");
8591 UsedBits |= Second.getUsedBits();
8592 return areUsedBitsDense(UsedBits);
8595 /// \brief Adjust the \p GlobalLSCost according to the target
8596 /// paring capabilities and the layout of the slices.
8597 /// \pre \p GlobalLSCost should account for at least as many loads as
8598 /// there is in the slices in \p LoadedSlices.
8599 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8600 LoadedSlice::Cost &GlobalLSCost) {
8601 unsigned NumberOfSlices = LoadedSlices.size();
8602 // If there is less than 2 elements, no pairing is possible.
8603 if (NumberOfSlices < 2)
8606 // Sort the slices so that elements that are likely to be next to each
8607 // other in memory are next to each other in the list.
8608 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8609 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8610 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8611 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8613 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8614 // First (resp. Second) is the first (resp. Second) potentially candidate
8615 // to be placed in a paired load.
8616 const LoadedSlice *First = nullptr;
8617 const LoadedSlice *Second = nullptr;
8618 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8619 // Set the beginning of the pair.
8622 Second = &LoadedSlices[CurrSlice];
8624 // If First is NULL, it means we start a new pair.
8625 // Get to the next slice.
8629 EVT LoadedType = First->getLoadedType();
8631 // If the types of the slices are different, we cannot pair them.
8632 if (LoadedType != Second->getLoadedType())
8635 // Check if the target supplies paired loads for this type.
8636 unsigned RequiredAlignment = 0;
8637 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8638 // move to the next pair, this type is hopeless.
8642 // Check if we meet the alignment requirement.
8643 if (RequiredAlignment > First->getAlignment())
8646 // Check that both loads are next to each other in memory.
8647 if (!areSlicesNextToEachOther(*First, *Second))
8650 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8651 --GlobalLSCost.Loads;
8652 // Move to the next pair.
8657 /// \brief Check the profitability of all involved LoadedSlice.
8658 /// Currently, it is considered profitable if there is exactly two
8659 /// involved slices (1) which are (2) next to each other in memory, and
8660 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8662 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8663 /// the elements themselves.
8665 /// FIXME: When the cost model will be mature enough, we can relax
8666 /// constraints (1) and (2).
8667 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8668 const APInt &UsedBits, bool ForCodeSize) {
8669 unsigned NumberOfSlices = LoadedSlices.size();
8670 if (StressLoadSlicing)
8671 return NumberOfSlices > 1;
8674 if (NumberOfSlices != 2)
8678 if (!areUsedBitsDense(UsedBits))
8682 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8683 // The original code has one big load.
8685 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8686 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8687 // Accumulate the cost of all the slices.
8688 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8689 GlobalSlicingCost += SliceCost;
8691 // Account as cost in the original configuration the gain obtained
8692 // with the current slices.
8693 OrigCost.addSliceGain(LS);
8696 // If the target supports paired load, adjust the cost accordingly.
8697 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8698 return OrigCost > GlobalSlicingCost;
8701 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8702 /// operations, split it in the various pieces being extracted.
8704 /// This sort of thing is introduced by SROA.
8705 /// This slicing takes care not to insert overlapping loads.
8706 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8707 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8708 if (Level < AfterLegalizeDAG)
8711 LoadSDNode *LD = cast<LoadSDNode>(N);
8712 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8713 !LD->getValueType(0).isInteger())
8716 // Keep track of already used bits to detect overlapping values.
8717 // In that case, we will just abort the transformation.
8718 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8720 SmallVector<LoadedSlice, 4> LoadedSlices;
8722 // Check if this load is used as several smaller chunks of bits.
8723 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8724 // of computation for each trunc.
8725 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8726 UI != UIEnd; ++UI) {
8727 // Skip the uses of the chain.
8728 if (UI.getUse().getResNo() != 0)
8734 // Check if this is a trunc(lshr).
8735 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8736 isa<ConstantSDNode>(User->getOperand(1))) {
8737 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8738 User = *User->use_begin();
8741 // At this point, User is a Truncate, iff we encountered, trunc or
8743 if (User->getOpcode() != ISD::TRUNCATE)
8746 // The width of the type must be a power of 2 and greater than 8-bits.
8747 // Otherwise the load cannot be represented in LLVM IR.
8748 // Moreover, if we shifted with a non-8-bits multiple, the slice
8749 // will be across several bytes. We do not support that.
8750 unsigned Width = User->getValueSizeInBits(0);
8751 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8754 // Build the slice for this chain of computations.
8755 LoadedSlice LS(User, LD, Shift, &DAG);
8756 APInt CurrentUsedBits = LS.getUsedBits();
8758 // Check if this slice overlaps with another.
8759 if ((CurrentUsedBits & UsedBits) != 0)
8761 // Update the bits used globally.
8762 UsedBits |= CurrentUsedBits;
8764 // Check if the new slice would be legal.
8768 // Record the slice.
8769 LoadedSlices.push_back(LS);
8772 // Abort slicing if it does not seem to be profitable.
8773 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8778 // Rewrite each chain to use an independent load.
8779 // By construction, each chain can be represented by a unique load.
8781 // Prepare the argument for the new token factor for all the slices.
8782 SmallVector<SDValue, 8> ArgChains;
8783 for (SmallVectorImpl<LoadedSlice>::const_iterator
8784 LSIt = LoadedSlices.begin(),
8785 LSItEnd = LoadedSlices.end();
8786 LSIt != LSItEnd; ++LSIt) {
8787 SDValue SliceInst = LSIt->loadSlice();
8788 CombineTo(LSIt->Inst, SliceInst, true);
8789 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8790 SliceInst = SliceInst.getOperand(0);
8791 assert(SliceInst->getOpcode() == ISD::LOAD &&
8792 "It takes more than a zext to get to the loaded slice!!");
8793 ArgChains.push_back(SliceInst.getValue(1));
8796 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8798 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8802 /// Check to see if V is (and load (ptr), imm), where the load is having
8803 /// specific bytes cleared out. If so, return the byte size being masked out
8804 /// and the shift amount.
8805 static std::pair<unsigned, unsigned>
8806 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8807 std::pair<unsigned, unsigned> Result(0, 0);
8809 // Check for the structure we're looking for.
8810 if (V->getOpcode() != ISD::AND ||
8811 !isa<ConstantSDNode>(V->getOperand(1)) ||
8812 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8815 // Check the chain and pointer.
8816 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8817 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8819 // The store should be chained directly to the load or be an operand of a
8821 if (LD == Chain.getNode())
8823 else if (Chain->getOpcode() != ISD::TokenFactor)
8824 return Result; // Fail.
8827 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8828 if (Chain->getOperand(i).getNode() == LD) {
8832 if (!isOk) return Result;
8835 // This only handles simple types.
8836 if (V.getValueType() != MVT::i16 &&
8837 V.getValueType() != MVT::i32 &&
8838 V.getValueType() != MVT::i64)
8841 // Check the constant mask. Invert it so that the bits being masked out are
8842 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8843 // follow the sign bit for uniformity.
8844 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8845 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8846 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8847 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8848 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8849 if (NotMaskLZ == 64) return Result; // All zero mask.
8851 // See if we have a continuous run of bits. If so, we have 0*1+0*
8852 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8855 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8856 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8857 NotMaskLZ -= 64-V.getValueSizeInBits();
8859 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8860 switch (MaskedBytes) {
8864 default: return Result; // All one mask, or 5-byte mask.
8867 // Verify that the first bit starts at a multiple of mask so that the access
8868 // is aligned the same as the access width.
8869 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8871 Result.first = MaskedBytes;
8872 Result.second = NotMaskTZ/8;
8877 /// Check to see if IVal is something that provides a value as specified by
8878 /// MaskInfo. If so, replace the specified store with a narrower store of
8881 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8882 SDValue IVal, StoreSDNode *St,
8884 unsigned NumBytes = MaskInfo.first;
8885 unsigned ByteShift = MaskInfo.second;
8886 SelectionDAG &DAG = DC->getDAG();
8888 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8889 // that uses this. If not, this is not a replacement.
8890 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8891 ByteShift*8, (ByteShift+NumBytes)*8);
8892 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8894 // Check that it is legal on the target to do this. It is legal if the new
8895 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8897 MVT VT = MVT::getIntegerVT(NumBytes*8);
8898 if (!DC->isTypeLegal(VT))
8901 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8902 // shifted by ByteShift and truncated down to NumBytes.
8904 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8905 DAG.getConstant(ByteShift*8,
8906 DC->getShiftAmountTy(IVal.getValueType())));
8908 // Figure out the offset for the store and the alignment of the access.
8910 unsigned NewAlign = St->getAlignment();
8912 if (DAG.getTargetLoweringInfo().isLittleEndian())
8913 StOffset = ByteShift;
8915 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8917 SDValue Ptr = St->getBasePtr();
8919 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8920 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8921 NewAlign = MinAlign(NewAlign, StOffset);
8924 // Truncate down to the new size.
8925 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8928 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8929 St->getPointerInfo().getWithOffset(StOffset),
8930 false, false, NewAlign).getNode();
8934 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8935 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8936 /// narrowing the load and store if it would end up being a win for performance
8938 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8939 StoreSDNode *ST = cast<StoreSDNode>(N);
8940 if (ST->isVolatile())
8943 SDValue Chain = ST->getChain();
8944 SDValue Value = ST->getValue();
8945 SDValue Ptr = ST->getBasePtr();
8946 EVT VT = Value.getValueType();
8948 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8951 unsigned Opc = Value.getOpcode();
8953 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8954 // is a byte mask indicating a consecutive number of bytes, check to see if
8955 // Y is known to provide just those bytes. If so, we try to replace the
8956 // load + replace + store sequence with a single (narrower) store, which makes
8958 if (Opc == ISD::OR) {
8959 std::pair<unsigned, unsigned> MaskedLoad;
8960 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8961 if (MaskedLoad.first)
8962 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8963 Value.getOperand(1), ST,this))
8964 return SDValue(NewST, 0);
8966 // Or is commutative, so try swapping X and Y.
8967 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8968 if (MaskedLoad.first)
8969 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8970 Value.getOperand(0), ST,this))
8971 return SDValue(NewST, 0);
8974 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8975 Value.getOperand(1).getOpcode() != ISD::Constant)
8978 SDValue N0 = Value.getOperand(0);
8979 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8980 Chain == SDValue(N0.getNode(), 1)) {
8981 LoadSDNode *LD = cast<LoadSDNode>(N0);
8982 if (LD->getBasePtr() != Ptr ||
8983 LD->getPointerInfo().getAddrSpace() !=
8984 ST->getPointerInfo().getAddrSpace())
8987 // Find the type to narrow it the load / op / store to.
8988 SDValue N1 = Value.getOperand(1);
8989 unsigned BitWidth = N1.getValueSizeInBits();
8990 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8991 if (Opc == ISD::AND)
8992 Imm ^= APInt::getAllOnesValue(BitWidth);
8993 if (Imm == 0 || Imm.isAllOnesValue())
8995 unsigned ShAmt = Imm.countTrailingZeros();
8996 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8997 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8998 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8999 while (NewBW < BitWidth &&
9000 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9001 TLI.isNarrowingProfitable(VT, NewVT))) {
9002 NewBW = NextPowerOf2(NewBW);
9003 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9005 if (NewBW >= BitWidth)
9008 // If the lsb changed does not start at the type bitwidth boundary,
9009 // start at the previous one.
9011 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9012 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9013 std::min(BitWidth, ShAmt + NewBW));
9014 if ((Imm & Mask) == Imm) {
9015 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9016 if (Opc == ISD::AND)
9017 NewImm ^= APInt::getAllOnesValue(NewBW);
9018 uint64_t PtrOff = ShAmt / 8;
9019 // For big endian targets, we need to adjust the offset to the pointer to
9020 // load the correct bytes.
9021 if (TLI.isBigEndian())
9022 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9024 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9025 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9026 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9029 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9030 Ptr.getValueType(), Ptr,
9031 DAG.getConstant(PtrOff, Ptr.getValueType()));
9032 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9033 LD->getChain(), NewPtr,
9034 LD->getPointerInfo().getWithOffset(PtrOff),
9035 LD->isVolatile(), LD->isNonTemporal(),
9036 LD->isInvariant(), NewAlign,
9038 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9039 DAG.getConstant(NewImm, NewVT));
9040 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9042 ST->getPointerInfo().getWithOffset(PtrOff),
9043 false, false, NewAlign);
9045 AddToWorklist(NewPtr.getNode());
9046 AddToWorklist(NewLD.getNode());
9047 AddToWorklist(NewVal.getNode());
9048 WorklistRemover DeadNodes(*this);
9049 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9058 /// For a given floating point load / store pair, if the load value isn't used
9059 /// by any other operations, then consider transforming the pair to integer
9060 /// load / store operations if the target deems the transformation profitable.
9061 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9062 StoreSDNode *ST = cast<StoreSDNode>(N);
9063 SDValue Chain = ST->getChain();
9064 SDValue Value = ST->getValue();
9065 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9066 Value.hasOneUse() &&
9067 Chain == SDValue(Value.getNode(), 1)) {
9068 LoadSDNode *LD = cast<LoadSDNode>(Value);
9069 EVT VT = LD->getMemoryVT();
9070 if (!VT.isFloatingPoint() ||
9071 VT != ST->getMemoryVT() ||
9072 LD->isNonTemporal() ||
9073 ST->isNonTemporal() ||
9074 LD->getPointerInfo().getAddrSpace() != 0 ||
9075 ST->getPointerInfo().getAddrSpace() != 0)
9078 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9079 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9080 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9081 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9082 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9085 unsigned LDAlign = LD->getAlignment();
9086 unsigned STAlign = ST->getAlignment();
9087 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9088 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9089 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9092 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9093 LD->getChain(), LD->getBasePtr(),
9094 LD->getPointerInfo(),
9095 false, false, false, LDAlign);
9097 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9098 NewLD, ST->getBasePtr(),
9099 ST->getPointerInfo(),
9100 false, false, STAlign);
9102 AddToWorklist(NewLD.getNode());
9103 AddToWorklist(NewST.getNode());
9104 WorklistRemover DeadNodes(*this);
9105 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9113 /// Helper struct to parse and store a memory address as base + index + offset.
9114 /// We ignore sign extensions when it is safe to do so.
9115 /// The following two expressions are not equivalent. To differentiate we need
9116 /// to store whether there was a sign extension involved in the index
9118 /// (load (i64 add (i64 copyfromreg %c)
9119 /// (i64 signextend (add (i8 load %index)
9123 /// (load (i64 add (i64 copyfromreg %c)
9124 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9126 struct BaseIndexOffset {
9130 bool IsIndexSignExt;
9132 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9134 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9135 bool IsIndexSignExt) :
9136 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9138 bool equalBaseIndex(const BaseIndexOffset &Other) {
9139 return Other.Base == Base && Other.Index == Index &&
9140 Other.IsIndexSignExt == IsIndexSignExt;
9143 /// Parses tree in Ptr for base, index, offset addresses.
9144 static BaseIndexOffset match(SDValue Ptr) {
9145 bool IsIndexSignExt = false;
9147 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9148 // instruction, then it could be just the BASE or everything else we don't
9149 // know how to handle. Just use Ptr as BASE and give up.
9150 if (Ptr->getOpcode() != ISD::ADD)
9151 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9153 // We know that we have at least an ADD instruction. Try to pattern match
9154 // the simple case of BASE + OFFSET.
9155 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9156 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9157 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9161 // Inside a loop the current BASE pointer is calculated using an ADD and a
9162 // MUL instruction. In this case Ptr is the actual BASE pointer.
9163 // (i64 add (i64 %array_ptr)
9164 // (i64 mul (i64 %induction_var)
9165 // (i64 %element_size)))
9166 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9167 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9169 // Look at Base + Index + Offset cases.
9170 SDValue Base = Ptr->getOperand(0);
9171 SDValue IndexOffset = Ptr->getOperand(1);
9173 // Skip signextends.
9174 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9175 IndexOffset = IndexOffset->getOperand(0);
9176 IsIndexSignExt = true;
9179 // Either the case of Base + Index (no offset) or something else.
9180 if (IndexOffset->getOpcode() != ISD::ADD)
9181 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9183 // Now we have the case of Base + Index + offset.
9184 SDValue Index = IndexOffset->getOperand(0);
9185 SDValue Offset = IndexOffset->getOperand(1);
9187 if (!isa<ConstantSDNode>(Offset))
9188 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9190 // Ignore signextends.
9191 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9192 Index = Index->getOperand(0);
9193 IsIndexSignExt = true;
9194 } else IsIndexSignExt = false;
9196 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9197 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9201 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9202 /// is located in a sequence of memory operations connected by a chain.
9204 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9205 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9206 // Ptr to the mem node.
9207 LSBaseSDNode *MemNode;
9208 // Offset from the base ptr.
9209 int64_t OffsetFromBase;
9210 // What is the sequence number of this mem node.
9211 // Lowest mem operand in the DAG starts at zero.
9212 unsigned SequenceNum;
9215 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9216 EVT MemVT = St->getMemoryVT();
9217 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9218 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9219 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9221 // Don't merge vectors into wider inputs.
9222 if (MemVT.isVector() || !MemVT.isSimple())
9225 // Perform an early exit check. Do not bother looking at stored values that
9226 // are not constants or loads.
9227 SDValue StoredVal = St->getValue();
9228 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9229 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9233 // Only look at ends of store sequences.
9234 SDValue Chain = SDValue(St, 0);
9235 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9238 // This holds the base pointer, index, and the offset in bytes from the base
9240 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9242 // We must have a base and an offset.
9243 if (!BasePtr.Base.getNode())
9246 // Do not handle stores to undef base pointers.
9247 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9250 // Save the LoadSDNodes that we find in the chain.
9251 // We need to make sure that these nodes do not interfere with
9252 // any of the store nodes.
9253 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9255 // Save the StoreSDNodes that we find in the chain.
9256 SmallVector<MemOpLink, 8> StoreNodes;
9258 // Walk up the chain and look for nodes with offsets from the same
9259 // base pointer. Stop when reaching an instruction with a different kind
9260 // or instruction which has a different base pointer.
9262 StoreSDNode *Index = St;
9264 // If the chain has more than one use, then we can't reorder the mem ops.
9265 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9268 // Find the base pointer and offset for this memory node.
9269 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9271 // Check that the base pointer is the same as the original one.
9272 if (!Ptr.equalBaseIndex(BasePtr))
9275 // Check that the alignment is the same.
9276 if (Index->getAlignment() != St->getAlignment())
9279 // The memory operands must not be volatile.
9280 if (Index->isVolatile() || Index->isIndexed())
9284 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9285 if (St->isTruncatingStore())
9288 // The stored memory type must be the same.
9289 if (Index->getMemoryVT() != MemVT)
9292 // We do not allow unaligned stores because we want to prevent overriding
9294 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9297 // We found a potential memory operand to merge.
9298 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9300 // Find the next memory operand in the chain. If the next operand in the
9301 // chain is a store then move up and continue the scan with the next
9302 // memory operand. If the next operand is a load save it and use alias
9303 // information to check if it interferes with anything.
9304 SDNode *NextInChain = Index->getChain().getNode();
9306 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9307 // We found a store node. Use it for the next iteration.
9310 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9311 if (Ldn->isVolatile()) {
9316 // Save the load node for later. Continue the scan.
9317 AliasLoadNodes.push_back(Ldn);
9318 NextInChain = Ldn->getChain().getNode();
9327 // Check if there is anything to merge.
9328 if (StoreNodes.size() < 2)
9331 // Sort the memory operands according to their distance from the base pointer.
9332 std::sort(StoreNodes.begin(), StoreNodes.end(),
9333 [](MemOpLink LHS, MemOpLink RHS) {
9334 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9335 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9336 LHS.SequenceNum > RHS.SequenceNum);
9339 // Scan the memory operations on the chain and find the first non-consecutive
9340 // store memory address.
9341 unsigned LastConsecutiveStore = 0;
9342 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9343 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9345 // Check that the addresses are consecutive starting from the second
9346 // element in the list of stores.
9348 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9349 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9354 // Check if this store interferes with any of the loads that we found.
9355 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9356 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9360 // We found a load that alias with this store. Stop the sequence.
9364 // Mark this node as useful.
9365 LastConsecutiveStore = i;
9368 // The node with the lowest store address.
9369 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9371 // Store the constants into memory as one consecutive store.
9373 unsigned LastLegalType = 0;
9374 unsigned LastLegalVectorType = 0;
9375 bool NonZero = false;
9376 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9377 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9378 SDValue StoredVal = St->getValue();
9380 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9381 NonZero |= !C->isNullValue();
9382 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9383 NonZero |= !C->getConstantFPValue()->isNullValue();
9389 // Find a legal type for the constant store.
9390 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9391 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9392 if (TLI.isTypeLegal(StoreTy))
9393 LastLegalType = i+1;
9394 // Or check whether a truncstore is legal.
9395 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9396 TargetLowering::TypePromoteInteger) {
9397 EVT LegalizedStoredValueTy =
9398 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9399 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9400 LastLegalType = i+1;
9403 // Find a legal type for the vector store.
9404 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9405 if (TLI.isTypeLegal(Ty))
9406 LastLegalVectorType = i + 1;
9409 // We only use vectors if the constant is known to be zero and the
9410 // function is not marked with the noimplicitfloat attribute.
9411 if (NonZero || NoVectors)
9412 LastLegalVectorType = 0;
9414 // Check if we found a legal integer type to store.
9415 if (LastLegalType == 0 && LastLegalVectorType == 0)
9418 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9419 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9421 // Make sure we have something to merge.
9425 unsigned EarliestNodeUsed = 0;
9426 for (unsigned i=0; i < NumElem; ++i) {
9427 // Find a chain for the new wide-store operand. Notice that some
9428 // of the store nodes that we found may not be selected for inclusion
9429 // in the wide store. The chain we use needs to be the chain of the
9430 // earliest store node which is *used* and replaced by the wide store.
9431 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9432 EarliestNodeUsed = i;
9435 // The earliest Node in the DAG.
9436 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9437 SDLoc DL(StoreNodes[0].MemNode);
9441 // Find a legal type for the vector store.
9442 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9443 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9444 StoredVal = DAG.getConstant(0, Ty);
9446 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9447 APInt StoreInt(StoreBW, 0);
9449 // Construct a single integer constant which is made of the smaller
9451 bool IsLE = TLI.isLittleEndian();
9452 for (unsigned i = 0; i < NumElem ; ++i) {
9453 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9454 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9455 SDValue Val = St->getValue();
9456 StoreInt<<=ElementSizeBytes*8;
9457 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9458 StoreInt|=C->getAPIntValue().zext(StoreBW);
9459 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9460 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9462 assert(false && "Invalid constant element type");
9466 // Create the new Load and Store operations.
9467 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9468 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9471 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9472 FirstInChain->getBasePtr(),
9473 FirstInChain->getPointerInfo(),
9475 FirstInChain->getAlignment());
9477 // Replace the first store with the new store
9478 CombineTo(EarliestOp, NewStore);
9479 // Erase all other stores.
9480 for (unsigned i = 0; i < NumElem ; ++i) {
9481 if (StoreNodes[i].MemNode == EarliestOp)
9483 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9484 // ReplaceAllUsesWith will replace all uses that existed when it was
9485 // called, but graph optimizations may cause new ones to appear. For
9486 // example, the case in pr14333 looks like
9488 // St's chain -> St -> another store -> X
9490 // And the only difference from St to the other store is the chain.
9491 // When we change it's chain to be St's chain they become identical,
9492 // get CSEed and the net result is that X is now a use of St.
9493 // Since we know that St is redundant, just iterate.
9494 while (!St->use_empty())
9495 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9496 deleteAndRecombine(St);
9502 // Below we handle the case of multiple consecutive stores that
9503 // come from multiple consecutive loads. We merge them into a single
9504 // wide load and a single wide store.
9506 // Look for load nodes which are used by the stored values.
9507 SmallVector<MemOpLink, 8> LoadNodes;
9509 // Find acceptable loads. Loads need to have the same chain (token factor),
9510 // must not be zext, volatile, indexed, and they must be consecutive.
9511 BaseIndexOffset LdBasePtr;
9512 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9513 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9514 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9517 // Loads must only have one use.
9518 if (!Ld->hasNUsesOfValue(1, 0))
9521 // Check that the alignment is the same as the stores.
9522 if (Ld->getAlignment() != St->getAlignment())
9525 // The memory operands must not be volatile.
9526 if (Ld->isVolatile() || Ld->isIndexed())
9529 // We do not accept ext loads.
9530 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9533 // The stored memory type must be the same.
9534 if (Ld->getMemoryVT() != MemVT)
9537 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9538 // If this is not the first ptr that we check.
9539 if (LdBasePtr.Base.getNode()) {
9540 // The base ptr must be the same.
9541 if (!LdPtr.equalBaseIndex(LdBasePtr))
9544 // Check that all other base pointers are the same as this one.
9548 // We found a potential memory operand to merge.
9549 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9552 if (LoadNodes.size() < 2)
9555 // If we have load/store pair instructions and we only have two values,
9557 unsigned RequiredAlignment;
9558 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9559 St->getAlignment() >= RequiredAlignment)
9562 // Scan the memory operations on the chain and find the first non-consecutive
9563 // load memory address. These variables hold the index in the store node
9565 unsigned LastConsecutiveLoad = 0;
9566 // This variable refers to the size and not index in the array.
9567 unsigned LastLegalVectorType = 0;
9568 unsigned LastLegalIntegerType = 0;
9569 StartAddress = LoadNodes[0].OffsetFromBase;
9570 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9571 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9572 // All loads much share the same chain.
9573 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9576 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9577 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9579 LastConsecutiveLoad = i;
9581 // Find a legal type for the vector store.
9582 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9583 if (TLI.isTypeLegal(StoreTy))
9584 LastLegalVectorType = i + 1;
9586 // Find a legal type for the integer store.
9587 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9588 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9589 if (TLI.isTypeLegal(StoreTy))
9590 LastLegalIntegerType = i + 1;
9591 // Or check whether a truncstore and extload is legal.
9592 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9593 TargetLowering::TypePromoteInteger) {
9594 EVT LegalizedStoredValueTy =
9595 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9596 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9597 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9598 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9599 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9600 LastLegalIntegerType = i+1;
9604 // Only use vector types if the vector type is larger than the integer type.
9605 // If they are the same, use integers.
9606 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9607 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9609 // We add +1 here because the LastXXX variables refer to location while
9610 // the NumElem refers to array/index size.
9611 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9612 NumElem = std::min(LastLegalType, NumElem);
9617 // The earliest Node in the DAG.
9618 unsigned EarliestNodeUsed = 0;
9619 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9620 for (unsigned i=1; i<NumElem; ++i) {
9621 // Find a chain for the new wide-store operand. Notice that some
9622 // of the store nodes that we found may not be selected for inclusion
9623 // in the wide store. The chain we use needs to be the chain of the
9624 // earliest store node which is *used* and replaced by the wide store.
9625 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9626 EarliestNodeUsed = i;
9629 // Find if it is better to use vectors or integers to load and store
9633 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9635 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9636 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9639 SDLoc LoadDL(LoadNodes[0].MemNode);
9640 SDLoc StoreDL(StoreNodes[0].MemNode);
9642 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9643 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9644 FirstLoad->getChain(),
9645 FirstLoad->getBasePtr(),
9646 FirstLoad->getPointerInfo(),
9647 false, false, false,
9648 FirstLoad->getAlignment());
9650 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9651 FirstInChain->getBasePtr(),
9652 FirstInChain->getPointerInfo(), false, false,
9653 FirstInChain->getAlignment());
9655 // Replace one of the loads with the new load.
9656 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9657 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9658 SDValue(NewLoad.getNode(), 1));
9660 // Remove the rest of the load chains.
9661 for (unsigned i = 1; i < NumElem ; ++i) {
9662 // Replace all chain users of the old load nodes with the chain of the new
9664 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9665 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9668 // Replace the first store with the new store.
9669 CombineTo(EarliestOp, NewStore);
9670 // Erase all other stores.
9671 for (unsigned i = 0; i < NumElem ; ++i) {
9672 // Remove all Store nodes.
9673 if (StoreNodes[i].MemNode == EarliestOp)
9675 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9676 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9677 deleteAndRecombine(St);
9683 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9684 StoreSDNode *ST = cast<StoreSDNode>(N);
9685 SDValue Chain = ST->getChain();
9686 SDValue Value = ST->getValue();
9687 SDValue Ptr = ST->getBasePtr();
9689 // If this is a store of a bit convert, store the input value if the
9690 // resultant store does not need a higher alignment than the original.
9691 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9692 ST->isUnindexed()) {
9693 unsigned OrigAlign = ST->getAlignment();
9694 EVT SVT = Value.getOperand(0).getValueType();
9695 unsigned Align = TLI.getDataLayout()->
9696 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9697 if (Align <= OrigAlign &&
9698 ((!LegalOperations && !ST->isVolatile()) ||
9699 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9700 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9701 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9702 ST->isNonTemporal(), OrigAlign,
9706 // Turn 'store undef, Ptr' -> nothing.
9707 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9710 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9711 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9712 // NOTE: If the original store is volatile, this transform must not increase
9713 // the number of stores. For example, on x86-32 an f64 can be stored in one
9714 // processor operation but an i64 (which is not legal) requires two. So the
9715 // transform should not be done in this case.
9716 if (Value.getOpcode() != ISD::TargetConstantFP) {
9718 switch (CFP->getSimpleValueType(0).SimpleTy) {
9719 default: llvm_unreachable("Unknown FP type");
9720 case MVT::f16: // We don't do this for these yet.
9726 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9727 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9728 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9729 bitcastToAPInt().getZExtValue(), MVT::i32);
9730 return DAG.getStore(Chain, SDLoc(N), Tmp,
9731 Ptr, ST->getMemOperand());
9735 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9736 !ST->isVolatile()) ||
9737 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9738 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9739 getZExtValue(), MVT::i64);
9740 return DAG.getStore(Chain, SDLoc(N), Tmp,
9741 Ptr, ST->getMemOperand());
9744 if (!ST->isVolatile() &&
9745 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9746 // Many FP stores are not made apparent until after legalize, e.g. for
9747 // argument passing. Since this is so common, custom legalize the
9748 // 64-bit integer store into two 32-bit stores.
9749 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9750 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9751 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9752 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9754 unsigned Alignment = ST->getAlignment();
9755 bool isVolatile = ST->isVolatile();
9756 bool isNonTemporal = ST->isNonTemporal();
9757 AAMDNodes AAInfo = ST->getAAInfo();
9759 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9760 Ptr, ST->getPointerInfo(),
9761 isVolatile, isNonTemporal,
9762 ST->getAlignment(), AAInfo);
9763 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9764 DAG.getConstant(4, Ptr.getValueType()));
9765 Alignment = MinAlign(Alignment, 4U);
9766 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9767 Ptr, ST->getPointerInfo().getWithOffset(4),
9768 isVolatile, isNonTemporal,
9770 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9779 // Try to infer better alignment information than the store already has.
9780 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9781 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9782 if (Align > ST->getAlignment())
9783 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9784 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9785 ST->isVolatile(), ST->isNonTemporal(), Align,
9790 // Try transforming a pair floating point load / store ops to integer
9791 // load / store ops.
9792 SDValue NewST = TransformFPLoadStorePair(N);
9793 if (NewST.getNode())
9796 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9797 : DAG.getSubtarget().useAA();
9799 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9800 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9803 if (UseAA && ST->isUnindexed()) {
9804 // Walk up chain skipping non-aliasing memory nodes.
9805 SDValue BetterChain = FindBetterChain(N, Chain);
9807 // If there is a better chain.
9808 if (Chain != BetterChain) {
9811 // Replace the chain to avoid dependency.
9812 if (ST->isTruncatingStore()) {
9813 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9814 ST->getMemoryVT(), ST->getMemOperand());
9816 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9817 ST->getMemOperand());
9820 // Create token to keep both nodes around.
9821 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9822 MVT::Other, Chain, ReplStore);
9824 // Make sure the new and old chains are cleaned up.
9825 AddToWorklist(Token.getNode());
9827 // Don't add users to work list.
9828 return CombineTo(N, Token, false);
9832 // Try transforming N to an indexed store.
9833 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9834 return SDValue(N, 0);
9836 // FIXME: is there such a thing as a truncating indexed store?
9837 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9838 Value.getValueType().isInteger()) {
9839 // See if we can simplify the input to this truncstore with knowledge that
9840 // only the low bits are being used. For example:
9841 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9843 GetDemandedBits(Value,
9844 APInt::getLowBitsSet(
9845 Value.getValueType().getScalarType().getSizeInBits(),
9846 ST->getMemoryVT().getScalarType().getSizeInBits()));
9847 AddToWorklist(Value.getNode());
9848 if (Shorter.getNode())
9849 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9850 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9852 // Otherwise, see if we can simplify the operation with
9853 // SimplifyDemandedBits, which only works if the value has a single use.
9854 if (SimplifyDemandedBits(Value,
9855 APInt::getLowBitsSet(
9856 Value.getValueType().getScalarType().getSizeInBits(),
9857 ST->getMemoryVT().getScalarType().getSizeInBits())))
9858 return SDValue(N, 0);
9861 // If this is a load followed by a store to the same location, then the store
9863 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9864 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9865 ST->isUnindexed() && !ST->isVolatile() &&
9866 // There can't be any side effects between the load and store, such as
9868 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9869 // The store is dead, remove it.
9874 // If this is a store followed by a store with the same value to the same
9875 // location, then the store is dead/noop.
9876 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9877 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9878 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9879 ST1->isUnindexed() && !ST1->isVolatile()) {
9880 // The store is dead, remove it.
9885 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9886 // truncating store. We can do this even if this is already a truncstore.
9887 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9888 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9889 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9890 ST->getMemoryVT())) {
9891 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9892 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9895 // Only perform this optimization before the types are legal, because we
9896 // don't want to perform this optimization on every DAGCombine invocation.
9898 bool EverChanged = false;
9901 // There can be multiple store sequences on the same chain.
9902 // Keep trying to merge store sequences until we are unable to do so
9903 // or until we merge the last store on the chain.
9904 bool Changed = MergeConsecutiveStores(ST);
9905 EverChanged |= Changed;
9906 if (!Changed) break;
9907 } while (ST->getOpcode() != ISD::DELETED_NODE);
9910 return SDValue(N, 0);
9913 return ReduceLoadOpStoreWidth(N);
9916 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9917 SDValue InVec = N->getOperand(0);
9918 SDValue InVal = N->getOperand(1);
9919 SDValue EltNo = N->getOperand(2);
9922 // If the inserted element is an UNDEF, just use the input vector.
9923 if (InVal.getOpcode() == ISD::UNDEF)
9926 EVT VT = InVec.getValueType();
9928 // If we can't generate a legal BUILD_VECTOR, exit
9929 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9932 // Check that we know which element is being inserted
9933 if (!isa<ConstantSDNode>(EltNo))
9935 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9937 // Canonicalize insert_vector_elt dag nodes.
9939 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9940 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9942 // Do this only if the child insert_vector node has one use; also
9943 // do this only if indices are both constants and Idx1 < Idx0.
9944 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9945 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9947 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9948 if (Elt < OtherElt) {
9950 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9951 InVec.getOperand(0), InVal, EltNo);
9952 AddToWorklist(NewOp.getNode());
9953 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9954 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9958 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9959 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9961 SmallVector<SDValue, 8> Ops;
9962 // Do not combine these two vectors if the output vector will not replace
9963 // the input vector.
9964 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9965 Ops.append(InVec.getNode()->op_begin(),
9966 InVec.getNode()->op_end());
9967 } else if (InVec.getOpcode() == ISD::UNDEF) {
9968 unsigned NElts = VT.getVectorNumElements();
9969 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9974 // Insert the element
9975 if (Elt < Ops.size()) {
9976 // All the operands of BUILD_VECTOR must have the same type;
9977 // we enforce that here.
9978 EVT OpVT = Ops[0].getValueType();
9979 if (InVal.getValueType() != OpVT)
9980 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9981 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9982 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9986 // Return the new vector
9987 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9990 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9991 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9992 EVT ResultVT = EVE->getValueType(0);
9993 EVT VecEltVT = InVecVT.getVectorElementType();
9994 unsigned Align = OriginalLoad->getAlignment();
9995 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9996 VecEltVT.getTypeForEVT(*DAG.getContext()));
9998 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10003 SDValue NewPtr = OriginalLoad->getBasePtr();
10005 EVT PtrType = NewPtr.getValueType();
10006 MachinePointerInfo MPI;
10007 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10008 int Elt = ConstEltNo->getZExtValue();
10009 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10010 if (TLI.isBigEndian())
10011 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10012 Offset = DAG.getConstant(PtrOff, PtrType);
10013 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10015 Offset = DAG.getNode(
10016 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10017 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10018 if (TLI.isBigEndian())
10019 Offset = DAG.getNode(
10020 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10021 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10022 MPI = OriginalLoad->getPointerInfo();
10024 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10026 // The replacement we need to do here is a little tricky: we need to
10027 // replace an extractelement of a load with a load.
10028 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10029 // Note that this replacement assumes that the extractvalue is the only
10030 // use of the load; that's okay because we don't want to perform this
10031 // transformation in other cases anyway.
10034 if (ResultVT.bitsGT(VecEltVT)) {
10035 // If the result type of vextract is wider than the load, then issue an
10036 // extending load instead.
10037 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10040 Load = DAG.getExtLoad(
10041 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10042 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10043 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10044 Chain = Load.getValue(1);
10046 Load = DAG.getLoad(
10047 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10048 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10049 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10050 Chain = Load.getValue(1);
10051 if (ResultVT.bitsLT(VecEltVT))
10052 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10054 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10056 WorklistRemover DeadNodes(*this);
10057 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10058 SDValue To[] = { Load, Chain };
10059 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10060 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10061 // worklist explicitly as well.
10062 AddToWorklist(Load.getNode());
10063 AddUsersToWorklist(Load.getNode()); // Add users too
10064 // Make sure to revisit this node to clean it up; it will usually be dead.
10065 AddToWorklist(EVE);
10067 return SDValue(EVE, 0);
10070 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10071 // (vextract (scalar_to_vector val, 0) -> val
10072 SDValue InVec = N->getOperand(0);
10073 EVT VT = InVec.getValueType();
10074 EVT NVT = N->getValueType(0);
10076 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10077 // Check if the result type doesn't match the inserted element type. A
10078 // SCALAR_TO_VECTOR may truncate the inserted element and the
10079 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10080 SDValue InOp = InVec.getOperand(0);
10081 if (InOp.getValueType() != NVT) {
10082 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10083 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10088 SDValue EltNo = N->getOperand(1);
10089 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10091 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10092 // We only perform this optimization before the op legalization phase because
10093 // we may introduce new vector instructions which are not backed by TD
10094 // patterns. For example on AVX, extracting elements from a wide vector
10095 // without using extract_subvector. However, if we can find an underlying
10096 // scalar value, then we can always use that.
10097 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10099 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10100 int NumElem = VT.getVectorNumElements();
10101 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10102 // Find the new index to extract from.
10103 int OrigElt = SVOp->getMaskElt(Elt);
10105 // Extracting an undef index is undef.
10107 return DAG.getUNDEF(NVT);
10109 // Select the right vector half to extract from.
10111 if (OrigElt < NumElem) {
10112 SVInVec = InVec->getOperand(0);
10114 SVInVec = InVec->getOperand(1);
10115 OrigElt -= NumElem;
10118 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10119 SDValue InOp = SVInVec.getOperand(OrigElt);
10120 if (InOp.getValueType() != NVT) {
10121 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10122 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10128 // FIXME: We should handle recursing on other vector shuffles and
10129 // scalar_to_vector here as well.
10131 if (!LegalOperations) {
10132 EVT IndexTy = TLI.getVectorIdxTy();
10133 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10134 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10138 bool BCNumEltsChanged = false;
10139 EVT ExtVT = VT.getVectorElementType();
10142 // If the result of load has to be truncated, then it's not necessarily
10144 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10147 if (InVec.getOpcode() == ISD::BITCAST) {
10148 // Don't duplicate a load with other uses.
10149 if (!InVec.hasOneUse())
10152 EVT BCVT = InVec.getOperand(0).getValueType();
10153 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10155 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10156 BCNumEltsChanged = true;
10157 InVec = InVec.getOperand(0);
10158 ExtVT = BCVT.getVectorElementType();
10161 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10162 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10163 ISD::isNormalLoad(InVec.getNode()) &&
10164 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10165 SDValue Index = N->getOperand(1);
10166 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10167 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10171 // Perform only after legalization to ensure build_vector / vector_shuffle
10172 // optimizations have already been done.
10173 if (!LegalOperations) return SDValue();
10175 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10176 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10177 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10180 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10182 LoadSDNode *LN0 = nullptr;
10183 const ShuffleVectorSDNode *SVN = nullptr;
10184 if (ISD::isNormalLoad(InVec.getNode())) {
10185 LN0 = cast<LoadSDNode>(InVec);
10186 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10187 InVec.getOperand(0).getValueType() == ExtVT &&
10188 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10189 // Don't duplicate a load with other uses.
10190 if (!InVec.hasOneUse())
10193 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10194 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10195 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10197 // (load $addr+1*size)
10199 // Don't duplicate a load with other uses.
10200 if (!InVec.hasOneUse())
10203 // If the bit convert changed the number of elements, it is unsafe
10204 // to examine the mask.
10205 if (BCNumEltsChanged)
10208 // Select the input vector, guarding against out of range extract vector.
10209 unsigned NumElems = VT.getVectorNumElements();
10210 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10211 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10213 if (InVec.getOpcode() == ISD::BITCAST) {
10214 // Don't duplicate a load with other uses.
10215 if (!InVec.hasOneUse())
10218 InVec = InVec.getOperand(0);
10220 if (ISD::isNormalLoad(InVec.getNode())) {
10221 LN0 = cast<LoadSDNode>(InVec);
10222 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10223 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10227 // Make sure we found a non-volatile load and the extractelement is
10229 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10232 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10234 return DAG.getUNDEF(LVT);
10236 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10242 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10243 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10244 // We perform this optimization post type-legalization because
10245 // the type-legalizer often scalarizes integer-promoted vectors.
10246 // Performing this optimization before may create bit-casts which
10247 // will be type-legalized to complex code sequences.
10248 // We perform this optimization only before the operation legalizer because we
10249 // may introduce illegal operations.
10250 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10253 unsigned NumInScalars = N->getNumOperands();
10255 EVT VT = N->getValueType(0);
10257 // Check to see if this is a BUILD_VECTOR of a bunch of values
10258 // which come from any_extend or zero_extend nodes. If so, we can create
10259 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10260 // optimizations. We do not handle sign-extend because we can't fill the sign
10262 EVT SourceType = MVT::Other;
10263 bool AllAnyExt = true;
10265 for (unsigned i = 0; i != NumInScalars; ++i) {
10266 SDValue In = N->getOperand(i);
10267 // Ignore undef inputs.
10268 if (In.getOpcode() == ISD::UNDEF) continue;
10270 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10271 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10273 // Abort if the element is not an extension.
10274 if (!ZeroExt && !AnyExt) {
10275 SourceType = MVT::Other;
10279 // The input is a ZeroExt or AnyExt. Check the original type.
10280 EVT InTy = In.getOperand(0).getValueType();
10282 // Check that all of the widened source types are the same.
10283 if (SourceType == MVT::Other)
10286 else if (InTy != SourceType) {
10287 // Multiple income types. Abort.
10288 SourceType = MVT::Other;
10292 // Check if all of the extends are ANY_EXTENDs.
10293 AllAnyExt &= AnyExt;
10296 // In order to have valid types, all of the inputs must be extended from the
10297 // same source type and all of the inputs must be any or zero extend.
10298 // Scalar sizes must be a power of two.
10299 EVT OutScalarTy = VT.getScalarType();
10300 bool ValidTypes = SourceType != MVT::Other &&
10301 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10302 isPowerOf2_32(SourceType.getSizeInBits());
10304 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10305 // turn into a single shuffle instruction.
10309 bool isLE = TLI.isLittleEndian();
10310 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10311 assert(ElemRatio > 1 && "Invalid element size ratio");
10312 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10313 DAG.getConstant(0, SourceType);
10315 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10316 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10318 // Populate the new build_vector
10319 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10320 SDValue Cast = N->getOperand(i);
10321 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10322 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10323 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10325 if (Cast.getOpcode() == ISD::UNDEF)
10326 In = DAG.getUNDEF(SourceType);
10328 In = Cast->getOperand(0);
10329 unsigned Index = isLE ? (i * ElemRatio) :
10330 (i * ElemRatio + (ElemRatio - 1));
10332 assert(Index < Ops.size() && "Invalid index");
10336 // The type of the new BUILD_VECTOR node.
10337 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10338 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10339 "Invalid vector size");
10340 // Check if the new vector type is legal.
10341 if (!isTypeLegal(VecVT)) return SDValue();
10343 // Make the new BUILD_VECTOR.
10344 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10346 // The new BUILD_VECTOR node has the potential to be further optimized.
10347 AddToWorklist(BV.getNode());
10348 // Bitcast to the desired type.
10349 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10352 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10353 EVT VT = N->getValueType(0);
10355 unsigned NumInScalars = N->getNumOperands();
10358 EVT SrcVT = MVT::Other;
10359 unsigned Opcode = ISD::DELETED_NODE;
10360 unsigned NumDefs = 0;
10362 for (unsigned i = 0; i != NumInScalars; ++i) {
10363 SDValue In = N->getOperand(i);
10364 unsigned Opc = In.getOpcode();
10366 if (Opc == ISD::UNDEF)
10369 // If all scalar values are floats and converted from integers.
10370 if (Opcode == ISD::DELETED_NODE &&
10371 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10378 EVT InVT = In.getOperand(0).getValueType();
10380 // If all scalar values are typed differently, bail out. It's chosen to
10381 // simplify BUILD_VECTOR of integer types.
10382 if (SrcVT == MVT::Other)
10389 // If the vector has just one element defined, it's not worth to fold it into
10390 // a vectorized one.
10394 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10395 && "Should only handle conversion from integer to float.");
10396 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10398 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10400 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10403 SmallVector<SDValue, 8> Opnds;
10404 for (unsigned i = 0; i != NumInScalars; ++i) {
10405 SDValue In = N->getOperand(i);
10407 if (In.getOpcode() == ISD::UNDEF)
10408 Opnds.push_back(DAG.getUNDEF(SrcVT));
10410 Opnds.push_back(In.getOperand(0));
10412 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10413 AddToWorklist(BV.getNode());
10415 return DAG.getNode(Opcode, dl, VT, BV);
10418 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10419 unsigned NumInScalars = N->getNumOperands();
10421 EVT VT = N->getValueType(0);
10423 // A vector built entirely of undefs is undef.
10424 if (ISD::allOperandsUndef(N))
10425 return DAG.getUNDEF(VT);
10427 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10431 V = reduceBuildVecConvertToConvertBuildVec(N);
10435 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10436 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10437 // at most two distinct vectors, turn this into a shuffle node.
10439 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10440 if (!isTypeLegal(VT))
10443 // May only combine to shuffle after legalize if shuffle is legal.
10444 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10447 SDValue VecIn1, VecIn2;
10448 for (unsigned i = 0; i != NumInScalars; ++i) {
10449 // Ignore undef inputs.
10450 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10452 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10453 // constant index, bail out.
10454 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10455 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10456 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10460 // We allow up to two distinct input vectors.
10461 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10462 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10465 if (!VecIn1.getNode()) {
10466 VecIn1 = ExtractedFromVec;
10467 } else if (!VecIn2.getNode()) {
10468 VecIn2 = ExtractedFromVec;
10470 // Too many inputs.
10471 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10476 // If everything is good, we can make a shuffle operation.
10477 if (VecIn1.getNode()) {
10478 SmallVector<int, 8> Mask;
10479 for (unsigned i = 0; i != NumInScalars; ++i) {
10480 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10481 Mask.push_back(-1);
10485 // If extracting from the first vector, just use the index directly.
10486 SDValue Extract = N->getOperand(i);
10487 SDValue ExtVal = Extract.getOperand(1);
10488 if (Extract.getOperand(0) == VecIn1) {
10489 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10490 if (ExtIndex > VT.getVectorNumElements())
10493 Mask.push_back(ExtIndex);
10497 // Otherwise, use InIdx + VecSize
10498 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10499 Mask.push_back(Idx+NumInScalars);
10502 // We can't generate a shuffle node with mismatched input and output types.
10503 // Attempt to transform a single input vector to the correct type.
10504 if ((VT != VecIn1.getValueType())) {
10505 // We don't support shuffeling between TWO values of different types.
10506 if (VecIn2.getNode())
10509 // We only support widening of vectors which are half the size of the
10510 // output registers. For example XMM->YMM widening on X86 with AVX.
10511 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10514 // If the input vector type has a different base type to the output
10515 // vector type, bail out.
10516 if (VecIn1.getValueType().getVectorElementType() !=
10517 VT.getVectorElementType())
10520 // Widen the input vector by adding undef values.
10521 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10522 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10525 // If VecIn2 is unused then change it to undef.
10526 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10528 // Check that we were able to transform all incoming values to the same
10530 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10531 VecIn1.getValueType() != VT)
10534 // Return the new VECTOR_SHUFFLE node.
10538 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10544 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10545 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10546 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10547 // inputs come from at most two distinct vectors, turn this into a shuffle
10550 // If we only have one input vector, we don't need to do any concatenation.
10551 if (N->getNumOperands() == 1)
10552 return N->getOperand(0);
10554 // Check if all of the operands are undefs.
10555 EVT VT = N->getValueType(0);
10556 if (ISD::allOperandsUndef(N))
10557 return DAG.getUNDEF(VT);
10559 // Optimize concat_vectors where one of the vectors is undef.
10560 if (N->getNumOperands() == 2 &&
10561 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10562 SDValue In = N->getOperand(0);
10563 assert(In.getValueType().isVector() && "Must concat vectors");
10565 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10566 if (In->getOpcode() == ISD::BITCAST &&
10567 !In->getOperand(0)->getValueType(0).isVector()) {
10568 SDValue Scalar = In->getOperand(0);
10569 EVT SclTy = Scalar->getValueType(0);
10571 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10574 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10575 VT.getSizeInBits() / SclTy.getSizeInBits());
10576 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10579 SDLoc dl = SDLoc(N);
10580 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10581 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10585 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10586 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10587 if (N->getNumOperands() == 2 &&
10588 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10589 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10590 EVT VT = N->getValueType(0);
10591 SDValue N0 = N->getOperand(0);
10592 SDValue N1 = N->getOperand(1);
10593 SmallVector<SDValue, 8> Opnds;
10594 unsigned BuildVecNumElts = N0.getNumOperands();
10596 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10597 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10598 if (SclTy0.isFloatingPoint()) {
10599 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10600 Opnds.push_back(N0.getOperand(i));
10601 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10602 Opnds.push_back(N1.getOperand(i));
10604 // If BUILD_VECTOR are from built from integer, they may have different
10605 // operand types. Get the smaller type and truncate all operands to it.
10606 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10607 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10608 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10609 N0.getOperand(i)));
10610 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10611 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10612 N1.getOperand(i)));
10615 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10618 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10619 // nodes often generate nop CONCAT_VECTOR nodes.
10620 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10621 // place the incoming vectors at the exact same location.
10622 SDValue SingleSource = SDValue();
10623 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10625 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10626 SDValue Op = N->getOperand(i);
10628 if (Op.getOpcode() == ISD::UNDEF)
10631 // Check if this is the identity extract:
10632 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10635 // Find the single incoming vector for the extract_subvector.
10636 if (SingleSource.getNode()) {
10637 if (Op.getOperand(0) != SingleSource)
10640 SingleSource = Op.getOperand(0);
10642 // Check the source type is the same as the type of the result.
10643 // If not, this concat may extend the vector, so we can not
10644 // optimize it away.
10645 if (SingleSource.getValueType() != N->getValueType(0))
10649 unsigned IdentityIndex = i * PartNumElem;
10650 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10651 // The extract index must be constant.
10655 // Check that we are reading from the identity index.
10656 if (CS->getZExtValue() != IdentityIndex)
10660 if (SingleSource.getNode())
10661 return SingleSource;
10666 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10667 EVT NVT = N->getValueType(0);
10668 SDValue V = N->getOperand(0);
10670 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10672 // (extract_subvec (concat V1, V2, ...), i)
10675 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10677 if (V->getOperand(0).getValueType() != NVT)
10679 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10680 unsigned NumElems = NVT.getVectorNumElements();
10681 assert((Idx % NumElems) == 0 &&
10682 "IDX in concat is not a multiple of the result vector length.");
10683 return V->getOperand(Idx / NumElems);
10687 if (V->getOpcode() == ISD::BITCAST)
10688 V = V.getOperand(0);
10690 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10692 // Handle only simple case where vector being inserted and vector
10693 // being extracted are of same type, and are half size of larger vectors.
10694 EVT BigVT = V->getOperand(0).getValueType();
10695 EVT SmallVT = V->getOperand(1).getValueType();
10696 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10699 // Only handle cases where both indexes are constants with the same type.
10700 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10701 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10703 if (InsIdx && ExtIdx &&
10704 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10705 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10707 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10709 // indices are equal or bit offsets are equal => V1
10710 // otherwise => (extract_subvec V1, ExtIdx)
10711 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10712 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10713 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10714 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10715 DAG.getNode(ISD::BITCAST, dl,
10716 N->getOperand(0).getValueType(),
10717 V->getOperand(0)), N->getOperand(1));
10724 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10725 SDValue V, SelectionDAG &DAG) {
10727 EVT VT = V.getValueType();
10729 switch (V.getOpcode()) {
10733 case ISD::CONCAT_VECTORS: {
10734 EVT OpVT = V->getOperand(0).getValueType();
10735 int OpSize = OpVT.getVectorNumElements();
10736 SmallBitVector OpUsedElements(OpSize, false);
10737 bool FoundSimplification = false;
10738 SmallVector<SDValue, 4> NewOps;
10739 NewOps.reserve(V->getNumOperands());
10740 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10741 SDValue Op = V->getOperand(i);
10742 bool OpUsed = false;
10743 for (int j = 0; j < OpSize; ++j)
10744 if (UsedElements[i * OpSize + j]) {
10745 OpUsedElements[j] = true;
10749 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10750 : DAG.getUNDEF(OpVT));
10751 FoundSimplification |= Op == NewOps.back();
10752 OpUsedElements.reset();
10754 if (FoundSimplification)
10755 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10759 case ISD::INSERT_SUBVECTOR: {
10760 SDValue BaseV = V->getOperand(0);
10761 SDValue SubV = V->getOperand(1);
10762 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10766 int SubSize = SubV.getValueType().getVectorNumElements();
10767 int Idx = IdxN->getZExtValue();
10768 bool SubVectorUsed = false;
10769 SmallBitVector SubUsedElements(SubSize, false);
10770 for (int i = 0; i < SubSize; ++i)
10771 if (UsedElements[i + Idx]) {
10772 SubVectorUsed = true;
10773 SubUsedElements[i] = true;
10774 UsedElements[i + Idx] = false;
10777 // Now recurse on both the base and sub vectors.
10778 SDValue SimplifiedSubV =
10780 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10781 : DAG.getUNDEF(SubV.getValueType());
10782 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10783 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10784 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10785 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10791 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10792 SDValue N1, SelectionDAG &DAG) {
10793 EVT VT = SVN->getValueType(0);
10794 int NumElts = VT.getVectorNumElements();
10795 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10796 for (int M : SVN->getMask())
10797 if (M >= 0 && M < NumElts)
10798 N0UsedElements[M] = true;
10799 else if (M >= NumElts)
10800 N1UsedElements[M - NumElts] = true;
10802 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10803 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10804 if (S0 == N0 && S1 == N1)
10807 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10810 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10811 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10812 EVT VT = N->getValueType(0);
10813 unsigned NumElts = VT.getVectorNumElements();
10815 SDValue N0 = N->getOperand(0);
10816 SDValue N1 = N->getOperand(1);
10817 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10819 SmallVector<SDValue, 4> Ops;
10820 EVT ConcatVT = N0.getOperand(0).getValueType();
10821 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10822 unsigned NumConcats = NumElts / NumElemsPerConcat;
10824 // Look at every vector that's inserted. We're looking for exact
10825 // subvector-sized copies from a concatenated vector
10826 for (unsigned I = 0; I != NumConcats; ++I) {
10827 // Make sure we're dealing with a copy.
10828 unsigned Begin = I * NumElemsPerConcat;
10829 bool AllUndef = true, NoUndef = true;
10830 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10831 if (SVN->getMaskElt(J) >= 0)
10838 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10841 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10842 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10845 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10846 if (FirstElt < N0.getNumOperands())
10847 Ops.push_back(N0.getOperand(FirstElt));
10849 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10851 } else if (AllUndef) {
10852 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10853 } else { // Mixed with general masks and undefs, can't do optimization.
10858 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10861 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10862 EVT VT = N->getValueType(0);
10863 unsigned NumElts = VT.getVectorNumElements();
10865 SDValue N0 = N->getOperand(0);
10866 SDValue N1 = N->getOperand(1);
10868 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10870 // Canonicalize shuffle undef, undef -> undef
10871 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10872 return DAG.getUNDEF(VT);
10874 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10876 // Canonicalize shuffle v, v -> v, undef
10878 SmallVector<int, 8> NewMask;
10879 for (unsigned i = 0; i != NumElts; ++i) {
10880 int Idx = SVN->getMaskElt(i);
10881 if (Idx >= (int)NumElts) Idx -= NumElts;
10882 NewMask.push_back(Idx);
10884 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10888 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10889 if (N0.getOpcode() == ISD::UNDEF) {
10890 SmallVector<int, 8> NewMask;
10891 for (unsigned i = 0; i != NumElts; ++i) {
10892 int Idx = SVN->getMaskElt(i);
10894 if (Idx >= (int)NumElts)
10897 Idx = -1; // remove reference to lhs
10899 NewMask.push_back(Idx);
10901 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10905 // Remove references to rhs if it is undef
10906 if (N1.getOpcode() == ISD::UNDEF) {
10907 bool Changed = false;
10908 SmallVector<int, 8> NewMask;
10909 for (unsigned i = 0; i != NumElts; ++i) {
10910 int Idx = SVN->getMaskElt(i);
10911 if (Idx >= (int)NumElts) {
10915 NewMask.push_back(Idx);
10918 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10921 // If it is a splat, check if the argument vector is another splat or a
10922 // build_vector with all scalar elements the same.
10923 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10924 SDNode *V = N0.getNode();
10926 // If this is a bit convert that changes the element type of the vector but
10927 // not the number of vector elements, look through it. Be careful not to
10928 // look though conversions that change things like v4f32 to v2f64.
10929 if (V->getOpcode() == ISD::BITCAST) {
10930 SDValue ConvInput = V->getOperand(0);
10931 if (ConvInput.getValueType().isVector() &&
10932 ConvInput.getValueType().getVectorNumElements() == NumElts)
10933 V = ConvInput.getNode();
10936 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10937 assert(V->getNumOperands() == NumElts &&
10938 "BUILD_VECTOR has wrong number of operands");
10940 bool AllSame = true;
10941 for (unsigned i = 0; i != NumElts; ++i) {
10942 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10943 Base = V->getOperand(i);
10947 // Splat of <u, u, u, u>, return <u, u, u, u>
10948 if (!Base.getNode())
10950 for (unsigned i = 0; i != NumElts; ++i) {
10951 if (V->getOperand(i) != Base) {
10956 // Splat of <x, x, x, x>, return <x, x, x, x>
10962 // There are various patterns used to build up a vector from smaller vectors,
10963 // subvectors, or elements. Scan chains of these and replace unused insertions
10964 // or components with undef.
10965 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
10968 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10969 Level < AfterLegalizeVectorOps &&
10970 (N1.getOpcode() == ISD::UNDEF ||
10971 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10972 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10973 SDValue V = partitionShuffleOfConcats(N, DAG);
10979 // If this shuffle node is simply a swizzle of another shuffle node,
10980 // then try to simplify it.
10981 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10982 N1.getOpcode() == ISD::UNDEF) {
10984 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10986 // The incoming shuffle must be of the same type as the result of the
10987 // current shuffle.
10988 assert(OtherSV->getOperand(0).getValueType() == VT &&
10989 "Shuffle types don't match");
10991 SmallVector<int, 4> Mask;
10992 // Compute the combined shuffle mask.
10993 for (unsigned i = 0; i != NumElts; ++i) {
10994 int Idx = SVN->getMaskElt(i);
10995 assert(Idx < (int)NumElts && "Index references undef operand");
10996 // Next, this index comes from the first value, which is the incoming
10997 // shuffle. Adopt the incoming index.
10999 Idx = OtherSV->getMaskElt(Idx);
11000 Mask.push_back(Idx);
11003 // Check if all indices in Mask are Undef. In case, propagate Undef.
11004 bool isUndefMask = true;
11005 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11006 isUndefMask &= Mask[i] < 0;
11009 return DAG.getUNDEF(VT);
11011 bool CommuteOperands = false;
11012 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
11013 // To be valid, the combine shuffle mask should only reference elements
11014 // from one of the two vectors in input to the inner shufflevector.
11015 bool IsValidMask = true;
11016 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11017 // See if the combined mask only reference undefs or elements coming
11018 // from the first shufflevector operand.
11019 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
11021 if (!IsValidMask) {
11022 IsValidMask = true;
11023 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11024 // Check that all the elements come from the second shuffle operand.
11025 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
11026 CommuteOperands = IsValidMask;
11029 // Early exit if the combined shuffle mask is not valid.
11034 // See if this pair of shuffles can be safely folded according to either
11035 // of the following rules:
11036 // shuffle(shuffle(x, y), undef) -> x
11037 // shuffle(shuffle(x, undef), undef) -> x
11038 // shuffle(shuffle(x, y), undef) -> y
11039 bool IsIdentityMask = true;
11040 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
11041 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
11046 // The combined shuffle must map each index to itself.
11047 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
11050 if (IsIdentityMask) {
11051 if (CommuteOperands)
11052 // optimize shuffle(shuffle(x, y), undef) -> y.
11053 return OtherSV->getOperand(1);
11055 // optimize shuffle(shuffle(x, undef), undef) -> x
11056 // optimize shuffle(shuffle(x, y), undef) -> x
11057 return OtherSV->getOperand(0);
11060 // It may still be beneficial to combine the two shuffles if the
11061 // resulting shuffle is legal.
11062 if (TLI.isTypeLegal(VT)) {
11063 if (!CommuteOperands) {
11064 if (TLI.isShuffleMaskLegal(Mask, VT))
11065 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
11066 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
11067 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
11070 // Compute the commuted shuffle mask.
11071 for (unsigned i = 0; i != NumElts; ++i) {
11075 else if (idx < (int)NumElts)
11076 Mask[i] = idx + NumElts;
11078 Mask[i] = idx - NumElts;
11081 if (TLI.isShuffleMaskLegal(Mask, VT))
11082 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
11083 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
11089 // Canonicalize shuffles according to rules:
11090 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11091 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11092 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11093 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
11094 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11095 TLI.isTypeLegal(VT)) {
11096 // The incoming shuffle must be of the same type as the result of the
11097 // current shuffle.
11098 assert(N1->getOperand(0).getValueType() == VT &&
11099 "Shuffle types don't match");
11101 SDValue SV0 = N1->getOperand(0);
11102 SDValue SV1 = N1->getOperand(1);
11103 bool HasSameOp0 = N0 == SV0;
11104 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11105 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11106 // Commute the operands of this shuffle so that next rule
11108 return DAG.getCommutedVectorShuffle(*SVN);
11111 // Try to fold according to rules:
11112 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11113 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11114 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11115 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11116 // Don't try to fold shuffles with illegal type.
11117 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11118 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
11119 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11121 // The incoming shuffle must be of the same type as the result of the
11122 // current shuffle.
11123 assert(OtherSV->getOperand(0).getValueType() == VT &&
11124 "Shuffle types don't match");
11126 SDValue SV0 = OtherSV->getOperand(0);
11127 SDValue SV1 = OtherSV->getOperand(1);
11128 bool HasSameOp0 = N1 == SV0;
11129 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11130 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
11134 SmallVector<int, 4> Mask;
11135 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11136 // operand, and SV1 as the second operand.
11137 for (unsigned i = 0; i != NumElts; ++i) {
11138 int Idx = SVN->getMaskElt(i);
11140 // Propagate Undef.
11141 Mask.push_back(Idx);
11145 if (Idx < (int)NumElts) {
11146 Idx = OtherSV->getMaskElt(Idx);
11147 if (IsSV1Undef && Idx >= (int) NumElts)
11148 Idx = -1; // Propagate Undef.
11150 Idx = HasSameOp0 ? Idx - NumElts : Idx;
11152 Mask.push_back(Idx);
11155 // Check if all indices in Mask are Undef. In case, propagate Undef.
11156 bool isUndefMask = true;
11157 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11158 isUndefMask &= Mask[i] < 0;
11161 return DAG.getUNDEF(VT);
11163 // Avoid introducing shuffles with illegal mask.
11164 if (TLI.isShuffleMaskLegal(Mask, VT)) {
11166 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11167 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11168 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11169 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11176 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11177 SDValue N0 = N->getOperand(0);
11178 SDValue N2 = N->getOperand(2);
11180 // If the input vector is a concatenation, and the insert replaces
11181 // one of the halves, we can optimize into a single concat_vectors.
11182 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11183 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11184 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11185 EVT VT = N->getValueType(0);
11187 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11188 // (concat_vectors Z, Y)
11190 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11191 N->getOperand(1), N0.getOperand(1));
11193 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11194 // (concat_vectors X, Z)
11195 if (InsIdx == VT.getVectorNumElements()/2)
11196 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11197 N0.getOperand(0), N->getOperand(1));
11203 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11204 /// with the destination vector and a zero vector.
11205 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11206 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11207 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11208 EVT VT = N->getValueType(0);
11210 SDValue LHS = N->getOperand(0);
11211 SDValue RHS = N->getOperand(1);
11212 if (N->getOpcode() == ISD::AND) {
11213 if (RHS.getOpcode() == ISD::BITCAST)
11214 RHS = RHS.getOperand(0);
11215 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11216 SmallVector<int, 8> Indices;
11217 unsigned NumElts = RHS.getNumOperands();
11218 for (unsigned i = 0; i != NumElts; ++i) {
11219 SDValue Elt = RHS.getOperand(i);
11220 if (!isa<ConstantSDNode>(Elt))
11223 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11224 Indices.push_back(i);
11225 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11226 Indices.push_back(NumElts);
11231 // Let's see if the target supports this vector_shuffle.
11232 EVT RVT = RHS.getValueType();
11233 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11236 // Return the new VECTOR_SHUFFLE node.
11237 EVT EltVT = RVT.getVectorElementType();
11238 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11239 DAG.getConstant(0, EltVT));
11240 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11241 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11242 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11243 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11250 /// Visit a binary vector operation, like ADD.
11251 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11252 assert(N->getValueType(0).isVector() &&
11253 "SimplifyVBinOp only works on vectors!");
11255 SDValue LHS = N->getOperand(0);
11256 SDValue RHS = N->getOperand(1);
11257 SDValue Shuffle = XformToShuffleWithZero(N);
11258 if (Shuffle.getNode()) return Shuffle;
11260 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11262 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11263 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11264 // Check if both vectors are constants. If not bail out.
11265 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11266 cast<BuildVectorSDNode>(RHS)->isConstant()))
11269 SmallVector<SDValue, 8> Ops;
11270 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11271 SDValue LHSOp = LHS.getOperand(i);
11272 SDValue RHSOp = RHS.getOperand(i);
11274 // Can't fold divide by zero.
11275 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11276 N->getOpcode() == ISD::FDIV) {
11277 if ((RHSOp.getOpcode() == ISD::Constant &&
11278 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11279 (RHSOp.getOpcode() == ISD::ConstantFP &&
11280 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11284 EVT VT = LHSOp.getValueType();
11285 EVT RVT = RHSOp.getValueType();
11287 // Integer BUILD_VECTOR operands may have types larger than the element
11288 // size (e.g., when the element type is not legal). Prior to type
11289 // legalization, the types may not match between the two BUILD_VECTORS.
11290 // Truncate one of the operands to make them match.
11291 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11292 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11294 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11298 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11300 if (FoldOp.getOpcode() != ISD::UNDEF &&
11301 FoldOp.getOpcode() != ISD::Constant &&
11302 FoldOp.getOpcode() != ISD::ConstantFP)
11304 Ops.push_back(FoldOp);
11305 AddToWorklist(FoldOp.getNode());
11308 if (Ops.size() == LHS.getNumOperands())
11309 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11312 // Type legalization might introduce new shuffles in the DAG.
11313 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11314 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11315 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11316 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11317 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11318 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11319 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11320 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11322 if (SVN0->getMask().equals(SVN1->getMask())) {
11323 EVT VT = N->getValueType(0);
11324 SDValue UndefVector = LHS.getOperand(1);
11325 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11326 LHS.getOperand(0), RHS.getOperand(0));
11327 AddUsersToWorklist(N);
11328 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11329 &SVN0->getMask()[0]);
11336 /// Visit a binary vector operation, like FABS/FNEG.
11337 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11338 assert(N->getValueType(0).isVector() &&
11339 "SimplifyVUnaryOp only works on vectors!");
11341 SDValue N0 = N->getOperand(0);
11343 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11346 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11347 SmallVector<SDValue, 8> Ops;
11348 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11349 SDValue Op = N0.getOperand(i);
11350 if (Op.getOpcode() != ISD::UNDEF &&
11351 Op.getOpcode() != ISD::ConstantFP)
11353 EVT EltVT = Op.getValueType();
11354 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11355 if (FoldOp.getOpcode() != ISD::UNDEF &&
11356 FoldOp.getOpcode() != ISD::ConstantFP)
11358 Ops.push_back(FoldOp);
11359 AddToWorklist(FoldOp.getNode());
11362 if (Ops.size() != N0.getNumOperands())
11365 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11368 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11369 SDValue N1, SDValue N2){
11370 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11372 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11373 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11375 // If we got a simplified select_cc node back from SimplifySelectCC, then
11376 // break it down into a new SETCC node, and a new SELECT node, and then return
11377 // the SELECT node, since we were called with a SELECT node.
11378 if (SCC.getNode()) {
11379 // Check to see if we got a select_cc back (to turn into setcc/select).
11380 // Otherwise, just return whatever node we got back, like fabs.
11381 if (SCC.getOpcode() == ISD::SELECT_CC) {
11382 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11384 SCC.getOperand(0), SCC.getOperand(1),
11385 SCC.getOperand(4));
11386 AddToWorklist(SETCC.getNode());
11387 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11388 SCC.getOperand(2), SCC.getOperand(3));
11396 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11397 /// being selected between, see if we can simplify the select. Callers of this
11398 /// should assume that TheSelect is deleted if this returns true. As such, they
11399 /// should return the appropriate thing (e.g. the node) back to the top-level of
11400 /// the DAG combiner loop to avoid it being looked at.
11401 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11404 // Cannot simplify select with vector condition
11405 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11407 // If this is a select from two identical things, try to pull the operation
11408 // through the select.
11409 if (LHS.getOpcode() != RHS.getOpcode() ||
11410 !LHS.hasOneUse() || !RHS.hasOneUse())
11413 // If this is a load and the token chain is identical, replace the select
11414 // of two loads with a load through a select of the address to load from.
11415 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11416 // constants have been dropped into the constant pool.
11417 if (LHS.getOpcode() == ISD::LOAD) {
11418 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11419 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11421 // Token chains must be identical.
11422 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11423 // Do not let this transformation reduce the number of volatile loads.
11424 LLD->isVolatile() || RLD->isVolatile() ||
11425 // If this is an EXTLOAD, the VT's must match.
11426 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11427 // If this is an EXTLOAD, the kind of extension must match.
11428 (LLD->getExtensionType() != RLD->getExtensionType() &&
11429 // The only exception is if one of the extensions is anyext.
11430 LLD->getExtensionType() != ISD::EXTLOAD &&
11431 RLD->getExtensionType() != ISD::EXTLOAD) ||
11432 // FIXME: this discards src value information. This is
11433 // over-conservative. It would be beneficial to be able to remember
11434 // both potential memory locations. Since we are discarding
11435 // src value info, don't do the transformation if the memory
11436 // locations are not in the default address space.
11437 LLD->getPointerInfo().getAddrSpace() != 0 ||
11438 RLD->getPointerInfo().getAddrSpace() != 0 ||
11439 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11440 LLD->getBasePtr().getValueType()))
11443 // Check that the select condition doesn't reach either load. If so,
11444 // folding this will induce a cycle into the DAG. If not, this is safe to
11445 // xform, so create a select of the addresses.
11447 if (TheSelect->getOpcode() == ISD::SELECT) {
11448 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11449 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11450 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11452 // The loads must not depend on one another.
11453 if (LLD->isPredecessorOf(RLD) ||
11454 RLD->isPredecessorOf(LLD))
11456 Addr = DAG.getSelect(SDLoc(TheSelect),
11457 LLD->getBasePtr().getValueType(),
11458 TheSelect->getOperand(0), LLD->getBasePtr(),
11459 RLD->getBasePtr());
11460 } else { // Otherwise SELECT_CC
11461 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11462 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11464 if ((LLD->hasAnyUseOfValue(1) &&
11465 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11466 (RLD->hasAnyUseOfValue(1) &&
11467 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11470 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11471 LLD->getBasePtr().getValueType(),
11472 TheSelect->getOperand(0),
11473 TheSelect->getOperand(1),
11474 LLD->getBasePtr(), RLD->getBasePtr(),
11475 TheSelect->getOperand(4));
11479 // It is safe to replace the two loads if they have different alignments,
11480 // but the new load must be the minimum (most restrictive) alignment of the
11482 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11483 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11484 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11485 Load = DAG.getLoad(TheSelect->getValueType(0),
11487 // FIXME: Discards pointer and AA info.
11488 LLD->getChain(), Addr, MachinePointerInfo(),
11489 LLD->isVolatile(), LLD->isNonTemporal(),
11490 isInvariant, Alignment);
11492 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11493 RLD->getExtensionType() : LLD->getExtensionType(),
11495 TheSelect->getValueType(0),
11496 // FIXME: Discards pointer and AA info.
11497 LLD->getChain(), Addr, MachinePointerInfo(),
11498 LLD->getMemoryVT(), LLD->isVolatile(),
11499 LLD->isNonTemporal(), isInvariant, Alignment);
11502 // Users of the select now use the result of the load.
11503 CombineTo(TheSelect, Load);
11505 // Users of the old loads now use the new load's chain. We know the
11506 // old-load value is dead now.
11507 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11508 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11515 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11516 /// where 'cond' is the comparison specified by CC.
11517 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11518 SDValue N2, SDValue N3,
11519 ISD::CondCode CC, bool NotExtCompare) {
11520 // (x ? y : y) -> y.
11521 if (N2 == N3) return N2;
11523 EVT VT = N2.getValueType();
11524 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11525 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11526 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11528 // Determine if the condition we're dealing with is constant
11529 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11530 N0, N1, CC, DL, false);
11531 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11532 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11534 // fold select_cc true, x, y -> x
11535 if (SCCC && !SCCC->isNullValue())
11537 // fold select_cc false, x, y -> y
11538 if (SCCC && SCCC->isNullValue())
11541 // Check to see if we can simplify the select into an fabs node
11542 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11543 // Allow either -0.0 or 0.0
11544 if (CFP->getValueAPF().isZero()) {
11545 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11546 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11547 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11548 N2 == N3.getOperand(0))
11549 return DAG.getNode(ISD::FABS, DL, VT, N0);
11551 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11552 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11553 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11554 N2.getOperand(0) == N3)
11555 return DAG.getNode(ISD::FABS, DL, VT, N3);
11559 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11560 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11561 // in it. This is a win when the constant is not otherwise available because
11562 // it replaces two constant pool loads with one. We only do this if the FP
11563 // type is known to be legal, because if it isn't, then we are before legalize
11564 // types an we want the other legalization to happen first (e.g. to avoid
11565 // messing with soft float) and if the ConstantFP is not legal, because if
11566 // it is legal, we may not need to store the FP constant in a constant pool.
11567 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11568 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11569 if (TLI.isTypeLegal(N2.getValueType()) &&
11570 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11571 TargetLowering::Legal &&
11572 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11573 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11574 // If both constants have multiple uses, then we won't need to do an
11575 // extra load, they are likely around in registers for other users.
11576 (TV->hasOneUse() || FV->hasOneUse())) {
11577 Constant *Elts[] = {
11578 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11579 const_cast<ConstantFP*>(TV->getConstantFPValue())
11581 Type *FPTy = Elts[0]->getType();
11582 const DataLayout &TD = *TLI.getDataLayout();
11584 // Create a ConstantArray of the two constants.
11585 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11586 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11587 TD.getPrefTypeAlignment(FPTy));
11588 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11590 // Get the offsets to the 0 and 1 element of the array so that we can
11591 // select between them.
11592 SDValue Zero = DAG.getIntPtrConstant(0);
11593 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11594 SDValue One = DAG.getIntPtrConstant(EltSize);
11596 SDValue Cond = DAG.getSetCC(DL,
11597 getSetCCResultType(N0.getValueType()),
11599 AddToWorklist(Cond.getNode());
11600 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11602 AddToWorklist(CstOffset.getNode());
11603 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11605 AddToWorklist(CPIdx.getNode());
11606 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11607 MachinePointerInfo::getConstantPool(), false,
11608 false, false, Alignment);
11613 // Check to see if we can perform the "gzip trick", transforming
11614 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11615 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11616 (N1C->isNullValue() || // (a < 0) ? b : 0
11617 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11618 EVT XType = N0.getValueType();
11619 EVT AType = N2.getValueType();
11620 if (XType.bitsGE(AType)) {
11621 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11622 // single-bit constant.
11623 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11624 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11625 ShCtV = XType.getSizeInBits()-ShCtV-1;
11626 SDValue ShCt = DAG.getConstant(ShCtV,
11627 getShiftAmountTy(N0.getValueType()));
11628 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11630 AddToWorklist(Shift.getNode());
11632 if (XType.bitsGT(AType)) {
11633 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11634 AddToWorklist(Shift.getNode());
11637 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11640 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11642 DAG.getConstant(XType.getSizeInBits()-1,
11643 getShiftAmountTy(N0.getValueType())));
11644 AddToWorklist(Shift.getNode());
11646 if (XType.bitsGT(AType)) {
11647 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11648 AddToWorklist(Shift.getNode());
11651 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11655 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11656 // where y is has a single bit set.
11657 // A plaintext description would be, we can turn the SELECT_CC into an AND
11658 // when the condition can be materialized as an all-ones register. Any
11659 // single bit-test can be materialized as an all-ones register with
11660 // shift-left and shift-right-arith.
11661 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11662 N0->getValueType(0) == VT &&
11663 N1C && N1C->isNullValue() &&
11664 N2C && N2C->isNullValue()) {
11665 SDValue AndLHS = N0->getOperand(0);
11666 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11667 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11668 // Shift the tested bit over the sign bit.
11669 APInt AndMask = ConstAndRHS->getAPIntValue();
11671 DAG.getConstant(AndMask.countLeadingZeros(),
11672 getShiftAmountTy(AndLHS.getValueType()));
11673 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11675 // Now arithmetic right shift it all the way over, so the result is either
11676 // all-ones, or zero.
11678 DAG.getConstant(AndMask.getBitWidth()-1,
11679 getShiftAmountTy(Shl.getValueType()));
11680 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11682 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11686 // fold select C, 16, 0 -> shl C, 4
11687 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11688 TLI.getBooleanContents(N0.getValueType()) ==
11689 TargetLowering::ZeroOrOneBooleanContent) {
11691 // If the caller doesn't want us to simplify this into a zext of a compare,
11693 if (NotExtCompare && N2C->getAPIntValue() == 1)
11696 // Get a SetCC of the condition
11697 // NOTE: Don't create a SETCC if it's not legal on this target.
11698 if (!LegalOperations ||
11699 TLI.isOperationLegal(ISD::SETCC,
11700 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11702 // cast from setcc result type to select result type
11704 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11706 if (N2.getValueType().bitsLT(SCC.getValueType()))
11707 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11708 N2.getValueType());
11710 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11711 N2.getValueType(), SCC);
11713 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11714 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11715 N2.getValueType(), SCC);
11718 AddToWorklist(SCC.getNode());
11719 AddToWorklist(Temp.getNode());
11721 if (N2C->getAPIntValue() == 1)
11724 // shl setcc result by log2 n2c
11725 return DAG.getNode(
11726 ISD::SHL, DL, N2.getValueType(), Temp,
11727 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11728 getShiftAmountTy(Temp.getValueType())));
11732 // Check to see if this is the equivalent of setcc
11733 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11734 // otherwise, go ahead with the folds.
11735 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11736 EVT XType = N0.getValueType();
11737 if (!LegalOperations ||
11738 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11739 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11740 if (Res.getValueType() != VT)
11741 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11745 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11746 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11747 (!LegalOperations ||
11748 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11749 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11750 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11751 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11752 getShiftAmountTy(Ctlz.getValueType())));
11754 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11755 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11756 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11757 XType, DAG.getConstant(0, XType), N0);
11758 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11759 return DAG.getNode(ISD::SRL, DL, XType,
11760 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11761 DAG.getConstant(XType.getSizeInBits()-1,
11762 getShiftAmountTy(XType)));
11764 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11765 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11766 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11767 DAG.getConstant(XType.getSizeInBits()-1,
11768 getShiftAmountTy(N0.getValueType())));
11769 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11773 // Check to see if this is an integer abs.
11774 // select_cc setg[te] X, 0, X, -X ->
11775 // select_cc setgt X, -1, X, -X ->
11776 // select_cc setl[te] X, 0, -X, X ->
11777 // select_cc setlt X, 1, -X, X ->
11778 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11780 ConstantSDNode *SubC = nullptr;
11781 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11782 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11783 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11784 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11785 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11786 (N1C->isOne() && CC == ISD::SETLT)) &&
11787 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11788 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11790 EVT XType = N0.getValueType();
11791 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11792 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11794 DAG.getConstant(XType.getSizeInBits()-1,
11795 getShiftAmountTy(N0.getValueType())));
11796 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11798 AddToWorklist(Shift.getNode());
11799 AddToWorklist(Add.getNode());
11800 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11807 /// This is a stub for TargetLowering::SimplifySetCC.
11808 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11809 SDValue N1, ISD::CondCode Cond,
11810 SDLoc DL, bool foldBooleans) {
11811 TargetLowering::DAGCombinerInfo
11812 DagCombineInfo(DAG, Level, false, this);
11813 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11816 /// Given an ISD::SDIV node expressing a divide by constant, return
11817 /// a DAG expression to select that will generate the same value by multiplying
11818 /// by a magic number.
11819 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11820 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11821 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11825 // Avoid division by zero.
11826 if (!C->getAPIntValue())
11829 std::vector<SDNode*> Built;
11831 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11833 for (SDNode *N : Built)
11838 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11839 /// DAG expression that will generate the same value by right shifting.
11840 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11841 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11845 // Avoid division by zero.
11846 if (!C->getAPIntValue())
11849 std::vector<SDNode *> Built;
11850 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11852 for (SDNode *N : Built)
11857 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11858 /// expression that will generate the same value by multiplying by a magic
11860 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11861 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11862 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11866 // Avoid division by zero.
11867 if (!C->getAPIntValue())
11870 std::vector<SDNode*> Built;
11872 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11874 for (SDNode *N : Built)
11879 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11880 if (Level >= AfterLegalizeDAG)
11883 // Expose the DAG combiner to the target combiner implementations.
11884 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11886 unsigned Iterations = 0;
11887 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
11889 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11890 // For the reciprocal, we need to find the zero of the function:
11891 // F(X) = A X - 1 [which has a zero at X = 1/A]
11893 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11894 // does not require additional intermediate precision]
11895 EVT VT = Op.getValueType();
11897 SDValue FPOne = DAG.getConstantFP(1.0, VT);
11899 AddToWorklist(Est.getNode());
11901 // Newton iterations: Est = Est + Est (1 - Arg * Est)
11902 for (unsigned i = 0; i < Iterations; ++i) {
11903 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11904 AddToWorklist(NewEst.getNode());
11906 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11907 AddToWorklist(NewEst.getNode());
11909 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11910 AddToWorklist(NewEst.getNode());
11912 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
11913 AddToWorklist(Est.getNode());
11922 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
11923 if (Level >= AfterLegalizeDAG)
11926 // Expose the DAG combiner to the target combiner implementations.
11927 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11928 unsigned Iterations = 0;
11929 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations)) {
11931 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11932 // For the reciprocal sqrt, we need to find the zero of the function:
11933 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
11935 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
11936 // As a result, we precompute A/2 prior to the iteration loop.
11937 EVT VT = Op.getValueType();
11939 SDValue FPThreeHalves = DAG.getConstantFP(1.5, VT);
11941 AddToWorklist(Est.getNode());
11943 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
11944 // this entire sequence requires only one FP constant.
11945 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, FPThreeHalves, Op);
11946 AddToWorklist(HalfArg.getNode());
11948 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Op);
11949 AddToWorklist(HalfArg.getNode());
11951 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
11952 for (unsigned i = 0; i < Iterations; ++i) {
11953 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
11954 AddToWorklist(NewEst.getNode());
11956 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
11957 AddToWorklist(NewEst.getNode());
11959 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPThreeHalves, NewEst);
11960 AddToWorklist(NewEst.getNode());
11962 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11963 AddToWorklist(Est.getNode());
11972 /// Return true if base is a frame index, which is known not to alias with
11973 /// anything but itself. Provides base object and offset as results.
11974 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11975 const GlobalValue *&GV, const void *&CV) {
11976 // Assume it is a primitive operation.
11977 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11979 // If it's an adding a simple constant then integrate the offset.
11980 if (Base.getOpcode() == ISD::ADD) {
11981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11982 Base = Base.getOperand(0);
11983 Offset += C->getZExtValue();
11987 // Return the underlying GlobalValue, and update the Offset. Return false
11988 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11989 // by multiple nodes with different offsets.
11990 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11991 GV = G->getGlobal();
11992 Offset += G->getOffset();
11996 // Return the underlying Constant value, and update the Offset. Return false
11997 // for ConstantSDNodes since the same constant pool entry may be represented
11998 // by multiple nodes with different offsets.
11999 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12000 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12001 : (const void *)C->getConstVal();
12002 Offset += C->getOffset();
12005 // If it's any of the following then it can't alias with anything but itself.
12006 return isa<FrameIndexSDNode>(Base);
12009 /// Return true if there is any possibility that the two addresses overlap.
12010 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12011 // If they are the same then they must be aliases.
12012 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12014 // If they are both volatile then they cannot be reordered.
12015 if (Op0->isVolatile() && Op1->isVolatile()) return true;
12017 // Gather base node and offset information.
12018 SDValue Base1, Base2;
12019 int64_t Offset1, Offset2;
12020 const GlobalValue *GV1, *GV2;
12021 const void *CV1, *CV2;
12022 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12023 Base1, Offset1, GV1, CV1);
12024 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12025 Base2, Offset2, GV2, CV2);
12027 // If they have a same base address then check to see if they overlap.
12028 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12029 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12030 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12032 // It is possible for different frame indices to alias each other, mostly
12033 // when tail call optimization reuses return address slots for arguments.
12034 // To catch this case, look up the actual index of frame indices to compute
12035 // the real alias relationship.
12036 if (isFrameIndex1 && isFrameIndex2) {
12037 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12038 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12039 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12040 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12041 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12044 // Otherwise, if we know what the bases are, and they aren't identical, then
12045 // we know they cannot alias.
12046 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12049 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12050 // compared to the size and offset of the access, we may be able to prove they
12051 // do not alias. This check is conservative for now to catch cases created by
12052 // splitting vector types.
12053 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12054 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12055 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12056 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12057 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12058 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12059 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12061 // There is no overlap between these relatively aligned accesses of similar
12062 // size, return no alias.
12063 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12064 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12068 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12070 : DAG.getSubtarget().useAA();
12072 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12073 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12077 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12078 // Use alias analysis information.
12079 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12080 Op1->getSrcValueOffset());
12081 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12082 Op0->getSrcValueOffset() - MinOffset;
12083 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12084 Op1->getSrcValueOffset() - MinOffset;
12085 AliasAnalysis::AliasResult AAResult =
12086 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12088 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12089 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12091 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12092 if (AAResult == AliasAnalysis::NoAlias)
12096 // Otherwise we have to assume they alias.
12100 /// Walk up chain skipping non-aliasing memory nodes,
12101 /// looking for aliasing nodes and adding them to the Aliases vector.
12102 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12103 SmallVectorImpl<SDValue> &Aliases) {
12104 SmallVector<SDValue, 8> Chains; // List of chains to visit.
12105 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
12107 // Get alias information for node.
12108 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12111 Chains.push_back(OriginalChain);
12112 unsigned Depth = 0;
12114 // Look at each chain and determine if it is an alias. If so, add it to the
12115 // aliases list. If not, then continue up the chain looking for the next
12117 while (!Chains.empty()) {
12118 SDValue Chain = Chains.back();
12121 // For TokenFactor nodes, look at each operand and only continue up the
12122 // chain until we find two aliases. If we've seen two aliases, assume we'll
12123 // find more and revert to original chain since the xform is unlikely to be
12126 // FIXME: The depth check could be made to return the last non-aliasing
12127 // chain we found before we hit a tokenfactor rather than the original
12129 if (Depth > 6 || Aliases.size() == 2) {
12131 Aliases.push_back(OriginalChain);
12135 // Don't bother if we've been before.
12136 if (!Visited.insert(Chain.getNode()))
12139 switch (Chain.getOpcode()) {
12140 case ISD::EntryToken:
12141 // Entry token is ideal chain operand, but handled in FindBetterChain.
12146 // Get alias information for Chain.
12147 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12148 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12150 // If chain is alias then stop here.
12151 if (!(IsLoad && IsOpLoad) &&
12152 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12153 Aliases.push_back(Chain);
12155 // Look further up the chain.
12156 Chains.push_back(Chain.getOperand(0));
12162 case ISD::TokenFactor:
12163 // We have to check each of the operands of the token factor for "small"
12164 // token factors, so we queue them up. Adding the operands to the queue
12165 // (stack) in reverse order maintains the original order and increases the
12166 // likelihood that getNode will find a matching token factor (CSE.)
12167 if (Chain.getNumOperands() > 16) {
12168 Aliases.push_back(Chain);
12171 for (unsigned n = Chain.getNumOperands(); n;)
12172 Chains.push_back(Chain.getOperand(--n));
12177 // For all other instructions we will just have to take what we can get.
12178 Aliases.push_back(Chain);
12183 // We need to be careful here to also search for aliases through the
12184 // value operand of a store, etc. Consider the following situation:
12186 // L1 = load Token1, %52
12187 // S1 = store Token1, L1, %51
12188 // L2 = load Token1, %52+8
12189 // S2 = store Token1, L2, %51+8
12190 // Token2 = Token(S1, S2)
12191 // L3 = load Token2, %53
12192 // S3 = store Token2, L3, %52
12193 // L4 = load Token2, %53+8
12194 // S4 = store Token2, L4, %52+8
12195 // If we search for aliases of S3 (which loads address %52), and we look
12196 // only through the chain, then we'll miss the trivial dependence on L1
12197 // (which also loads from %52). We then might change all loads and
12198 // stores to use Token1 as their chain operand, which could result in
12199 // copying %53 into %52 before copying %52 into %51 (which should
12202 // The problem is, however, that searching for such data dependencies
12203 // can become expensive, and the cost is not directly related to the
12204 // chain depth. Instead, we'll rule out such configurations here by
12205 // insisting that we've visited all chain users (except for users
12206 // of the original chain, which is not necessary). When doing this,
12207 // we need to look through nodes we don't care about (otherwise, things
12208 // like register copies will interfere with trivial cases).
12210 SmallVector<const SDNode *, 16> Worklist;
12211 for (const SDNode *N : Visited)
12212 if (N != OriginalChain.getNode())
12213 Worklist.push_back(N);
12215 while (!Worklist.empty()) {
12216 const SDNode *M = Worklist.pop_back_val();
12218 // We have already visited M, and want to make sure we've visited any uses
12219 // of M that we care about. For uses that we've not visisted, and don't
12220 // care about, queue them to the worklist.
12222 for (SDNode::use_iterator UI = M->use_begin(),
12223 UIE = M->use_end(); UI != UIE; ++UI)
12224 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12225 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12226 // We've not visited this use, and we care about it (it could have an
12227 // ordering dependency with the original node).
12229 Aliases.push_back(OriginalChain);
12233 // We've not visited this use, but we don't care about it. Mark it as
12234 // visited and enqueue it to the worklist.
12235 Worklist.push_back(*UI);
12240 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12241 /// (aliasing node.)
12242 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12243 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
12245 // Accumulate all the aliases to this node.
12246 GatherAllAliases(N, OldChain, Aliases);
12248 // If no operands then chain to entry token.
12249 if (Aliases.size() == 0)
12250 return DAG.getEntryNode();
12252 // If a single operand then chain to it. We don't need to revisit it.
12253 if (Aliases.size() == 1)
12256 // Construct a custom tailored token factor.
12257 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12260 /// This is the entry point for the file.
12261 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12262 CodeGenOpt::Level OptLevel) {
12263 /// This is the main entry point to this class.
12264 DAGCombiner(*this, AA, OptLevel).Run(Level);